1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// \file 9 /// This file implements semantic analysis for OpenMP directives and 10 /// clauses. 11 /// 12 //===----------------------------------------------------------------------===// 13 14 #include "TreeTransform.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/AST/DeclCXX.h" 20 #include "clang/AST/DeclOpenMP.h" 21 #include "clang/AST/OpenMPClause.h" 22 #include "clang/AST/StmtCXX.h" 23 #include "clang/AST/StmtOpenMP.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/AST/TypeOrdering.h" 26 #include "clang/Basic/DiagnosticSema.h" 27 #include "clang/Basic/OpenMPKinds.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Sema/Initialization.h" 31 #include "clang/Sema/Lookup.h" 32 #include "clang/Sema/Scope.h" 33 #include "clang/Sema/ScopeInfo.h" 34 #include "clang/Sema/SemaInternal.h" 35 #include "llvm/ADT/IndexedMap.h" 36 #include "llvm/ADT/PointerEmbeddedInt.h" 37 #include "llvm/ADT/STLExtras.h" 38 #include "llvm/ADT/SmallSet.h" 39 #include "llvm/ADT/StringExtras.h" 40 #include "llvm/Frontend/OpenMP/OMPAssume.h" 41 #include "llvm/Frontend/OpenMP/OMPConstants.h" 42 #include <set> 43 44 using namespace clang; 45 using namespace llvm::omp; 46 47 //===----------------------------------------------------------------------===// 48 // Stack of data-sharing attributes for variables 49 //===----------------------------------------------------------------------===// 50 51 static const Expr *checkMapClauseExpressionBase( 52 Sema &SemaRef, Expr *E, 53 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 54 OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose); 55 56 namespace { 57 /// Default data sharing attributes, which can be applied to directive. 58 enum DefaultDataSharingAttributes { 59 DSA_unspecified = 0, /// Data sharing attribute not specified. 60 DSA_none = 1 << 0, /// Default data sharing attribute 'none'. 61 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'. 62 DSA_private = 1 << 2, /// Default data sharing attribute 'private'. 63 DSA_firstprivate = 1 << 3, /// Default data sharing attribute 'firstprivate'. 64 }; 65 66 /// Stack for tracking declarations used in OpenMP directives and 67 /// clauses and their data-sharing attributes. 68 class DSAStackTy { 69 public: 70 struct DSAVarData { 71 OpenMPDirectiveKind DKind = OMPD_unknown; 72 OpenMPClauseKind CKind = OMPC_unknown; 73 unsigned Modifier = 0; 74 const Expr *RefExpr = nullptr; 75 DeclRefExpr *PrivateCopy = nullptr; 76 SourceLocation ImplicitDSALoc; 77 bool AppliedToPointee = false; 78 DSAVarData() = default; 79 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 80 const Expr *RefExpr, DeclRefExpr *PrivateCopy, 81 SourceLocation ImplicitDSALoc, unsigned Modifier, 82 bool AppliedToPointee) 83 : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr), 84 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc), 85 AppliedToPointee(AppliedToPointee) {} 86 }; 87 using OperatorOffsetTy = 88 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>; 89 using DoacrossDependMapTy = 90 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>; 91 /// Kind of the declaration used in the uses_allocators clauses. 92 enum class UsesAllocatorsDeclKind { 93 /// Predefined allocator 94 PredefinedAllocator, 95 /// User-defined allocator 96 UserDefinedAllocator, 97 /// The declaration that represent allocator trait 98 AllocatorTrait, 99 }; 100 101 private: 102 struct DSAInfo { 103 OpenMPClauseKind Attributes = OMPC_unknown; 104 unsigned Modifier = 0; 105 /// Pointer to a reference expression and a flag which shows that the 106 /// variable is marked as lastprivate(true) or not (false). 107 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr; 108 DeclRefExpr *PrivateCopy = nullptr; 109 /// true if the attribute is applied to the pointee, not the variable 110 /// itself. 111 bool AppliedToPointee = false; 112 }; 113 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>; 114 using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>; 115 using LCDeclInfo = std::pair<unsigned, VarDecl *>; 116 using LoopControlVariablesMapTy = 117 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>; 118 /// Struct that associates a component with the clause kind where they are 119 /// found. 120 struct MappedExprComponentTy { 121 OMPClauseMappableExprCommon::MappableExprComponentLists Components; 122 OpenMPClauseKind Kind = OMPC_unknown; 123 }; 124 using MappedExprComponentsTy = 125 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>; 126 using CriticalsWithHintsTy = 127 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>; 128 struct ReductionData { 129 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>; 130 SourceRange ReductionRange; 131 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp; 132 ReductionData() = default; 133 void set(BinaryOperatorKind BO, SourceRange RR) { 134 ReductionRange = RR; 135 ReductionOp = BO; 136 } 137 void set(const Expr *RefExpr, SourceRange RR) { 138 ReductionRange = RR; 139 ReductionOp = RefExpr; 140 } 141 }; 142 using DeclReductionMapTy = 143 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>; 144 struct DefaultmapInfo { 145 OpenMPDefaultmapClauseModifier ImplicitBehavior = 146 OMPC_DEFAULTMAP_MODIFIER_unknown; 147 SourceLocation SLoc; 148 DefaultmapInfo() = default; 149 DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc) 150 : ImplicitBehavior(M), SLoc(Loc) {} 151 }; 152 153 struct SharingMapTy { 154 DeclSAMapTy SharingMap; 155 DeclReductionMapTy ReductionMap; 156 UsedRefMapTy AlignedMap; 157 UsedRefMapTy NontemporalMap; 158 MappedExprComponentsTy MappedExprComponents; 159 LoopControlVariablesMapTy LCVMap; 160 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 161 SourceLocation DefaultAttrLoc; 162 DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown]; 163 OpenMPDirectiveKind Directive = OMPD_unknown; 164 DeclarationNameInfo DirectiveName; 165 Scope *CurScope = nullptr; 166 DeclContext *Context = nullptr; 167 SourceLocation ConstructLoc; 168 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 169 /// get the data (loop counters etc.) about enclosing loop-based construct. 170 /// This data is required during codegen. 171 DoacrossDependMapTy DoacrossDepends; 172 /// First argument (Expr *) contains optional argument of the 173 /// 'ordered' clause, the second one is true if the regions has 'ordered' 174 /// clause, false otherwise. 175 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion; 176 unsigned AssociatedLoops = 1; 177 bool HasMutipleLoops = false; 178 const Decl *PossiblyLoopCounter = nullptr; 179 bool NowaitRegion = false; 180 bool UntiedRegion = false; 181 bool CancelRegion = false; 182 bool LoopStart = false; 183 bool BodyComplete = false; 184 SourceLocation PrevScanLocation; 185 SourceLocation PrevOrderedLocation; 186 SourceLocation InnerTeamsRegionLoc; 187 /// Reference to the taskgroup task_reduction reference expression. 188 Expr *TaskgroupReductionRef = nullptr; 189 llvm::DenseSet<QualType> MappedClassesQualTypes; 190 SmallVector<Expr *, 4> InnerUsedAllocators; 191 llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates; 192 /// List of globals marked as declare target link in this target region 193 /// (isOpenMPTargetExecutionDirective(Directive) == true). 194 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls; 195 /// List of decls used in inclusive/exclusive clauses of the scan directive. 196 llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective; 197 llvm::DenseMap<CanonicalDeclPtr<const Decl>, UsesAllocatorsDeclKind> 198 UsesAllocatorsDecls; 199 Expr *DeclareMapperVar = nullptr; 200 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 201 Scope *CurScope, SourceLocation Loc) 202 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 203 ConstructLoc(Loc) {} 204 SharingMapTy() = default; 205 }; 206 207 using StackTy = SmallVector<SharingMapTy, 4>; 208 209 /// Stack of used declaration and their data-sharing attributes. 210 DeclSAMapTy Threadprivates; 211 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr; 212 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack; 213 /// true, if check for DSA must be from parent directive, false, if 214 /// from current directive. 215 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 216 Sema &SemaRef; 217 bool ForceCapturing = false; 218 /// true if all the variables in the target executable directives must be 219 /// captured by reference. 220 bool ForceCaptureByReferenceInTargetExecutable = false; 221 CriticalsWithHintsTy Criticals; 222 unsigned IgnoredStackElements = 0; 223 224 /// Iterators over the stack iterate in order from innermost to outermost 225 /// directive. 226 using const_iterator = StackTy::const_reverse_iterator; 227 const_iterator begin() const { 228 return Stack.empty() ? const_iterator() 229 : Stack.back().first.rbegin() + IgnoredStackElements; 230 } 231 const_iterator end() const { 232 return Stack.empty() ? const_iterator() : Stack.back().first.rend(); 233 } 234 using iterator = StackTy::reverse_iterator; 235 iterator begin() { 236 return Stack.empty() ? iterator() 237 : Stack.back().first.rbegin() + IgnoredStackElements; 238 } 239 iterator end() { 240 return Stack.empty() ? iterator() : Stack.back().first.rend(); 241 } 242 243 // Convenience operations to get at the elements of the stack. 244 245 bool isStackEmpty() const { 246 return Stack.empty() || 247 Stack.back().second != CurrentNonCapturingFunctionScope || 248 Stack.back().first.size() <= IgnoredStackElements; 249 } 250 size_t getStackSize() const { 251 return isStackEmpty() ? 0 252 : Stack.back().first.size() - IgnoredStackElements; 253 } 254 255 SharingMapTy *getTopOfStackOrNull() { 256 size_t Size = getStackSize(); 257 if (Size == 0) 258 return nullptr; 259 return &Stack.back().first[Size - 1]; 260 } 261 const SharingMapTy *getTopOfStackOrNull() const { 262 return const_cast<DSAStackTy &>(*this).getTopOfStackOrNull(); 263 } 264 SharingMapTy &getTopOfStack() { 265 assert(!isStackEmpty() && "no current directive"); 266 return *getTopOfStackOrNull(); 267 } 268 const SharingMapTy &getTopOfStack() const { 269 return const_cast<DSAStackTy &>(*this).getTopOfStack(); 270 } 271 272 SharingMapTy *getSecondOnStackOrNull() { 273 size_t Size = getStackSize(); 274 if (Size <= 1) 275 return nullptr; 276 return &Stack.back().first[Size - 2]; 277 } 278 const SharingMapTy *getSecondOnStackOrNull() const { 279 return const_cast<DSAStackTy &>(*this).getSecondOnStackOrNull(); 280 } 281 282 /// Get the stack element at a certain level (previously returned by 283 /// \c getNestingLevel). 284 /// 285 /// Note that nesting levels count from outermost to innermost, and this is 286 /// the reverse of our iteration order where new inner levels are pushed at 287 /// the front of the stack. 288 SharingMapTy &getStackElemAtLevel(unsigned Level) { 289 assert(Level < getStackSize() && "no such stack element"); 290 return Stack.back().first[Level]; 291 } 292 const SharingMapTy &getStackElemAtLevel(unsigned Level) const { 293 return const_cast<DSAStackTy &>(*this).getStackElemAtLevel(Level); 294 } 295 296 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const; 297 298 /// Checks if the variable is a local for OpenMP region. 299 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const; 300 301 /// Vector of previously declared requires directives 302 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls; 303 /// omp_allocator_handle_t type. 304 QualType OMPAllocatorHandleT; 305 /// omp_depend_t type. 306 QualType OMPDependT; 307 /// omp_event_handle_t type. 308 QualType OMPEventHandleT; 309 /// omp_alloctrait_t type. 310 QualType OMPAlloctraitT; 311 /// Expression for the predefined allocators. 312 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = { 313 nullptr}; 314 /// Vector of previously encountered target directives 315 SmallVector<SourceLocation, 2> TargetLocations; 316 SourceLocation AtomicLocation; 317 /// Vector of declare variant construct traits. 318 SmallVector<llvm::omp::TraitProperty, 8> ConstructTraits; 319 320 public: 321 explicit DSAStackTy(Sema &S) : SemaRef(S) {} 322 323 /// Sets omp_allocator_handle_t type. 324 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; } 325 /// Gets omp_allocator_handle_t type. 326 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; } 327 /// Sets omp_alloctrait_t type. 328 void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; } 329 /// Gets omp_alloctrait_t type. 330 QualType getOMPAlloctraitT() const { return OMPAlloctraitT; } 331 /// Sets the given default allocator. 332 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, 333 Expr *Allocator) { 334 OMPPredefinedAllocators[AllocatorKind] = Allocator; 335 } 336 /// Returns the specified default allocator. 337 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const { 338 return OMPPredefinedAllocators[AllocatorKind]; 339 } 340 /// Sets omp_depend_t type. 341 void setOMPDependT(QualType Ty) { OMPDependT = Ty; } 342 /// Gets omp_depend_t type. 343 QualType getOMPDependT() const { return OMPDependT; } 344 345 /// Sets omp_event_handle_t type. 346 void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; } 347 /// Gets omp_event_handle_t type. 348 QualType getOMPEventHandleT() const { return OMPEventHandleT; } 349 350 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 351 OpenMPClauseKind getClauseParsingMode() const { 352 assert(isClauseParsingMode() && "Must be in clause parsing mode."); 353 return ClauseKindMode; 354 } 355 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 356 357 bool isBodyComplete() const { 358 const SharingMapTy *Top = getTopOfStackOrNull(); 359 return Top && Top->BodyComplete; 360 } 361 void setBodyComplete() { getTopOfStack().BodyComplete = true; } 362 363 bool isForceVarCapturing() const { return ForceCapturing; } 364 void setForceVarCapturing(bool V) { ForceCapturing = V; } 365 366 void setForceCaptureByReferenceInTargetExecutable(bool V) { 367 ForceCaptureByReferenceInTargetExecutable = V; 368 } 369 bool isForceCaptureByReferenceInTargetExecutable() const { 370 return ForceCaptureByReferenceInTargetExecutable; 371 } 372 373 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 374 Scope *CurScope, SourceLocation Loc) { 375 assert(!IgnoredStackElements && 376 "cannot change stack while ignoring elements"); 377 if (Stack.empty() || 378 Stack.back().second != CurrentNonCapturingFunctionScope) 379 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope); 380 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc); 381 Stack.back().first.back().DefaultAttrLoc = Loc; 382 } 383 384 void pop() { 385 assert(!IgnoredStackElements && 386 "cannot change stack while ignoring elements"); 387 assert(!Stack.back().first.empty() && 388 "Data-sharing attributes stack is empty!"); 389 Stack.back().first.pop_back(); 390 } 391 392 /// RAII object to temporarily leave the scope of a directive when we want to 393 /// logically operate in its parent. 394 class ParentDirectiveScope { 395 DSAStackTy &Self; 396 bool Active; 397 398 public: 399 ParentDirectiveScope(DSAStackTy &Self, bool Activate) 400 : Self(Self), Active(false) { 401 if (Activate) 402 enable(); 403 } 404 ~ParentDirectiveScope() { disable(); } 405 void disable() { 406 if (Active) { 407 --Self.IgnoredStackElements; 408 Active = false; 409 } 410 } 411 void enable() { 412 if (!Active) { 413 ++Self.IgnoredStackElements; 414 Active = true; 415 } 416 } 417 }; 418 419 /// Marks that we're started loop parsing. 420 void loopInit() { 421 assert(isOpenMPLoopDirective(getCurrentDirective()) && 422 "Expected loop-based directive."); 423 getTopOfStack().LoopStart = true; 424 } 425 /// Start capturing of the variables in the loop context. 426 void loopStart() { 427 assert(isOpenMPLoopDirective(getCurrentDirective()) && 428 "Expected loop-based directive."); 429 getTopOfStack().LoopStart = false; 430 } 431 /// true, if variables are captured, false otherwise. 432 bool isLoopStarted() const { 433 assert(isOpenMPLoopDirective(getCurrentDirective()) && 434 "Expected loop-based directive."); 435 return !getTopOfStack().LoopStart; 436 } 437 /// Marks (or clears) declaration as possibly loop counter. 438 void resetPossibleLoopCounter(const Decl *D = nullptr) { 439 getTopOfStack().PossiblyLoopCounter = D ? D->getCanonicalDecl() : D; 440 } 441 /// Gets the possible loop counter decl. 442 const Decl *getPossiblyLoopCunter() const { 443 return getTopOfStack().PossiblyLoopCounter; 444 } 445 /// Start new OpenMP region stack in new non-capturing function. 446 void pushFunction() { 447 assert(!IgnoredStackElements && 448 "cannot change stack while ignoring elements"); 449 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction(); 450 assert(!isa<CapturingScopeInfo>(CurFnScope)); 451 CurrentNonCapturingFunctionScope = CurFnScope; 452 } 453 /// Pop region stack for non-capturing function. 454 void popFunction(const FunctionScopeInfo *OldFSI) { 455 assert(!IgnoredStackElements && 456 "cannot change stack while ignoring elements"); 457 if (!Stack.empty() && Stack.back().second == OldFSI) { 458 assert(Stack.back().first.empty()); 459 Stack.pop_back(); 460 } 461 CurrentNonCapturingFunctionScope = nullptr; 462 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) { 463 if (!isa<CapturingScopeInfo>(FSI)) { 464 CurrentNonCapturingFunctionScope = FSI; 465 break; 466 } 467 } 468 } 469 470 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) { 471 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint); 472 } 473 const std::pair<const OMPCriticalDirective *, llvm::APSInt> 474 getCriticalWithHint(const DeclarationNameInfo &Name) const { 475 auto I = Criticals.find(Name.getAsString()); 476 if (I != Criticals.end()) 477 return I->second; 478 return std::make_pair(nullptr, llvm::APSInt()); 479 } 480 /// If 'aligned' declaration for given variable \a D was not seen yet, 481 /// add it and return NULL; otherwise return previous occurrence's expression 482 /// for diagnostics. 483 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE); 484 /// If 'nontemporal' declaration for given variable \a D was not seen yet, 485 /// add it and return NULL; otherwise return previous occurrence's expression 486 /// for diagnostics. 487 const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE); 488 489 /// Register specified variable as loop control variable. 490 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture); 491 /// Check if the specified variable is a loop control variable for 492 /// current region. 493 /// \return The index of the loop control variable in the list of associated 494 /// for-loops (from outer to inner). 495 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const; 496 /// Check if the specified variable is a loop control variable for 497 /// parent region. 498 /// \return The index of the loop control variable in the list of associated 499 /// for-loops (from outer to inner). 500 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const; 501 /// Check if the specified variable is a loop control variable for 502 /// current region. 503 /// \return The index of the loop control variable in the list of associated 504 /// for-loops (from outer to inner). 505 const LCDeclInfo isLoopControlVariable(const ValueDecl *D, 506 unsigned Level) const; 507 /// Get the loop control variable for the I-th loop (or nullptr) in 508 /// parent directive. 509 const ValueDecl *getParentLoopControlVariable(unsigned I) const; 510 511 /// Marks the specified decl \p D as used in scan directive. 512 void markDeclAsUsedInScanDirective(ValueDecl *D) { 513 if (SharingMapTy *Stack = getSecondOnStackOrNull()) 514 Stack->UsedInScanDirective.insert(D); 515 } 516 517 /// Checks if the specified declaration was used in the inner scan directive. 518 bool isUsedInScanDirective(ValueDecl *D) const { 519 if (const SharingMapTy *Stack = getTopOfStackOrNull()) 520 return Stack->UsedInScanDirective.contains(D); 521 return false; 522 } 523 524 /// Adds explicit data sharing attribute to the specified declaration. 525 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 526 DeclRefExpr *PrivateCopy = nullptr, unsigned Modifier = 0, 527 bool AppliedToPointee = false); 528 529 /// Adds additional information for the reduction items with the reduction id 530 /// represented as an operator. 531 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 532 BinaryOperatorKind BOK); 533 /// Adds additional information for the reduction items with the reduction id 534 /// represented as reduction identifier. 535 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 536 const Expr *ReductionRef); 537 /// Returns the location and reduction operation from the innermost parent 538 /// region for the given \p D. 539 const DSAVarData 540 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 541 BinaryOperatorKind &BOK, 542 Expr *&TaskgroupDescriptor) const; 543 /// Returns the location and reduction operation from the innermost parent 544 /// region for the given \p D. 545 const DSAVarData 546 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 547 const Expr *&ReductionRef, 548 Expr *&TaskgroupDescriptor) const; 549 /// Return reduction reference expression for the current taskgroup or 550 /// parallel/worksharing directives with task reductions. 551 Expr *getTaskgroupReductionRef() const { 552 assert((getTopOfStack().Directive == OMPD_taskgroup || 553 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 554 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 555 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 556 "taskgroup reference expression requested for non taskgroup or " 557 "parallel/worksharing directive."); 558 return getTopOfStack().TaskgroupReductionRef; 559 } 560 /// Checks if the given \p VD declaration is actually a taskgroup reduction 561 /// descriptor variable at the \p Level of OpenMP regions. 562 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const { 563 return getStackElemAtLevel(Level).TaskgroupReductionRef && 564 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef) 565 ->getDecl() == VD; 566 } 567 568 /// Returns data sharing attributes from top of the stack for the 569 /// specified declaration. 570 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 571 /// Returns data-sharing attributes for the specified declaration. 572 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const; 573 /// Returns data-sharing attributes for the specified declaration. 574 const DSAVarData getImplicitDSA(ValueDecl *D, unsigned Level) const; 575 /// Checks if the specified variables has data-sharing attributes which 576 /// match specified \a CPred predicate in any directive which matches \a DPred 577 /// predicate. 578 const DSAVarData 579 hasDSA(ValueDecl *D, 580 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 581 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 582 bool FromParent) const; 583 /// Checks if the specified variables has data-sharing attributes which 584 /// match specified \a CPred predicate in any innermost directive which 585 /// matches \a DPred predicate. 586 const DSAVarData 587 hasInnermostDSA(ValueDecl *D, 588 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 589 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 590 bool FromParent) const; 591 /// Checks if the specified variables has explicit data-sharing 592 /// attributes which match specified \a CPred predicate at the specified 593 /// OpenMP region. 594 bool 595 hasExplicitDSA(const ValueDecl *D, 596 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 597 unsigned Level, bool NotLastprivate = false) const; 598 599 /// Returns true if the directive at level \Level matches in the 600 /// specified \a DPred predicate. 601 bool hasExplicitDirective( 602 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 603 unsigned Level) const; 604 605 /// Finds a directive which matches specified \a DPred predicate. 606 bool hasDirective( 607 const llvm::function_ref<bool( 608 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)> 609 DPred, 610 bool FromParent) const; 611 612 /// Returns currently analyzed directive. 613 OpenMPDirectiveKind getCurrentDirective() const { 614 const SharingMapTy *Top = getTopOfStackOrNull(); 615 return Top ? Top->Directive : OMPD_unknown; 616 } 617 /// Returns directive kind at specified level. 618 OpenMPDirectiveKind getDirective(unsigned Level) const { 619 assert(!isStackEmpty() && "No directive at specified level."); 620 return getStackElemAtLevel(Level).Directive; 621 } 622 /// Returns the capture region at the specified level. 623 OpenMPDirectiveKind getCaptureRegion(unsigned Level, 624 unsigned OpenMPCaptureLevel) const { 625 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 626 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level)); 627 return CaptureRegions[OpenMPCaptureLevel]; 628 } 629 /// Returns parent directive. 630 OpenMPDirectiveKind getParentDirective() const { 631 const SharingMapTy *Parent = getSecondOnStackOrNull(); 632 return Parent ? Parent->Directive : OMPD_unknown; 633 } 634 635 /// Add requires decl to internal vector 636 void addRequiresDecl(OMPRequiresDecl *RD) { RequiresDecls.push_back(RD); } 637 638 /// Checks if the defined 'requires' directive has specified type of clause. 639 template <typename ClauseType> bool hasRequiresDeclWithClause() const { 640 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) { 641 return llvm::any_of(D->clauselists(), [](const OMPClause *C) { 642 return isa<ClauseType>(C); 643 }); 644 }); 645 } 646 647 /// Checks for a duplicate clause amongst previously declared requires 648 /// directives 649 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const { 650 bool IsDuplicate = false; 651 for (OMPClause *CNew : ClauseList) { 652 for (const OMPRequiresDecl *D : RequiresDecls) { 653 for (const OMPClause *CPrev : D->clauselists()) { 654 if (CNew->getClauseKind() == CPrev->getClauseKind()) { 655 SemaRef.Diag(CNew->getBeginLoc(), 656 diag::err_omp_requires_clause_redeclaration) 657 << getOpenMPClauseName(CNew->getClauseKind()); 658 SemaRef.Diag(CPrev->getBeginLoc(), 659 diag::note_omp_requires_previous_clause) 660 << getOpenMPClauseName(CPrev->getClauseKind()); 661 IsDuplicate = true; 662 } 663 } 664 } 665 } 666 return IsDuplicate; 667 } 668 669 /// Add location of previously encountered target to internal vector 670 void addTargetDirLocation(SourceLocation LocStart) { 671 TargetLocations.push_back(LocStart); 672 } 673 674 /// Add location for the first encountered atomicc directive. 675 void addAtomicDirectiveLoc(SourceLocation Loc) { 676 if (AtomicLocation.isInvalid()) 677 AtomicLocation = Loc; 678 } 679 680 /// Returns the location of the first encountered atomic directive in the 681 /// module. 682 SourceLocation getAtomicDirectiveLoc() const { return AtomicLocation; } 683 684 // Return previously encountered target region locations. 685 ArrayRef<SourceLocation> getEncounteredTargetLocs() const { 686 return TargetLocations; 687 } 688 689 /// Set default data sharing attribute to none. 690 void setDefaultDSANone(SourceLocation Loc) { 691 getTopOfStack().DefaultAttr = DSA_none; 692 getTopOfStack().DefaultAttrLoc = Loc; 693 } 694 /// Set default data sharing attribute to shared. 695 void setDefaultDSAShared(SourceLocation Loc) { 696 getTopOfStack().DefaultAttr = DSA_shared; 697 getTopOfStack().DefaultAttrLoc = Loc; 698 } 699 /// Set default data sharing attribute to private. 700 void setDefaultDSAPrivate(SourceLocation Loc) { 701 getTopOfStack().DefaultAttr = DSA_private; 702 getTopOfStack().DefaultAttrLoc = Loc; 703 } 704 /// Set default data sharing attribute to firstprivate. 705 void setDefaultDSAFirstPrivate(SourceLocation Loc) { 706 getTopOfStack().DefaultAttr = DSA_firstprivate; 707 getTopOfStack().DefaultAttrLoc = Loc; 708 } 709 /// Set default data mapping attribute to Modifier:Kind 710 void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M, 711 OpenMPDefaultmapClauseKind Kind, SourceLocation Loc) { 712 DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind]; 713 DMI.ImplicitBehavior = M; 714 DMI.SLoc = Loc; 715 } 716 /// Check whether the implicit-behavior has been set in defaultmap 717 bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) { 718 if (VariableCategory == OMPC_DEFAULTMAP_unknown) 719 return getTopOfStack() 720 .DefaultmapMap[OMPC_DEFAULTMAP_aggregate] 721 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown || 722 getTopOfStack() 723 .DefaultmapMap[OMPC_DEFAULTMAP_scalar] 724 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown || 725 getTopOfStack() 726 .DefaultmapMap[OMPC_DEFAULTMAP_pointer] 727 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown; 728 return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior != 729 OMPC_DEFAULTMAP_MODIFIER_unknown; 730 } 731 732 ArrayRef<llvm::omp::TraitProperty> getConstructTraits() { 733 return ConstructTraits; 734 } 735 void handleConstructTrait(ArrayRef<llvm::omp::TraitProperty> Traits, 736 bool ScopeEntry) { 737 if (ScopeEntry) 738 ConstructTraits.append(Traits.begin(), Traits.end()); 739 else 740 for (llvm::omp::TraitProperty Trait : llvm::reverse(Traits)) { 741 llvm::omp::TraitProperty Top = ConstructTraits.pop_back_val(); 742 assert(Top == Trait && "Something left a trait on the stack!"); 743 (void)Trait; 744 (void)Top; 745 } 746 } 747 748 DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const { 749 return getStackSize() <= Level ? DSA_unspecified 750 : getStackElemAtLevel(Level).DefaultAttr; 751 } 752 DefaultDataSharingAttributes getDefaultDSA() const { 753 return isStackEmpty() ? DSA_unspecified : getTopOfStack().DefaultAttr; 754 } 755 SourceLocation getDefaultDSALocation() const { 756 return isStackEmpty() ? SourceLocation() : getTopOfStack().DefaultAttrLoc; 757 } 758 OpenMPDefaultmapClauseModifier 759 getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const { 760 return isStackEmpty() 761 ? OMPC_DEFAULTMAP_MODIFIER_unknown 762 : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior; 763 } 764 OpenMPDefaultmapClauseModifier 765 getDefaultmapModifierAtLevel(unsigned Level, 766 OpenMPDefaultmapClauseKind Kind) const { 767 return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior; 768 } 769 bool isDefaultmapCapturedByRef(unsigned Level, 770 OpenMPDefaultmapClauseKind Kind) const { 771 OpenMPDefaultmapClauseModifier M = 772 getDefaultmapModifierAtLevel(Level, Kind); 773 if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) { 774 return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) || 775 (M == OMPC_DEFAULTMAP_MODIFIER_to) || 776 (M == OMPC_DEFAULTMAP_MODIFIER_from) || 777 (M == OMPC_DEFAULTMAP_MODIFIER_tofrom); 778 } 779 return true; 780 } 781 static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M, 782 OpenMPDefaultmapClauseKind Kind) { 783 switch (Kind) { 784 case OMPC_DEFAULTMAP_scalar: 785 case OMPC_DEFAULTMAP_pointer: 786 return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) || 787 (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) || 788 (M == OMPC_DEFAULTMAP_MODIFIER_default); 789 case OMPC_DEFAULTMAP_aggregate: 790 return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate; 791 default: 792 break; 793 } 794 llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum"); 795 } 796 bool mustBeFirstprivateAtLevel(unsigned Level, 797 OpenMPDefaultmapClauseKind Kind) const { 798 OpenMPDefaultmapClauseModifier M = 799 getDefaultmapModifierAtLevel(Level, Kind); 800 return mustBeFirstprivateBase(M, Kind); 801 } 802 bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const { 803 OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind); 804 return mustBeFirstprivateBase(M, Kind); 805 } 806 807 /// Checks if the specified variable is a threadprivate. 808 bool isThreadPrivate(VarDecl *D) { 809 const DSAVarData DVar = getTopDSA(D, false); 810 return isOpenMPThreadPrivate(DVar.CKind); 811 } 812 813 /// Marks current region as ordered (it has an 'ordered' clause). 814 void setOrderedRegion(bool IsOrdered, const Expr *Param, 815 OMPOrderedClause *Clause) { 816 if (IsOrdered) 817 getTopOfStack().OrderedRegion.emplace(Param, Clause); 818 else 819 getTopOfStack().OrderedRegion.reset(); 820 } 821 /// Returns true, if region is ordered (has associated 'ordered' clause), 822 /// false - otherwise. 823 bool isOrderedRegion() const { 824 if (const SharingMapTy *Top = getTopOfStackOrNull()) 825 return Top->OrderedRegion.hasValue(); 826 return false; 827 } 828 /// Returns optional parameter for the ordered region. 829 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const { 830 if (const SharingMapTy *Top = getTopOfStackOrNull()) 831 if (Top->OrderedRegion.hasValue()) 832 return Top->OrderedRegion.getValue(); 833 return std::make_pair(nullptr, nullptr); 834 } 835 /// Returns true, if parent region is ordered (has associated 836 /// 'ordered' clause), false - otherwise. 837 bool isParentOrderedRegion() const { 838 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 839 return Parent->OrderedRegion.hasValue(); 840 return false; 841 } 842 /// Returns optional parameter for the ordered region. 843 std::pair<const Expr *, OMPOrderedClause *> 844 getParentOrderedRegionParam() const { 845 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 846 if (Parent->OrderedRegion.hasValue()) 847 return Parent->OrderedRegion.getValue(); 848 return std::make_pair(nullptr, nullptr); 849 } 850 /// Marks current region as nowait (it has a 'nowait' clause). 851 void setNowaitRegion(bool IsNowait = true) { 852 getTopOfStack().NowaitRegion = IsNowait; 853 } 854 /// Returns true, if parent region is nowait (has associated 855 /// 'nowait' clause), false - otherwise. 856 bool isParentNowaitRegion() const { 857 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 858 return Parent->NowaitRegion; 859 return false; 860 } 861 /// Marks current region as untied (it has a 'untied' clause). 862 void setUntiedRegion(bool IsUntied = true) { 863 getTopOfStack().UntiedRegion = IsUntied; 864 } 865 /// Return true if current region is untied. 866 bool isUntiedRegion() const { 867 const SharingMapTy *Top = getTopOfStackOrNull(); 868 return Top ? Top->UntiedRegion : false; 869 } 870 /// Marks parent region as cancel region. 871 void setParentCancelRegion(bool Cancel = true) { 872 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 873 Parent->CancelRegion |= Cancel; 874 } 875 /// Return true if current region has inner cancel construct. 876 bool isCancelRegion() const { 877 const SharingMapTy *Top = getTopOfStackOrNull(); 878 return Top ? Top->CancelRegion : false; 879 } 880 881 /// Mark that parent region already has scan directive. 882 void setParentHasScanDirective(SourceLocation Loc) { 883 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 884 Parent->PrevScanLocation = Loc; 885 } 886 /// Return true if current region has inner cancel construct. 887 bool doesParentHasScanDirective() const { 888 const SharingMapTy *Top = getSecondOnStackOrNull(); 889 return Top ? Top->PrevScanLocation.isValid() : false; 890 } 891 /// Return true if current region has inner cancel construct. 892 SourceLocation getParentScanDirectiveLoc() const { 893 const SharingMapTy *Top = getSecondOnStackOrNull(); 894 return Top ? Top->PrevScanLocation : SourceLocation(); 895 } 896 /// Mark that parent region already has ordered directive. 897 void setParentHasOrderedDirective(SourceLocation Loc) { 898 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 899 Parent->PrevOrderedLocation = Loc; 900 } 901 /// Return true if current region has inner ordered construct. 902 bool doesParentHasOrderedDirective() const { 903 const SharingMapTy *Top = getSecondOnStackOrNull(); 904 return Top ? Top->PrevOrderedLocation.isValid() : false; 905 } 906 /// Returns the location of the previously specified ordered directive. 907 SourceLocation getParentOrderedDirectiveLoc() const { 908 const SharingMapTy *Top = getSecondOnStackOrNull(); 909 return Top ? Top->PrevOrderedLocation : SourceLocation(); 910 } 911 912 /// Set collapse value for the region. 913 void setAssociatedLoops(unsigned Val) { 914 getTopOfStack().AssociatedLoops = Val; 915 if (Val > 1) 916 getTopOfStack().HasMutipleLoops = true; 917 } 918 /// Return collapse value for region. 919 unsigned getAssociatedLoops() const { 920 const SharingMapTy *Top = getTopOfStackOrNull(); 921 return Top ? Top->AssociatedLoops : 0; 922 } 923 /// Returns true if the construct is associated with multiple loops. 924 bool hasMutipleLoops() const { 925 const SharingMapTy *Top = getTopOfStackOrNull(); 926 return Top ? Top->HasMutipleLoops : false; 927 } 928 929 /// Marks current target region as one with closely nested teams 930 /// region. 931 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 932 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 933 Parent->InnerTeamsRegionLoc = TeamsRegionLoc; 934 } 935 /// Returns true, if current region has closely nested teams region. 936 bool hasInnerTeamsRegion() const { 937 return getInnerTeamsRegionLoc().isValid(); 938 } 939 /// Returns location of the nested teams region (if any). 940 SourceLocation getInnerTeamsRegionLoc() const { 941 const SharingMapTy *Top = getTopOfStackOrNull(); 942 return Top ? Top->InnerTeamsRegionLoc : SourceLocation(); 943 } 944 945 Scope *getCurScope() const { 946 const SharingMapTy *Top = getTopOfStackOrNull(); 947 return Top ? Top->CurScope : nullptr; 948 } 949 void setContext(DeclContext *DC) { getTopOfStack().Context = DC; } 950 SourceLocation getConstructLoc() const { 951 const SharingMapTy *Top = getTopOfStackOrNull(); 952 return Top ? Top->ConstructLoc : SourceLocation(); 953 } 954 955 /// Do the check specified in \a Check to all component lists and return true 956 /// if any issue is found. 957 bool checkMappableExprComponentListsForDecl( 958 const ValueDecl *VD, bool CurrentRegionOnly, 959 const llvm::function_ref< 960 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 961 OpenMPClauseKind)> 962 Check) const { 963 if (isStackEmpty()) 964 return false; 965 auto SI = begin(); 966 auto SE = end(); 967 968 if (SI == SE) 969 return false; 970 971 if (CurrentRegionOnly) 972 SE = std::next(SI); 973 else 974 std::advance(SI, 1); 975 976 for (; SI != SE; ++SI) { 977 auto MI = SI->MappedExprComponents.find(VD); 978 if (MI != SI->MappedExprComponents.end()) 979 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 980 MI->second.Components) 981 if (Check(L, MI->second.Kind)) 982 return true; 983 } 984 return false; 985 } 986 987 /// Do the check specified in \a Check to all component lists at a given level 988 /// and return true if any issue is found. 989 bool checkMappableExprComponentListsForDeclAtLevel( 990 const ValueDecl *VD, unsigned Level, 991 const llvm::function_ref< 992 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 993 OpenMPClauseKind)> 994 Check) const { 995 if (getStackSize() <= Level) 996 return false; 997 998 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 999 auto MI = StackElem.MappedExprComponents.find(VD); 1000 if (MI != StackElem.MappedExprComponents.end()) 1001 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 1002 MI->second.Components) 1003 if (Check(L, MI->second.Kind)) 1004 return true; 1005 return false; 1006 } 1007 1008 /// Create a new mappable expression component list associated with a given 1009 /// declaration and initialize it with the provided list of components. 1010 void addMappableExpressionComponents( 1011 const ValueDecl *VD, 1012 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 1013 OpenMPClauseKind WhereFoundClauseKind) { 1014 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD]; 1015 // Create new entry and append the new components there. 1016 MEC.Components.resize(MEC.Components.size() + 1); 1017 MEC.Components.back().append(Components.begin(), Components.end()); 1018 MEC.Kind = WhereFoundClauseKind; 1019 } 1020 1021 unsigned getNestingLevel() const { 1022 assert(!isStackEmpty()); 1023 return getStackSize() - 1; 1024 } 1025 void addDoacrossDependClause(OMPDependClause *C, 1026 const OperatorOffsetTy &OpsOffs) { 1027 SharingMapTy *Parent = getSecondOnStackOrNull(); 1028 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive)); 1029 Parent->DoacrossDepends.try_emplace(C, OpsOffs); 1030 } 1031 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 1032 getDoacrossDependClauses() const { 1033 const SharingMapTy &StackElem = getTopOfStack(); 1034 if (isOpenMPWorksharingDirective(StackElem.Directive)) { 1035 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends; 1036 return llvm::make_range(Ref.begin(), Ref.end()); 1037 } 1038 return llvm::make_range(StackElem.DoacrossDepends.end(), 1039 StackElem.DoacrossDepends.end()); 1040 } 1041 1042 // Store types of classes which have been explicitly mapped 1043 void addMappedClassesQualTypes(QualType QT) { 1044 SharingMapTy &StackElem = getTopOfStack(); 1045 StackElem.MappedClassesQualTypes.insert(QT); 1046 } 1047 1048 // Return set of mapped classes types 1049 bool isClassPreviouslyMapped(QualType QT) const { 1050 const SharingMapTy &StackElem = getTopOfStack(); 1051 return StackElem.MappedClassesQualTypes.contains(QT); 1052 } 1053 1054 /// Adds global declare target to the parent target region. 1055 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) { 1056 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 1057 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && 1058 "Expected declare target link global."); 1059 for (auto &Elem : *this) { 1060 if (isOpenMPTargetExecutionDirective(Elem.Directive)) { 1061 Elem.DeclareTargetLinkVarDecls.push_back(E); 1062 return; 1063 } 1064 } 1065 } 1066 1067 /// Returns the list of globals with declare target link if current directive 1068 /// is target. 1069 ArrayRef<DeclRefExpr *> getLinkGlobals() const { 1070 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) && 1071 "Expected target executable directive."); 1072 return getTopOfStack().DeclareTargetLinkVarDecls; 1073 } 1074 1075 /// Adds list of allocators expressions. 1076 void addInnerAllocatorExpr(Expr *E) { 1077 getTopOfStack().InnerUsedAllocators.push_back(E); 1078 } 1079 /// Return list of used allocators. 1080 ArrayRef<Expr *> getInnerAllocators() const { 1081 return getTopOfStack().InnerUsedAllocators; 1082 } 1083 /// Marks the declaration as implicitly firstprivate nin the task-based 1084 /// regions. 1085 void addImplicitTaskFirstprivate(unsigned Level, Decl *D) { 1086 getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D); 1087 } 1088 /// Checks if the decl is implicitly firstprivate in the task-based region. 1089 bool isImplicitTaskFirstprivate(Decl *D) const { 1090 return getTopOfStack().ImplicitTaskFirstprivates.contains(D); 1091 } 1092 1093 /// Marks decl as used in uses_allocators clause as the allocator. 1094 void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) { 1095 getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind); 1096 } 1097 /// Checks if specified decl is used in uses allocator clause as the 1098 /// allocator. 1099 Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level, 1100 const Decl *D) const { 1101 const SharingMapTy &StackElem = getTopOfStack(); 1102 auto I = StackElem.UsesAllocatorsDecls.find(D); 1103 if (I == StackElem.UsesAllocatorsDecls.end()) 1104 return None; 1105 return I->getSecond(); 1106 } 1107 Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const { 1108 const SharingMapTy &StackElem = getTopOfStack(); 1109 auto I = StackElem.UsesAllocatorsDecls.find(D); 1110 if (I == StackElem.UsesAllocatorsDecls.end()) 1111 return None; 1112 return I->getSecond(); 1113 } 1114 1115 void addDeclareMapperVarRef(Expr *Ref) { 1116 SharingMapTy &StackElem = getTopOfStack(); 1117 StackElem.DeclareMapperVar = Ref; 1118 } 1119 const Expr *getDeclareMapperVarRef() const { 1120 const SharingMapTy *Top = getTopOfStackOrNull(); 1121 return Top ? Top->DeclareMapperVar : nullptr; 1122 } 1123 }; 1124 1125 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) { 1126 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind); 1127 } 1128 1129 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) { 1130 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || 1131 DKind == OMPD_unknown; 1132 } 1133 1134 } // namespace 1135 1136 static const Expr *getExprAsWritten(const Expr *E) { 1137 if (const auto *FE = dyn_cast<FullExpr>(E)) 1138 E = FE->getSubExpr(); 1139 1140 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 1141 E = MTE->getSubExpr(); 1142 1143 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 1144 E = Binder->getSubExpr(); 1145 1146 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 1147 E = ICE->getSubExprAsWritten(); 1148 return E->IgnoreParens(); 1149 } 1150 1151 static Expr *getExprAsWritten(Expr *E) { 1152 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E))); 1153 } 1154 1155 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) { 1156 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) 1157 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 1158 D = ME->getMemberDecl(); 1159 const auto *VD = dyn_cast<VarDecl>(D); 1160 const auto *FD = dyn_cast<FieldDecl>(D); 1161 if (VD != nullptr) { 1162 VD = VD->getCanonicalDecl(); 1163 D = VD; 1164 } else { 1165 assert(FD); 1166 FD = FD->getCanonicalDecl(); 1167 D = FD; 1168 } 1169 return D; 1170 } 1171 1172 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 1173 return const_cast<ValueDecl *>( 1174 getCanonicalDecl(const_cast<const ValueDecl *>(D))); 1175 } 1176 1177 DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter, 1178 ValueDecl *D) const { 1179 D = getCanonicalDecl(D); 1180 auto *VD = dyn_cast<VarDecl>(D); 1181 const auto *FD = dyn_cast<FieldDecl>(D); 1182 DSAVarData DVar; 1183 if (Iter == end()) { 1184 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1185 // in a region but not in construct] 1186 // File-scope or namespace-scope variables referenced in called routines 1187 // in the region are shared unless they appear in a threadprivate 1188 // directive. 1189 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD)) 1190 DVar.CKind = OMPC_shared; 1191 1192 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 1193 // in a region but not in construct] 1194 // Variables with static storage duration that are declared in called 1195 // routines in the region are shared. 1196 if (VD && VD->hasGlobalStorage()) 1197 DVar.CKind = OMPC_shared; 1198 1199 // Non-static data members are shared by default. 1200 if (FD) 1201 DVar.CKind = OMPC_shared; 1202 1203 return DVar; 1204 } 1205 1206 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1207 // in a Construct, C/C++, predetermined, p.1] 1208 // Variables with automatic storage duration that are declared in a scope 1209 // inside the construct are private. 1210 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 1211 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 1212 DVar.CKind = OMPC_private; 1213 return DVar; 1214 } 1215 1216 DVar.DKind = Iter->Directive; 1217 // Explicitly specified attributes and local variables with predetermined 1218 // attributes. 1219 if (Iter->SharingMap.count(D)) { 1220 const DSAInfo &Data = Iter->SharingMap.lookup(D); 1221 DVar.RefExpr = Data.RefExpr.getPointer(); 1222 DVar.PrivateCopy = Data.PrivateCopy; 1223 DVar.CKind = Data.Attributes; 1224 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1225 DVar.Modifier = Data.Modifier; 1226 DVar.AppliedToPointee = Data.AppliedToPointee; 1227 return DVar; 1228 } 1229 1230 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1231 // in a Construct, C/C++, implicitly determined, p.1] 1232 // In a parallel or task construct, the data-sharing attributes of these 1233 // variables are determined by the default clause, if present. 1234 switch (Iter->DefaultAttr) { 1235 case DSA_shared: 1236 DVar.CKind = OMPC_shared; 1237 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1238 return DVar; 1239 case DSA_none: 1240 return DVar; 1241 case DSA_firstprivate: 1242 if (VD && VD->getStorageDuration() == SD_Static && 1243 VD->getDeclContext()->isFileContext()) { 1244 DVar.CKind = OMPC_unknown; 1245 } else { 1246 DVar.CKind = OMPC_firstprivate; 1247 } 1248 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1249 return DVar; 1250 case DSA_private: 1251 // each variable with static storage duration that is declared 1252 // in a namespace or global scope and referenced in the construct, 1253 // and that does not have a predetermined data-sharing attribute 1254 if (VD && VD->getStorageDuration() == SD_Static && 1255 VD->getDeclContext()->isFileContext()) { 1256 DVar.CKind = OMPC_unknown; 1257 } else { 1258 DVar.CKind = OMPC_private; 1259 } 1260 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1261 return DVar; 1262 case DSA_unspecified: 1263 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1264 // in a Construct, implicitly determined, p.2] 1265 // In a parallel construct, if no default clause is present, these 1266 // variables are shared. 1267 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1268 if ((isOpenMPParallelDirective(DVar.DKind) && 1269 !isOpenMPTaskLoopDirective(DVar.DKind)) || 1270 isOpenMPTeamsDirective(DVar.DKind)) { 1271 DVar.CKind = OMPC_shared; 1272 return DVar; 1273 } 1274 1275 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1276 // in a Construct, implicitly determined, p.4] 1277 // In a task construct, if no default clause is present, a variable that in 1278 // the enclosing context is determined to be shared by all implicit tasks 1279 // bound to the current team is shared. 1280 if (isOpenMPTaskingDirective(DVar.DKind)) { 1281 DSAVarData DVarTemp; 1282 const_iterator I = Iter, E = end(); 1283 do { 1284 ++I; 1285 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 1286 // Referenced in a Construct, implicitly determined, p.6] 1287 // In a task construct, if no default clause is present, a variable 1288 // whose data-sharing attribute is not determined by the rules above is 1289 // firstprivate. 1290 DVarTemp = getDSA(I, D); 1291 if (DVarTemp.CKind != OMPC_shared) { 1292 DVar.RefExpr = nullptr; 1293 DVar.CKind = OMPC_firstprivate; 1294 return DVar; 1295 } 1296 } while (I != E && !isImplicitTaskingRegion(I->Directive)); 1297 DVar.CKind = 1298 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 1299 return DVar; 1300 } 1301 } 1302 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1303 // in a Construct, implicitly determined, p.3] 1304 // For constructs other than task, if no default clause is present, these 1305 // variables inherit their data-sharing attributes from the enclosing 1306 // context. 1307 return getDSA(++Iter, D); 1308 } 1309 1310 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D, 1311 const Expr *NewDE) { 1312 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 1313 D = getCanonicalDecl(D); 1314 SharingMapTy &StackElem = getTopOfStack(); 1315 auto It = StackElem.AlignedMap.find(D); 1316 if (It == StackElem.AlignedMap.end()) { 1317 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 1318 StackElem.AlignedMap[D] = NewDE; 1319 return nullptr; 1320 } 1321 assert(It->second && "Unexpected nullptr expr in the aligned map"); 1322 return It->second; 1323 } 1324 1325 const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D, 1326 const Expr *NewDE) { 1327 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 1328 D = getCanonicalDecl(D); 1329 SharingMapTy &StackElem = getTopOfStack(); 1330 auto It = StackElem.NontemporalMap.find(D); 1331 if (It == StackElem.NontemporalMap.end()) { 1332 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 1333 StackElem.NontemporalMap[D] = NewDE; 1334 return nullptr; 1335 } 1336 assert(It->second && "Unexpected nullptr expr in the aligned map"); 1337 return It->second; 1338 } 1339 1340 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) { 1341 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1342 D = getCanonicalDecl(D); 1343 SharingMapTy &StackElem = getTopOfStack(); 1344 StackElem.LCVMap.try_emplace( 1345 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)); 1346 } 1347 1348 const DSAStackTy::LCDeclInfo 1349 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const { 1350 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1351 D = getCanonicalDecl(D); 1352 const SharingMapTy &StackElem = getTopOfStack(); 1353 auto It = StackElem.LCVMap.find(D); 1354 if (It != StackElem.LCVMap.end()) 1355 return It->second; 1356 return {0, nullptr}; 1357 } 1358 1359 const DSAStackTy::LCDeclInfo 1360 DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const { 1361 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1362 D = getCanonicalDecl(D); 1363 for (unsigned I = Level + 1; I > 0; --I) { 1364 const SharingMapTy &StackElem = getStackElemAtLevel(I - 1); 1365 auto It = StackElem.LCVMap.find(D); 1366 if (It != StackElem.LCVMap.end()) 1367 return It->second; 1368 } 1369 return {0, nullptr}; 1370 } 1371 1372 const DSAStackTy::LCDeclInfo 1373 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const { 1374 const SharingMapTy *Parent = getSecondOnStackOrNull(); 1375 assert(Parent && "Data-sharing attributes stack is empty"); 1376 D = getCanonicalDecl(D); 1377 auto It = Parent->LCVMap.find(D); 1378 if (It != Parent->LCVMap.end()) 1379 return It->second; 1380 return {0, nullptr}; 1381 } 1382 1383 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const { 1384 const SharingMapTy *Parent = getSecondOnStackOrNull(); 1385 assert(Parent && "Data-sharing attributes stack is empty"); 1386 if (Parent->LCVMap.size() < I) 1387 return nullptr; 1388 for (const auto &Pair : Parent->LCVMap) 1389 if (Pair.second.first == I) 1390 return Pair.first; 1391 return nullptr; 1392 } 1393 1394 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 1395 DeclRefExpr *PrivateCopy, unsigned Modifier, 1396 bool AppliedToPointee) { 1397 D = getCanonicalDecl(D); 1398 if (A == OMPC_threadprivate) { 1399 DSAInfo &Data = Threadprivates[D]; 1400 Data.Attributes = A; 1401 Data.RefExpr.setPointer(E); 1402 Data.PrivateCopy = nullptr; 1403 Data.Modifier = Modifier; 1404 } else { 1405 DSAInfo &Data = getTopOfStack().SharingMap[D]; 1406 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 1407 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 1408 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 1409 (isLoopControlVariable(D).first && A == OMPC_private)); 1410 Data.Modifier = Modifier; 1411 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 1412 Data.RefExpr.setInt(/*IntVal=*/true); 1413 return; 1414 } 1415 const bool IsLastprivate = 1416 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 1417 Data.Attributes = A; 1418 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 1419 Data.PrivateCopy = PrivateCopy; 1420 Data.AppliedToPointee = AppliedToPointee; 1421 if (PrivateCopy) { 1422 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()]; 1423 Data.Modifier = Modifier; 1424 Data.Attributes = A; 1425 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 1426 Data.PrivateCopy = nullptr; 1427 Data.AppliedToPointee = AppliedToPointee; 1428 } 1429 } 1430 } 1431 1432 /// Build a variable declaration for OpenMP loop iteration variable. 1433 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 1434 StringRef Name, const AttrVec *Attrs = nullptr, 1435 DeclRefExpr *OrigRef = nullptr) { 1436 DeclContext *DC = SemaRef.CurContext; 1437 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 1438 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 1439 auto *Decl = 1440 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 1441 if (Attrs) { 1442 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 1443 I != E; ++I) 1444 Decl->addAttr(*I); 1445 } 1446 Decl->setImplicit(); 1447 if (OrigRef) { 1448 Decl->addAttr( 1449 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef)); 1450 } 1451 return Decl; 1452 } 1453 1454 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 1455 SourceLocation Loc, 1456 bool RefersToCapture = false) { 1457 D->setReferenced(); 1458 D->markUsed(S.Context); 1459 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 1460 SourceLocation(), D, RefersToCapture, Loc, Ty, 1461 VK_LValue); 1462 } 1463 1464 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 1465 BinaryOperatorKind BOK) { 1466 D = getCanonicalDecl(D); 1467 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1468 assert( 1469 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && 1470 "Additional reduction info may be specified only for reduction items."); 1471 ReductionData &ReductionData = getTopOfStack().ReductionMap[D]; 1472 assert(ReductionData.ReductionRange.isInvalid() && 1473 (getTopOfStack().Directive == OMPD_taskgroup || 1474 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 1475 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 1476 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 1477 "Additional reduction info may be specified only once for reduction " 1478 "items."); 1479 ReductionData.set(BOK, SR); 1480 Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef; 1481 if (!TaskgroupReductionRef) { 1482 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1483 SemaRef.Context.VoidPtrTy, ".task_red."); 1484 TaskgroupReductionRef = 1485 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1486 } 1487 } 1488 1489 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 1490 const Expr *ReductionRef) { 1491 D = getCanonicalDecl(D); 1492 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1493 assert( 1494 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && 1495 "Additional reduction info may be specified only for reduction items."); 1496 ReductionData &ReductionData = getTopOfStack().ReductionMap[D]; 1497 assert(ReductionData.ReductionRange.isInvalid() && 1498 (getTopOfStack().Directive == OMPD_taskgroup || 1499 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 1500 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 1501 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 1502 "Additional reduction info may be specified only once for reduction " 1503 "items."); 1504 ReductionData.set(ReductionRef, SR); 1505 Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef; 1506 if (!TaskgroupReductionRef) { 1507 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1508 SemaRef.Context.VoidPtrTy, ".task_red."); 1509 TaskgroupReductionRef = 1510 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1511 } 1512 } 1513 1514 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1515 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK, 1516 Expr *&TaskgroupDescriptor) const { 1517 D = getCanonicalDecl(D); 1518 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1519 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) { 1520 const DSAInfo &Data = I->SharingMap.lookup(D); 1521 if (Data.Attributes != OMPC_reduction || 1522 Data.Modifier != OMPC_REDUCTION_task) 1523 continue; 1524 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1525 if (!ReductionData.ReductionOp || 1526 ReductionData.ReductionOp.is<const Expr *>()) 1527 return DSAVarData(); 1528 SR = ReductionData.ReductionRange; 1529 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>(); 1530 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1531 "expression for the descriptor is not " 1532 "set."); 1533 TaskgroupDescriptor = I->TaskgroupReductionRef; 1534 return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(), 1535 Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task, 1536 /*AppliedToPointee=*/false); 1537 } 1538 return DSAVarData(); 1539 } 1540 1541 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1542 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef, 1543 Expr *&TaskgroupDescriptor) const { 1544 D = getCanonicalDecl(D); 1545 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1546 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) { 1547 const DSAInfo &Data = I->SharingMap.lookup(D); 1548 if (Data.Attributes != OMPC_reduction || 1549 Data.Modifier != OMPC_REDUCTION_task) 1550 continue; 1551 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1552 if (!ReductionData.ReductionOp || 1553 !ReductionData.ReductionOp.is<const Expr *>()) 1554 return DSAVarData(); 1555 SR = ReductionData.ReductionRange; 1556 ReductionRef = ReductionData.ReductionOp.get<const Expr *>(); 1557 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1558 "expression for the descriptor is not " 1559 "set."); 1560 TaskgroupDescriptor = I->TaskgroupReductionRef; 1561 return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(), 1562 Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task, 1563 /*AppliedToPointee=*/false); 1564 } 1565 return DSAVarData(); 1566 } 1567 1568 bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const { 1569 D = D->getCanonicalDecl(); 1570 for (const_iterator E = end(); I != E; ++I) { 1571 if (isImplicitOrExplicitTaskingRegion(I->Directive) || 1572 isOpenMPTargetExecutionDirective(I->Directive)) { 1573 if (I->CurScope) { 1574 Scope *TopScope = I->CurScope->getParent(); 1575 Scope *CurScope = getCurScope(); 1576 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D)) 1577 CurScope = CurScope->getParent(); 1578 return CurScope != TopScope; 1579 } 1580 for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent()) 1581 if (I->Context == DC) 1582 return true; 1583 return false; 1584 } 1585 } 1586 return false; 1587 } 1588 1589 static bool isConstNotMutableType(Sema &SemaRef, QualType Type, 1590 bool AcceptIfMutable = true, 1591 bool *IsClassType = nullptr) { 1592 ASTContext &Context = SemaRef.getASTContext(); 1593 Type = Type.getNonReferenceType().getCanonicalType(); 1594 bool IsConstant = Type.isConstant(Context); 1595 Type = Context.getBaseElementType(Type); 1596 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus 1597 ? Type->getAsCXXRecordDecl() 1598 : nullptr; 1599 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 1600 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate()) 1601 RD = CTD->getTemplatedDecl(); 1602 if (IsClassType) 1603 *IsClassType = RD; 1604 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD && 1605 RD->hasDefinition() && RD->hasMutableFields()); 1606 } 1607 1608 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D, 1609 QualType Type, OpenMPClauseKind CKind, 1610 SourceLocation ELoc, 1611 bool AcceptIfMutable = true, 1612 bool ListItemNotVar = false) { 1613 ASTContext &Context = SemaRef.getASTContext(); 1614 bool IsClassType; 1615 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) { 1616 unsigned Diag = ListItemNotVar ? diag::err_omp_const_list_item 1617 : IsClassType ? diag::err_omp_const_not_mutable_variable 1618 : diag::err_omp_const_variable; 1619 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind); 1620 if (!ListItemNotVar && D) { 1621 const VarDecl *VD = dyn_cast<VarDecl>(D); 1622 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 1623 VarDecl::DeclarationOnly; 1624 SemaRef.Diag(D->getLocation(), 1625 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1626 << D; 1627 } 1628 return true; 1629 } 1630 return false; 1631 } 1632 1633 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, 1634 bool FromParent) { 1635 D = getCanonicalDecl(D); 1636 DSAVarData DVar; 1637 1638 auto *VD = dyn_cast<VarDecl>(D); 1639 auto TI = Threadprivates.find(D); 1640 if (TI != Threadprivates.end()) { 1641 DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); 1642 DVar.CKind = OMPC_threadprivate; 1643 DVar.Modifier = TI->getSecond().Modifier; 1644 return DVar; 1645 } 1646 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 1647 DVar.RefExpr = buildDeclRefExpr( 1648 SemaRef, VD, D->getType().getNonReferenceType(), 1649 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation()); 1650 DVar.CKind = OMPC_threadprivate; 1651 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1652 return DVar; 1653 } 1654 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1655 // in a Construct, C/C++, predetermined, p.1] 1656 // Variables appearing in threadprivate directives are threadprivate. 1657 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 1658 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1659 SemaRef.getLangOpts().OpenMPUseTLS && 1660 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 1661 (VD && VD->getStorageClass() == SC_Register && 1662 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 1663 DVar.RefExpr = buildDeclRefExpr( 1664 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation()); 1665 DVar.CKind = OMPC_threadprivate; 1666 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1667 return DVar; 1668 } 1669 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD && 1670 VD->isLocalVarDeclOrParm() && !isStackEmpty() && 1671 !isLoopControlVariable(D).first) { 1672 const_iterator IterTarget = 1673 std::find_if(begin(), end(), [](const SharingMapTy &Data) { 1674 return isOpenMPTargetExecutionDirective(Data.Directive); 1675 }); 1676 if (IterTarget != end()) { 1677 const_iterator ParentIterTarget = IterTarget + 1; 1678 for (const_iterator Iter = begin(); Iter != ParentIterTarget; ++Iter) { 1679 if (isOpenMPLocal(VD, Iter)) { 1680 DVar.RefExpr = 1681 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1682 D->getLocation()); 1683 DVar.CKind = OMPC_threadprivate; 1684 return DVar; 1685 } 1686 } 1687 if (!isClauseParsingMode() || IterTarget != begin()) { 1688 auto DSAIter = IterTarget->SharingMap.find(D); 1689 if (DSAIter != IterTarget->SharingMap.end() && 1690 isOpenMPPrivate(DSAIter->getSecond().Attributes)) { 1691 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer(); 1692 DVar.CKind = OMPC_threadprivate; 1693 return DVar; 1694 } 1695 const_iterator End = end(); 1696 if (!SemaRef.isOpenMPCapturedByRef(D, 1697 std::distance(ParentIterTarget, End), 1698 /*OpenMPCaptureLevel=*/0)) { 1699 DVar.RefExpr = 1700 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1701 IterTarget->ConstructLoc); 1702 DVar.CKind = OMPC_threadprivate; 1703 return DVar; 1704 } 1705 } 1706 } 1707 } 1708 1709 if (isStackEmpty()) 1710 // Not in OpenMP execution region and top scope was already checked. 1711 return DVar; 1712 1713 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1714 // in a Construct, C/C++, predetermined, p.4] 1715 // Static data members are shared. 1716 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1717 // in a Construct, C/C++, predetermined, p.7] 1718 // Variables with static storage duration that are declared in a scope 1719 // inside the construct are shared. 1720 if (VD && VD->isStaticDataMember()) { 1721 // Check for explicitly specified attributes. 1722 const_iterator I = begin(); 1723 const_iterator EndI = end(); 1724 if (FromParent && I != EndI) 1725 ++I; 1726 if (I != EndI) { 1727 auto It = I->SharingMap.find(D); 1728 if (It != I->SharingMap.end()) { 1729 const DSAInfo &Data = It->getSecond(); 1730 DVar.RefExpr = Data.RefExpr.getPointer(); 1731 DVar.PrivateCopy = Data.PrivateCopy; 1732 DVar.CKind = Data.Attributes; 1733 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1734 DVar.DKind = I->Directive; 1735 DVar.Modifier = Data.Modifier; 1736 DVar.AppliedToPointee = Data.AppliedToPointee; 1737 return DVar; 1738 } 1739 } 1740 1741 DVar.CKind = OMPC_shared; 1742 return DVar; 1743 } 1744 1745 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; }; 1746 // The predetermined shared attribute for const-qualified types having no 1747 // mutable members was removed after OpenMP 3.1. 1748 if (SemaRef.LangOpts.OpenMP <= 31) { 1749 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1750 // in a Construct, C/C++, predetermined, p.6] 1751 // Variables with const qualified type having no mutable member are 1752 // shared. 1753 if (isConstNotMutableType(SemaRef, D->getType())) { 1754 // Variables with const-qualified type having no mutable member may be 1755 // listed in a firstprivate clause, even if they are static data members. 1756 DSAVarData DVarTemp = hasInnermostDSA( 1757 D, 1758 [](OpenMPClauseKind C, bool) { 1759 return C == OMPC_firstprivate || C == OMPC_shared; 1760 }, 1761 MatchesAlways, FromParent); 1762 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 1763 return DVarTemp; 1764 1765 DVar.CKind = OMPC_shared; 1766 return DVar; 1767 } 1768 } 1769 1770 // Explicitly specified attributes and local variables with predetermined 1771 // attributes. 1772 const_iterator I = begin(); 1773 const_iterator EndI = end(); 1774 if (FromParent && I != EndI) 1775 ++I; 1776 if (I == EndI) 1777 return DVar; 1778 auto It = I->SharingMap.find(D); 1779 if (It != I->SharingMap.end()) { 1780 const DSAInfo &Data = It->getSecond(); 1781 DVar.RefExpr = Data.RefExpr.getPointer(); 1782 DVar.PrivateCopy = Data.PrivateCopy; 1783 DVar.CKind = Data.Attributes; 1784 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1785 DVar.DKind = I->Directive; 1786 DVar.Modifier = Data.Modifier; 1787 DVar.AppliedToPointee = Data.AppliedToPointee; 1788 } 1789 1790 return DVar; 1791 } 1792 1793 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1794 bool FromParent) const { 1795 if (isStackEmpty()) { 1796 const_iterator I; 1797 return getDSA(I, D); 1798 } 1799 D = getCanonicalDecl(D); 1800 const_iterator StartI = begin(); 1801 const_iterator EndI = end(); 1802 if (FromParent && StartI != EndI) 1803 ++StartI; 1804 return getDSA(StartI, D); 1805 } 1806 1807 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1808 unsigned Level) const { 1809 if (getStackSize() <= Level) 1810 return DSAVarData(); 1811 D = getCanonicalDecl(D); 1812 const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level); 1813 return getDSA(StartI, D); 1814 } 1815 1816 const DSAStackTy::DSAVarData 1817 DSAStackTy::hasDSA(ValueDecl *D, 1818 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1819 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1820 bool FromParent) const { 1821 if (isStackEmpty()) 1822 return {}; 1823 D = getCanonicalDecl(D); 1824 const_iterator I = begin(); 1825 const_iterator EndI = end(); 1826 if (FromParent && I != EndI) 1827 ++I; 1828 for (; I != EndI; ++I) { 1829 if (!DPred(I->Directive) && 1830 !isImplicitOrExplicitTaskingRegion(I->Directive)) 1831 continue; 1832 const_iterator NewI = I; 1833 DSAVarData DVar = getDSA(NewI, D); 1834 if (I == NewI && CPred(DVar.CKind, DVar.AppliedToPointee)) 1835 return DVar; 1836 } 1837 return {}; 1838 } 1839 1840 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 1841 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1842 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1843 bool FromParent) const { 1844 if (isStackEmpty()) 1845 return {}; 1846 D = getCanonicalDecl(D); 1847 const_iterator StartI = begin(); 1848 const_iterator EndI = end(); 1849 if (FromParent && StartI != EndI) 1850 ++StartI; 1851 if (StartI == EndI || !DPred(StartI->Directive)) 1852 return {}; 1853 const_iterator NewI = StartI; 1854 DSAVarData DVar = getDSA(NewI, D); 1855 return (NewI == StartI && CPred(DVar.CKind, DVar.AppliedToPointee)) 1856 ? DVar 1857 : DSAVarData(); 1858 } 1859 1860 bool DSAStackTy::hasExplicitDSA( 1861 const ValueDecl *D, 1862 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1863 unsigned Level, bool NotLastprivate) const { 1864 if (getStackSize() <= Level) 1865 return false; 1866 D = getCanonicalDecl(D); 1867 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 1868 auto I = StackElem.SharingMap.find(D); 1869 if (I != StackElem.SharingMap.end() && I->getSecond().RefExpr.getPointer() && 1870 CPred(I->getSecond().Attributes, I->getSecond().AppliedToPointee) && 1871 (!NotLastprivate || !I->getSecond().RefExpr.getInt())) 1872 return true; 1873 // Check predetermined rules for the loop control variables. 1874 auto LI = StackElem.LCVMap.find(D); 1875 if (LI != StackElem.LCVMap.end()) 1876 return CPred(OMPC_private, /*AppliedToPointee=*/false); 1877 return false; 1878 } 1879 1880 bool DSAStackTy::hasExplicitDirective( 1881 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1882 unsigned Level) const { 1883 if (getStackSize() <= Level) 1884 return false; 1885 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 1886 return DPred(StackElem.Directive); 1887 } 1888 1889 bool DSAStackTy::hasDirective( 1890 const llvm::function_ref<bool(OpenMPDirectiveKind, 1891 const DeclarationNameInfo &, SourceLocation)> 1892 DPred, 1893 bool FromParent) const { 1894 // We look only in the enclosing region. 1895 size_t Skip = FromParent ? 2 : 1; 1896 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end(); 1897 I != E; ++I) { 1898 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 1899 return true; 1900 } 1901 return false; 1902 } 1903 1904 void Sema::InitDataSharingAttributesStack() { 1905 VarDataSharingAttributesStack = new DSAStackTy(*this); 1906 } 1907 1908 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 1909 1910 void Sema::pushOpenMPFunctionRegion() { DSAStack->pushFunction(); } 1911 1912 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 1913 DSAStack->popFunction(OldFSI); 1914 } 1915 1916 static bool isOpenMPDeviceDelayedContext(Sema &S) { 1917 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && 1918 "Expected OpenMP device compilation."); 1919 return !S.isInOpenMPTargetExecutionDirective(); 1920 } 1921 1922 namespace { 1923 /// Status of the function emission on the host/device. 1924 enum class FunctionEmissionStatus { 1925 Emitted, 1926 Discarded, 1927 Unknown, 1928 }; 1929 } // anonymous namespace 1930 1931 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc, 1932 unsigned DiagID, 1933 FunctionDecl *FD) { 1934 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 1935 "Expected OpenMP device compilation."); 1936 1937 SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop; 1938 if (FD) { 1939 FunctionEmissionStatus FES = getEmissionStatus(FD); 1940 switch (FES) { 1941 case FunctionEmissionStatus::Emitted: 1942 Kind = SemaDiagnosticBuilder::K_Immediate; 1943 break; 1944 case FunctionEmissionStatus::Unknown: 1945 // TODO: We should always delay diagnostics here in case a target 1946 // region is in a function we do not emit. However, as the 1947 // current diagnostics are associated with the function containing 1948 // the target region and we do not emit that one, we would miss out 1949 // on diagnostics for the target region itself. We need to anchor 1950 // the diagnostics with the new generated function *or* ensure we 1951 // emit diagnostics associated with the surrounding function. 1952 Kind = isOpenMPDeviceDelayedContext(*this) 1953 ? SemaDiagnosticBuilder::K_Deferred 1954 : SemaDiagnosticBuilder::K_Immediate; 1955 break; 1956 case FunctionEmissionStatus::TemplateDiscarded: 1957 case FunctionEmissionStatus::OMPDiscarded: 1958 Kind = SemaDiagnosticBuilder::K_Nop; 1959 break; 1960 case FunctionEmissionStatus::CUDADiscarded: 1961 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation"); 1962 break; 1963 } 1964 } 1965 1966 return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this); 1967 } 1968 1969 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc, 1970 unsigned DiagID, 1971 FunctionDecl *FD) { 1972 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice && 1973 "Expected OpenMP host compilation."); 1974 1975 SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop; 1976 if (FD) { 1977 FunctionEmissionStatus FES = getEmissionStatus(FD); 1978 switch (FES) { 1979 case FunctionEmissionStatus::Emitted: 1980 Kind = SemaDiagnosticBuilder::K_Immediate; 1981 break; 1982 case FunctionEmissionStatus::Unknown: 1983 Kind = SemaDiagnosticBuilder::K_Deferred; 1984 break; 1985 case FunctionEmissionStatus::TemplateDiscarded: 1986 case FunctionEmissionStatus::OMPDiscarded: 1987 case FunctionEmissionStatus::CUDADiscarded: 1988 Kind = SemaDiagnosticBuilder::K_Nop; 1989 break; 1990 } 1991 } 1992 1993 return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this); 1994 } 1995 1996 static OpenMPDefaultmapClauseKind 1997 getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) { 1998 if (LO.OpenMP <= 45) { 1999 if (VD->getType().getNonReferenceType()->isScalarType()) 2000 return OMPC_DEFAULTMAP_scalar; 2001 return OMPC_DEFAULTMAP_aggregate; 2002 } 2003 if (VD->getType().getNonReferenceType()->isAnyPointerType()) 2004 return OMPC_DEFAULTMAP_pointer; 2005 if (VD->getType().getNonReferenceType()->isScalarType()) 2006 return OMPC_DEFAULTMAP_scalar; 2007 return OMPC_DEFAULTMAP_aggregate; 2008 } 2009 2010 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, 2011 unsigned OpenMPCaptureLevel) const { 2012 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2013 2014 ASTContext &Ctx = getASTContext(); 2015 bool IsByRef = true; 2016 2017 // Find the directive that is associated with the provided scope. 2018 D = cast<ValueDecl>(D->getCanonicalDecl()); 2019 QualType Ty = D->getType(); 2020 2021 bool IsVariableUsedInMapClause = false; 2022 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 2023 // This table summarizes how a given variable should be passed to the device 2024 // given its type and the clauses where it appears. This table is based on 2025 // the description in OpenMP 4.5 [2.10.4, target Construct] and 2026 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 2027 // 2028 // ========================================================================= 2029 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 2030 // | |(tofrom:scalar)| | pvt | | | | 2031 // ========================================================================= 2032 // | scl | | | | - | | bycopy| 2033 // | scl | | - | x | - | - | bycopy| 2034 // | scl | | x | - | - | - | null | 2035 // | scl | x | | | - | | byref | 2036 // | scl | x | - | x | - | - | bycopy| 2037 // | scl | x | x | - | - | - | null | 2038 // | scl | | - | - | - | x | byref | 2039 // | scl | x | - | - | - | x | byref | 2040 // 2041 // | agg | n.a. | | | - | | byref | 2042 // | agg | n.a. | - | x | - | - | byref | 2043 // | agg | n.a. | x | - | - | - | null | 2044 // | agg | n.a. | - | - | - | x | byref | 2045 // | agg | n.a. | - | - | - | x[] | byref | 2046 // 2047 // | ptr | n.a. | | | - | | bycopy| 2048 // | ptr | n.a. | - | x | - | - | bycopy| 2049 // | ptr | n.a. | x | - | - | - | null | 2050 // | ptr | n.a. | - | - | - | x | byref | 2051 // | ptr | n.a. | - | - | - | x[] | bycopy| 2052 // | ptr | n.a. | - | - | x | | bycopy| 2053 // | ptr | n.a. | - | - | x | x | bycopy| 2054 // | ptr | n.a. | - | - | x | x[] | bycopy| 2055 // ========================================================================= 2056 // Legend: 2057 // scl - scalar 2058 // ptr - pointer 2059 // agg - aggregate 2060 // x - applies 2061 // - - invalid in this combination 2062 // [] - mapped with an array section 2063 // byref - should be mapped by reference 2064 // byval - should be mapped by value 2065 // null - initialize a local variable to null on the device 2066 // 2067 // Observations: 2068 // - All scalar declarations that show up in a map clause have to be passed 2069 // by reference, because they may have been mapped in the enclosing data 2070 // environment. 2071 // - If the scalar value does not fit the size of uintptr, it has to be 2072 // passed by reference, regardless the result in the table above. 2073 // - For pointers mapped by value that have either an implicit map or an 2074 // array section, the runtime library may pass the NULL value to the 2075 // device instead of the value passed to it by the compiler. 2076 2077 if (Ty->isReferenceType()) 2078 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 2079 2080 // Locate map clauses and see if the variable being captured is referred to 2081 // in any of those clauses. Here we only care about variables, not fields, 2082 // because fields are part of aggregates. 2083 bool IsVariableAssociatedWithSection = false; 2084 2085 DSAStack->checkMappableExprComponentListsForDeclAtLevel( 2086 D, Level, 2087 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, 2088 D](OMPClauseMappableExprCommon::MappableExprComponentListRef 2089 MapExprComponents, 2090 OpenMPClauseKind WhereFoundClauseKind) { 2091 // Only the map clause information influences how a variable is 2092 // captured. E.g. is_device_ptr does not require changing the default 2093 // behavior. 2094 if (WhereFoundClauseKind != OMPC_map) 2095 return false; 2096 2097 auto EI = MapExprComponents.rbegin(); 2098 auto EE = MapExprComponents.rend(); 2099 2100 assert(EI != EE && "Invalid map expression!"); 2101 2102 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 2103 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 2104 2105 ++EI; 2106 if (EI == EE) 2107 return false; 2108 2109 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 2110 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 2111 isa<MemberExpr>(EI->getAssociatedExpression()) || 2112 isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) { 2113 IsVariableAssociatedWithSection = true; 2114 // There is nothing more we need to know about this variable. 2115 return true; 2116 } 2117 2118 // Keep looking for more map info. 2119 return false; 2120 }); 2121 2122 if (IsVariableUsedInMapClause) { 2123 // If variable is identified in a map clause it is always captured by 2124 // reference except if it is a pointer that is dereferenced somehow. 2125 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 2126 } else { 2127 // By default, all the data that has a scalar type is mapped by copy 2128 // (except for reduction variables). 2129 // Defaultmap scalar is mutual exclusive to defaultmap pointer 2130 IsByRef = (DSAStack->isForceCaptureByReferenceInTargetExecutable() && 2131 !Ty->isAnyPointerType()) || 2132 !Ty->isScalarType() || 2133 DSAStack->isDefaultmapCapturedByRef( 2134 Level, getVariableCategoryFromDecl(LangOpts, D)) || 2135 DSAStack->hasExplicitDSA( 2136 D, 2137 [](OpenMPClauseKind K, bool AppliedToPointee) { 2138 return K == OMPC_reduction && !AppliedToPointee; 2139 }, 2140 Level); 2141 } 2142 } 2143 2144 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 2145 IsByRef = 2146 ((IsVariableUsedInMapClause && 2147 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) == 2148 OMPD_target) || 2149 !(DSAStack->hasExplicitDSA( 2150 D, 2151 [](OpenMPClauseKind K, bool AppliedToPointee) -> bool { 2152 return K == OMPC_firstprivate || 2153 (K == OMPC_reduction && AppliedToPointee); 2154 }, 2155 Level, /*NotLastprivate=*/true) || 2156 DSAStack->isUsesAllocatorsDecl(Level, D))) && 2157 // If the variable is artificial and must be captured by value - try to 2158 // capture by value. 2159 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() && 2160 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) && 2161 // If the variable is implicitly firstprivate and scalar - capture by 2162 // copy 2163 !((DSAStack->getDefaultDSA() == DSA_firstprivate || 2164 DSAStack->getDefaultDSA() == DSA_private) && 2165 !DSAStack->hasExplicitDSA( 2166 D, [](OpenMPClauseKind K, bool) { return K != OMPC_unknown; }, 2167 Level) && 2168 !DSAStack->isLoopControlVariable(D, Level).first); 2169 } 2170 2171 // When passing data by copy, we need to make sure it fits the uintptr size 2172 // and alignment, because the runtime library only deals with uintptr types. 2173 // If it does not fit the uintptr size, we need to pass the data by reference 2174 // instead. 2175 if (!IsByRef && 2176 (Ctx.getTypeSizeInChars(Ty) > 2177 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 2178 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 2179 IsByRef = true; 2180 } 2181 2182 return IsByRef; 2183 } 2184 2185 unsigned Sema::getOpenMPNestingLevel() const { 2186 assert(getLangOpts().OpenMP); 2187 return DSAStack->getNestingLevel(); 2188 } 2189 2190 bool Sema::isInOpenMPTaskUntiedContext() const { 2191 return isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) && 2192 DSAStack->isUntiedRegion(); 2193 } 2194 2195 bool Sema::isInOpenMPTargetExecutionDirective() const { 2196 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) && 2197 !DSAStack->isClauseParsingMode()) || 2198 DSAStack->hasDirective( 2199 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 2200 SourceLocation) -> bool { 2201 return isOpenMPTargetExecutionDirective(K); 2202 }, 2203 false); 2204 } 2205 2206 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo, 2207 unsigned StopAt) { 2208 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2209 D = getCanonicalDecl(D); 2210 2211 auto *VD = dyn_cast<VarDecl>(D); 2212 // Do not capture constexpr variables. 2213 if (VD && VD->isConstexpr()) 2214 return nullptr; 2215 2216 // If we want to determine whether the variable should be captured from the 2217 // perspective of the current capturing scope, and we've already left all the 2218 // capturing scopes of the top directive on the stack, check from the 2219 // perspective of its parent directive (if any) instead. 2220 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII( 2221 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete()); 2222 2223 // If we are attempting to capture a global variable in a directive with 2224 // 'target' we return true so that this global is also mapped to the device. 2225 // 2226 if (VD && !VD->hasLocalStorage() && 2227 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) { 2228 if (isInOpenMPTargetExecutionDirective()) { 2229 DSAStackTy::DSAVarData DVarTop = 2230 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 2231 if (DVarTop.CKind != OMPC_unknown && DVarTop.RefExpr) 2232 return VD; 2233 // If the declaration is enclosed in a 'declare target' directive, 2234 // then it should not be captured. 2235 // 2236 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 2237 return nullptr; 2238 CapturedRegionScopeInfo *CSI = nullptr; 2239 for (FunctionScopeInfo *FSI : llvm::drop_begin( 2240 llvm::reverse(FunctionScopes), 2241 CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) { 2242 if (!isa<CapturingScopeInfo>(FSI)) 2243 return nullptr; 2244 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI)) 2245 if (RSI->CapRegionKind == CR_OpenMP) { 2246 CSI = RSI; 2247 break; 2248 } 2249 } 2250 assert(CSI && "Failed to find CapturedRegionScopeInfo"); 2251 SmallVector<OpenMPDirectiveKind, 4> Regions; 2252 getOpenMPCaptureRegions(Regions, 2253 DSAStack->getDirective(CSI->OpenMPLevel)); 2254 if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task) 2255 return VD; 2256 } 2257 if (isInOpenMPDeclareTargetContext()) { 2258 // Try to mark variable as declare target if it is used in capturing 2259 // regions. 2260 if (LangOpts.OpenMP <= 45 && 2261 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 2262 checkDeclIsAllowedInOpenMPTarget(nullptr, VD); 2263 return nullptr; 2264 } 2265 } 2266 2267 if (CheckScopeInfo) { 2268 bool OpenMPFound = false; 2269 for (unsigned I = StopAt + 1; I > 0; --I) { 2270 FunctionScopeInfo *FSI = FunctionScopes[I - 1]; 2271 if (!isa<CapturingScopeInfo>(FSI)) 2272 return nullptr; 2273 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI)) 2274 if (RSI->CapRegionKind == CR_OpenMP) { 2275 OpenMPFound = true; 2276 break; 2277 } 2278 } 2279 if (!OpenMPFound) 2280 return nullptr; 2281 } 2282 2283 if (DSAStack->getCurrentDirective() != OMPD_unknown && 2284 (!DSAStack->isClauseParsingMode() || 2285 DSAStack->getParentDirective() != OMPD_unknown)) { 2286 auto &&Info = DSAStack->isLoopControlVariable(D); 2287 if (Info.first || 2288 (VD && VD->hasLocalStorage() && 2289 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) || 2290 (VD && DSAStack->isForceVarCapturing())) 2291 return VD ? VD : Info.second; 2292 DSAStackTy::DSAVarData DVarTop = 2293 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 2294 if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) && 2295 (!VD || VD->hasLocalStorage() || !DVarTop.AppliedToPointee)) 2296 return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl()); 2297 // Threadprivate variables must not be captured. 2298 if (isOpenMPThreadPrivate(DVarTop.CKind)) 2299 return nullptr; 2300 // The variable is not private or it is the variable in the directive with 2301 // default(none) clause and not used in any clause. 2302 DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA( 2303 D, 2304 [](OpenMPClauseKind C, bool AppliedToPointee) { 2305 return isOpenMPPrivate(C) && !AppliedToPointee; 2306 }, 2307 [](OpenMPDirectiveKind) { return true; }, 2308 DSAStack->isClauseParsingMode()); 2309 // Global shared must not be captured. 2310 if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown && 2311 ((DSAStack->getDefaultDSA() != DSA_none && 2312 DSAStack->getDefaultDSA() != DSA_private && 2313 DSAStack->getDefaultDSA() != DSA_firstprivate) || 2314 DVarTop.CKind == OMPC_shared)) 2315 return nullptr; 2316 if (DVarPrivate.CKind != OMPC_unknown || 2317 (VD && (DSAStack->getDefaultDSA() == DSA_none || 2318 DSAStack->getDefaultDSA() == DSA_private || 2319 DSAStack->getDefaultDSA() == DSA_firstprivate))) 2320 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 2321 } 2322 return nullptr; 2323 } 2324 2325 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 2326 unsigned Level) const { 2327 FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 2328 } 2329 2330 void Sema::startOpenMPLoop() { 2331 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 2332 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) 2333 DSAStack->loopInit(); 2334 } 2335 2336 void Sema::startOpenMPCXXRangeFor() { 2337 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 2338 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 2339 DSAStack->resetPossibleLoopCounter(); 2340 DSAStack->loopStart(); 2341 } 2342 } 2343 2344 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, 2345 unsigned CapLevel) const { 2346 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2347 if (DSAStack->hasExplicitDirective(isOpenMPTaskingDirective, Level)) { 2348 bool IsTriviallyCopyable = 2349 D->getType().getNonReferenceType().isTriviallyCopyableType(Context) && 2350 !D->getType() 2351 .getNonReferenceType() 2352 .getCanonicalType() 2353 ->getAsCXXRecordDecl(); 2354 OpenMPDirectiveKind DKind = DSAStack->getDirective(Level); 2355 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2356 getOpenMPCaptureRegions(CaptureRegions, DKind); 2357 if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) && 2358 (IsTriviallyCopyable || 2359 !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) { 2360 if (DSAStack->hasExplicitDSA( 2361 D, 2362 [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; }, 2363 Level, /*NotLastprivate=*/true)) 2364 return OMPC_firstprivate; 2365 DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level); 2366 if (DVar.CKind != OMPC_shared && 2367 !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) { 2368 DSAStack->addImplicitTaskFirstprivate(Level, D); 2369 return OMPC_firstprivate; 2370 } 2371 } 2372 } 2373 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 2374 if (DSAStack->getAssociatedLoops() > 0 && !DSAStack->isLoopStarted()) { 2375 DSAStack->resetPossibleLoopCounter(D); 2376 DSAStack->loopStart(); 2377 return OMPC_private; 2378 } 2379 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() || 2380 DSAStack->isLoopControlVariable(D).first) && 2381 !DSAStack->hasExplicitDSA( 2382 D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; }, 2383 Level) && 2384 !isOpenMPSimdDirective(DSAStack->getCurrentDirective())) 2385 return OMPC_private; 2386 } 2387 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2388 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) && 2389 DSAStack->isForceVarCapturing() && 2390 !DSAStack->hasExplicitDSA( 2391 D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; }, 2392 Level)) 2393 return OMPC_private; 2394 } 2395 // User-defined allocators are private since they must be defined in the 2396 // context of target region. 2397 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) && 2398 DSAStack->isUsesAllocatorsDecl(Level, D).value_or( 2399 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) == 2400 DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator) 2401 return OMPC_private; 2402 return (DSAStack->hasExplicitDSA( 2403 D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; }, 2404 Level) || 2405 (DSAStack->isClauseParsingMode() && 2406 DSAStack->getClauseParsingMode() == OMPC_private) || 2407 // Consider taskgroup reduction descriptor variable a private 2408 // to avoid possible capture in the region. 2409 (DSAStack->hasExplicitDirective( 2410 [](OpenMPDirectiveKind K) { 2411 return K == OMPD_taskgroup || 2412 ((isOpenMPParallelDirective(K) || 2413 isOpenMPWorksharingDirective(K)) && 2414 !isOpenMPSimdDirective(K)); 2415 }, 2416 Level) && 2417 DSAStack->isTaskgroupReductionRef(D, Level))) 2418 ? OMPC_private 2419 : OMPC_unknown; 2420 } 2421 2422 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, 2423 unsigned Level) { 2424 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2425 D = getCanonicalDecl(D); 2426 OpenMPClauseKind OMPC = OMPC_unknown; 2427 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) { 2428 const unsigned NewLevel = I - 1; 2429 if (DSAStack->hasExplicitDSA( 2430 D, 2431 [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) { 2432 if (isOpenMPPrivate(K) && !AppliedToPointee) { 2433 OMPC = K; 2434 return true; 2435 } 2436 return false; 2437 }, 2438 NewLevel)) 2439 break; 2440 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel( 2441 D, NewLevel, 2442 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 2443 OpenMPClauseKind) { return true; })) { 2444 OMPC = OMPC_map; 2445 break; 2446 } 2447 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 2448 NewLevel)) { 2449 OMPC = OMPC_map; 2450 if (DSAStack->mustBeFirstprivateAtLevel( 2451 NewLevel, getVariableCategoryFromDecl(LangOpts, D))) 2452 OMPC = OMPC_firstprivate; 2453 break; 2454 } 2455 } 2456 if (OMPC != OMPC_unknown) 2457 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC))); 2458 } 2459 2460 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, 2461 unsigned CaptureLevel) const { 2462 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2463 // Return true if the current level is no longer enclosed in a target region. 2464 2465 SmallVector<OpenMPDirectiveKind, 4> Regions; 2466 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level)); 2467 const auto *VD = dyn_cast<VarDecl>(D); 2468 return VD && !VD->hasLocalStorage() && 2469 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 2470 Level) && 2471 Regions[CaptureLevel] != OMPD_task; 2472 } 2473 2474 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, 2475 unsigned CaptureLevel) const { 2476 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2477 // Return true if the current level is no longer enclosed in a target region. 2478 2479 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2480 if (!VD->hasLocalStorage()) { 2481 if (isInOpenMPTargetExecutionDirective()) 2482 return true; 2483 DSAStackTy::DSAVarData TopDVar = 2484 DSAStack->getTopDSA(D, /*FromParent=*/false); 2485 unsigned NumLevels = 2486 getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 2487 if (Level == 0) 2488 // non-file scope static variale with default(firstprivate) 2489 // should be gloabal captured. 2490 return (NumLevels == CaptureLevel + 1 && 2491 (TopDVar.CKind != OMPC_shared || 2492 DSAStack->getDefaultDSA() == DSA_firstprivate)); 2493 do { 2494 --Level; 2495 DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level); 2496 if (DVar.CKind != OMPC_shared) 2497 return true; 2498 } while (Level > 0); 2499 } 2500 } 2501 return true; 2502 } 2503 2504 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 2505 2506 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, 2507 OMPTraitInfo &TI) { 2508 OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI)); 2509 } 2510 2511 void Sema::ActOnOpenMPEndDeclareVariant() { 2512 assert(isInOpenMPDeclareVariantScope() && 2513 "Not in OpenMP declare variant scope!"); 2514 2515 OMPDeclareVariantScopes.pop_back(); 2516 } 2517 2518 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, 2519 const FunctionDecl *Callee, 2520 SourceLocation Loc) { 2521 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode."); 2522 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 2523 OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl()); 2524 // Ignore host functions during device analyzis. 2525 if (LangOpts.OpenMPIsDevice && 2526 (!DevTy || *DevTy == OMPDeclareTargetDeclAttr::DT_Host)) 2527 return; 2528 // Ignore nohost functions during host analyzis. 2529 if (!LangOpts.OpenMPIsDevice && DevTy && 2530 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 2531 return; 2532 const FunctionDecl *FD = Callee->getMostRecentDecl(); 2533 DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD); 2534 if (LangOpts.OpenMPIsDevice && DevTy && 2535 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) { 2536 // Diagnose host function called during device codegen. 2537 StringRef HostDevTy = 2538 getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host); 2539 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0; 2540 Diag(*OMPDeclareTargetDeclAttr::getLocation(FD), 2541 diag::note_omp_marked_device_type_here) 2542 << HostDevTy; 2543 return; 2544 } 2545 if (!LangOpts.OpenMPIsDevice && !LangOpts.OpenMPOffloadMandatory && DevTy && 2546 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 2547 // Diagnose nohost function called during host codegen. 2548 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName( 2549 OMPC_device_type, OMPC_DEVICE_TYPE_nohost); 2550 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1; 2551 Diag(*OMPDeclareTargetDeclAttr::getLocation(FD), 2552 diag::note_omp_marked_device_type_here) 2553 << NoHostDevTy; 2554 } 2555 } 2556 2557 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 2558 const DeclarationNameInfo &DirName, 2559 Scope *CurScope, SourceLocation Loc) { 2560 DSAStack->push(DKind, DirName, CurScope, Loc); 2561 PushExpressionEvaluationContext( 2562 ExpressionEvaluationContext::PotentiallyEvaluated); 2563 } 2564 2565 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 2566 DSAStack->setClauseParsingMode(K); 2567 } 2568 2569 void Sema::EndOpenMPClause() { 2570 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 2571 CleanupVarDeclMarking(); 2572 } 2573 2574 static std::pair<ValueDecl *, bool> 2575 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 2576 SourceRange &ERange, bool AllowArraySection = false); 2577 2578 /// Check consistency of the reduction clauses. 2579 static void checkReductionClauses(Sema &S, DSAStackTy *Stack, 2580 ArrayRef<OMPClause *> Clauses) { 2581 bool InscanFound = false; 2582 SourceLocation InscanLoc; 2583 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions. 2584 // A reduction clause without the inscan reduction-modifier may not appear on 2585 // a construct on which a reduction clause with the inscan reduction-modifier 2586 // appears. 2587 for (OMPClause *C : Clauses) { 2588 if (C->getClauseKind() != OMPC_reduction) 2589 continue; 2590 auto *RC = cast<OMPReductionClause>(C); 2591 if (RC->getModifier() == OMPC_REDUCTION_inscan) { 2592 InscanFound = true; 2593 InscanLoc = RC->getModifierLoc(); 2594 continue; 2595 } 2596 if (RC->getModifier() == OMPC_REDUCTION_task) { 2597 // OpenMP 5.0, 2.19.5.4 reduction Clause. 2598 // A reduction clause with the task reduction-modifier may only appear on 2599 // a parallel construct, a worksharing construct or a combined or 2600 // composite construct for which any of the aforementioned constructs is a 2601 // constituent construct and simd or loop are not constituent constructs. 2602 OpenMPDirectiveKind CurDir = Stack->getCurrentDirective(); 2603 if (!(isOpenMPParallelDirective(CurDir) || 2604 isOpenMPWorksharingDirective(CurDir)) || 2605 isOpenMPSimdDirective(CurDir)) 2606 S.Diag(RC->getModifierLoc(), 2607 diag::err_omp_reduction_task_not_parallel_or_worksharing); 2608 continue; 2609 } 2610 } 2611 if (InscanFound) { 2612 for (OMPClause *C : Clauses) { 2613 if (C->getClauseKind() != OMPC_reduction) 2614 continue; 2615 auto *RC = cast<OMPReductionClause>(C); 2616 if (RC->getModifier() != OMPC_REDUCTION_inscan) { 2617 S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown 2618 ? RC->getBeginLoc() 2619 : RC->getModifierLoc(), 2620 diag::err_omp_inscan_reduction_expected); 2621 S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction); 2622 continue; 2623 } 2624 for (Expr *Ref : RC->varlists()) { 2625 assert(Ref && "NULL expr in OpenMP nontemporal clause."); 2626 SourceLocation ELoc; 2627 SourceRange ERange; 2628 Expr *SimpleRefExpr = Ref; 2629 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 2630 /*AllowArraySection=*/true); 2631 ValueDecl *D = Res.first; 2632 if (!D) 2633 continue; 2634 if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) { 2635 S.Diag(Ref->getExprLoc(), 2636 diag::err_omp_reduction_not_inclusive_exclusive) 2637 << Ref->getSourceRange(); 2638 } 2639 } 2640 } 2641 } 2642 } 2643 2644 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack, 2645 ArrayRef<OMPClause *> Clauses); 2646 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 2647 bool WithInit); 2648 2649 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 2650 const ValueDecl *D, 2651 const DSAStackTy::DSAVarData &DVar, 2652 bool IsLoopIterVar = false); 2653 2654 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 2655 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 2656 // A variable of class type (or array thereof) that appears in a lastprivate 2657 // clause requires an accessible, unambiguous default constructor for the 2658 // class type, unless the list item is also specified in a firstprivate 2659 // clause. 2660 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 2661 for (OMPClause *C : D->clauses()) { 2662 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 2663 SmallVector<Expr *, 8> PrivateCopies; 2664 for (Expr *DE : Clause->varlists()) { 2665 if (DE->isValueDependent() || DE->isTypeDependent()) { 2666 PrivateCopies.push_back(nullptr); 2667 continue; 2668 } 2669 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 2670 auto *VD = cast<VarDecl>(DRE->getDecl()); 2671 QualType Type = VD->getType().getNonReferenceType(); 2672 const DSAStackTy::DSAVarData DVar = 2673 DSAStack->getTopDSA(VD, /*FromParent=*/false); 2674 if (DVar.CKind == OMPC_lastprivate) { 2675 // Generate helper private variable and initialize it with the 2676 // default value. The address of the original variable is replaced 2677 // by the address of the new private variable in CodeGen. This new 2678 // variable is not added to IdResolver, so the code in the OpenMP 2679 // region uses original variable for proper diagnostics. 2680 VarDecl *VDPrivate = buildVarDecl( 2681 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 2682 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE); 2683 ActOnUninitializedDecl(VDPrivate); 2684 if (VDPrivate->isInvalidDecl()) { 2685 PrivateCopies.push_back(nullptr); 2686 continue; 2687 } 2688 PrivateCopies.push_back(buildDeclRefExpr( 2689 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 2690 } else { 2691 // The variable is also a firstprivate, so initialization sequence 2692 // for private copy is generated already. 2693 PrivateCopies.push_back(nullptr); 2694 } 2695 } 2696 Clause->setPrivateCopies(PrivateCopies); 2697 continue; 2698 } 2699 // Finalize nontemporal clause by handling private copies, if any. 2700 if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) { 2701 SmallVector<Expr *, 8> PrivateRefs; 2702 for (Expr *RefExpr : Clause->varlists()) { 2703 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 2704 SourceLocation ELoc; 2705 SourceRange ERange; 2706 Expr *SimpleRefExpr = RefExpr; 2707 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 2708 if (Res.second) 2709 // It will be analyzed later. 2710 PrivateRefs.push_back(RefExpr); 2711 ValueDecl *D = Res.first; 2712 if (!D) 2713 continue; 2714 2715 const DSAStackTy::DSAVarData DVar = 2716 DSAStack->getTopDSA(D, /*FromParent=*/false); 2717 PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy 2718 : SimpleRefExpr); 2719 } 2720 Clause->setPrivateRefs(PrivateRefs); 2721 continue; 2722 } 2723 if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) { 2724 for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) { 2725 OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I); 2726 auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts()); 2727 if (!DRE) 2728 continue; 2729 ValueDecl *VD = DRE->getDecl(); 2730 if (!VD || !isa<VarDecl>(VD)) 2731 continue; 2732 DSAStackTy::DSAVarData DVar = 2733 DSAStack->getTopDSA(VD, /*FromParent=*/false); 2734 // OpenMP [2.12.5, target Construct] 2735 // Memory allocators that appear in a uses_allocators clause cannot 2736 // appear in other data-sharing attribute clauses or data-mapping 2737 // attribute clauses in the same construct. 2738 Expr *MapExpr = nullptr; 2739 if (DVar.RefExpr || 2740 DSAStack->checkMappableExprComponentListsForDecl( 2741 VD, /*CurrentRegionOnly=*/true, 2742 [VD, &MapExpr]( 2743 OMPClauseMappableExprCommon::MappableExprComponentListRef 2744 MapExprComponents, 2745 OpenMPClauseKind C) { 2746 auto MI = MapExprComponents.rbegin(); 2747 auto ME = MapExprComponents.rend(); 2748 if (MI != ME && 2749 MI->getAssociatedDeclaration()->getCanonicalDecl() == 2750 VD->getCanonicalDecl()) { 2751 MapExpr = MI->getAssociatedExpression(); 2752 return true; 2753 } 2754 return false; 2755 })) { 2756 Diag(D.Allocator->getExprLoc(), 2757 diag::err_omp_allocator_used_in_clauses) 2758 << D.Allocator->getSourceRange(); 2759 if (DVar.RefExpr) 2760 reportOriginalDsa(*this, DSAStack, VD, DVar); 2761 else 2762 Diag(MapExpr->getExprLoc(), diag::note_used_here) 2763 << MapExpr->getSourceRange(); 2764 } 2765 } 2766 continue; 2767 } 2768 } 2769 // Check allocate clauses. 2770 if (!CurContext->isDependentContext()) 2771 checkAllocateClauses(*this, DSAStack, D->clauses()); 2772 checkReductionClauses(*this, DSAStack, D->clauses()); 2773 } 2774 2775 DSAStack->pop(); 2776 DiscardCleanupsInEvaluationContext(); 2777 PopExpressionEvaluationContext(); 2778 } 2779 2780 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 2781 Expr *NumIterations, Sema &SemaRef, 2782 Scope *S, DSAStackTy *Stack); 2783 2784 namespace { 2785 2786 class VarDeclFilterCCC final : public CorrectionCandidateCallback { 2787 private: 2788 Sema &SemaRef; 2789 2790 public: 2791 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 2792 bool ValidateCandidate(const TypoCorrection &Candidate) override { 2793 NamedDecl *ND = Candidate.getCorrectionDecl(); 2794 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 2795 return VD->hasGlobalStorage() && 2796 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 2797 SemaRef.getCurScope()); 2798 } 2799 return false; 2800 } 2801 2802 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2803 return std::make_unique<VarDeclFilterCCC>(*this); 2804 } 2805 }; 2806 2807 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback { 2808 private: 2809 Sema &SemaRef; 2810 2811 public: 2812 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 2813 bool ValidateCandidate(const TypoCorrection &Candidate) override { 2814 NamedDecl *ND = Candidate.getCorrectionDecl(); 2815 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) || 2816 isa<FunctionDecl>(ND))) { 2817 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 2818 SemaRef.getCurScope()); 2819 } 2820 return false; 2821 } 2822 2823 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2824 return std::make_unique<VarOrFuncDeclFilterCCC>(*this); 2825 } 2826 }; 2827 2828 } // namespace 2829 2830 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 2831 CXXScopeSpec &ScopeSpec, 2832 const DeclarationNameInfo &Id, 2833 OpenMPDirectiveKind Kind) { 2834 LookupResult Lookup(*this, Id, LookupOrdinaryName); 2835 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 2836 2837 if (Lookup.isAmbiguous()) 2838 return ExprError(); 2839 2840 VarDecl *VD; 2841 if (!Lookup.isSingleResult()) { 2842 VarDeclFilterCCC CCC(*this); 2843 if (TypoCorrection Corrected = 2844 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC, 2845 CTK_ErrorRecovery)) { 2846 diagnoseTypo(Corrected, 2847 PDiag(Lookup.empty() 2848 ? diag::err_undeclared_var_use_suggest 2849 : diag::err_omp_expected_var_arg_suggest) 2850 << Id.getName()); 2851 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 2852 } else { 2853 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 2854 : diag::err_omp_expected_var_arg) 2855 << Id.getName(); 2856 return ExprError(); 2857 } 2858 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) { 2859 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 2860 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 2861 return ExprError(); 2862 } 2863 Lookup.suppressDiagnostics(); 2864 2865 // OpenMP [2.9.2, Syntax, C/C++] 2866 // Variables must be file-scope, namespace-scope, or static block-scope. 2867 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) { 2868 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 2869 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal(); 2870 bool IsDecl = 2871 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2872 Diag(VD->getLocation(), 2873 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2874 << VD; 2875 return ExprError(); 2876 } 2877 2878 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 2879 NamedDecl *ND = CanonicalVD; 2880 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 2881 // A threadprivate directive for file-scope variables must appear outside 2882 // any definition or declaration. 2883 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 2884 !getCurLexicalContext()->isTranslationUnit()) { 2885 Diag(Id.getLoc(), diag::err_omp_var_scope) 2886 << getOpenMPDirectiveName(Kind) << VD; 2887 bool IsDecl = 2888 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2889 Diag(VD->getLocation(), 2890 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2891 << VD; 2892 return ExprError(); 2893 } 2894 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 2895 // A threadprivate directive for static class member variables must appear 2896 // in the class definition, in the same scope in which the member 2897 // variables are declared. 2898 if (CanonicalVD->isStaticDataMember() && 2899 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 2900 Diag(Id.getLoc(), diag::err_omp_var_scope) 2901 << getOpenMPDirectiveName(Kind) << VD; 2902 bool IsDecl = 2903 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2904 Diag(VD->getLocation(), 2905 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2906 << VD; 2907 return ExprError(); 2908 } 2909 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 2910 // A threadprivate directive for namespace-scope variables must appear 2911 // outside any definition or declaration other than the namespace 2912 // definition itself. 2913 if (CanonicalVD->getDeclContext()->isNamespace() && 2914 (!getCurLexicalContext()->isFileContext() || 2915 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 2916 Diag(Id.getLoc(), diag::err_omp_var_scope) 2917 << getOpenMPDirectiveName(Kind) << VD; 2918 bool IsDecl = 2919 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2920 Diag(VD->getLocation(), 2921 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2922 << VD; 2923 return ExprError(); 2924 } 2925 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 2926 // A threadprivate directive for static block-scope variables must appear 2927 // in the scope of the variable and not in a nested scope. 2928 if (CanonicalVD->isLocalVarDecl() && CurScope && 2929 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 2930 Diag(Id.getLoc(), diag::err_omp_var_scope) 2931 << getOpenMPDirectiveName(Kind) << VD; 2932 bool IsDecl = 2933 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2934 Diag(VD->getLocation(), 2935 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2936 << VD; 2937 return ExprError(); 2938 } 2939 2940 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 2941 // A threadprivate directive must lexically precede all references to any 2942 // of the variables in its list. 2943 if (Kind == OMPD_threadprivate && VD->isUsed() && 2944 !DSAStack->isThreadPrivate(VD)) { 2945 Diag(Id.getLoc(), diag::err_omp_var_used) 2946 << getOpenMPDirectiveName(Kind) << VD; 2947 return ExprError(); 2948 } 2949 2950 QualType ExprType = VD->getType().getNonReferenceType(); 2951 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 2952 SourceLocation(), VD, 2953 /*RefersToEnclosingVariableOrCapture=*/false, 2954 Id.getLoc(), ExprType, VK_LValue); 2955 } 2956 2957 Sema::DeclGroupPtrTy 2958 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 2959 ArrayRef<Expr *> VarList) { 2960 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 2961 CurContext->addDecl(D); 2962 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2963 } 2964 return nullptr; 2965 } 2966 2967 namespace { 2968 class LocalVarRefChecker final 2969 : public ConstStmtVisitor<LocalVarRefChecker, bool> { 2970 Sema &SemaRef; 2971 2972 public: 2973 bool VisitDeclRefExpr(const DeclRefExpr *E) { 2974 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 2975 if (VD->hasLocalStorage()) { 2976 SemaRef.Diag(E->getBeginLoc(), 2977 diag::err_omp_local_var_in_threadprivate_init) 2978 << E->getSourceRange(); 2979 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 2980 << VD << VD->getSourceRange(); 2981 return true; 2982 } 2983 } 2984 return false; 2985 } 2986 bool VisitStmt(const Stmt *S) { 2987 for (const Stmt *Child : S->children()) { 2988 if (Child && Visit(Child)) 2989 return true; 2990 } 2991 return false; 2992 } 2993 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 2994 }; 2995 } // namespace 2996 2997 OMPThreadPrivateDecl * 2998 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 2999 SmallVector<Expr *, 8> Vars; 3000 for (Expr *RefExpr : VarList) { 3001 auto *DE = cast<DeclRefExpr>(RefExpr); 3002 auto *VD = cast<VarDecl>(DE->getDecl()); 3003 SourceLocation ILoc = DE->getExprLoc(); 3004 3005 // Mark variable as used. 3006 VD->setReferenced(); 3007 VD->markUsed(Context); 3008 3009 QualType QType = VD->getType(); 3010 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 3011 // It will be analyzed later. 3012 Vars.push_back(DE); 3013 continue; 3014 } 3015 3016 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 3017 // A threadprivate variable must not have an incomplete type. 3018 if (RequireCompleteType(ILoc, VD->getType(), 3019 diag::err_omp_threadprivate_incomplete_type)) { 3020 continue; 3021 } 3022 3023 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 3024 // A threadprivate variable must not have a reference type. 3025 if (VD->getType()->isReferenceType()) { 3026 Diag(ILoc, diag::err_omp_ref_type_arg) 3027 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 3028 bool IsDecl = 3029 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 3030 Diag(VD->getLocation(), 3031 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 3032 << VD; 3033 continue; 3034 } 3035 3036 // Check if this is a TLS variable. If TLS is not being supported, produce 3037 // the corresponding diagnostic. 3038 if ((VD->getTLSKind() != VarDecl::TLS_None && 3039 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 3040 getLangOpts().OpenMPUseTLS && 3041 getASTContext().getTargetInfo().isTLSSupported())) || 3042 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 3043 !VD->isLocalVarDecl())) { 3044 Diag(ILoc, diag::err_omp_var_thread_local) 3045 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 3046 bool IsDecl = 3047 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 3048 Diag(VD->getLocation(), 3049 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 3050 << VD; 3051 continue; 3052 } 3053 3054 // Check if initial value of threadprivate variable reference variable with 3055 // local storage (it is not supported by runtime). 3056 if (const Expr *Init = VD->getAnyInitializer()) { 3057 LocalVarRefChecker Checker(*this); 3058 if (Checker.Visit(Init)) 3059 continue; 3060 } 3061 3062 Vars.push_back(RefExpr); 3063 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 3064 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 3065 Context, SourceRange(Loc, Loc))); 3066 if (ASTMutationListener *ML = Context.getASTMutationListener()) 3067 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 3068 } 3069 OMPThreadPrivateDecl *D = nullptr; 3070 if (!Vars.empty()) { 3071 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 3072 Vars); 3073 D->setAccess(AS_public); 3074 } 3075 return D; 3076 } 3077 3078 static OMPAllocateDeclAttr::AllocatorTypeTy 3079 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) { 3080 if (!Allocator) 3081 return OMPAllocateDeclAttr::OMPNullMemAlloc; 3082 if (Allocator->isTypeDependent() || Allocator->isValueDependent() || 3083 Allocator->isInstantiationDependent() || 3084 Allocator->containsUnexpandedParameterPack()) 3085 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; 3086 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; 3087 const Expr *AE = Allocator->IgnoreParenImpCasts(); 3088 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 3089 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 3090 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind); 3091 llvm::FoldingSetNodeID AEId, DAEId; 3092 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true); 3093 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true); 3094 if (AEId == DAEId) { 3095 AllocatorKindRes = AllocatorKind; 3096 break; 3097 } 3098 } 3099 return AllocatorKindRes; 3100 } 3101 3102 static bool checkPreviousOMPAllocateAttribute( 3103 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD, 3104 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) { 3105 if (!VD->hasAttr<OMPAllocateDeclAttr>()) 3106 return false; 3107 const auto *A = VD->getAttr<OMPAllocateDeclAttr>(); 3108 Expr *PrevAllocator = A->getAllocator(); 3109 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind = 3110 getAllocatorKind(S, Stack, PrevAllocator); 3111 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind; 3112 if (AllocatorsMatch && 3113 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc && 3114 Allocator && PrevAllocator) { 3115 const Expr *AE = Allocator->IgnoreParenImpCasts(); 3116 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts(); 3117 llvm::FoldingSetNodeID AEId, PAEId; 3118 AE->Profile(AEId, S.Context, /*Canonical=*/true); 3119 PAE->Profile(PAEId, S.Context, /*Canonical=*/true); 3120 AllocatorsMatch = AEId == PAEId; 3121 } 3122 if (!AllocatorsMatch) { 3123 SmallString<256> AllocatorBuffer; 3124 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer); 3125 if (Allocator) 3126 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy()); 3127 SmallString<256> PrevAllocatorBuffer; 3128 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer); 3129 if (PrevAllocator) 3130 PrevAllocator->printPretty(PrevAllocatorStream, nullptr, 3131 S.getPrintingPolicy()); 3132 3133 SourceLocation AllocatorLoc = 3134 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc(); 3135 SourceRange AllocatorRange = 3136 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange(); 3137 SourceLocation PrevAllocatorLoc = 3138 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation(); 3139 SourceRange PrevAllocatorRange = 3140 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange(); 3141 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator) 3142 << (Allocator ? 1 : 0) << AllocatorStream.str() 3143 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str() 3144 << AllocatorRange; 3145 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator) 3146 << PrevAllocatorRange; 3147 return true; 3148 } 3149 return false; 3150 } 3151 3152 static void 3153 applyOMPAllocateAttribute(Sema &S, VarDecl *VD, 3154 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, 3155 Expr *Allocator, Expr *Alignment, SourceRange SR) { 3156 if (VD->hasAttr<OMPAllocateDeclAttr>()) 3157 return; 3158 if (Alignment && 3159 (Alignment->isTypeDependent() || Alignment->isValueDependent() || 3160 Alignment->isInstantiationDependent() || 3161 Alignment->containsUnexpandedParameterPack())) 3162 // Apply later when we have a usable value. 3163 return; 3164 if (Allocator && 3165 (Allocator->isTypeDependent() || Allocator->isValueDependent() || 3166 Allocator->isInstantiationDependent() || 3167 Allocator->containsUnexpandedParameterPack())) 3168 return; 3169 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind, 3170 Allocator, Alignment, SR); 3171 VD->addAttr(A); 3172 if (ASTMutationListener *ML = S.Context.getASTMutationListener()) 3173 ML->DeclarationMarkedOpenMPAllocate(VD, A); 3174 } 3175 3176 Sema::DeclGroupPtrTy 3177 Sema::ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList, 3178 ArrayRef<OMPClause *> Clauses, 3179 DeclContext *Owner) { 3180 assert(Clauses.size() <= 2 && "Expected at most two clauses."); 3181 Expr *Alignment = nullptr; 3182 Expr *Allocator = nullptr; 3183 if (Clauses.empty()) { 3184 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions. 3185 // allocate directives that appear in a target region must specify an 3186 // allocator clause unless a requires directive with the dynamic_allocators 3187 // clause is present in the same compilation unit. 3188 if (LangOpts.OpenMPIsDevice && 3189 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>()) 3190 targetDiag(Loc, diag::err_expected_allocator_clause); 3191 } else { 3192 for (const OMPClause *C : Clauses) 3193 if (const auto *AC = dyn_cast<OMPAllocatorClause>(C)) 3194 Allocator = AC->getAllocator(); 3195 else if (const auto *AC = dyn_cast<OMPAlignClause>(C)) 3196 Alignment = AC->getAlignment(); 3197 else 3198 llvm_unreachable("Unexpected clause on allocate directive"); 3199 } 3200 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind = 3201 getAllocatorKind(*this, DSAStack, Allocator); 3202 SmallVector<Expr *, 8> Vars; 3203 for (Expr *RefExpr : VarList) { 3204 auto *DE = cast<DeclRefExpr>(RefExpr); 3205 auto *VD = cast<VarDecl>(DE->getDecl()); 3206 3207 // Check if this is a TLS variable or global register. 3208 if (VD->getTLSKind() != VarDecl::TLS_None || 3209 VD->hasAttr<OMPThreadPrivateDeclAttr>() || 3210 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 3211 !VD->isLocalVarDecl())) 3212 continue; 3213 3214 // If the used several times in the allocate directive, the same allocator 3215 // must be used. 3216 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD, 3217 AllocatorKind, Allocator)) 3218 continue; 3219 3220 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++ 3221 // If a list item has a static storage type, the allocator expression in the 3222 // allocator clause must be a constant expression that evaluates to one of 3223 // the predefined memory allocator values. 3224 if (Allocator && VD->hasGlobalStorage()) { 3225 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) { 3226 Diag(Allocator->getExprLoc(), 3227 diag::err_omp_expected_predefined_allocator) 3228 << Allocator->getSourceRange(); 3229 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 3230 VarDecl::DeclarationOnly; 3231 Diag(VD->getLocation(), 3232 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 3233 << VD; 3234 continue; 3235 } 3236 } 3237 3238 Vars.push_back(RefExpr); 3239 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator, Alignment, 3240 DE->getSourceRange()); 3241 } 3242 if (Vars.empty()) 3243 return nullptr; 3244 if (!Owner) 3245 Owner = getCurLexicalContext(); 3246 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses); 3247 D->setAccess(AS_public); 3248 Owner->addDecl(D); 3249 return DeclGroupPtrTy::make(DeclGroupRef(D)); 3250 } 3251 3252 Sema::DeclGroupPtrTy 3253 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc, 3254 ArrayRef<OMPClause *> ClauseList) { 3255 OMPRequiresDecl *D = nullptr; 3256 if (!CurContext->isFileContext()) { 3257 Diag(Loc, diag::err_omp_invalid_scope) << "requires"; 3258 } else { 3259 D = CheckOMPRequiresDecl(Loc, ClauseList); 3260 if (D) { 3261 CurContext->addDecl(D); 3262 DSAStack->addRequiresDecl(D); 3263 } 3264 } 3265 return DeclGroupPtrTy::make(DeclGroupRef(D)); 3266 } 3267 3268 void Sema::ActOnOpenMPAssumesDirective(SourceLocation Loc, 3269 OpenMPDirectiveKind DKind, 3270 ArrayRef<std::string> Assumptions, 3271 bool SkippedClauses) { 3272 if (!SkippedClauses && Assumptions.empty()) 3273 Diag(Loc, diag::err_omp_no_clause_for_directive) 3274 << llvm::omp::getAllAssumeClauseOptions() 3275 << llvm::omp::getOpenMPDirectiveName(DKind); 3276 3277 auto *AA = AssumptionAttr::Create(Context, llvm::join(Assumptions, ","), Loc); 3278 if (DKind == llvm::omp::Directive::OMPD_begin_assumes) { 3279 OMPAssumeScoped.push_back(AA); 3280 return; 3281 } 3282 3283 // Global assumes without assumption clauses are ignored. 3284 if (Assumptions.empty()) 3285 return; 3286 3287 assert(DKind == llvm::omp::Directive::OMPD_assumes && 3288 "Unexpected omp assumption directive!"); 3289 OMPAssumeGlobal.push_back(AA); 3290 3291 // The OMPAssumeGlobal scope above will take care of new declarations but 3292 // we also want to apply the assumption to existing ones, e.g., to 3293 // declarations in included headers. To this end, we traverse all existing 3294 // declaration contexts and annotate function declarations here. 3295 SmallVector<DeclContext *, 8> DeclContexts; 3296 auto *Ctx = CurContext; 3297 while (Ctx->getLexicalParent()) 3298 Ctx = Ctx->getLexicalParent(); 3299 DeclContexts.push_back(Ctx); 3300 while (!DeclContexts.empty()) { 3301 DeclContext *DC = DeclContexts.pop_back_val(); 3302 for (auto *SubDC : DC->decls()) { 3303 if (SubDC->isInvalidDecl()) 3304 continue; 3305 if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) { 3306 DeclContexts.push_back(CTD->getTemplatedDecl()); 3307 llvm::append_range(DeclContexts, CTD->specializations()); 3308 continue; 3309 } 3310 if (auto *DC = dyn_cast<DeclContext>(SubDC)) 3311 DeclContexts.push_back(DC); 3312 if (auto *F = dyn_cast<FunctionDecl>(SubDC)) { 3313 F->addAttr(AA); 3314 continue; 3315 } 3316 } 3317 } 3318 } 3319 3320 void Sema::ActOnOpenMPEndAssumesDirective() { 3321 assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!"); 3322 OMPAssumeScoped.pop_back(); 3323 } 3324 3325 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc, 3326 ArrayRef<OMPClause *> ClauseList) { 3327 /// For target specific clauses, the requires directive cannot be 3328 /// specified after the handling of any of the target regions in the 3329 /// current compilation unit. 3330 ArrayRef<SourceLocation> TargetLocations = 3331 DSAStack->getEncounteredTargetLocs(); 3332 SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc(); 3333 if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) { 3334 for (const OMPClause *CNew : ClauseList) { 3335 // Check if any of the requires clauses affect target regions. 3336 if (isa<OMPUnifiedSharedMemoryClause>(CNew) || 3337 isa<OMPUnifiedAddressClause>(CNew) || 3338 isa<OMPReverseOffloadClause>(CNew) || 3339 isa<OMPDynamicAllocatorsClause>(CNew)) { 3340 Diag(Loc, diag::err_omp_directive_before_requires) 3341 << "target" << getOpenMPClauseName(CNew->getClauseKind()); 3342 for (SourceLocation TargetLoc : TargetLocations) { 3343 Diag(TargetLoc, diag::note_omp_requires_encountered_directive) 3344 << "target"; 3345 } 3346 } else if (!AtomicLoc.isInvalid() && 3347 isa<OMPAtomicDefaultMemOrderClause>(CNew)) { 3348 Diag(Loc, diag::err_omp_directive_before_requires) 3349 << "atomic" << getOpenMPClauseName(CNew->getClauseKind()); 3350 Diag(AtomicLoc, diag::note_omp_requires_encountered_directive) 3351 << "atomic"; 3352 } 3353 } 3354 } 3355 3356 if (!DSAStack->hasDuplicateRequiresClause(ClauseList)) 3357 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc, 3358 ClauseList); 3359 return nullptr; 3360 } 3361 3362 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 3363 const ValueDecl *D, 3364 const DSAStackTy::DSAVarData &DVar, 3365 bool IsLoopIterVar) { 3366 if (DVar.RefExpr) { 3367 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 3368 << getOpenMPClauseName(DVar.CKind); 3369 return; 3370 } 3371 enum { 3372 PDSA_StaticMemberShared, 3373 PDSA_StaticLocalVarShared, 3374 PDSA_LoopIterVarPrivate, 3375 PDSA_LoopIterVarLinear, 3376 PDSA_LoopIterVarLastprivate, 3377 PDSA_ConstVarShared, 3378 PDSA_GlobalVarShared, 3379 PDSA_TaskVarFirstprivate, 3380 PDSA_LocalVarPrivate, 3381 PDSA_Implicit 3382 } Reason = PDSA_Implicit; 3383 bool ReportHint = false; 3384 auto ReportLoc = D->getLocation(); 3385 auto *VD = dyn_cast<VarDecl>(D); 3386 if (IsLoopIterVar) { 3387 if (DVar.CKind == OMPC_private) 3388 Reason = PDSA_LoopIterVarPrivate; 3389 else if (DVar.CKind == OMPC_lastprivate) 3390 Reason = PDSA_LoopIterVarLastprivate; 3391 else 3392 Reason = PDSA_LoopIterVarLinear; 3393 } else if (isOpenMPTaskingDirective(DVar.DKind) && 3394 DVar.CKind == OMPC_firstprivate) { 3395 Reason = PDSA_TaskVarFirstprivate; 3396 ReportLoc = DVar.ImplicitDSALoc; 3397 } else if (VD && VD->isStaticLocal()) 3398 Reason = PDSA_StaticLocalVarShared; 3399 else if (VD && VD->isStaticDataMember()) 3400 Reason = PDSA_StaticMemberShared; 3401 else if (VD && VD->isFileVarDecl()) 3402 Reason = PDSA_GlobalVarShared; 3403 else if (D->getType().isConstant(SemaRef.getASTContext())) 3404 Reason = PDSA_ConstVarShared; 3405 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 3406 ReportHint = true; 3407 Reason = PDSA_LocalVarPrivate; 3408 } 3409 if (Reason != PDSA_Implicit) { 3410 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 3411 << Reason << ReportHint 3412 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 3413 } else if (DVar.ImplicitDSALoc.isValid()) { 3414 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 3415 << getOpenMPClauseName(DVar.CKind); 3416 } 3417 } 3418 3419 static OpenMPMapClauseKind 3420 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M, 3421 bool IsAggregateOrDeclareTarget) { 3422 OpenMPMapClauseKind Kind = OMPC_MAP_unknown; 3423 switch (M) { 3424 case OMPC_DEFAULTMAP_MODIFIER_alloc: 3425 Kind = OMPC_MAP_alloc; 3426 break; 3427 case OMPC_DEFAULTMAP_MODIFIER_to: 3428 Kind = OMPC_MAP_to; 3429 break; 3430 case OMPC_DEFAULTMAP_MODIFIER_from: 3431 Kind = OMPC_MAP_from; 3432 break; 3433 case OMPC_DEFAULTMAP_MODIFIER_tofrom: 3434 Kind = OMPC_MAP_tofrom; 3435 break; 3436 case OMPC_DEFAULTMAP_MODIFIER_present: 3437 // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description] 3438 // If implicit-behavior is present, each variable referenced in the 3439 // construct in the category specified by variable-category is treated as if 3440 // it had been listed in a map clause with the map-type of alloc and 3441 // map-type-modifier of present. 3442 Kind = OMPC_MAP_alloc; 3443 break; 3444 case OMPC_DEFAULTMAP_MODIFIER_firstprivate: 3445 case OMPC_DEFAULTMAP_MODIFIER_last: 3446 llvm_unreachable("Unexpected defaultmap implicit behavior"); 3447 case OMPC_DEFAULTMAP_MODIFIER_none: 3448 case OMPC_DEFAULTMAP_MODIFIER_default: 3449 case OMPC_DEFAULTMAP_MODIFIER_unknown: 3450 // IsAggregateOrDeclareTarget could be true if: 3451 // 1. the implicit behavior for aggregate is tofrom 3452 // 2. it's a declare target link 3453 if (IsAggregateOrDeclareTarget) { 3454 Kind = OMPC_MAP_tofrom; 3455 break; 3456 } 3457 llvm_unreachable("Unexpected defaultmap implicit behavior"); 3458 } 3459 assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known"); 3460 return Kind; 3461 } 3462 3463 namespace { 3464 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> { 3465 DSAStackTy *Stack; 3466 Sema &SemaRef; 3467 bool ErrorFound = false; 3468 bool TryCaptureCXXThisMembers = false; 3469 CapturedStmt *CS = nullptr; 3470 const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1; 3471 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate; 3472 llvm::SmallVector<Expr *, 4> ImplicitPrivate; 3473 llvm::SmallVector<Expr *, 4> ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete]; 3474 llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> 3475 ImplicitMapModifier[DefaultmapKindNum]; 3476 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA; 3477 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations; 3478 3479 void VisitSubCaptures(OMPExecutableDirective *S) { 3480 // Check implicitly captured variables. 3481 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt()) 3482 return; 3483 if (S->getDirectiveKind() == OMPD_atomic || 3484 S->getDirectiveKind() == OMPD_critical || 3485 S->getDirectiveKind() == OMPD_section || 3486 S->getDirectiveKind() == OMPD_master || 3487 S->getDirectiveKind() == OMPD_masked || 3488 isOpenMPLoopTransformationDirective(S->getDirectiveKind())) { 3489 Visit(S->getAssociatedStmt()); 3490 return; 3491 } 3492 visitSubCaptures(S->getInnermostCapturedStmt()); 3493 // Try to capture inner this->member references to generate correct mappings 3494 // and diagnostics. 3495 if (TryCaptureCXXThisMembers || 3496 (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 3497 llvm::any_of(S->getInnermostCapturedStmt()->captures(), 3498 [](const CapturedStmt::Capture &C) { 3499 return C.capturesThis(); 3500 }))) { 3501 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers; 3502 TryCaptureCXXThisMembers = true; 3503 Visit(S->getInnermostCapturedStmt()->getCapturedStmt()); 3504 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers; 3505 } 3506 // In tasks firstprivates are not captured anymore, need to analyze them 3507 // explicitly. 3508 if (isOpenMPTaskingDirective(S->getDirectiveKind()) && 3509 !isOpenMPTaskLoopDirective(S->getDirectiveKind())) { 3510 for (OMPClause *C : S->clauses()) 3511 if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) { 3512 for (Expr *Ref : FC->varlists()) 3513 Visit(Ref); 3514 } 3515 } 3516 } 3517 3518 public: 3519 void VisitDeclRefExpr(DeclRefExpr *E) { 3520 if (TryCaptureCXXThisMembers || E->isTypeDependent() || 3521 E->isValueDependent() || E->containsUnexpandedParameterPack() || 3522 E->isInstantiationDependent()) 3523 return; 3524 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 3525 // Check the datasharing rules for the expressions in the clauses. 3526 if (!CS || (isa<OMPCapturedExprDecl>(VD) && !CS->capturesVariable(VD) && 3527 !Stack->getTopDSA(VD, /*FromParent=*/false).RefExpr)) { 3528 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD)) 3529 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) { 3530 Visit(CED->getInit()); 3531 return; 3532 } 3533 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD)) 3534 // Do not analyze internal variables and do not enclose them into 3535 // implicit clauses. 3536 return; 3537 VD = VD->getCanonicalDecl(); 3538 // Skip internally declared variables. 3539 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) && 3540 !Stack->isImplicitTaskFirstprivate(VD)) 3541 return; 3542 // Skip allocators in uses_allocators clauses. 3543 if (Stack->isUsesAllocatorsDecl(VD)) 3544 return; 3545 3546 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 3547 // Check if the variable has explicit DSA set and stop analysis if it so. 3548 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second) 3549 return; 3550 3551 // Skip internally declared static variables. 3552 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 3553 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 3554 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) && 3555 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || 3556 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) && 3557 !Stack->isImplicitTaskFirstprivate(VD)) 3558 return; 3559 3560 SourceLocation ELoc = E->getExprLoc(); 3561 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 3562 // The default(none) clause requires that each variable that is referenced 3563 // in the construct, and does not have a predetermined data-sharing 3564 // attribute, must have its data-sharing attribute explicitly determined 3565 // by being listed in a data-sharing attribute clause. 3566 if (DVar.CKind == OMPC_unknown && 3567 (Stack->getDefaultDSA() == DSA_none || 3568 Stack->getDefaultDSA() == DSA_private || 3569 Stack->getDefaultDSA() == DSA_firstprivate) && 3570 isImplicitOrExplicitTaskingRegion(DKind) && 3571 VarsWithInheritedDSA.count(VD) == 0) { 3572 bool InheritedDSA = Stack->getDefaultDSA() == DSA_none; 3573 if (!InheritedDSA && (Stack->getDefaultDSA() == DSA_firstprivate || 3574 Stack->getDefaultDSA() == DSA_private)) { 3575 DSAStackTy::DSAVarData DVar = 3576 Stack->getImplicitDSA(VD, /*FromParent=*/false); 3577 InheritedDSA = DVar.CKind == OMPC_unknown; 3578 } 3579 if (InheritedDSA) 3580 VarsWithInheritedDSA[VD] = E; 3581 if (Stack->getDefaultDSA() == DSA_none) 3582 return; 3583 } 3584 3585 // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description] 3586 // If implicit-behavior is none, each variable referenced in the 3587 // construct that does not have a predetermined data-sharing attribute 3588 // and does not appear in a to or link clause on a declare target 3589 // directive must be listed in a data-mapping attribute clause, a 3590 // data-sharing attribute clause (including a data-sharing attribute 3591 // clause on a combined construct where target. is one of the 3592 // constituent constructs), or an is_device_ptr clause. 3593 OpenMPDefaultmapClauseKind ClauseKind = 3594 getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD); 3595 if (SemaRef.getLangOpts().OpenMP >= 50) { 3596 bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) == 3597 OMPC_DEFAULTMAP_MODIFIER_none; 3598 if (DVar.CKind == OMPC_unknown && IsModifierNone && 3599 VarsWithInheritedDSA.count(VD) == 0 && !Res) { 3600 // Only check for data-mapping attribute and is_device_ptr here 3601 // since we have already make sure that the declaration does not 3602 // have a data-sharing attribute above 3603 if (!Stack->checkMappableExprComponentListsForDecl( 3604 VD, /*CurrentRegionOnly=*/true, 3605 [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef 3606 MapExprComponents, 3607 OpenMPClauseKind) { 3608 auto MI = MapExprComponents.rbegin(); 3609 auto ME = MapExprComponents.rend(); 3610 return MI != ME && MI->getAssociatedDeclaration() == VD; 3611 })) { 3612 VarsWithInheritedDSA[VD] = E; 3613 return; 3614 } 3615 } 3616 } 3617 if (SemaRef.getLangOpts().OpenMP > 50) { 3618 bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) == 3619 OMPC_DEFAULTMAP_MODIFIER_present; 3620 if (IsModifierPresent) { 3621 if (llvm::find(ImplicitMapModifier[ClauseKind], 3622 OMPC_MAP_MODIFIER_present) == 3623 std::end(ImplicitMapModifier[ClauseKind])) { 3624 ImplicitMapModifier[ClauseKind].push_back( 3625 OMPC_MAP_MODIFIER_present); 3626 } 3627 } 3628 } 3629 3630 if (isOpenMPTargetExecutionDirective(DKind) && 3631 !Stack->isLoopControlVariable(VD).first) { 3632 if (!Stack->checkMappableExprComponentListsForDecl( 3633 VD, /*CurrentRegionOnly=*/true, 3634 [this](OMPClauseMappableExprCommon::MappableExprComponentListRef 3635 StackComponents, 3636 OpenMPClauseKind) { 3637 if (SemaRef.LangOpts.OpenMP >= 50) 3638 return !StackComponents.empty(); 3639 // Variable is used if it has been marked as an array, array 3640 // section, array shaping or the variable iself. 3641 return StackComponents.size() == 1 || 3642 std::all_of( 3643 std::next(StackComponents.rbegin()), 3644 StackComponents.rend(), 3645 [](const OMPClauseMappableExprCommon:: 3646 MappableComponent &MC) { 3647 return MC.getAssociatedDeclaration() == 3648 nullptr && 3649 (isa<OMPArraySectionExpr>( 3650 MC.getAssociatedExpression()) || 3651 isa<OMPArrayShapingExpr>( 3652 MC.getAssociatedExpression()) || 3653 isa<ArraySubscriptExpr>( 3654 MC.getAssociatedExpression())); 3655 }); 3656 })) { 3657 bool IsFirstprivate = false; 3658 // By default lambdas are captured as firstprivates. 3659 if (const auto *RD = 3660 VD->getType().getNonReferenceType()->getAsCXXRecordDecl()) 3661 IsFirstprivate = RD->isLambda(); 3662 IsFirstprivate = 3663 IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res); 3664 if (IsFirstprivate) { 3665 ImplicitFirstprivate.emplace_back(E); 3666 } else { 3667 OpenMPDefaultmapClauseModifier M = 3668 Stack->getDefaultmapModifier(ClauseKind); 3669 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier( 3670 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res); 3671 ImplicitMap[ClauseKind][Kind].emplace_back(E); 3672 } 3673 return; 3674 } 3675 } 3676 3677 // OpenMP [2.9.3.6, Restrictions, p.2] 3678 // A list item that appears in a reduction clause of the innermost 3679 // enclosing worksharing or parallel construct may not be accessed in an 3680 // explicit task. 3681 DVar = Stack->hasInnermostDSA( 3682 VD, 3683 [](OpenMPClauseKind C, bool AppliedToPointee) { 3684 return C == OMPC_reduction && !AppliedToPointee; 3685 }, 3686 [](OpenMPDirectiveKind K) { 3687 return isOpenMPParallelDirective(K) || 3688 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 3689 }, 3690 /*FromParent=*/true); 3691 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 3692 ErrorFound = true; 3693 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 3694 reportOriginalDsa(SemaRef, Stack, VD, DVar); 3695 return; 3696 } 3697 3698 // Define implicit data-sharing attributes for task. 3699 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false); 3700 if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) || 3701 (((Stack->getDefaultDSA() == DSA_firstprivate && 3702 DVar.CKind == OMPC_firstprivate) || 3703 (Stack->getDefaultDSA() == DSA_private && 3704 DVar.CKind == OMPC_private)) && 3705 !DVar.RefExpr)) && 3706 !Stack->isLoopControlVariable(VD).first) { 3707 if (Stack->getDefaultDSA() == DSA_private) 3708 ImplicitPrivate.push_back(E); 3709 else 3710 ImplicitFirstprivate.push_back(E); 3711 return; 3712 } 3713 3714 // Store implicitly used globals with declare target link for parent 3715 // target. 3716 if (!isOpenMPTargetExecutionDirective(DKind) && Res && 3717 *Res == OMPDeclareTargetDeclAttr::MT_Link) { 3718 Stack->addToParentTargetRegionLinkGlobals(E); 3719 return; 3720 } 3721 } 3722 } 3723 void VisitMemberExpr(MemberExpr *E) { 3724 if (E->isTypeDependent() || E->isValueDependent() || 3725 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 3726 return; 3727 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 3728 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 3729 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) { 3730 if (!FD) 3731 return; 3732 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false); 3733 // Check if the variable has explicit DSA set and stop analysis if it 3734 // so. 3735 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second) 3736 return; 3737 3738 if (isOpenMPTargetExecutionDirective(DKind) && 3739 !Stack->isLoopControlVariable(FD).first && 3740 !Stack->checkMappableExprComponentListsForDecl( 3741 FD, /*CurrentRegionOnly=*/true, 3742 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 3743 StackComponents, 3744 OpenMPClauseKind) { 3745 return isa<CXXThisExpr>( 3746 cast<MemberExpr>( 3747 StackComponents.back().getAssociatedExpression()) 3748 ->getBase() 3749 ->IgnoreParens()); 3750 })) { 3751 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 3752 // A bit-field cannot appear in a map clause. 3753 // 3754 if (FD->isBitField()) 3755 return; 3756 3757 // Check to see if the member expression is referencing a class that 3758 // has already been explicitly mapped 3759 if (Stack->isClassPreviouslyMapped(TE->getType())) 3760 return; 3761 3762 OpenMPDefaultmapClauseModifier Modifier = 3763 Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate); 3764 OpenMPDefaultmapClauseKind ClauseKind = 3765 getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD); 3766 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier( 3767 Modifier, /*IsAggregateOrDeclareTarget*/ true); 3768 ImplicitMap[ClauseKind][Kind].emplace_back(E); 3769 return; 3770 } 3771 3772 SourceLocation ELoc = E->getExprLoc(); 3773 // OpenMP [2.9.3.6, Restrictions, p.2] 3774 // A list item that appears in a reduction clause of the innermost 3775 // enclosing worksharing or parallel construct may not be accessed in 3776 // an explicit task. 3777 DVar = Stack->hasInnermostDSA( 3778 FD, 3779 [](OpenMPClauseKind C, bool AppliedToPointee) { 3780 return C == OMPC_reduction && !AppliedToPointee; 3781 }, 3782 [](OpenMPDirectiveKind K) { 3783 return isOpenMPParallelDirective(K) || 3784 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 3785 }, 3786 /*FromParent=*/true); 3787 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 3788 ErrorFound = true; 3789 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 3790 reportOriginalDsa(SemaRef, Stack, FD, DVar); 3791 return; 3792 } 3793 3794 // Define implicit data-sharing attributes for task. 3795 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false); 3796 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 3797 !Stack->isLoopControlVariable(FD).first) { 3798 // Check if there is a captured expression for the current field in the 3799 // region. Do not mark it as firstprivate unless there is no captured 3800 // expression. 3801 // TODO: try to make it firstprivate. 3802 if (DVar.CKind != OMPC_unknown) 3803 ImplicitFirstprivate.push_back(E); 3804 } 3805 return; 3806 } 3807 if (isOpenMPTargetExecutionDirective(DKind)) { 3808 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 3809 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map, 3810 Stack->getCurrentDirective(), 3811 /*NoDiagnose=*/true)) 3812 return; 3813 const auto *VD = cast<ValueDecl>( 3814 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl()); 3815 if (!Stack->checkMappableExprComponentListsForDecl( 3816 VD, /*CurrentRegionOnly=*/true, 3817 [&CurComponents]( 3818 OMPClauseMappableExprCommon::MappableExprComponentListRef 3819 StackComponents, 3820 OpenMPClauseKind) { 3821 auto CCI = CurComponents.rbegin(); 3822 auto CCE = CurComponents.rend(); 3823 for (const auto &SC : llvm::reverse(StackComponents)) { 3824 // Do both expressions have the same kind? 3825 if (CCI->getAssociatedExpression()->getStmtClass() != 3826 SC.getAssociatedExpression()->getStmtClass()) 3827 if (!((isa<OMPArraySectionExpr>( 3828 SC.getAssociatedExpression()) || 3829 isa<OMPArrayShapingExpr>( 3830 SC.getAssociatedExpression())) && 3831 isa<ArraySubscriptExpr>( 3832 CCI->getAssociatedExpression()))) 3833 return false; 3834 3835 const Decl *CCD = CCI->getAssociatedDeclaration(); 3836 const Decl *SCD = SC.getAssociatedDeclaration(); 3837 CCD = CCD ? CCD->getCanonicalDecl() : nullptr; 3838 SCD = SCD ? SCD->getCanonicalDecl() : nullptr; 3839 if (SCD != CCD) 3840 return false; 3841 std::advance(CCI, 1); 3842 if (CCI == CCE) 3843 break; 3844 } 3845 return true; 3846 })) { 3847 Visit(E->getBase()); 3848 } 3849 } else if (!TryCaptureCXXThisMembers) { 3850 Visit(E->getBase()); 3851 } 3852 } 3853 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 3854 for (OMPClause *C : S->clauses()) { 3855 // Skip analysis of arguments of private clauses for task|target 3856 // directives. 3857 if (isa_and_nonnull<OMPPrivateClause>(C)) 3858 continue; 3859 // Skip analysis of arguments of implicitly defined firstprivate clause 3860 // for task|target directives. 3861 // Skip analysis of arguments of implicitly defined map clause for target 3862 // directives. 3863 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) && 3864 C->isImplicit() && 3865 !isOpenMPTaskingDirective(Stack->getCurrentDirective()))) { 3866 for (Stmt *CC : C->children()) { 3867 if (CC) 3868 Visit(CC); 3869 } 3870 } 3871 } 3872 // Check implicitly captured variables. 3873 VisitSubCaptures(S); 3874 } 3875 3876 void VisitOMPLoopTransformationDirective(OMPLoopTransformationDirective *S) { 3877 // Loop transformation directives do not introduce data sharing 3878 VisitStmt(S); 3879 } 3880 3881 void VisitCallExpr(CallExpr *S) { 3882 for (Stmt *C : S->arguments()) { 3883 if (C) { 3884 // Check implicitly captured variables in the task-based directives to 3885 // check if they must be firstprivatized. 3886 Visit(C); 3887 } 3888 } 3889 if (Expr *Callee = S->getCallee()) 3890 if (auto *CE = dyn_cast<MemberExpr>(Callee->IgnoreParenImpCasts())) 3891 Visit(CE->getBase()); 3892 } 3893 void VisitStmt(Stmt *S) { 3894 for (Stmt *C : S->children()) { 3895 if (C) { 3896 // Check implicitly captured variables in the task-based directives to 3897 // check if they must be firstprivatized. 3898 Visit(C); 3899 } 3900 } 3901 } 3902 3903 void visitSubCaptures(CapturedStmt *S) { 3904 for (const CapturedStmt::Capture &Cap : S->captures()) { 3905 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy()) 3906 continue; 3907 VarDecl *VD = Cap.getCapturedVar(); 3908 // Do not try to map the variable if it or its sub-component was mapped 3909 // already. 3910 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 3911 Stack->checkMappableExprComponentListsForDecl( 3912 VD, /*CurrentRegionOnly=*/true, 3913 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 3914 OpenMPClauseKind) { return true; })) 3915 continue; 3916 DeclRefExpr *DRE = buildDeclRefExpr( 3917 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context), 3918 Cap.getLocation(), /*RefersToCapture=*/true); 3919 Visit(DRE); 3920 } 3921 } 3922 bool isErrorFound() const { return ErrorFound; } 3923 ArrayRef<Expr *> getImplicitFirstprivate() const { 3924 return ImplicitFirstprivate; 3925 } 3926 ArrayRef<Expr *> getImplicitPrivate() const { return ImplicitPrivate; } 3927 ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind DK, 3928 OpenMPMapClauseKind MK) const { 3929 return ImplicitMap[DK][MK]; 3930 } 3931 ArrayRef<OpenMPMapModifierKind> 3932 getImplicitMapModifier(OpenMPDefaultmapClauseKind Kind) const { 3933 return ImplicitMapModifier[Kind]; 3934 } 3935 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const { 3936 return VarsWithInheritedDSA; 3937 } 3938 3939 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 3940 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) { 3941 // Process declare target link variables for the target directives. 3942 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) { 3943 for (DeclRefExpr *E : Stack->getLinkGlobals()) 3944 Visit(E); 3945 } 3946 } 3947 }; 3948 } // namespace 3949 3950 static void handleDeclareVariantConstructTrait(DSAStackTy *Stack, 3951 OpenMPDirectiveKind DKind, 3952 bool ScopeEntry) { 3953 SmallVector<llvm::omp::TraitProperty, 8> Traits; 3954 if (isOpenMPTargetExecutionDirective(DKind)) 3955 Traits.emplace_back(llvm::omp::TraitProperty::construct_target_target); 3956 if (isOpenMPTeamsDirective(DKind)) 3957 Traits.emplace_back(llvm::omp::TraitProperty::construct_teams_teams); 3958 if (isOpenMPParallelDirective(DKind)) 3959 Traits.emplace_back(llvm::omp::TraitProperty::construct_parallel_parallel); 3960 if (isOpenMPWorksharingDirective(DKind)) 3961 Traits.emplace_back(llvm::omp::TraitProperty::construct_for_for); 3962 if (isOpenMPSimdDirective(DKind)) 3963 Traits.emplace_back(llvm::omp::TraitProperty::construct_simd_simd); 3964 Stack->handleConstructTrait(Traits, ScopeEntry); 3965 } 3966 3967 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 3968 switch (DKind) { 3969 case OMPD_parallel: 3970 case OMPD_parallel_for: 3971 case OMPD_parallel_for_simd: 3972 case OMPD_parallel_sections: 3973 case OMPD_parallel_master: 3974 case OMPD_parallel_masked: 3975 case OMPD_parallel_loop: 3976 case OMPD_teams: 3977 case OMPD_teams_distribute: 3978 case OMPD_teams_distribute_simd: { 3979 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3980 QualType KmpInt32PtrTy = 3981 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3982 Sema::CapturedParamNameType Params[] = { 3983 std::make_pair(".global_tid.", KmpInt32PtrTy), 3984 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3985 std::make_pair(StringRef(), QualType()) // __context with shared vars 3986 }; 3987 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3988 Params); 3989 break; 3990 } 3991 case OMPD_target_teams: 3992 case OMPD_target_parallel: 3993 case OMPD_target_parallel_for: 3994 case OMPD_target_parallel_for_simd: 3995 case OMPD_target_teams_loop: 3996 case OMPD_target_parallel_loop: 3997 case OMPD_target_teams_distribute: 3998 case OMPD_target_teams_distribute_simd: { 3999 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4000 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4001 QualType KmpInt32PtrTy = 4002 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4003 QualType Args[] = {VoidPtrTy}; 4004 FunctionProtoType::ExtProtoInfo EPI; 4005 EPI.Variadic = true; 4006 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4007 Sema::CapturedParamNameType Params[] = { 4008 std::make_pair(".global_tid.", KmpInt32Ty), 4009 std::make_pair(".part_id.", KmpInt32PtrTy), 4010 std::make_pair(".privates.", VoidPtrTy), 4011 std::make_pair( 4012 ".copy_fn.", 4013 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4014 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4015 std::make_pair(StringRef(), QualType()) // __context with shared vars 4016 }; 4017 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4018 Params, /*OpenMPCaptureLevel=*/0); 4019 // Mark this captured region as inlined, because we don't use outlined 4020 // function directly. 4021 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4022 AlwaysInlineAttr::CreateImplicit( 4023 Context, {}, AttributeCommonInfo::AS_Keyword, 4024 AlwaysInlineAttr::Keyword_forceinline)); 4025 Sema::CapturedParamNameType ParamsTarget[] = { 4026 std::make_pair(StringRef(), QualType()) // __context with shared vars 4027 }; 4028 // Start a captured region for 'target' with no implicit parameters. 4029 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4030 ParamsTarget, /*OpenMPCaptureLevel=*/1); 4031 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 4032 std::make_pair(".global_tid.", KmpInt32PtrTy), 4033 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4034 std::make_pair(StringRef(), QualType()) // __context with shared vars 4035 }; 4036 // Start a captured region for 'teams' or 'parallel'. Both regions have 4037 // the same implicit parameters. 4038 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4039 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2); 4040 break; 4041 } 4042 case OMPD_target: 4043 case OMPD_target_simd: { 4044 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4045 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4046 QualType KmpInt32PtrTy = 4047 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4048 QualType Args[] = {VoidPtrTy}; 4049 FunctionProtoType::ExtProtoInfo EPI; 4050 EPI.Variadic = true; 4051 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4052 Sema::CapturedParamNameType Params[] = { 4053 std::make_pair(".global_tid.", KmpInt32Ty), 4054 std::make_pair(".part_id.", KmpInt32PtrTy), 4055 std::make_pair(".privates.", VoidPtrTy), 4056 std::make_pair( 4057 ".copy_fn.", 4058 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4059 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4060 std::make_pair(StringRef(), QualType()) // __context with shared vars 4061 }; 4062 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4063 Params, /*OpenMPCaptureLevel=*/0); 4064 // Mark this captured region as inlined, because we don't use outlined 4065 // function directly. 4066 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4067 AlwaysInlineAttr::CreateImplicit( 4068 Context, {}, AttributeCommonInfo::AS_Keyword, 4069 AlwaysInlineAttr::Keyword_forceinline)); 4070 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4071 std::make_pair(StringRef(), QualType()), 4072 /*OpenMPCaptureLevel=*/1); 4073 break; 4074 } 4075 case OMPD_atomic: 4076 case OMPD_critical: 4077 case OMPD_section: 4078 case OMPD_master: 4079 case OMPD_masked: 4080 case OMPD_tile: 4081 case OMPD_unroll: 4082 break; 4083 case OMPD_loop: 4084 // TODO: 'loop' may require additional parameters depending on the binding. 4085 // Treat similar to OMPD_simd/OMPD_for for now. 4086 case OMPD_simd: 4087 case OMPD_for: 4088 case OMPD_for_simd: 4089 case OMPD_sections: 4090 case OMPD_single: 4091 case OMPD_taskgroup: 4092 case OMPD_distribute: 4093 case OMPD_distribute_simd: 4094 case OMPD_ordered: 4095 case OMPD_target_data: 4096 case OMPD_dispatch: { 4097 Sema::CapturedParamNameType Params[] = { 4098 std::make_pair(StringRef(), QualType()) // __context with shared vars 4099 }; 4100 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4101 Params); 4102 break; 4103 } 4104 case OMPD_task: { 4105 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4106 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4107 QualType KmpInt32PtrTy = 4108 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4109 QualType Args[] = {VoidPtrTy}; 4110 FunctionProtoType::ExtProtoInfo EPI; 4111 EPI.Variadic = true; 4112 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4113 Sema::CapturedParamNameType Params[] = { 4114 std::make_pair(".global_tid.", KmpInt32Ty), 4115 std::make_pair(".part_id.", KmpInt32PtrTy), 4116 std::make_pair(".privates.", VoidPtrTy), 4117 std::make_pair( 4118 ".copy_fn.", 4119 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4120 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4121 std::make_pair(StringRef(), QualType()) // __context with shared vars 4122 }; 4123 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4124 Params); 4125 // Mark this captured region as inlined, because we don't use outlined 4126 // function directly. 4127 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4128 AlwaysInlineAttr::CreateImplicit( 4129 Context, {}, AttributeCommonInfo::AS_Keyword, 4130 AlwaysInlineAttr::Keyword_forceinline)); 4131 break; 4132 } 4133 case OMPD_taskloop: 4134 case OMPD_taskloop_simd: 4135 case OMPD_master_taskloop: 4136 case OMPD_master_taskloop_simd: { 4137 QualType KmpInt32Ty = 4138 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 4139 .withConst(); 4140 QualType KmpUInt64Ty = 4141 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 4142 .withConst(); 4143 QualType KmpInt64Ty = 4144 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 4145 .withConst(); 4146 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4147 QualType KmpInt32PtrTy = 4148 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4149 QualType Args[] = {VoidPtrTy}; 4150 FunctionProtoType::ExtProtoInfo EPI; 4151 EPI.Variadic = true; 4152 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4153 Sema::CapturedParamNameType Params[] = { 4154 std::make_pair(".global_tid.", KmpInt32Ty), 4155 std::make_pair(".part_id.", KmpInt32PtrTy), 4156 std::make_pair(".privates.", VoidPtrTy), 4157 std::make_pair( 4158 ".copy_fn.", 4159 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4160 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4161 std::make_pair(".lb.", KmpUInt64Ty), 4162 std::make_pair(".ub.", KmpUInt64Ty), 4163 std::make_pair(".st.", KmpInt64Ty), 4164 std::make_pair(".liter.", KmpInt32Ty), 4165 std::make_pair(".reductions.", VoidPtrTy), 4166 std::make_pair(StringRef(), QualType()) // __context with shared vars 4167 }; 4168 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4169 Params); 4170 // Mark this captured region as inlined, because we don't use outlined 4171 // function directly. 4172 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4173 AlwaysInlineAttr::CreateImplicit( 4174 Context, {}, AttributeCommonInfo::AS_Keyword, 4175 AlwaysInlineAttr::Keyword_forceinline)); 4176 break; 4177 } 4178 case OMPD_parallel_master_taskloop: 4179 case OMPD_parallel_master_taskloop_simd: { 4180 QualType KmpInt32Ty = 4181 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 4182 .withConst(); 4183 QualType KmpUInt64Ty = 4184 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 4185 .withConst(); 4186 QualType KmpInt64Ty = 4187 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 4188 .withConst(); 4189 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4190 QualType KmpInt32PtrTy = 4191 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4192 Sema::CapturedParamNameType ParamsParallel[] = { 4193 std::make_pair(".global_tid.", KmpInt32PtrTy), 4194 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4195 std::make_pair(StringRef(), QualType()) // __context with shared vars 4196 }; 4197 // Start a captured region for 'parallel'. 4198 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4199 ParamsParallel, /*OpenMPCaptureLevel=*/0); 4200 QualType Args[] = {VoidPtrTy}; 4201 FunctionProtoType::ExtProtoInfo EPI; 4202 EPI.Variadic = true; 4203 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4204 Sema::CapturedParamNameType Params[] = { 4205 std::make_pair(".global_tid.", KmpInt32Ty), 4206 std::make_pair(".part_id.", KmpInt32PtrTy), 4207 std::make_pair(".privates.", VoidPtrTy), 4208 std::make_pair( 4209 ".copy_fn.", 4210 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4211 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4212 std::make_pair(".lb.", KmpUInt64Ty), 4213 std::make_pair(".ub.", KmpUInt64Ty), 4214 std::make_pair(".st.", KmpInt64Ty), 4215 std::make_pair(".liter.", KmpInt32Ty), 4216 std::make_pair(".reductions.", VoidPtrTy), 4217 std::make_pair(StringRef(), QualType()) // __context with shared vars 4218 }; 4219 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4220 Params, /*OpenMPCaptureLevel=*/1); 4221 // Mark this captured region as inlined, because we don't use outlined 4222 // function directly. 4223 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4224 AlwaysInlineAttr::CreateImplicit( 4225 Context, {}, AttributeCommonInfo::AS_Keyword, 4226 AlwaysInlineAttr::Keyword_forceinline)); 4227 break; 4228 } 4229 case OMPD_distribute_parallel_for_simd: 4230 case OMPD_distribute_parallel_for: { 4231 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4232 QualType KmpInt32PtrTy = 4233 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4234 Sema::CapturedParamNameType Params[] = { 4235 std::make_pair(".global_tid.", KmpInt32PtrTy), 4236 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4237 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 4238 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 4239 std::make_pair(StringRef(), QualType()) // __context with shared vars 4240 }; 4241 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4242 Params); 4243 break; 4244 } 4245 case OMPD_target_teams_distribute_parallel_for: 4246 case OMPD_target_teams_distribute_parallel_for_simd: { 4247 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4248 QualType KmpInt32PtrTy = 4249 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4250 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4251 4252 QualType Args[] = {VoidPtrTy}; 4253 FunctionProtoType::ExtProtoInfo EPI; 4254 EPI.Variadic = true; 4255 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4256 Sema::CapturedParamNameType Params[] = { 4257 std::make_pair(".global_tid.", KmpInt32Ty), 4258 std::make_pair(".part_id.", KmpInt32PtrTy), 4259 std::make_pair(".privates.", VoidPtrTy), 4260 std::make_pair( 4261 ".copy_fn.", 4262 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4263 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4264 std::make_pair(StringRef(), QualType()) // __context with shared vars 4265 }; 4266 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4267 Params, /*OpenMPCaptureLevel=*/0); 4268 // Mark this captured region as inlined, because we don't use outlined 4269 // function directly. 4270 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4271 AlwaysInlineAttr::CreateImplicit( 4272 Context, {}, AttributeCommonInfo::AS_Keyword, 4273 AlwaysInlineAttr::Keyword_forceinline)); 4274 Sema::CapturedParamNameType ParamsTarget[] = { 4275 std::make_pair(StringRef(), QualType()) // __context with shared vars 4276 }; 4277 // Start a captured region for 'target' with no implicit parameters. 4278 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4279 ParamsTarget, /*OpenMPCaptureLevel=*/1); 4280 4281 Sema::CapturedParamNameType ParamsTeams[] = { 4282 std::make_pair(".global_tid.", KmpInt32PtrTy), 4283 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4284 std::make_pair(StringRef(), QualType()) // __context with shared vars 4285 }; 4286 // Start a captured region for 'target' with no implicit parameters. 4287 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4288 ParamsTeams, /*OpenMPCaptureLevel=*/2); 4289 4290 Sema::CapturedParamNameType ParamsParallel[] = { 4291 std::make_pair(".global_tid.", KmpInt32PtrTy), 4292 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4293 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 4294 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 4295 std::make_pair(StringRef(), QualType()) // __context with shared vars 4296 }; 4297 // Start a captured region for 'teams' or 'parallel'. Both regions have 4298 // the same implicit parameters. 4299 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4300 ParamsParallel, /*OpenMPCaptureLevel=*/3); 4301 break; 4302 } 4303 4304 case OMPD_teams_loop: { 4305 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4306 QualType KmpInt32PtrTy = 4307 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4308 4309 Sema::CapturedParamNameType ParamsTeams[] = { 4310 std::make_pair(".global_tid.", KmpInt32PtrTy), 4311 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4312 std::make_pair(StringRef(), QualType()) // __context with shared vars 4313 }; 4314 // Start a captured region for 'teams'. 4315 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4316 ParamsTeams, /*OpenMPCaptureLevel=*/0); 4317 break; 4318 } 4319 4320 case OMPD_teams_distribute_parallel_for: 4321 case OMPD_teams_distribute_parallel_for_simd: { 4322 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4323 QualType KmpInt32PtrTy = 4324 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4325 4326 Sema::CapturedParamNameType ParamsTeams[] = { 4327 std::make_pair(".global_tid.", KmpInt32PtrTy), 4328 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4329 std::make_pair(StringRef(), QualType()) // __context with shared vars 4330 }; 4331 // Start a captured region for 'target' with no implicit parameters. 4332 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4333 ParamsTeams, /*OpenMPCaptureLevel=*/0); 4334 4335 Sema::CapturedParamNameType ParamsParallel[] = { 4336 std::make_pair(".global_tid.", KmpInt32PtrTy), 4337 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4338 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 4339 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 4340 std::make_pair(StringRef(), QualType()) // __context with shared vars 4341 }; 4342 // Start a captured region for 'teams' or 'parallel'. Both regions have 4343 // the same implicit parameters. 4344 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4345 ParamsParallel, /*OpenMPCaptureLevel=*/1); 4346 break; 4347 } 4348 case OMPD_target_update: 4349 case OMPD_target_enter_data: 4350 case OMPD_target_exit_data: { 4351 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4352 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4353 QualType KmpInt32PtrTy = 4354 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4355 QualType Args[] = {VoidPtrTy}; 4356 FunctionProtoType::ExtProtoInfo EPI; 4357 EPI.Variadic = true; 4358 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4359 Sema::CapturedParamNameType Params[] = { 4360 std::make_pair(".global_tid.", KmpInt32Ty), 4361 std::make_pair(".part_id.", KmpInt32PtrTy), 4362 std::make_pair(".privates.", VoidPtrTy), 4363 std::make_pair( 4364 ".copy_fn.", 4365 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4366 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4367 std::make_pair(StringRef(), QualType()) // __context with shared vars 4368 }; 4369 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4370 Params); 4371 // Mark this captured region as inlined, because we don't use outlined 4372 // function directly. 4373 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4374 AlwaysInlineAttr::CreateImplicit( 4375 Context, {}, AttributeCommonInfo::AS_Keyword, 4376 AlwaysInlineAttr::Keyword_forceinline)); 4377 break; 4378 } 4379 case OMPD_threadprivate: 4380 case OMPD_allocate: 4381 case OMPD_taskyield: 4382 case OMPD_barrier: 4383 case OMPD_taskwait: 4384 case OMPD_cancellation_point: 4385 case OMPD_cancel: 4386 case OMPD_flush: 4387 case OMPD_depobj: 4388 case OMPD_scan: 4389 case OMPD_declare_reduction: 4390 case OMPD_declare_mapper: 4391 case OMPD_declare_simd: 4392 case OMPD_declare_target: 4393 case OMPD_end_declare_target: 4394 case OMPD_requires: 4395 case OMPD_declare_variant: 4396 case OMPD_begin_declare_variant: 4397 case OMPD_end_declare_variant: 4398 case OMPD_metadirective: 4399 llvm_unreachable("OpenMP Directive is not allowed"); 4400 case OMPD_unknown: 4401 default: 4402 llvm_unreachable("Unknown OpenMP directive"); 4403 } 4404 DSAStack->setContext(CurContext); 4405 handleDeclareVariantConstructTrait(DSAStack, DKind, /* ScopeEntry */ true); 4406 } 4407 4408 int Sema::getNumberOfConstructScopes(unsigned Level) const { 4409 return getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 4410 } 4411 4412 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 4413 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 4414 getOpenMPCaptureRegions(CaptureRegions, DKind); 4415 return CaptureRegions.size(); 4416 } 4417 4418 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 4419 Expr *CaptureExpr, bool WithInit, 4420 bool AsExpression) { 4421 assert(CaptureExpr); 4422 ASTContext &C = S.getASTContext(); 4423 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 4424 QualType Ty = Init->getType(); 4425 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 4426 if (S.getLangOpts().CPlusPlus) { 4427 Ty = C.getLValueReferenceType(Ty); 4428 } else { 4429 Ty = C.getPointerType(Ty); 4430 ExprResult Res = 4431 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 4432 if (!Res.isUsable()) 4433 return nullptr; 4434 Init = Res.get(); 4435 } 4436 WithInit = true; 4437 } 4438 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 4439 CaptureExpr->getBeginLoc()); 4440 if (!WithInit) 4441 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C)); 4442 S.CurContext->addHiddenDecl(CED); 4443 Sema::TentativeAnalysisScope Trap(S); 4444 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 4445 return CED; 4446 } 4447 4448 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 4449 bool WithInit) { 4450 OMPCapturedExprDecl *CD; 4451 if (VarDecl *VD = S.isOpenMPCapturedDecl(D)) 4452 CD = cast<OMPCapturedExprDecl>(VD); 4453 else 4454 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 4455 /*AsExpression=*/false); 4456 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 4457 CaptureExpr->getExprLoc()); 4458 } 4459 4460 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 4461 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get(); 4462 if (!Ref) { 4463 OMPCapturedExprDecl *CD = buildCaptureDecl( 4464 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr, 4465 /*WithInit=*/true, /*AsExpression=*/true); 4466 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 4467 CaptureExpr->getExprLoc()); 4468 } 4469 ExprResult Res = Ref; 4470 if (!S.getLangOpts().CPlusPlus && 4471 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 4472 Ref->getType()->isPointerType()) { 4473 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 4474 if (!Res.isUsable()) 4475 return ExprError(); 4476 } 4477 return S.DefaultLvalueConversion(Res.get()); 4478 } 4479 4480 namespace { 4481 // OpenMP directives parsed in this section are represented as a 4482 // CapturedStatement with an associated statement. If a syntax error 4483 // is detected during the parsing of the associated statement, the 4484 // compiler must abort processing and close the CapturedStatement. 4485 // 4486 // Combined directives such as 'target parallel' have more than one 4487 // nested CapturedStatements. This RAII ensures that we unwind out 4488 // of all the nested CapturedStatements when an error is found. 4489 class CaptureRegionUnwinderRAII { 4490 private: 4491 Sema &S; 4492 bool &ErrorFound; 4493 OpenMPDirectiveKind DKind = OMPD_unknown; 4494 4495 public: 4496 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 4497 OpenMPDirectiveKind DKind) 4498 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 4499 ~CaptureRegionUnwinderRAII() { 4500 if (ErrorFound) { 4501 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 4502 while (--ThisCaptureLevel >= 0) 4503 S.ActOnCapturedRegionError(); 4504 } 4505 } 4506 }; 4507 } // namespace 4508 4509 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) { 4510 // Capture variables captured by reference in lambdas for target-based 4511 // directives. 4512 if (!CurContext->isDependentContext() && 4513 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) || 4514 isOpenMPTargetDataManagementDirective( 4515 DSAStack->getCurrentDirective()))) { 4516 QualType Type = V->getType(); 4517 if (const auto *RD = Type.getCanonicalType() 4518 .getNonReferenceType() 4519 ->getAsCXXRecordDecl()) { 4520 bool SavedForceCaptureByReferenceInTargetExecutable = 4521 DSAStack->isForceCaptureByReferenceInTargetExecutable(); 4522 DSAStack->setForceCaptureByReferenceInTargetExecutable( 4523 /*V=*/true); 4524 if (RD->isLambda()) { 4525 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures; 4526 FieldDecl *ThisCapture; 4527 RD->getCaptureFields(Captures, ThisCapture); 4528 for (const LambdaCapture &LC : RD->captures()) { 4529 if (LC.getCaptureKind() == LCK_ByRef) { 4530 VarDecl *VD = LC.getCapturedVar(); 4531 DeclContext *VDC = VD->getDeclContext(); 4532 if (!VDC->Encloses(CurContext)) 4533 continue; 4534 MarkVariableReferenced(LC.getLocation(), VD); 4535 } else if (LC.getCaptureKind() == LCK_This) { 4536 QualType ThisTy = getCurrentThisType(); 4537 if (!ThisTy.isNull() && 4538 Context.typesAreCompatible(ThisTy, ThisCapture->getType())) 4539 CheckCXXThisCapture(LC.getLocation()); 4540 } 4541 } 4542 } 4543 DSAStack->setForceCaptureByReferenceInTargetExecutable( 4544 SavedForceCaptureByReferenceInTargetExecutable); 4545 } 4546 } 4547 } 4548 4549 static bool checkOrderedOrderSpecified(Sema &S, 4550 const ArrayRef<OMPClause *> Clauses) { 4551 const OMPOrderedClause *Ordered = nullptr; 4552 const OMPOrderClause *Order = nullptr; 4553 4554 for (const OMPClause *Clause : Clauses) { 4555 if (Clause->getClauseKind() == OMPC_ordered) 4556 Ordered = cast<OMPOrderedClause>(Clause); 4557 else if (Clause->getClauseKind() == OMPC_order) { 4558 Order = cast<OMPOrderClause>(Clause); 4559 if (Order->getKind() != OMPC_ORDER_concurrent) 4560 Order = nullptr; 4561 } 4562 if (Ordered && Order) 4563 break; 4564 } 4565 4566 if (Ordered && Order) { 4567 S.Diag(Order->getKindKwLoc(), 4568 diag::err_omp_simple_clause_incompatible_with_ordered) 4569 << getOpenMPClauseName(OMPC_order) 4570 << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent) 4571 << SourceRange(Order->getBeginLoc(), Order->getEndLoc()); 4572 S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param) 4573 << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc()); 4574 return true; 4575 } 4576 return false; 4577 } 4578 4579 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 4580 ArrayRef<OMPClause *> Clauses) { 4581 handleDeclareVariantConstructTrait(DSAStack, DSAStack->getCurrentDirective(), 4582 /* ScopeEntry */ false); 4583 if (DSAStack->getCurrentDirective() == OMPD_atomic || 4584 DSAStack->getCurrentDirective() == OMPD_critical || 4585 DSAStack->getCurrentDirective() == OMPD_section || 4586 DSAStack->getCurrentDirective() == OMPD_master || 4587 DSAStack->getCurrentDirective() == OMPD_masked) 4588 return S; 4589 4590 bool ErrorFound = false; 4591 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 4592 *this, ErrorFound, DSAStack->getCurrentDirective()); 4593 if (!S.isUsable()) { 4594 ErrorFound = true; 4595 return StmtError(); 4596 } 4597 4598 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 4599 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 4600 OMPOrderedClause *OC = nullptr; 4601 OMPScheduleClause *SC = nullptr; 4602 SmallVector<const OMPLinearClause *, 4> LCs; 4603 SmallVector<const OMPClauseWithPreInit *, 4> PICs; 4604 // This is required for proper codegen. 4605 for (OMPClause *Clause : Clauses) { 4606 if (!LangOpts.OpenMPSimd && 4607 isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) && 4608 Clause->getClauseKind() == OMPC_in_reduction) { 4609 // Capture taskgroup task_reduction descriptors inside the tasking regions 4610 // with the corresponding in_reduction items. 4611 auto *IRC = cast<OMPInReductionClause>(Clause); 4612 for (Expr *E : IRC->taskgroup_descriptors()) 4613 if (E) 4614 MarkDeclarationsReferencedInExpr(E); 4615 } 4616 if (isOpenMPPrivate(Clause->getClauseKind()) || 4617 Clause->getClauseKind() == OMPC_copyprivate || 4618 (getLangOpts().OpenMPUseTLS && 4619 getASTContext().getTargetInfo().isTLSSupported() && 4620 Clause->getClauseKind() == OMPC_copyin)) { 4621 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 4622 // Mark all variables in private list clauses as used in inner region. 4623 for (Stmt *VarRef : Clause->children()) { 4624 if (auto *E = cast_or_null<Expr>(VarRef)) { 4625 MarkDeclarationsReferencedInExpr(E); 4626 } 4627 } 4628 DSAStack->setForceVarCapturing(/*V=*/false); 4629 } else if (isOpenMPLoopTransformationDirective( 4630 DSAStack->getCurrentDirective())) { 4631 assert(CaptureRegions.empty() && 4632 "No captured regions in loop transformation directives."); 4633 } else if (CaptureRegions.size() > 1 || 4634 CaptureRegions.back() != OMPD_unknown) { 4635 if (auto *C = OMPClauseWithPreInit::get(Clause)) 4636 PICs.push_back(C); 4637 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 4638 if (Expr *E = C->getPostUpdateExpr()) 4639 MarkDeclarationsReferencedInExpr(E); 4640 } 4641 } 4642 if (Clause->getClauseKind() == OMPC_schedule) 4643 SC = cast<OMPScheduleClause>(Clause); 4644 else if (Clause->getClauseKind() == OMPC_ordered) 4645 OC = cast<OMPOrderedClause>(Clause); 4646 else if (Clause->getClauseKind() == OMPC_linear) 4647 LCs.push_back(cast<OMPLinearClause>(Clause)); 4648 } 4649 // Capture allocator expressions if used. 4650 for (Expr *E : DSAStack->getInnerAllocators()) 4651 MarkDeclarationsReferencedInExpr(E); 4652 // OpenMP, 2.7.1 Loop Construct, Restrictions 4653 // The nonmonotonic modifier cannot be specified if an ordered clause is 4654 // specified. 4655 if (SC && 4656 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 4657 SC->getSecondScheduleModifier() == 4658 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 4659 OC) { 4660 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 4661 ? SC->getFirstScheduleModifierLoc() 4662 : SC->getSecondScheduleModifierLoc(), 4663 diag::err_omp_simple_clause_incompatible_with_ordered) 4664 << getOpenMPClauseName(OMPC_schedule) 4665 << getOpenMPSimpleClauseTypeName(OMPC_schedule, 4666 OMPC_SCHEDULE_MODIFIER_nonmonotonic) 4667 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 4668 ErrorFound = true; 4669 } 4670 // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions. 4671 // If an order(concurrent) clause is present, an ordered clause may not appear 4672 // on the same directive. 4673 if (checkOrderedOrderSpecified(*this, Clauses)) 4674 ErrorFound = true; 4675 if (!LCs.empty() && OC && OC->getNumForLoops()) { 4676 for (const OMPLinearClause *C : LCs) { 4677 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered) 4678 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 4679 } 4680 ErrorFound = true; 4681 } 4682 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 4683 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 4684 OC->getNumForLoops()) { 4685 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd) 4686 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 4687 ErrorFound = true; 4688 } 4689 if (ErrorFound) { 4690 return StmtError(); 4691 } 4692 StmtResult SR = S; 4693 unsigned CompletedRegions = 0; 4694 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 4695 // Mark all variables in private list clauses as used in inner region. 4696 // Required for proper codegen of combined directives. 4697 // TODO: add processing for other clauses. 4698 if (ThisCaptureRegion != OMPD_unknown) { 4699 for (const clang::OMPClauseWithPreInit *C : PICs) { 4700 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 4701 // Find the particular capture region for the clause if the 4702 // directive is a combined one with multiple capture regions. 4703 // If the directive is not a combined one, the capture region 4704 // associated with the clause is OMPD_unknown and is generated 4705 // only once. 4706 if (CaptureRegion == ThisCaptureRegion || 4707 CaptureRegion == OMPD_unknown) { 4708 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 4709 for (Decl *D : DS->decls()) 4710 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 4711 } 4712 } 4713 } 4714 } 4715 if (ThisCaptureRegion == OMPD_target) { 4716 // Capture allocator traits in the target region. They are used implicitly 4717 // and, thus, are not captured by default. 4718 for (OMPClause *C : Clauses) { 4719 if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) { 4720 for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End; 4721 ++I) { 4722 OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I); 4723 if (Expr *E = D.AllocatorTraits) 4724 MarkDeclarationsReferencedInExpr(E); 4725 } 4726 continue; 4727 } 4728 } 4729 } 4730 if (ThisCaptureRegion == OMPD_parallel) { 4731 // Capture temp arrays for inscan reductions and locals in aligned 4732 // clauses. 4733 for (OMPClause *C : Clauses) { 4734 if (auto *RC = dyn_cast<OMPReductionClause>(C)) { 4735 if (RC->getModifier() != OMPC_REDUCTION_inscan) 4736 continue; 4737 for (Expr *E : RC->copy_array_temps()) 4738 MarkDeclarationsReferencedInExpr(E); 4739 } 4740 if (auto *AC = dyn_cast<OMPAlignedClause>(C)) { 4741 for (Expr *E : AC->varlists()) 4742 MarkDeclarationsReferencedInExpr(E); 4743 } 4744 } 4745 } 4746 if (++CompletedRegions == CaptureRegions.size()) 4747 DSAStack->setBodyComplete(); 4748 SR = ActOnCapturedRegionEnd(SR.get()); 4749 } 4750 return SR; 4751 } 4752 4753 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 4754 OpenMPDirectiveKind CancelRegion, 4755 SourceLocation StartLoc) { 4756 // CancelRegion is only needed for cancel and cancellation_point. 4757 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 4758 return false; 4759 4760 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 4761 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 4762 return false; 4763 4764 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 4765 << getOpenMPDirectiveName(CancelRegion); 4766 return true; 4767 } 4768 4769 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack, 4770 OpenMPDirectiveKind CurrentRegion, 4771 const DeclarationNameInfo &CurrentName, 4772 OpenMPDirectiveKind CancelRegion, 4773 OpenMPBindClauseKind BindKind, 4774 SourceLocation StartLoc) { 4775 if (Stack->getCurScope()) { 4776 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective(); 4777 OpenMPDirectiveKind OffendingRegion = ParentRegion; 4778 bool NestingProhibited = false; 4779 bool CloseNesting = true; 4780 bool OrphanSeen = false; 4781 enum { 4782 NoRecommend, 4783 ShouldBeInParallelRegion, 4784 ShouldBeInOrderedRegion, 4785 ShouldBeInTargetRegion, 4786 ShouldBeInTeamsRegion, 4787 ShouldBeInLoopSimdRegion, 4788 } Recommend = NoRecommend; 4789 if (isOpenMPSimdDirective(ParentRegion) && 4790 ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) || 4791 (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered && 4792 CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic && 4793 CurrentRegion != OMPD_scan))) { 4794 // OpenMP [2.16, Nesting of Regions] 4795 // OpenMP constructs may not be nested inside a simd region. 4796 // OpenMP [2.8.1,simd Construct, Restrictions] 4797 // An ordered construct with the simd clause is the only OpenMP 4798 // construct that can appear in the simd region. 4799 // Allowing a SIMD construct nested in another SIMD construct is an 4800 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 4801 // message. 4802 // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions] 4803 // The only OpenMP constructs that can be encountered during execution of 4804 // a simd region are the atomic construct, the loop construct, the simd 4805 // construct and the ordered construct with the simd clause. 4806 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 4807 ? diag::err_omp_prohibited_region_simd 4808 : diag::warn_omp_nesting_simd) 4809 << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0); 4810 return CurrentRegion != OMPD_simd; 4811 } 4812 if (ParentRegion == OMPD_atomic) { 4813 // OpenMP [2.16, Nesting of Regions] 4814 // OpenMP constructs may not be nested inside an atomic region. 4815 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 4816 return true; 4817 } 4818 if (CurrentRegion == OMPD_section) { 4819 // OpenMP [2.7.2, sections Construct, Restrictions] 4820 // Orphaned section directives are prohibited. That is, the section 4821 // directives must appear within the sections construct and must not be 4822 // encountered elsewhere in the sections region. 4823 if (ParentRegion != OMPD_sections && 4824 ParentRegion != OMPD_parallel_sections) { 4825 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 4826 << (ParentRegion != OMPD_unknown) 4827 << getOpenMPDirectiveName(ParentRegion); 4828 return true; 4829 } 4830 return false; 4831 } 4832 // Allow some constructs (except teams and cancellation constructs) to be 4833 // orphaned (they could be used in functions, called from OpenMP regions 4834 // with the required preconditions). 4835 if (ParentRegion == OMPD_unknown && 4836 !isOpenMPNestingTeamsDirective(CurrentRegion) && 4837 CurrentRegion != OMPD_cancellation_point && 4838 CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan) 4839 return false; 4840 if (CurrentRegion == OMPD_cancellation_point || 4841 CurrentRegion == OMPD_cancel) { 4842 // OpenMP [2.16, Nesting of Regions] 4843 // A cancellation point construct for which construct-type-clause is 4844 // taskgroup must be nested inside a task construct. A cancellation 4845 // point construct for which construct-type-clause is not taskgroup must 4846 // be closely nested inside an OpenMP construct that matches the type 4847 // specified in construct-type-clause. 4848 // A cancel construct for which construct-type-clause is taskgroup must be 4849 // nested inside a task construct. A cancel construct for which 4850 // construct-type-clause is not taskgroup must be closely nested inside an 4851 // OpenMP construct that matches the type specified in 4852 // construct-type-clause. 4853 NestingProhibited = 4854 !((CancelRegion == OMPD_parallel && 4855 (ParentRegion == OMPD_parallel || 4856 ParentRegion == OMPD_target_parallel)) || 4857 (CancelRegion == OMPD_for && 4858 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 4859 ParentRegion == OMPD_target_parallel_for || 4860 ParentRegion == OMPD_distribute_parallel_for || 4861 ParentRegion == OMPD_teams_distribute_parallel_for || 4862 ParentRegion == OMPD_target_teams_distribute_parallel_for)) || 4863 (CancelRegion == OMPD_taskgroup && 4864 (ParentRegion == OMPD_task || 4865 (SemaRef.getLangOpts().OpenMP >= 50 && 4866 (ParentRegion == OMPD_taskloop || 4867 ParentRegion == OMPD_master_taskloop || 4868 ParentRegion == OMPD_parallel_master_taskloop)))) || 4869 (CancelRegion == OMPD_sections && 4870 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 4871 ParentRegion == OMPD_parallel_sections))); 4872 OrphanSeen = ParentRegion == OMPD_unknown; 4873 } else if (CurrentRegion == OMPD_master || CurrentRegion == OMPD_masked) { 4874 // OpenMP 5.1 [2.22, Nesting of Regions] 4875 // A masked region may not be closely nested inside a worksharing, loop, 4876 // atomic, task, or taskloop region. 4877 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 4878 isOpenMPGenericLoopDirective(ParentRegion) || 4879 isOpenMPTaskingDirective(ParentRegion); 4880 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 4881 // OpenMP [2.16, Nesting of Regions] 4882 // A critical region may not be nested (closely or otherwise) inside a 4883 // critical region with the same name. Note that this restriction is not 4884 // sufficient to prevent deadlock. 4885 SourceLocation PreviousCriticalLoc; 4886 bool DeadLock = Stack->hasDirective( 4887 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 4888 const DeclarationNameInfo &DNI, 4889 SourceLocation Loc) { 4890 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 4891 PreviousCriticalLoc = Loc; 4892 return true; 4893 } 4894 return false; 4895 }, 4896 false /* skip top directive */); 4897 if (DeadLock) { 4898 SemaRef.Diag(StartLoc, 4899 diag::err_omp_prohibited_region_critical_same_name) 4900 << CurrentName.getName(); 4901 if (PreviousCriticalLoc.isValid()) 4902 SemaRef.Diag(PreviousCriticalLoc, 4903 diag::note_omp_previous_critical_region); 4904 return true; 4905 } 4906 } else if (CurrentRegion == OMPD_barrier) { 4907 // OpenMP 5.1 [2.22, Nesting of Regions] 4908 // A barrier region may not be closely nested inside a worksharing, loop, 4909 // task, taskloop, critical, ordered, atomic, or masked region. 4910 NestingProhibited = 4911 isOpenMPWorksharingDirective(ParentRegion) || 4912 isOpenMPGenericLoopDirective(ParentRegion) || 4913 isOpenMPTaskingDirective(ParentRegion) || 4914 ParentRegion == OMPD_master || ParentRegion == OMPD_masked || 4915 ParentRegion == OMPD_parallel_master || 4916 ParentRegion == OMPD_parallel_masked || 4917 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered; 4918 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 4919 !isOpenMPParallelDirective(CurrentRegion) && 4920 !isOpenMPTeamsDirective(CurrentRegion)) { 4921 // OpenMP 5.1 [2.22, Nesting of Regions] 4922 // A loop region that binds to a parallel region or a worksharing region 4923 // may not be closely nested inside a worksharing, loop, task, taskloop, 4924 // critical, ordered, atomic, or masked region. 4925 NestingProhibited = 4926 isOpenMPWorksharingDirective(ParentRegion) || 4927 isOpenMPGenericLoopDirective(ParentRegion) || 4928 isOpenMPTaskingDirective(ParentRegion) || 4929 ParentRegion == OMPD_master || ParentRegion == OMPD_masked || 4930 ParentRegion == OMPD_parallel_master || 4931 ParentRegion == OMPD_parallel_masked || 4932 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered; 4933 Recommend = ShouldBeInParallelRegion; 4934 } else if (CurrentRegion == OMPD_ordered) { 4935 // OpenMP [2.16, Nesting of Regions] 4936 // An ordered region may not be closely nested inside a critical, 4937 // atomic, or explicit task region. 4938 // An ordered region must be closely nested inside a loop region (or 4939 // parallel loop region) with an ordered clause. 4940 // OpenMP [2.8.1,simd Construct, Restrictions] 4941 // An ordered construct with the simd clause is the only OpenMP construct 4942 // that can appear in the simd region. 4943 NestingProhibited = ParentRegion == OMPD_critical || 4944 isOpenMPTaskingDirective(ParentRegion) || 4945 !(isOpenMPSimdDirective(ParentRegion) || 4946 Stack->isParentOrderedRegion()); 4947 Recommend = ShouldBeInOrderedRegion; 4948 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 4949 // OpenMP [2.16, Nesting of Regions] 4950 // If specified, a teams construct must be contained within a target 4951 // construct. 4952 NestingProhibited = 4953 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) || 4954 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown && 4955 ParentRegion != OMPD_target); 4956 OrphanSeen = ParentRegion == OMPD_unknown; 4957 Recommend = ShouldBeInTargetRegion; 4958 } else if (CurrentRegion == OMPD_scan) { 4959 // OpenMP [2.16, Nesting of Regions] 4960 // If specified, a teams construct must be contained within a target 4961 // construct. 4962 NestingProhibited = 4963 SemaRef.LangOpts.OpenMP < 50 || 4964 (ParentRegion != OMPD_simd && ParentRegion != OMPD_for && 4965 ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for && 4966 ParentRegion != OMPD_parallel_for_simd); 4967 OrphanSeen = ParentRegion == OMPD_unknown; 4968 Recommend = ShouldBeInLoopSimdRegion; 4969 } 4970 if (!NestingProhibited && 4971 !isOpenMPTargetExecutionDirective(CurrentRegion) && 4972 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 4973 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 4974 // OpenMP [5.1, 2.22, Nesting of Regions] 4975 // distribute, distribute simd, distribute parallel worksharing-loop, 4976 // distribute parallel worksharing-loop SIMD, loop, parallel regions, 4977 // including any parallel regions arising from combined constructs, 4978 // omp_get_num_teams() regions, and omp_get_team_num() regions are the 4979 // only OpenMP regions that may be strictly nested inside the teams 4980 // region. 4981 // 4982 // As an extension, we permit atomic within teams as well. 4983 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 4984 !isOpenMPDistributeDirective(CurrentRegion) && 4985 CurrentRegion != OMPD_loop && 4986 !(SemaRef.getLangOpts().OpenMPExtensions && 4987 CurrentRegion == OMPD_atomic); 4988 Recommend = ShouldBeInParallelRegion; 4989 } 4990 if (!NestingProhibited && CurrentRegion == OMPD_loop) { 4991 // OpenMP [5.1, 2.11.7, loop Construct, Restrictions] 4992 // If the bind clause is present on the loop construct and binding is 4993 // teams then the corresponding loop region must be strictly nested inside 4994 // a teams region. 4995 NestingProhibited = BindKind == OMPC_BIND_teams && 4996 ParentRegion != OMPD_teams && 4997 ParentRegion != OMPD_target_teams; 4998 Recommend = ShouldBeInTeamsRegion; 4999 } 5000 if (!NestingProhibited && 5001 isOpenMPNestingDistributeDirective(CurrentRegion)) { 5002 // OpenMP 4.5 [2.17 Nesting of Regions] 5003 // The region associated with the distribute construct must be strictly 5004 // nested inside a teams region 5005 NestingProhibited = 5006 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 5007 Recommend = ShouldBeInTeamsRegion; 5008 } 5009 if (!NestingProhibited && 5010 (isOpenMPTargetExecutionDirective(CurrentRegion) || 5011 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 5012 // OpenMP 4.5 [2.17 Nesting of Regions] 5013 // If a target, target update, target data, target enter data, or 5014 // target exit data construct is encountered during execution of a 5015 // target region, the behavior is unspecified. 5016 NestingProhibited = Stack->hasDirective( 5017 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 5018 SourceLocation) { 5019 if (isOpenMPTargetExecutionDirective(K)) { 5020 OffendingRegion = K; 5021 return true; 5022 } 5023 return false; 5024 }, 5025 false /* don't skip top directive */); 5026 CloseNesting = false; 5027 } 5028 if (NestingProhibited) { 5029 if (OrphanSeen) { 5030 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 5031 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 5032 } else { 5033 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 5034 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 5035 << Recommend << getOpenMPDirectiveName(CurrentRegion); 5036 } 5037 return true; 5038 } 5039 } 5040 return false; 5041 } 5042 5043 struct Kind2Unsigned { 5044 using argument_type = OpenMPDirectiveKind; 5045 unsigned operator()(argument_type DK) { return unsigned(DK); } 5046 }; 5047 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 5048 ArrayRef<OMPClause *> Clauses, 5049 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 5050 bool ErrorFound = false; 5051 unsigned NamedModifiersNumber = 0; 5052 llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers; 5053 FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1); 5054 SmallVector<SourceLocation, 4> NameModifierLoc; 5055 for (const OMPClause *C : Clauses) { 5056 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 5057 // At most one if clause without a directive-name-modifier can appear on 5058 // the directive. 5059 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 5060 if (FoundNameModifiers[CurNM]) { 5061 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 5062 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 5063 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 5064 ErrorFound = true; 5065 } else if (CurNM != OMPD_unknown) { 5066 NameModifierLoc.push_back(IC->getNameModifierLoc()); 5067 ++NamedModifiersNumber; 5068 } 5069 FoundNameModifiers[CurNM] = IC; 5070 if (CurNM == OMPD_unknown) 5071 continue; 5072 // Check if the specified name modifier is allowed for the current 5073 // directive. 5074 // At most one if clause with the particular directive-name-modifier can 5075 // appear on the directive. 5076 if (!llvm::is_contained(AllowedNameModifiers, CurNM)) { 5077 S.Diag(IC->getNameModifierLoc(), 5078 diag::err_omp_wrong_if_directive_name_modifier) 5079 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 5080 ErrorFound = true; 5081 } 5082 } 5083 } 5084 // If any if clause on the directive includes a directive-name-modifier then 5085 // all if clauses on the directive must include a directive-name-modifier. 5086 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 5087 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 5088 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(), 5089 diag::err_omp_no_more_if_clause); 5090 } else { 5091 std::string Values; 5092 std::string Sep(", "); 5093 unsigned AllowedCnt = 0; 5094 unsigned TotalAllowedNum = 5095 AllowedNameModifiers.size() - NamedModifiersNumber; 5096 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 5097 ++Cnt) { 5098 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 5099 if (!FoundNameModifiers[NM]) { 5100 Values += "'"; 5101 Values += getOpenMPDirectiveName(NM); 5102 Values += "'"; 5103 if (AllowedCnt + 2 == TotalAllowedNum) 5104 Values += " or "; 5105 else if (AllowedCnt + 1 != TotalAllowedNum) 5106 Values += Sep; 5107 ++AllowedCnt; 5108 } 5109 } 5110 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(), 5111 diag::err_omp_unnamed_if_clause) 5112 << (TotalAllowedNum > 1) << Values; 5113 } 5114 for (SourceLocation Loc : NameModifierLoc) { 5115 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 5116 } 5117 ErrorFound = true; 5118 } 5119 return ErrorFound; 5120 } 5121 5122 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr, 5123 SourceLocation &ELoc, 5124 SourceRange &ERange, 5125 bool AllowArraySection) { 5126 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 5127 RefExpr->containsUnexpandedParameterPack()) 5128 return std::make_pair(nullptr, true); 5129 5130 // OpenMP [3.1, C/C++] 5131 // A list item is a variable name. 5132 // OpenMP [2.9.3.3, Restrictions, p.1] 5133 // A variable that is part of another variable (as an array or 5134 // structure element) cannot appear in a private clause. 5135 RefExpr = RefExpr->IgnoreParens(); 5136 enum { 5137 NoArrayExpr = -1, 5138 ArraySubscript = 0, 5139 OMPArraySection = 1 5140 } IsArrayExpr = NoArrayExpr; 5141 if (AllowArraySection) { 5142 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 5143 Expr *Base = ASE->getBase()->IgnoreParenImpCasts(); 5144 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 5145 Base = TempASE->getBase()->IgnoreParenImpCasts(); 5146 RefExpr = Base; 5147 IsArrayExpr = ArraySubscript; 5148 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 5149 Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 5150 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 5151 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 5152 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 5153 Base = TempASE->getBase()->IgnoreParenImpCasts(); 5154 RefExpr = Base; 5155 IsArrayExpr = OMPArraySection; 5156 } 5157 } 5158 ELoc = RefExpr->getExprLoc(); 5159 ERange = RefExpr->getSourceRange(); 5160 RefExpr = RefExpr->IgnoreParenImpCasts(); 5161 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 5162 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 5163 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 5164 (S.getCurrentThisType().isNull() || !ME || 5165 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 5166 !isa<FieldDecl>(ME->getMemberDecl()))) { 5167 if (IsArrayExpr != NoArrayExpr) { 5168 S.Diag(ELoc, diag::err_omp_expected_base_var_name) 5169 << IsArrayExpr << ERange; 5170 } else { 5171 S.Diag(ELoc, 5172 AllowArraySection 5173 ? diag::err_omp_expected_var_name_member_expr_or_array_item 5174 : diag::err_omp_expected_var_name_member_expr) 5175 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 5176 } 5177 return std::make_pair(nullptr, false); 5178 } 5179 return std::make_pair( 5180 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false); 5181 } 5182 5183 namespace { 5184 /// Checks if the allocator is used in uses_allocators clause to be allowed in 5185 /// target regions. 5186 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> { 5187 DSAStackTy *S = nullptr; 5188 5189 public: 5190 bool VisitDeclRefExpr(const DeclRefExpr *E) { 5191 return S->isUsesAllocatorsDecl(E->getDecl()) 5192 .value_or(DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) == 5193 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait; 5194 } 5195 bool VisitStmt(const Stmt *S) { 5196 for (const Stmt *Child : S->children()) { 5197 if (Child && Visit(Child)) 5198 return true; 5199 } 5200 return false; 5201 } 5202 explicit AllocatorChecker(DSAStackTy *S) : S(S) {} 5203 }; 5204 } // namespace 5205 5206 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack, 5207 ArrayRef<OMPClause *> Clauses) { 5208 assert(!S.CurContext->isDependentContext() && 5209 "Expected non-dependent context."); 5210 auto AllocateRange = 5211 llvm::make_filter_range(Clauses, OMPAllocateClause::classof); 5212 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>> DeclToCopy; 5213 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) { 5214 return isOpenMPPrivate(C->getClauseKind()); 5215 }); 5216 for (OMPClause *Cl : PrivateRange) { 5217 MutableArrayRef<Expr *>::iterator I, It, Et; 5218 if (Cl->getClauseKind() == OMPC_private) { 5219 auto *PC = cast<OMPPrivateClause>(Cl); 5220 I = PC->private_copies().begin(); 5221 It = PC->varlist_begin(); 5222 Et = PC->varlist_end(); 5223 } else if (Cl->getClauseKind() == OMPC_firstprivate) { 5224 auto *PC = cast<OMPFirstprivateClause>(Cl); 5225 I = PC->private_copies().begin(); 5226 It = PC->varlist_begin(); 5227 Et = PC->varlist_end(); 5228 } else if (Cl->getClauseKind() == OMPC_lastprivate) { 5229 auto *PC = cast<OMPLastprivateClause>(Cl); 5230 I = PC->private_copies().begin(); 5231 It = PC->varlist_begin(); 5232 Et = PC->varlist_end(); 5233 } else if (Cl->getClauseKind() == OMPC_linear) { 5234 auto *PC = cast<OMPLinearClause>(Cl); 5235 I = PC->privates().begin(); 5236 It = PC->varlist_begin(); 5237 Et = PC->varlist_end(); 5238 } else if (Cl->getClauseKind() == OMPC_reduction) { 5239 auto *PC = cast<OMPReductionClause>(Cl); 5240 I = PC->privates().begin(); 5241 It = PC->varlist_begin(); 5242 Et = PC->varlist_end(); 5243 } else if (Cl->getClauseKind() == OMPC_task_reduction) { 5244 auto *PC = cast<OMPTaskReductionClause>(Cl); 5245 I = PC->privates().begin(); 5246 It = PC->varlist_begin(); 5247 Et = PC->varlist_end(); 5248 } else if (Cl->getClauseKind() == OMPC_in_reduction) { 5249 auto *PC = cast<OMPInReductionClause>(Cl); 5250 I = PC->privates().begin(); 5251 It = PC->varlist_begin(); 5252 Et = PC->varlist_end(); 5253 } else { 5254 llvm_unreachable("Expected private clause."); 5255 } 5256 for (Expr *E : llvm::make_range(It, Et)) { 5257 if (!*I) { 5258 ++I; 5259 continue; 5260 } 5261 SourceLocation ELoc; 5262 SourceRange ERange; 5263 Expr *SimpleRefExpr = E; 5264 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 5265 /*AllowArraySection=*/true); 5266 DeclToCopy.try_emplace(Res.first, 5267 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl())); 5268 ++I; 5269 } 5270 } 5271 for (OMPClause *C : AllocateRange) { 5272 auto *AC = cast<OMPAllocateClause>(C); 5273 if (S.getLangOpts().OpenMP >= 50 && 5274 !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() && 5275 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 5276 AC->getAllocator()) { 5277 Expr *Allocator = AC->getAllocator(); 5278 // OpenMP, 2.12.5 target Construct 5279 // Memory allocators that do not appear in a uses_allocators clause cannot 5280 // appear as an allocator in an allocate clause or be used in the target 5281 // region unless a requires directive with the dynamic_allocators clause 5282 // is present in the same compilation unit. 5283 AllocatorChecker Checker(Stack); 5284 if (Checker.Visit(Allocator)) 5285 S.Diag(Allocator->getExprLoc(), 5286 diag::err_omp_allocator_not_in_uses_allocators) 5287 << Allocator->getSourceRange(); 5288 } 5289 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind = 5290 getAllocatorKind(S, Stack, AC->getAllocator()); 5291 // OpenMP, 2.11.4 allocate Clause, Restrictions. 5292 // For task, taskloop or target directives, allocation requests to memory 5293 // allocators with the trait access set to thread result in unspecified 5294 // behavior. 5295 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc && 5296 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 5297 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) { 5298 S.Diag(AC->getAllocator()->getExprLoc(), 5299 diag::warn_omp_allocate_thread_on_task_target_directive) 5300 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 5301 } 5302 for (Expr *E : AC->varlists()) { 5303 SourceLocation ELoc; 5304 SourceRange ERange; 5305 Expr *SimpleRefExpr = E; 5306 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange); 5307 ValueDecl *VD = Res.first; 5308 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false); 5309 if (!isOpenMPPrivate(Data.CKind)) { 5310 S.Diag(E->getExprLoc(), 5311 diag::err_omp_expected_private_copy_for_allocate); 5312 continue; 5313 } 5314 VarDecl *PrivateVD = DeclToCopy[VD]; 5315 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD, 5316 AllocatorKind, AC->getAllocator())) 5317 continue; 5318 // Placeholder until allocate clause supports align modifier. 5319 Expr *Alignment = nullptr; 5320 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(), 5321 Alignment, E->getSourceRange()); 5322 } 5323 } 5324 } 5325 5326 namespace { 5327 /// Rewrite statements and expressions for Sema \p Actions CurContext. 5328 /// 5329 /// Used to wrap already parsed statements/expressions into a new CapturedStmt 5330 /// context. DeclRefExpr used inside the new context are changed to refer to the 5331 /// captured variable instead. 5332 class CaptureVars : public TreeTransform<CaptureVars> { 5333 using BaseTransform = TreeTransform<CaptureVars>; 5334 5335 public: 5336 CaptureVars(Sema &Actions) : BaseTransform(Actions) {} 5337 5338 bool AlwaysRebuild() { return true; } 5339 }; 5340 } // namespace 5341 5342 static VarDecl *precomputeExpr(Sema &Actions, 5343 SmallVectorImpl<Stmt *> &BodyStmts, Expr *E, 5344 StringRef Name) { 5345 Expr *NewE = AssertSuccess(CaptureVars(Actions).TransformExpr(E)); 5346 VarDecl *NewVar = buildVarDecl(Actions, {}, NewE->getType(), Name, nullptr, 5347 dyn_cast<DeclRefExpr>(E->IgnoreImplicit())); 5348 auto *NewDeclStmt = cast<DeclStmt>(AssertSuccess( 5349 Actions.ActOnDeclStmt(Actions.ConvertDeclToDeclGroup(NewVar), {}, {}))); 5350 Actions.AddInitializerToDecl(NewDeclStmt->getSingleDecl(), NewE, false); 5351 BodyStmts.push_back(NewDeclStmt); 5352 return NewVar; 5353 } 5354 5355 /// Create a closure that computes the number of iterations of a loop. 5356 /// 5357 /// \param Actions The Sema object. 5358 /// \param LogicalTy Type for the logical iteration number. 5359 /// \param Rel Comparison operator of the loop condition. 5360 /// \param StartExpr Value of the loop counter at the first iteration. 5361 /// \param StopExpr Expression the loop counter is compared against in the loop 5362 /// condition. \param StepExpr Amount of increment after each iteration. 5363 /// 5364 /// \return Closure (CapturedStmt) of the distance calculation. 5365 static CapturedStmt *buildDistanceFunc(Sema &Actions, QualType LogicalTy, 5366 BinaryOperator::Opcode Rel, 5367 Expr *StartExpr, Expr *StopExpr, 5368 Expr *StepExpr) { 5369 ASTContext &Ctx = Actions.getASTContext(); 5370 TypeSourceInfo *LogicalTSI = Ctx.getTrivialTypeSourceInfo(LogicalTy); 5371 5372 // Captured regions currently don't support return values, we use an 5373 // out-parameter instead. All inputs are implicit captures. 5374 // TODO: Instead of capturing each DeclRefExpr occurring in 5375 // StartExpr/StopExpr/Step, these could also be passed as a value capture. 5376 QualType ResultTy = Ctx.getLValueReferenceType(LogicalTy); 5377 Sema::CapturedParamNameType Params[] = {{"Distance", ResultTy}, 5378 {StringRef(), QualType()}}; 5379 Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params); 5380 5381 Stmt *Body; 5382 { 5383 Sema::CompoundScopeRAII CompoundScope(Actions); 5384 CapturedDecl *CS = cast<CapturedDecl>(Actions.CurContext); 5385 5386 // Get the LValue expression for the result. 5387 ImplicitParamDecl *DistParam = CS->getParam(0); 5388 DeclRefExpr *DistRef = Actions.BuildDeclRefExpr( 5389 DistParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr); 5390 5391 SmallVector<Stmt *, 4> BodyStmts; 5392 5393 // Capture all referenced variable references. 5394 // TODO: Instead of computing NewStart/NewStop/NewStep inside the 5395 // CapturedStmt, we could compute them before and capture the result, to be 5396 // used jointly with the LoopVar function. 5397 VarDecl *NewStart = precomputeExpr(Actions, BodyStmts, StartExpr, ".start"); 5398 VarDecl *NewStop = precomputeExpr(Actions, BodyStmts, StopExpr, ".stop"); 5399 VarDecl *NewStep = precomputeExpr(Actions, BodyStmts, StepExpr, ".step"); 5400 auto BuildVarRef = [&](VarDecl *VD) { 5401 return buildDeclRefExpr(Actions, VD, VD->getType(), {}); 5402 }; 5403 5404 IntegerLiteral *Zero = IntegerLiteral::Create( 5405 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 0), LogicalTy, {}); 5406 IntegerLiteral *One = IntegerLiteral::Create( 5407 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {}); 5408 Expr *Dist; 5409 if (Rel == BO_NE) { 5410 // When using a != comparison, the increment can be +1 or -1. This can be 5411 // dynamic at runtime, so we need to check for the direction. 5412 Expr *IsNegStep = AssertSuccess( 5413 Actions.BuildBinOp(nullptr, {}, BO_LT, BuildVarRef(NewStep), Zero)); 5414 5415 // Positive increment. 5416 Expr *ForwardRange = AssertSuccess(Actions.BuildBinOp( 5417 nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart))); 5418 ForwardRange = AssertSuccess( 5419 Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, ForwardRange)); 5420 Expr *ForwardDist = AssertSuccess(Actions.BuildBinOp( 5421 nullptr, {}, BO_Div, ForwardRange, BuildVarRef(NewStep))); 5422 5423 // Negative increment. 5424 Expr *BackwardRange = AssertSuccess(Actions.BuildBinOp( 5425 nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop))); 5426 BackwardRange = AssertSuccess( 5427 Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, BackwardRange)); 5428 Expr *NegIncAmount = AssertSuccess( 5429 Actions.BuildUnaryOp(nullptr, {}, UO_Minus, BuildVarRef(NewStep))); 5430 Expr *BackwardDist = AssertSuccess( 5431 Actions.BuildBinOp(nullptr, {}, BO_Div, BackwardRange, NegIncAmount)); 5432 5433 // Use the appropriate case. 5434 Dist = AssertSuccess(Actions.ActOnConditionalOp( 5435 {}, {}, IsNegStep, BackwardDist, ForwardDist)); 5436 } else { 5437 assert((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) && 5438 "Expected one of these relational operators"); 5439 5440 // We can derive the direction from any other comparison operator. It is 5441 // non well-formed OpenMP if Step increments/decrements in the other 5442 // directions. Whether at least the first iteration passes the loop 5443 // condition. 5444 Expr *HasAnyIteration = AssertSuccess(Actions.BuildBinOp( 5445 nullptr, {}, Rel, BuildVarRef(NewStart), BuildVarRef(NewStop))); 5446 5447 // Compute the range between first and last counter value. 5448 Expr *Range; 5449 if (Rel == BO_GE || Rel == BO_GT) 5450 Range = AssertSuccess(Actions.BuildBinOp( 5451 nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop))); 5452 else 5453 Range = AssertSuccess(Actions.BuildBinOp( 5454 nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart))); 5455 5456 // Ensure unsigned range space. 5457 Range = 5458 AssertSuccess(Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, Range)); 5459 5460 if (Rel == BO_LE || Rel == BO_GE) { 5461 // Add one to the range if the relational operator is inclusive. 5462 Range = 5463 AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, Range, One)); 5464 } 5465 5466 // Divide by the absolute step amount. If the range is not a multiple of 5467 // the step size, rounding-up the effective upper bound ensures that the 5468 // last iteration is included. 5469 // Note that the rounding-up may cause an overflow in a temporry that 5470 // could be avoided, but would have occurred in a C-style for-loop as well. 5471 Expr *Divisor = BuildVarRef(NewStep); 5472 if (Rel == BO_GE || Rel == BO_GT) 5473 Divisor = 5474 AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Minus, Divisor)); 5475 Expr *DivisorMinusOne = 5476 AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Sub, Divisor, One)); 5477 Expr *RangeRoundUp = AssertSuccess( 5478 Actions.BuildBinOp(nullptr, {}, BO_Add, Range, DivisorMinusOne)); 5479 Dist = AssertSuccess( 5480 Actions.BuildBinOp(nullptr, {}, BO_Div, RangeRoundUp, Divisor)); 5481 5482 // If there is not at least one iteration, the range contains garbage. Fix 5483 // to zero in this case. 5484 Dist = AssertSuccess( 5485 Actions.ActOnConditionalOp({}, {}, HasAnyIteration, Dist, Zero)); 5486 } 5487 5488 // Assign the result to the out-parameter. 5489 Stmt *ResultAssign = AssertSuccess(Actions.BuildBinOp( 5490 Actions.getCurScope(), {}, BO_Assign, DistRef, Dist)); 5491 BodyStmts.push_back(ResultAssign); 5492 5493 Body = AssertSuccess(Actions.ActOnCompoundStmt({}, {}, BodyStmts, false)); 5494 } 5495 5496 return cast<CapturedStmt>( 5497 AssertSuccess(Actions.ActOnCapturedRegionEnd(Body))); 5498 } 5499 5500 /// Create a closure that computes the loop variable from the logical iteration 5501 /// number. 5502 /// 5503 /// \param Actions The Sema object. 5504 /// \param LoopVarTy Type for the loop variable used for result value. 5505 /// \param LogicalTy Type for the logical iteration number. 5506 /// \param StartExpr Value of the loop counter at the first iteration. 5507 /// \param Step Amount of increment after each iteration. 5508 /// \param Deref Whether the loop variable is a dereference of the loop 5509 /// counter variable. 5510 /// 5511 /// \return Closure (CapturedStmt) of the loop value calculation. 5512 static CapturedStmt *buildLoopVarFunc(Sema &Actions, QualType LoopVarTy, 5513 QualType LogicalTy, 5514 DeclRefExpr *StartExpr, Expr *Step, 5515 bool Deref) { 5516 ASTContext &Ctx = Actions.getASTContext(); 5517 5518 // Pass the result as an out-parameter. Passing as return value would require 5519 // the OpenMPIRBuilder to know additional C/C++ semantics, such as how to 5520 // invoke a copy constructor. 5521 QualType TargetParamTy = Ctx.getLValueReferenceType(LoopVarTy); 5522 Sema::CapturedParamNameType Params[] = {{"LoopVar", TargetParamTy}, 5523 {"Logical", LogicalTy}, 5524 {StringRef(), QualType()}}; 5525 Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params); 5526 5527 // Capture the initial iterator which represents the LoopVar value at the 5528 // zero's logical iteration. Since the original ForStmt/CXXForRangeStmt update 5529 // it in every iteration, capture it by value before it is modified. 5530 VarDecl *StartVar = cast<VarDecl>(StartExpr->getDecl()); 5531 bool Invalid = Actions.tryCaptureVariable(StartVar, {}, 5532 Sema::TryCapture_ExplicitByVal, {}); 5533 (void)Invalid; 5534 assert(!Invalid && "Expecting capture-by-value to work."); 5535 5536 Expr *Body; 5537 { 5538 Sema::CompoundScopeRAII CompoundScope(Actions); 5539 auto *CS = cast<CapturedDecl>(Actions.CurContext); 5540 5541 ImplicitParamDecl *TargetParam = CS->getParam(0); 5542 DeclRefExpr *TargetRef = Actions.BuildDeclRefExpr( 5543 TargetParam, LoopVarTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr); 5544 ImplicitParamDecl *IndvarParam = CS->getParam(1); 5545 DeclRefExpr *LogicalRef = Actions.BuildDeclRefExpr( 5546 IndvarParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr); 5547 5548 // Capture the Start expression. 5549 CaptureVars Recap(Actions); 5550 Expr *NewStart = AssertSuccess(Recap.TransformExpr(StartExpr)); 5551 Expr *NewStep = AssertSuccess(Recap.TransformExpr(Step)); 5552 5553 Expr *Skip = AssertSuccess( 5554 Actions.BuildBinOp(nullptr, {}, BO_Mul, NewStep, LogicalRef)); 5555 // TODO: Explicitly cast to the iterator's difference_type instead of 5556 // relying on implicit conversion. 5557 Expr *Advanced = 5558 AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, NewStart, Skip)); 5559 5560 if (Deref) { 5561 // For range-based for-loops convert the loop counter value to a concrete 5562 // loop variable value by dereferencing the iterator. 5563 Advanced = 5564 AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Deref, Advanced)); 5565 } 5566 5567 // Assign the result to the output parameter. 5568 Body = AssertSuccess(Actions.BuildBinOp(Actions.getCurScope(), {}, 5569 BO_Assign, TargetRef, Advanced)); 5570 } 5571 return cast<CapturedStmt>( 5572 AssertSuccess(Actions.ActOnCapturedRegionEnd(Body))); 5573 } 5574 5575 StmtResult Sema::ActOnOpenMPCanonicalLoop(Stmt *AStmt) { 5576 ASTContext &Ctx = getASTContext(); 5577 5578 // Extract the common elements of ForStmt and CXXForRangeStmt: 5579 // Loop variable, repeat condition, increment 5580 Expr *Cond, *Inc; 5581 VarDecl *LIVDecl, *LUVDecl; 5582 if (auto *For = dyn_cast<ForStmt>(AStmt)) { 5583 Stmt *Init = For->getInit(); 5584 if (auto *LCVarDeclStmt = dyn_cast<DeclStmt>(Init)) { 5585 // For statement declares loop variable. 5586 LIVDecl = cast<VarDecl>(LCVarDeclStmt->getSingleDecl()); 5587 } else if (auto *LCAssign = dyn_cast<BinaryOperator>(Init)) { 5588 // For statement reuses variable. 5589 assert(LCAssign->getOpcode() == BO_Assign && 5590 "init part must be a loop variable assignment"); 5591 auto *CounterRef = cast<DeclRefExpr>(LCAssign->getLHS()); 5592 LIVDecl = cast<VarDecl>(CounterRef->getDecl()); 5593 } else 5594 llvm_unreachable("Cannot determine loop variable"); 5595 LUVDecl = LIVDecl; 5596 5597 Cond = For->getCond(); 5598 Inc = For->getInc(); 5599 } else if (auto *RangeFor = dyn_cast<CXXForRangeStmt>(AStmt)) { 5600 DeclStmt *BeginStmt = RangeFor->getBeginStmt(); 5601 LIVDecl = cast<VarDecl>(BeginStmt->getSingleDecl()); 5602 LUVDecl = RangeFor->getLoopVariable(); 5603 5604 Cond = RangeFor->getCond(); 5605 Inc = RangeFor->getInc(); 5606 } else 5607 llvm_unreachable("unhandled kind of loop"); 5608 5609 QualType CounterTy = LIVDecl->getType(); 5610 QualType LVTy = LUVDecl->getType(); 5611 5612 // Analyze the loop condition. 5613 Expr *LHS, *RHS; 5614 BinaryOperator::Opcode CondRel; 5615 Cond = Cond->IgnoreImplicit(); 5616 if (auto *CondBinExpr = dyn_cast<BinaryOperator>(Cond)) { 5617 LHS = CondBinExpr->getLHS(); 5618 RHS = CondBinExpr->getRHS(); 5619 CondRel = CondBinExpr->getOpcode(); 5620 } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Cond)) { 5621 assert(CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands"); 5622 LHS = CondCXXOp->getArg(0); 5623 RHS = CondCXXOp->getArg(1); 5624 switch (CondCXXOp->getOperator()) { 5625 case OO_ExclaimEqual: 5626 CondRel = BO_NE; 5627 break; 5628 case OO_Less: 5629 CondRel = BO_LT; 5630 break; 5631 case OO_LessEqual: 5632 CondRel = BO_LE; 5633 break; 5634 case OO_Greater: 5635 CondRel = BO_GT; 5636 break; 5637 case OO_GreaterEqual: 5638 CondRel = BO_GE; 5639 break; 5640 default: 5641 llvm_unreachable("unexpected iterator operator"); 5642 } 5643 } else 5644 llvm_unreachable("unexpected loop condition"); 5645 5646 // Normalize such that the loop counter is on the LHS. 5647 if (!isa<DeclRefExpr>(LHS->IgnoreImplicit()) || 5648 cast<DeclRefExpr>(LHS->IgnoreImplicit())->getDecl() != LIVDecl) { 5649 std::swap(LHS, RHS); 5650 CondRel = BinaryOperator::reverseComparisonOp(CondRel); 5651 } 5652 auto *CounterRef = cast<DeclRefExpr>(LHS->IgnoreImplicit()); 5653 5654 // Decide the bit width for the logical iteration counter. By default use the 5655 // unsigned ptrdiff_t integer size (for iterators and pointers). 5656 // TODO: For iterators, use iterator::difference_type, 5657 // std::iterator_traits<>::difference_type or decltype(it - end). 5658 QualType LogicalTy = Ctx.getUnsignedPointerDiffType(); 5659 if (CounterTy->isIntegerType()) { 5660 unsigned BitWidth = Ctx.getIntWidth(CounterTy); 5661 LogicalTy = Ctx.getIntTypeForBitwidth(BitWidth, false); 5662 } 5663 5664 // Analyze the loop increment. 5665 Expr *Step; 5666 if (auto *IncUn = dyn_cast<UnaryOperator>(Inc)) { 5667 int Direction; 5668 switch (IncUn->getOpcode()) { 5669 case UO_PreInc: 5670 case UO_PostInc: 5671 Direction = 1; 5672 break; 5673 case UO_PreDec: 5674 case UO_PostDec: 5675 Direction = -1; 5676 break; 5677 default: 5678 llvm_unreachable("unhandled unary increment operator"); 5679 } 5680 Step = IntegerLiteral::Create( 5681 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), Direction), LogicalTy, {}); 5682 } else if (auto *IncBin = dyn_cast<BinaryOperator>(Inc)) { 5683 if (IncBin->getOpcode() == BO_AddAssign) { 5684 Step = IncBin->getRHS(); 5685 } else if (IncBin->getOpcode() == BO_SubAssign) { 5686 Step = 5687 AssertSuccess(BuildUnaryOp(nullptr, {}, UO_Minus, IncBin->getRHS())); 5688 } else 5689 llvm_unreachable("unhandled binary increment operator"); 5690 } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Inc)) { 5691 switch (CondCXXOp->getOperator()) { 5692 case OO_PlusPlus: 5693 Step = IntegerLiteral::Create( 5694 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {}); 5695 break; 5696 case OO_MinusMinus: 5697 Step = IntegerLiteral::Create( 5698 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), -1), LogicalTy, {}); 5699 break; 5700 case OO_PlusEqual: 5701 Step = CondCXXOp->getArg(1); 5702 break; 5703 case OO_MinusEqual: 5704 Step = AssertSuccess( 5705 BuildUnaryOp(nullptr, {}, UO_Minus, CondCXXOp->getArg(1))); 5706 break; 5707 default: 5708 llvm_unreachable("unhandled overloaded increment operator"); 5709 } 5710 } else 5711 llvm_unreachable("unknown increment expression"); 5712 5713 CapturedStmt *DistanceFunc = 5714 buildDistanceFunc(*this, LogicalTy, CondRel, LHS, RHS, Step); 5715 CapturedStmt *LoopVarFunc = buildLoopVarFunc( 5716 *this, LVTy, LogicalTy, CounterRef, Step, isa<CXXForRangeStmt>(AStmt)); 5717 DeclRefExpr *LVRef = BuildDeclRefExpr(LUVDecl, LUVDecl->getType(), VK_LValue, 5718 {}, nullptr, nullptr, {}, nullptr); 5719 return OMPCanonicalLoop::create(getASTContext(), AStmt, DistanceFunc, 5720 LoopVarFunc, LVRef); 5721 } 5722 5723 StmtResult Sema::ActOnOpenMPLoopnest(Stmt *AStmt) { 5724 // Handle a literal loop. 5725 if (isa<ForStmt>(AStmt) || isa<CXXForRangeStmt>(AStmt)) 5726 return ActOnOpenMPCanonicalLoop(AStmt); 5727 5728 // If not a literal loop, it must be the result of a loop transformation. 5729 OMPExecutableDirective *LoopTransform = cast<OMPExecutableDirective>(AStmt); 5730 assert( 5731 isOpenMPLoopTransformationDirective(LoopTransform->getDirectiveKind()) && 5732 "Loop transformation directive expected"); 5733 return LoopTransform; 5734 } 5735 5736 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S, 5737 CXXScopeSpec &MapperIdScopeSpec, 5738 const DeclarationNameInfo &MapperId, 5739 QualType Type, 5740 Expr *UnresolvedMapper); 5741 5742 /// Perform DFS through the structure/class data members trying to find 5743 /// member(s) with user-defined 'default' mapper and generate implicit map 5744 /// clauses for such members with the found 'default' mapper. 5745 static void 5746 processImplicitMapsWithDefaultMappers(Sema &S, DSAStackTy *Stack, 5747 SmallVectorImpl<OMPClause *> &Clauses) { 5748 // Check for the deault mapper for data members. 5749 if (S.getLangOpts().OpenMP < 50) 5750 return; 5751 SmallVector<OMPClause *, 4> ImplicitMaps; 5752 for (int Cnt = 0, EndCnt = Clauses.size(); Cnt < EndCnt; ++Cnt) { 5753 auto *C = dyn_cast<OMPMapClause>(Clauses[Cnt]); 5754 if (!C) 5755 continue; 5756 SmallVector<Expr *, 4> SubExprs; 5757 auto *MI = C->mapperlist_begin(); 5758 for (auto I = C->varlist_begin(), End = C->varlist_end(); I != End; 5759 ++I, ++MI) { 5760 // Expression is mapped using mapper - skip it. 5761 if (*MI) 5762 continue; 5763 Expr *E = *I; 5764 // Expression is dependent - skip it, build the mapper when it gets 5765 // instantiated. 5766 if (E->isTypeDependent() || E->isValueDependent() || 5767 E->containsUnexpandedParameterPack()) 5768 continue; 5769 // Array section - need to check for the mapping of the array section 5770 // element. 5771 QualType CanonType = E->getType().getCanonicalType(); 5772 if (CanonType->isSpecificBuiltinType(BuiltinType::OMPArraySection)) { 5773 const auto *OASE = cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts()); 5774 QualType BaseType = 5775 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 5776 QualType ElemType; 5777 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 5778 ElemType = ATy->getElementType(); 5779 else 5780 ElemType = BaseType->getPointeeType(); 5781 CanonType = ElemType; 5782 } 5783 5784 // DFS over data members in structures/classes. 5785 SmallVector<std::pair<QualType, FieldDecl *>, 4> Types( 5786 1, {CanonType, nullptr}); 5787 llvm::DenseMap<const Type *, Expr *> Visited; 5788 SmallVector<std::pair<FieldDecl *, unsigned>, 4> ParentChain( 5789 1, {nullptr, 1}); 5790 while (!Types.empty()) { 5791 QualType BaseType; 5792 FieldDecl *CurFD; 5793 std::tie(BaseType, CurFD) = Types.pop_back_val(); 5794 while (ParentChain.back().second == 0) 5795 ParentChain.pop_back(); 5796 --ParentChain.back().second; 5797 if (BaseType.isNull()) 5798 continue; 5799 // Only structs/classes are allowed to have mappers. 5800 const RecordDecl *RD = BaseType.getCanonicalType()->getAsRecordDecl(); 5801 if (!RD) 5802 continue; 5803 auto It = Visited.find(BaseType.getTypePtr()); 5804 if (It == Visited.end()) { 5805 // Try to find the associated user-defined mapper. 5806 CXXScopeSpec MapperIdScopeSpec; 5807 DeclarationNameInfo DefaultMapperId; 5808 DefaultMapperId.setName(S.Context.DeclarationNames.getIdentifier( 5809 &S.Context.Idents.get("default"))); 5810 DefaultMapperId.setLoc(E->getExprLoc()); 5811 ExprResult ER = buildUserDefinedMapperRef( 5812 S, Stack->getCurScope(), MapperIdScopeSpec, DefaultMapperId, 5813 BaseType, /*UnresolvedMapper=*/nullptr); 5814 if (ER.isInvalid()) 5815 continue; 5816 It = Visited.try_emplace(BaseType.getTypePtr(), ER.get()).first; 5817 } 5818 // Found default mapper. 5819 if (It->second) { 5820 auto *OE = new (S.Context) OpaqueValueExpr(E->getExprLoc(), CanonType, 5821 VK_LValue, OK_Ordinary, E); 5822 OE->setIsUnique(/*V=*/true); 5823 Expr *BaseExpr = OE; 5824 for (const auto &P : ParentChain) { 5825 if (P.first) { 5826 BaseExpr = S.BuildMemberExpr( 5827 BaseExpr, /*IsArrow=*/false, E->getExprLoc(), 5828 NestedNameSpecifierLoc(), SourceLocation(), P.first, 5829 DeclAccessPair::make(P.first, P.first->getAccess()), 5830 /*HadMultipleCandidates=*/false, DeclarationNameInfo(), 5831 P.first->getType(), VK_LValue, OK_Ordinary); 5832 BaseExpr = S.DefaultLvalueConversion(BaseExpr).get(); 5833 } 5834 } 5835 if (CurFD) 5836 BaseExpr = S.BuildMemberExpr( 5837 BaseExpr, /*IsArrow=*/false, E->getExprLoc(), 5838 NestedNameSpecifierLoc(), SourceLocation(), CurFD, 5839 DeclAccessPair::make(CurFD, CurFD->getAccess()), 5840 /*HadMultipleCandidates=*/false, DeclarationNameInfo(), 5841 CurFD->getType(), VK_LValue, OK_Ordinary); 5842 SubExprs.push_back(BaseExpr); 5843 continue; 5844 } 5845 // Check for the "default" mapper for data members. 5846 bool FirstIter = true; 5847 for (FieldDecl *FD : RD->fields()) { 5848 if (!FD) 5849 continue; 5850 QualType FieldTy = FD->getType(); 5851 if (FieldTy.isNull() || 5852 !(FieldTy->isStructureOrClassType() || FieldTy->isUnionType())) 5853 continue; 5854 if (FirstIter) { 5855 FirstIter = false; 5856 ParentChain.emplace_back(CurFD, 1); 5857 } else { 5858 ++ParentChain.back().second; 5859 } 5860 Types.emplace_back(FieldTy, FD); 5861 } 5862 } 5863 } 5864 if (SubExprs.empty()) 5865 continue; 5866 CXXScopeSpec MapperIdScopeSpec; 5867 DeclarationNameInfo MapperId; 5868 if (OMPClause *NewClause = S.ActOnOpenMPMapClause( 5869 C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), 5870 MapperIdScopeSpec, MapperId, C->getMapType(), 5871 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(), 5872 SubExprs, OMPVarListLocTy())) 5873 Clauses.push_back(NewClause); 5874 } 5875 } 5876 5877 StmtResult Sema::ActOnOpenMPExecutableDirective( 5878 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 5879 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 5880 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 5881 StmtResult Res = StmtError(); 5882 OpenMPBindClauseKind BindKind = OMPC_BIND_unknown; 5883 if (const OMPBindClause *BC = 5884 OMPExecutableDirective::getSingleClause<OMPBindClause>(Clauses)) 5885 BindKind = BC->getBindKind(); 5886 // First check CancelRegion which is then used in checkNestingOfRegions. 5887 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 5888 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 5889 BindKind, StartLoc)) 5890 return StmtError(); 5891 5892 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 5893 VarsWithInheritedDSAType VarsWithInheritedDSA; 5894 bool ErrorFound = false; 5895 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 5896 if (AStmt && !CurContext->isDependentContext() && Kind != OMPD_atomic && 5897 Kind != OMPD_critical && Kind != OMPD_section && Kind != OMPD_master && 5898 Kind != OMPD_masked && !isOpenMPLoopTransformationDirective(Kind)) { 5899 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5900 5901 // Check default data sharing attributes for referenced variables. 5902 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 5903 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 5904 Stmt *S = AStmt; 5905 while (--ThisCaptureLevel >= 0) 5906 S = cast<CapturedStmt>(S)->getCapturedStmt(); 5907 DSAChecker.Visit(S); 5908 if (!isOpenMPTargetDataManagementDirective(Kind) && 5909 !isOpenMPTaskingDirective(Kind)) { 5910 // Visit subcaptures to generate implicit clauses for captured vars. 5911 auto *CS = cast<CapturedStmt>(AStmt); 5912 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 5913 getOpenMPCaptureRegions(CaptureRegions, Kind); 5914 // Ignore outer tasking regions for target directives. 5915 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task) 5916 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 5917 DSAChecker.visitSubCaptures(CS); 5918 } 5919 if (DSAChecker.isErrorFound()) 5920 return StmtError(); 5921 // Generate list of implicitly defined firstprivate variables. 5922 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 5923 5924 SmallVector<Expr *, 4> ImplicitFirstprivates( 5925 DSAChecker.getImplicitFirstprivate().begin(), 5926 DSAChecker.getImplicitFirstprivate().end()); 5927 SmallVector<Expr *, 4> ImplicitPrivates( 5928 DSAChecker.getImplicitPrivate().begin(), 5929 DSAChecker.getImplicitPrivate().end()); 5930 const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1; 5931 SmallVector<Expr *, 4> ImplicitMaps[DefaultmapKindNum][OMPC_MAP_delete]; 5932 SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> 5933 ImplicitMapModifiers[DefaultmapKindNum]; 5934 SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers> 5935 ImplicitMapModifiersLoc[DefaultmapKindNum]; 5936 // Get the original location of present modifier from Defaultmap clause. 5937 SourceLocation PresentModifierLocs[DefaultmapKindNum]; 5938 for (OMPClause *C : Clauses) { 5939 if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C)) 5940 if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present) 5941 PresentModifierLocs[DMC->getDefaultmapKind()] = 5942 DMC->getDefaultmapModifierLoc(); 5943 } 5944 for (unsigned VC = 0; VC < DefaultmapKindNum; ++VC) { 5945 auto Kind = static_cast<OpenMPDefaultmapClauseKind>(VC); 5946 for (unsigned I = 0; I < OMPC_MAP_delete; ++I) { 5947 ArrayRef<Expr *> ImplicitMap = DSAChecker.getImplicitMap( 5948 Kind, static_cast<OpenMPMapClauseKind>(I)); 5949 ImplicitMaps[VC][I].append(ImplicitMap.begin(), ImplicitMap.end()); 5950 } 5951 ArrayRef<OpenMPMapModifierKind> ImplicitModifier = 5952 DSAChecker.getImplicitMapModifier(Kind); 5953 ImplicitMapModifiers[VC].append(ImplicitModifier.begin(), 5954 ImplicitModifier.end()); 5955 std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[VC]), 5956 ImplicitModifier.size(), PresentModifierLocs[VC]); 5957 } 5958 // Mark taskgroup task_reduction descriptors as implicitly firstprivate. 5959 for (OMPClause *C : Clauses) { 5960 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) { 5961 for (Expr *E : IRC->taskgroup_descriptors()) 5962 if (E) 5963 ImplicitFirstprivates.emplace_back(E); 5964 } 5965 // OpenMP 5.0, 2.10.1 task Construct 5966 // [detach clause]... The event-handle will be considered as if it was 5967 // specified on a firstprivate clause. 5968 if (auto *DC = dyn_cast<OMPDetachClause>(C)) 5969 ImplicitFirstprivates.push_back(DC->getEventHandler()); 5970 } 5971 if (!ImplicitFirstprivates.empty()) { 5972 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 5973 ImplicitFirstprivates, SourceLocation(), SourceLocation(), 5974 SourceLocation())) { 5975 ClausesWithImplicit.push_back(Implicit); 5976 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 5977 ImplicitFirstprivates.size(); 5978 } else { 5979 ErrorFound = true; 5980 } 5981 } 5982 if (!ImplicitPrivates.empty()) { 5983 if (OMPClause *Implicit = 5984 ActOnOpenMPPrivateClause(ImplicitPrivates, SourceLocation(), 5985 SourceLocation(), SourceLocation())) { 5986 ClausesWithImplicit.push_back(Implicit); 5987 ErrorFound = cast<OMPPrivateClause>(Implicit)->varlist_size() != 5988 ImplicitPrivates.size(); 5989 } else { 5990 ErrorFound = true; 5991 } 5992 } 5993 // OpenMP 5.0 [2.19.7] 5994 // If a list item appears in a reduction, lastprivate or linear 5995 // clause on a combined target construct then it is treated as 5996 // if it also appears in a map clause with a map-type of tofrom 5997 if (getLangOpts().OpenMP >= 50 && Kind != OMPD_target && 5998 isOpenMPTargetExecutionDirective(Kind)) { 5999 SmallVector<Expr *, 4> ImplicitExprs; 6000 for (OMPClause *C : Clauses) { 6001 if (auto *RC = dyn_cast<OMPReductionClause>(C)) 6002 for (Expr *E : RC->varlists()) 6003 if (!isa<DeclRefExpr>(E->IgnoreParenImpCasts())) 6004 ImplicitExprs.emplace_back(E); 6005 } 6006 if (!ImplicitExprs.empty()) { 6007 ArrayRef<Expr *> Exprs = ImplicitExprs; 6008 CXXScopeSpec MapperIdScopeSpec; 6009 DeclarationNameInfo MapperId; 6010 if (OMPClause *Implicit = ActOnOpenMPMapClause( 6011 OMPC_MAP_MODIFIER_unknown, SourceLocation(), MapperIdScopeSpec, 6012 MapperId, OMPC_MAP_tofrom, 6013 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(), 6014 Exprs, OMPVarListLocTy(), /*NoDiagnose=*/true)) 6015 ClausesWithImplicit.emplace_back(Implicit); 6016 } 6017 } 6018 for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) { 6019 int ClauseKindCnt = -1; 6020 for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) { 6021 ++ClauseKindCnt; 6022 if (ImplicitMap.empty()) 6023 continue; 6024 CXXScopeSpec MapperIdScopeSpec; 6025 DeclarationNameInfo MapperId; 6026 auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt); 6027 if (OMPClause *Implicit = ActOnOpenMPMapClause( 6028 ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I], 6029 MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true, 6030 SourceLocation(), SourceLocation(), ImplicitMap, 6031 OMPVarListLocTy())) { 6032 ClausesWithImplicit.emplace_back(Implicit); 6033 ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() != 6034 ImplicitMap.size(); 6035 } else { 6036 ErrorFound = true; 6037 } 6038 } 6039 } 6040 // Build expressions for implicit maps of data members with 'default' 6041 // mappers. 6042 if (LangOpts.OpenMP >= 50) 6043 processImplicitMapsWithDefaultMappers(*this, DSAStack, 6044 ClausesWithImplicit); 6045 } 6046 6047 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 6048 switch (Kind) { 6049 case OMPD_parallel: 6050 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 6051 EndLoc); 6052 AllowedNameModifiers.push_back(OMPD_parallel); 6053 break; 6054 case OMPD_simd: 6055 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 6056 VarsWithInheritedDSA); 6057 if (LangOpts.OpenMP >= 50) 6058 AllowedNameModifiers.push_back(OMPD_simd); 6059 break; 6060 case OMPD_tile: 6061 Res = 6062 ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 6063 break; 6064 case OMPD_unroll: 6065 Res = ActOnOpenMPUnrollDirective(ClausesWithImplicit, AStmt, StartLoc, 6066 EndLoc); 6067 break; 6068 case OMPD_for: 6069 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 6070 VarsWithInheritedDSA); 6071 break; 6072 case OMPD_for_simd: 6073 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 6074 EndLoc, VarsWithInheritedDSA); 6075 if (LangOpts.OpenMP >= 50) 6076 AllowedNameModifiers.push_back(OMPD_simd); 6077 break; 6078 case OMPD_sections: 6079 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 6080 EndLoc); 6081 break; 6082 case OMPD_section: 6083 assert(ClausesWithImplicit.empty() && 6084 "No clauses are allowed for 'omp section' directive"); 6085 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 6086 break; 6087 case OMPD_single: 6088 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 6089 EndLoc); 6090 break; 6091 case OMPD_master: 6092 assert(ClausesWithImplicit.empty() && 6093 "No clauses are allowed for 'omp master' directive"); 6094 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 6095 break; 6096 case OMPD_masked: 6097 Res = ActOnOpenMPMaskedDirective(ClausesWithImplicit, AStmt, StartLoc, 6098 EndLoc); 6099 break; 6100 case OMPD_critical: 6101 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 6102 StartLoc, EndLoc); 6103 break; 6104 case OMPD_parallel_for: 6105 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 6106 EndLoc, VarsWithInheritedDSA); 6107 AllowedNameModifiers.push_back(OMPD_parallel); 6108 break; 6109 case OMPD_parallel_for_simd: 6110 Res = ActOnOpenMPParallelForSimdDirective( 6111 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6112 AllowedNameModifiers.push_back(OMPD_parallel); 6113 if (LangOpts.OpenMP >= 50) 6114 AllowedNameModifiers.push_back(OMPD_simd); 6115 break; 6116 case OMPD_parallel_master: 6117 Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt, 6118 StartLoc, EndLoc); 6119 AllowedNameModifiers.push_back(OMPD_parallel); 6120 break; 6121 case OMPD_parallel_masked: 6122 Res = ActOnOpenMPParallelMaskedDirective(ClausesWithImplicit, AStmt, 6123 StartLoc, EndLoc); 6124 AllowedNameModifiers.push_back(OMPD_parallel); 6125 break; 6126 case OMPD_parallel_sections: 6127 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 6128 StartLoc, EndLoc); 6129 AllowedNameModifiers.push_back(OMPD_parallel); 6130 break; 6131 case OMPD_task: 6132 Res = 6133 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 6134 AllowedNameModifiers.push_back(OMPD_task); 6135 break; 6136 case OMPD_taskyield: 6137 assert(ClausesWithImplicit.empty() && 6138 "No clauses are allowed for 'omp taskyield' directive"); 6139 assert(AStmt == nullptr && 6140 "No associated statement allowed for 'omp taskyield' directive"); 6141 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 6142 break; 6143 case OMPD_barrier: 6144 assert(ClausesWithImplicit.empty() && 6145 "No clauses are allowed for 'omp barrier' directive"); 6146 assert(AStmt == nullptr && 6147 "No associated statement allowed for 'omp barrier' directive"); 6148 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 6149 break; 6150 case OMPD_taskwait: 6151 assert(AStmt == nullptr && 6152 "No associated statement allowed for 'omp taskwait' directive"); 6153 Res = ActOnOpenMPTaskwaitDirective(ClausesWithImplicit, StartLoc, EndLoc); 6154 break; 6155 case OMPD_taskgroup: 6156 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, 6157 EndLoc); 6158 break; 6159 case OMPD_flush: 6160 assert(AStmt == nullptr && 6161 "No associated statement allowed for 'omp flush' directive"); 6162 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 6163 break; 6164 case OMPD_depobj: 6165 assert(AStmt == nullptr && 6166 "No associated statement allowed for 'omp depobj' directive"); 6167 Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc); 6168 break; 6169 case OMPD_scan: 6170 assert(AStmt == nullptr && 6171 "No associated statement allowed for 'omp scan' directive"); 6172 Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc); 6173 break; 6174 case OMPD_ordered: 6175 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 6176 EndLoc); 6177 break; 6178 case OMPD_atomic: 6179 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 6180 EndLoc); 6181 break; 6182 case OMPD_teams: 6183 Res = 6184 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 6185 break; 6186 case OMPD_target: 6187 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 6188 EndLoc); 6189 AllowedNameModifiers.push_back(OMPD_target); 6190 break; 6191 case OMPD_target_parallel: 6192 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 6193 StartLoc, EndLoc); 6194 AllowedNameModifiers.push_back(OMPD_target); 6195 AllowedNameModifiers.push_back(OMPD_parallel); 6196 break; 6197 case OMPD_target_parallel_for: 6198 Res = ActOnOpenMPTargetParallelForDirective( 6199 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6200 AllowedNameModifiers.push_back(OMPD_target); 6201 AllowedNameModifiers.push_back(OMPD_parallel); 6202 break; 6203 case OMPD_cancellation_point: 6204 assert(ClausesWithImplicit.empty() && 6205 "No clauses are allowed for 'omp cancellation point' directive"); 6206 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 6207 "cancellation point' directive"); 6208 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 6209 break; 6210 case OMPD_cancel: 6211 assert(AStmt == nullptr && 6212 "No associated statement allowed for 'omp cancel' directive"); 6213 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 6214 CancelRegion); 6215 AllowedNameModifiers.push_back(OMPD_cancel); 6216 break; 6217 case OMPD_target_data: 6218 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 6219 EndLoc); 6220 AllowedNameModifiers.push_back(OMPD_target_data); 6221 break; 6222 case OMPD_target_enter_data: 6223 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 6224 EndLoc, AStmt); 6225 AllowedNameModifiers.push_back(OMPD_target_enter_data); 6226 break; 6227 case OMPD_target_exit_data: 6228 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 6229 EndLoc, AStmt); 6230 AllowedNameModifiers.push_back(OMPD_target_exit_data); 6231 break; 6232 case OMPD_taskloop: 6233 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 6234 EndLoc, VarsWithInheritedDSA); 6235 AllowedNameModifiers.push_back(OMPD_taskloop); 6236 break; 6237 case OMPD_taskloop_simd: 6238 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 6239 EndLoc, VarsWithInheritedDSA); 6240 AllowedNameModifiers.push_back(OMPD_taskloop); 6241 if (LangOpts.OpenMP >= 50) 6242 AllowedNameModifiers.push_back(OMPD_simd); 6243 break; 6244 case OMPD_master_taskloop: 6245 Res = ActOnOpenMPMasterTaskLoopDirective( 6246 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6247 AllowedNameModifiers.push_back(OMPD_taskloop); 6248 break; 6249 case OMPD_master_taskloop_simd: 6250 Res = ActOnOpenMPMasterTaskLoopSimdDirective( 6251 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6252 AllowedNameModifiers.push_back(OMPD_taskloop); 6253 if (LangOpts.OpenMP >= 50) 6254 AllowedNameModifiers.push_back(OMPD_simd); 6255 break; 6256 case OMPD_parallel_master_taskloop: 6257 Res = ActOnOpenMPParallelMasterTaskLoopDirective( 6258 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6259 AllowedNameModifiers.push_back(OMPD_taskloop); 6260 AllowedNameModifiers.push_back(OMPD_parallel); 6261 break; 6262 case OMPD_parallel_master_taskloop_simd: 6263 Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective( 6264 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6265 AllowedNameModifiers.push_back(OMPD_taskloop); 6266 AllowedNameModifiers.push_back(OMPD_parallel); 6267 if (LangOpts.OpenMP >= 50) 6268 AllowedNameModifiers.push_back(OMPD_simd); 6269 break; 6270 case OMPD_distribute: 6271 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 6272 EndLoc, VarsWithInheritedDSA); 6273 break; 6274 case OMPD_target_update: 6275 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, 6276 EndLoc, AStmt); 6277 AllowedNameModifiers.push_back(OMPD_target_update); 6278 break; 6279 case OMPD_distribute_parallel_for: 6280 Res = ActOnOpenMPDistributeParallelForDirective( 6281 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6282 AllowedNameModifiers.push_back(OMPD_parallel); 6283 break; 6284 case OMPD_distribute_parallel_for_simd: 6285 Res = ActOnOpenMPDistributeParallelForSimdDirective( 6286 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6287 AllowedNameModifiers.push_back(OMPD_parallel); 6288 if (LangOpts.OpenMP >= 50) 6289 AllowedNameModifiers.push_back(OMPD_simd); 6290 break; 6291 case OMPD_distribute_simd: 6292 Res = ActOnOpenMPDistributeSimdDirective( 6293 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6294 if (LangOpts.OpenMP >= 50) 6295 AllowedNameModifiers.push_back(OMPD_simd); 6296 break; 6297 case OMPD_target_parallel_for_simd: 6298 Res = ActOnOpenMPTargetParallelForSimdDirective( 6299 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6300 AllowedNameModifiers.push_back(OMPD_target); 6301 AllowedNameModifiers.push_back(OMPD_parallel); 6302 if (LangOpts.OpenMP >= 50) 6303 AllowedNameModifiers.push_back(OMPD_simd); 6304 break; 6305 case OMPD_target_simd: 6306 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 6307 EndLoc, VarsWithInheritedDSA); 6308 AllowedNameModifiers.push_back(OMPD_target); 6309 if (LangOpts.OpenMP >= 50) 6310 AllowedNameModifiers.push_back(OMPD_simd); 6311 break; 6312 case OMPD_teams_distribute: 6313 Res = ActOnOpenMPTeamsDistributeDirective( 6314 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6315 break; 6316 case OMPD_teams_distribute_simd: 6317 Res = ActOnOpenMPTeamsDistributeSimdDirective( 6318 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6319 if (LangOpts.OpenMP >= 50) 6320 AllowedNameModifiers.push_back(OMPD_simd); 6321 break; 6322 case OMPD_teams_distribute_parallel_for_simd: 6323 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 6324 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6325 AllowedNameModifiers.push_back(OMPD_parallel); 6326 if (LangOpts.OpenMP >= 50) 6327 AllowedNameModifiers.push_back(OMPD_simd); 6328 break; 6329 case OMPD_teams_distribute_parallel_for: 6330 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 6331 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6332 AllowedNameModifiers.push_back(OMPD_parallel); 6333 break; 6334 case OMPD_target_teams: 6335 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 6336 EndLoc); 6337 AllowedNameModifiers.push_back(OMPD_target); 6338 break; 6339 case OMPD_target_teams_distribute: 6340 Res = ActOnOpenMPTargetTeamsDistributeDirective( 6341 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6342 AllowedNameModifiers.push_back(OMPD_target); 6343 break; 6344 case OMPD_target_teams_distribute_parallel_for: 6345 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 6346 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6347 AllowedNameModifiers.push_back(OMPD_target); 6348 AllowedNameModifiers.push_back(OMPD_parallel); 6349 break; 6350 case OMPD_target_teams_distribute_parallel_for_simd: 6351 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 6352 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6353 AllowedNameModifiers.push_back(OMPD_target); 6354 AllowedNameModifiers.push_back(OMPD_parallel); 6355 if (LangOpts.OpenMP >= 50) 6356 AllowedNameModifiers.push_back(OMPD_simd); 6357 break; 6358 case OMPD_target_teams_distribute_simd: 6359 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 6360 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6361 AllowedNameModifiers.push_back(OMPD_target); 6362 if (LangOpts.OpenMP >= 50) 6363 AllowedNameModifiers.push_back(OMPD_simd); 6364 break; 6365 case OMPD_interop: 6366 assert(AStmt == nullptr && 6367 "No associated statement allowed for 'omp interop' directive"); 6368 Res = ActOnOpenMPInteropDirective(ClausesWithImplicit, StartLoc, EndLoc); 6369 break; 6370 case OMPD_dispatch: 6371 Res = ActOnOpenMPDispatchDirective(ClausesWithImplicit, AStmt, StartLoc, 6372 EndLoc); 6373 break; 6374 case OMPD_loop: 6375 Res = ActOnOpenMPGenericLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 6376 EndLoc, VarsWithInheritedDSA); 6377 break; 6378 case OMPD_teams_loop: 6379 Res = ActOnOpenMPTeamsGenericLoopDirective( 6380 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6381 break; 6382 case OMPD_target_teams_loop: 6383 Res = ActOnOpenMPTargetTeamsGenericLoopDirective( 6384 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6385 break; 6386 case OMPD_parallel_loop: 6387 Res = ActOnOpenMPParallelGenericLoopDirective( 6388 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6389 break; 6390 case OMPD_target_parallel_loop: 6391 Res = ActOnOpenMPTargetParallelGenericLoopDirective( 6392 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6393 break; 6394 case OMPD_declare_target: 6395 case OMPD_end_declare_target: 6396 case OMPD_threadprivate: 6397 case OMPD_allocate: 6398 case OMPD_declare_reduction: 6399 case OMPD_declare_mapper: 6400 case OMPD_declare_simd: 6401 case OMPD_requires: 6402 case OMPD_declare_variant: 6403 case OMPD_begin_declare_variant: 6404 case OMPD_end_declare_variant: 6405 llvm_unreachable("OpenMP Directive is not allowed"); 6406 case OMPD_unknown: 6407 default: 6408 llvm_unreachable("Unknown OpenMP directive"); 6409 } 6410 6411 ErrorFound = Res.isInvalid() || ErrorFound; 6412 6413 // Check variables in the clauses if default(none) or 6414 // default(firstprivate) was specified. 6415 if (DSAStack->getDefaultDSA() == DSA_none || 6416 DSAStack->getDefaultDSA() == DSA_private || 6417 DSAStack->getDefaultDSA() == DSA_firstprivate) { 6418 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr); 6419 for (OMPClause *C : Clauses) { 6420 switch (C->getClauseKind()) { 6421 case OMPC_num_threads: 6422 case OMPC_dist_schedule: 6423 // Do not analyse if no parent teams directive. 6424 if (isOpenMPTeamsDirective(Kind)) 6425 break; 6426 continue; 6427 case OMPC_if: 6428 if (isOpenMPTeamsDirective(Kind) && 6429 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target) 6430 break; 6431 if (isOpenMPParallelDirective(Kind) && 6432 isOpenMPTaskLoopDirective(Kind) && 6433 cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel) 6434 break; 6435 continue; 6436 case OMPC_schedule: 6437 case OMPC_detach: 6438 break; 6439 case OMPC_grainsize: 6440 case OMPC_num_tasks: 6441 case OMPC_final: 6442 case OMPC_priority: 6443 case OMPC_novariants: 6444 case OMPC_nocontext: 6445 // Do not analyze if no parent parallel directive. 6446 if (isOpenMPParallelDirective(Kind)) 6447 break; 6448 continue; 6449 case OMPC_ordered: 6450 case OMPC_device: 6451 case OMPC_num_teams: 6452 case OMPC_thread_limit: 6453 case OMPC_hint: 6454 case OMPC_collapse: 6455 case OMPC_safelen: 6456 case OMPC_simdlen: 6457 case OMPC_sizes: 6458 case OMPC_default: 6459 case OMPC_proc_bind: 6460 case OMPC_private: 6461 case OMPC_firstprivate: 6462 case OMPC_lastprivate: 6463 case OMPC_shared: 6464 case OMPC_reduction: 6465 case OMPC_task_reduction: 6466 case OMPC_in_reduction: 6467 case OMPC_linear: 6468 case OMPC_aligned: 6469 case OMPC_copyin: 6470 case OMPC_copyprivate: 6471 case OMPC_nowait: 6472 case OMPC_untied: 6473 case OMPC_mergeable: 6474 case OMPC_allocate: 6475 case OMPC_read: 6476 case OMPC_write: 6477 case OMPC_update: 6478 case OMPC_capture: 6479 case OMPC_compare: 6480 case OMPC_seq_cst: 6481 case OMPC_acq_rel: 6482 case OMPC_acquire: 6483 case OMPC_release: 6484 case OMPC_relaxed: 6485 case OMPC_depend: 6486 case OMPC_threads: 6487 case OMPC_simd: 6488 case OMPC_map: 6489 case OMPC_nogroup: 6490 case OMPC_defaultmap: 6491 case OMPC_to: 6492 case OMPC_from: 6493 case OMPC_use_device_ptr: 6494 case OMPC_use_device_addr: 6495 case OMPC_is_device_ptr: 6496 case OMPC_has_device_addr: 6497 case OMPC_nontemporal: 6498 case OMPC_order: 6499 case OMPC_destroy: 6500 case OMPC_inclusive: 6501 case OMPC_exclusive: 6502 case OMPC_uses_allocators: 6503 case OMPC_affinity: 6504 case OMPC_bind: 6505 continue; 6506 case OMPC_allocator: 6507 case OMPC_flush: 6508 case OMPC_depobj: 6509 case OMPC_threadprivate: 6510 case OMPC_uniform: 6511 case OMPC_unknown: 6512 case OMPC_unified_address: 6513 case OMPC_unified_shared_memory: 6514 case OMPC_reverse_offload: 6515 case OMPC_dynamic_allocators: 6516 case OMPC_atomic_default_mem_order: 6517 case OMPC_device_type: 6518 case OMPC_match: 6519 case OMPC_when: 6520 default: 6521 llvm_unreachable("Unexpected clause"); 6522 } 6523 for (Stmt *CC : C->children()) { 6524 if (CC) 6525 DSAChecker.Visit(CC); 6526 } 6527 } 6528 for (const auto &P : DSAChecker.getVarsWithInheritedDSA()) 6529 VarsWithInheritedDSA[P.getFirst()] = P.getSecond(); 6530 } 6531 for (const auto &P : VarsWithInheritedDSA) { 6532 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst())) 6533 continue; 6534 ErrorFound = true; 6535 if (DSAStack->getDefaultDSA() == DSA_none || 6536 DSAStack->getDefaultDSA() == DSA_private || 6537 DSAStack->getDefaultDSA() == DSA_firstprivate) { 6538 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 6539 << P.first << P.second->getSourceRange(); 6540 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none); 6541 } else if (getLangOpts().OpenMP >= 50) { 6542 Diag(P.second->getExprLoc(), 6543 diag::err_omp_defaultmap_no_attr_for_variable) 6544 << P.first << P.second->getSourceRange(); 6545 Diag(DSAStack->getDefaultDSALocation(), 6546 diag::note_omp_defaultmap_attr_none); 6547 } 6548 } 6549 6550 if (!AllowedNameModifiers.empty()) 6551 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 6552 ErrorFound; 6553 6554 if (ErrorFound) 6555 return StmtError(); 6556 6557 if (!CurContext->isDependentContext() && 6558 isOpenMPTargetExecutionDirective(Kind) && 6559 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || 6560 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() || 6561 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() || 6562 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) { 6563 // Register target to DSA Stack. 6564 DSAStack->addTargetDirLocation(StartLoc); 6565 } 6566 6567 return Res; 6568 } 6569 6570 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 6571 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 6572 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 6573 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 6574 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 6575 assert(Aligneds.size() == Alignments.size()); 6576 assert(Linears.size() == LinModifiers.size()); 6577 assert(Linears.size() == Steps.size()); 6578 if (!DG || DG.get().isNull()) 6579 return DeclGroupPtrTy(); 6580 6581 const int SimdId = 0; 6582 if (!DG.get().isSingleDecl()) { 6583 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant) 6584 << SimdId; 6585 return DG; 6586 } 6587 Decl *ADecl = DG.get().getSingleDecl(); 6588 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 6589 ADecl = FTD->getTemplatedDecl(); 6590 6591 auto *FD = dyn_cast<FunctionDecl>(ADecl); 6592 if (!FD) { 6593 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId; 6594 return DeclGroupPtrTy(); 6595 } 6596 6597 // OpenMP [2.8.2, declare simd construct, Description] 6598 // The parameter of the simdlen clause must be a constant positive integer 6599 // expression. 6600 ExprResult SL; 6601 if (Simdlen) 6602 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 6603 // OpenMP [2.8.2, declare simd construct, Description] 6604 // The special this pointer can be used as if was one of the arguments to the 6605 // function in any of the linear, aligned, or uniform clauses. 6606 // The uniform clause declares one or more arguments to have an invariant 6607 // value for all concurrent invocations of the function in the execution of a 6608 // single SIMD loop. 6609 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs; 6610 const Expr *UniformedLinearThis = nullptr; 6611 for (const Expr *E : Uniforms) { 6612 E = E->IgnoreParenImpCasts(); 6613 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 6614 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 6615 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 6616 FD->getParamDecl(PVD->getFunctionScopeIndex()) 6617 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 6618 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E); 6619 continue; 6620 } 6621 if (isa<CXXThisExpr>(E)) { 6622 UniformedLinearThis = E; 6623 continue; 6624 } 6625 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 6626 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 6627 } 6628 // OpenMP [2.8.2, declare simd construct, Description] 6629 // The aligned clause declares that the object to which each list item points 6630 // is aligned to the number of bytes expressed in the optional parameter of 6631 // the aligned clause. 6632 // The special this pointer can be used as if was one of the arguments to the 6633 // function in any of the linear, aligned, or uniform clauses. 6634 // The type of list items appearing in the aligned clause must be array, 6635 // pointer, reference to array, or reference to pointer. 6636 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs; 6637 const Expr *AlignedThis = nullptr; 6638 for (const Expr *E : Aligneds) { 6639 E = E->IgnoreParenImpCasts(); 6640 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 6641 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 6642 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 6643 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 6644 FD->getParamDecl(PVD->getFunctionScopeIndex()) 6645 ->getCanonicalDecl() == CanonPVD) { 6646 // OpenMP [2.8.1, simd construct, Restrictions] 6647 // A list-item cannot appear in more than one aligned clause. 6648 if (AlignedArgs.count(CanonPVD) > 0) { 6649 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice) 6650 << 1 << getOpenMPClauseName(OMPC_aligned) 6651 << E->getSourceRange(); 6652 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 6653 diag::note_omp_explicit_dsa) 6654 << getOpenMPClauseName(OMPC_aligned); 6655 continue; 6656 } 6657 AlignedArgs[CanonPVD] = E; 6658 QualType QTy = PVD->getType() 6659 .getNonReferenceType() 6660 .getUnqualifiedType() 6661 .getCanonicalType(); 6662 const Type *Ty = QTy.getTypePtrOrNull(); 6663 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 6664 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 6665 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 6666 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 6667 } 6668 continue; 6669 } 6670 } 6671 if (isa<CXXThisExpr>(E)) { 6672 if (AlignedThis) { 6673 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice) 6674 << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange(); 6675 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 6676 << getOpenMPClauseName(OMPC_aligned); 6677 } 6678 AlignedThis = E; 6679 continue; 6680 } 6681 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 6682 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 6683 } 6684 // The optional parameter of the aligned clause, alignment, must be a constant 6685 // positive integer expression. If no optional parameter is specified, 6686 // implementation-defined default alignments for SIMD instructions on the 6687 // target platforms are assumed. 6688 SmallVector<const Expr *, 4> NewAligns; 6689 for (Expr *E : Alignments) { 6690 ExprResult Align; 6691 if (E) 6692 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 6693 NewAligns.push_back(Align.get()); 6694 } 6695 // OpenMP [2.8.2, declare simd construct, Description] 6696 // The linear clause declares one or more list items to be private to a SIMD 6697 // lane and to have a linear relationship with respect to the iteration space 6698 // of a loop. 6699 // The special this pointer can be used as if was one of the arguments to the 6700 // function in any of the linear, aligned, or uniform clauses. 6701 // When a linear-step expression is specified in a linear clause it must be 6702 // either a constant integer expression or an integer-typed parameter that is 6703 // specified in a uniform clause on the directive. 6704 llvm::DenseMap<const Decl *, const Expr *> LinearArgs; 6705 const bool IsUniformedThis = UniformedLinearThis != nullptr; 6706 auto MI = LinModifiers.begin(); 6707 for (const Expr *E : Linears) { 6708 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 6709 ++MI; 6710 E = E->IgnoreParenImpCasts(); 6711 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 6712 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 6713 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 6714 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 6715 FD->getParamDecl(PVD->getFunctionScopeIndex()) 6716 ->getCanonicalDecl() == CanonPVD) { 6717 // OpenMP [2.15.3.7, linear Clause, Restrictions] 6718 // A list-item cannot appear in more than one linear clause. 6719 if (LinearArgs.count(CanonPVD) > 0) { 6720 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 6721 << getOpenMPClauseName(OMPC_linear) 6722 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 6723 Diag(LinearArgs[CanonPVD]->getExprLoc(), 6724 diag::note_omp_explicit_dsa) 6725 << getOpenMPClauseName(OMPC_linear); 6726 continue; 6727 } 6728 // Each argument can appear in at most one uniform or linear clause. 6729 if (UniformedArgs.count(CanonPVD) > 0) { 6730 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 6731 << getOpenMPClauseName(OMPC_linear) 6732 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 6733 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 6734 diag::note_omp_explicit_dsa) 6735 << getOpenMPClauseName(OMPC_uniform); 6736 continue; 6737 } 6738 LinearArgs[CanonPVD] = E; 6739 if (E->isValueDependent() || E->isTypeDependent() || 6740 E->isInstantiationDependent() || 6741 E->containsUnexpandedParameterPack()) 6742 continue; 6743 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 6744 PVD->getOriginalType(), 6745 /*IsDeclareSimd=*/true); 6746 continue; 6747 } 6748 } 6749 if (isa<CXXThisExpr>(E)) { 6750 if (UniformedLinearThis) { 6751 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 6752 << getOpenMPClauseName(OMPC_linear) 6753 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 6754 << E->getSourceRange(); 6755 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 6756 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 6757 : OMPC_linear); 6758 continue; 6759 } 6760 UniformedLinearThis = E; 6761 if (E->isValueDependent() || E->isTypeDependent() || 6762 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 6763 continue; 6764 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 6765 E->getType(), /*IsDeclareSimd=*/true); 6766 continue; 6767 } 6768 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 6769 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 6770 } 6771 Expr *Step = nullptr; 6772 Expr *NewStep = nullptr; 6773 SmallVector<Expr *, 4> NewSteps; 6774 for (Expr *E : Steps) { 6775 // Skip the same step expression, it was checked already. 6776 if (Step == E || !E) { 6777 NewSteps.push_back(E ? NewStep : nullptr); 6778 continue; 6779 } 6780 Step = E; 6781 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step)) 6782 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 6783 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 6784 if (UniformedArgs.count(CanonPVD) == 0) { 6785 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 6786 << Step->getSourceRange(); 6787 } else if (E->isValueDependent() || E->isTypeDependent() || 6788 E->isInstantiationDependent() || 6789 E->containsUnexpandedParameterPack() || 6790 CanonPVD->getType()->hasIntegerRepresentation()) { 6791 NewSteps.push_back(Step); 6792 } else { 6793 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 6794 << Step->getSourceRange(); 6795 } 6796 continue; 6797 } 6798 NewStep = Step; 6799 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 6800 !Step->isInstantiationDependent() && 6801 !Step->containsUnexpandedParameterPack()) { 6802 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 6803 .get(); 6804 if (NewStep) 6805 NewStep = 6806 VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get(); 6807 } 6808 NewSteps.push_back(NewStep); 6809 } 6810 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 6811 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 6812 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 6813 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 6814 const_cast<Expr **>(Linears.data()), Linears.size(), 6815 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 6816 NewSteps.data(), NewSteps.size(), SR); 6817 ADecl->addAttr(NewAttr); 6818 return DG; 6819 } 6820 6821 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto, 6822 QualType NewType) { 6823 assert(NewType->isFunctionProtoType() && 6824 "Expected function type with prototype."); 6825 assert(FD->getType()->isFunctionNoProtoType() && 6826 "Expected function with type with no prototype."); 6827 assert(FDWithProto->getType()->isFunctionProtoType() && 6828 "Expected function with prototype."); 6829 // Synthesize parameters with the same types. 6830 FD->setType(NewType); 6831 SmallVector<ParmVarDecl *, 16> Params; 6832 for (const ParmVarDecl *P : FDWithProto->parameters()) { 6833 auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(), 6834 SourceLocation(), nullptr, P->getType(), 6835 /*TInfo=*/nullptr, SC_None, nullptr); 6836 Param->setScopeInfo(0, Params.size()); 6837 Param->setImplicit(); 6838 Params.push_back(Param); 6839 } 6840 6841 FD->setParams(Params); 6842 } 6843 6844 void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) { 6845 if (D->isInvalidDecl()) 6846 return; 6847 FunctionDecl *FD = nullptr; 6848 if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D)) 6849 FD = UTemplDecl->getTemplatedDecl(); 6850 else 6851 FD = cast<FunctionDecl>(D); 6852 assert(FD && "Expected a function declaration!"); 6853 6854 // If we are instantiating templates we do *not* apply scoped assumptions but 6855 // only global ones. We apply scoped assumption to the template definition 6856 // though. 6857 if (!inTemplateInstantiation()) { 6858 for (AssumptionAttr *AA : OMPAssumeScoped) 6859 FD->addAttr(AA); 6860 } 6861 for (AssumptionAttr *AA : OMPAssumeGlobal) 6862 FD->addAttr(AA); 6863 } 6864 6865 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI) 6866 : TI(&TI), NameSuffix(TI.getMangledName()) {} 6867 6868 void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 6869 Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, 6870 SmallVectorImpl<FunctionDecl *> &Bases) { 6871 if (!D.getIdentifier()) 6872 return; 6873 6874 OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back(); 6875 6876 // Template specialization is an extension, check if we do it. 6877 bool IsTemplated = !TemplateParamLists.empty(); 6878 if (IsTemplated & 6879 !DVScope.TI->isExtensionActive( 6880 llvm::omp::TraitProperty::implementation_extension_allow_templates)) 6881 return; 6882 6883 IdentifierInfo *BaseII = D.getIdentifier(); 6884 LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(), 6885 LookupOrdinaryName); 6886 LookupParsedName(Lookup, S, &D.getCXXScopeSpec()); 6887 6888 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6889 QualType FType = TInfo->getType(); 6890 6891 bool IsConstexpr = 6892 D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr; 6893 bool IsConsteval = 6894 D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval; 6895 6896 for (auto *Candidate : Lookup) { 6897 auto *CandidateDecl = Candidate->getUnderlyingDecl(); 6898 FunctionDecl *UDecl = nullptr; 6899 if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl)) { 6900 auto *FTD = cast<FunctionTemplateDecl>(CandidateDecl); 6901 if (FTD->getTemplateParameters()->size() == TemplateParamLists.size()) 6902 UDecl = FTD->getTemplatedDecl(); 6903 } else if (!IsTemplated) 6904 UDecl = dyn_cast<FunctionDecl>(CandidateDecl); 6905 if (!UDecl) 6906 continue; 6907 6908 // Don't specialize constexpr/consteval functions with 6909 // non-constexpr/consteval functions. 6910 if (UDecl->isConstexpr() && !IsConstexpr) 6911 continue; 6912 if (UDecl->isConsteval() && !IsConsteval) 6913 continue; 6914 6915 QualType UDeclTy = UDecl->getType(); 6916 if (!UDeclTy->isDependentType()) { 6917 QualType NewType = Context.mergeFunctionTypes( 6918 FType, UDeclTy, /* OfBlockPointer */ false, 6919 /* Unqualified */ false, /* AllowCXX */ true); 6920 if (NewType.isNull()) 6921 continue; 6922 } 6923 6924 // Found a base! 6925 Bases.push_back(UDecl); 6926 } 6927 6928 bool UseImplicitBase = !DVScope.TI->isExtensionActive( 6929 llvm::omp::TraitProperty::implementation_extension_disable_implicit_base); 6930 // If no base was found we create a declaration that we use as base. 6931 if (Bases.empty() && UseImplicitBase) { 6932 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 6933 Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists); 6934 BaseD->setImplicit(true); 6935 if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD)) 6936 Bases.push_back(BaseTemplD->getTemplatedDecl()); 6937 else 6938 Bases.push_back(cast<FunctionDecl>(BaseD)); 6939 } 6940 6941 std::string MangledName; 6942 MangledName += D.getIdentifier()->getName(); 6943 MangledName += getOpenMPVariantManglingSeparatorStr(); 6944 MangledName += DVScope.NameSuffix; 6945 IdentifierInfo &VariantII = Context.Idents.get(MangledName); 6946 6947 VariantII.setMangledOpenMPVariantName(true); 6948 D.SetIdentifier(&VariantII, D.getBeginLoc()); 6949 } 6950 6951 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 6952 Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) { 6953 // Do not mark function as is used to prevent its emission if this is the 6954 // only place where it is used. 6955 EnterExpressionEvaluationContext Unevaluated( 6956 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6957 6958 FunctionDecl *FD = nullptr; 6959 if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D)) 6960 FD = UTemplDecl->getTemplatedDecl(); 6961 else 6962 FD = cast<FunctionDecl>(D); 6963 auto *VariantFuncRef = DeclRefExpr::Create( 6964 Context, NestedNameSpecifierLoc(), SourceLocation(), FD, 6965 /* RefersToEnclosingVariableOrCapture */ false, 6966 /* NameLoc */ FD->getLocation(), FD->getType(), 6967 ExprValueKind::VK_PRValue); 6968 6969 OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back(); 6970 auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit( 6971 Context, VariantFuncRef, DVScope.TI, 6972 /*NothingArgs=*/nullptr, /*NothingArgsSize=*/0, 6973 /*NeedDevicePtrArgs=*/nullptr, /*NeedDevicePtrArgsSize=*/0, 6974 /*AppendArgs=*/nullptr, /*AppendArgsSize=*/0); 6975 for (FunctionDecl *BaseFD : Bases) 6976 BaseFD->addAttr(OMPDeclareVariantA); 6977 } 6978 6979 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope, 6980 SourceLocation LParenLoc, 6981 MultiExprArg ArgExprs, 6982 SourceLocation RParenLoc, Expr *ExecConfig) { 6983 // The common case is a regular call we do not want to specialize at all. Try 6984 // to make that case fast by bailing early. 6985 CallExpr *CE = dyn_cast<CallExpr>(Call.get()); 6986 if (!CE) 6987 return Call; 6988 6989 FunctionDecl *CalleeFnDecl = CE->getDirectCallee(); 6990 if (!CalleeFnDecl) 6991 return Call; 6992 6993 if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>()) 6994 return Call; 6995 6996 ASTContext &Context = getASTContext(); 6997 std::function<void(StringRef)> DiagUnknownTrait = [this, 6998 CE](StringRef ISATrait) { 6999 // TODO Track the selector locations in a way that is accessible here to 7000 // improve the diagnostic location. 7001 Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait) 7002 << ISATrait; 7003 }; 7004 TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait), 7005 getCurFunctionDecl(), DSAStack->getConstructTraits()); 7006 7007 QualType CalleeFnType = CalleeFnDecl->getType(); 7008 7009 SmallVector<Expr *, 4> Exprs; 7010 SmallVector<VariantMatchInfo, 4> VMIs; 7011 while (CalleeFnDecl) { 7012 for (OMPDeclareVariantAttr *A : 7013 CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) { 7014 Expr *VariantRef = A->getVariantFuncRef(); 7015 7016 VariantMatchInfo VMI; 7017 OMPTraitInfo &TI = A->getTraitInfo(); 7018 TI.getAsVariantMatchInfo(Context, VMI); 7019 if (!isVariantApplicableInContext(VMI, OMPCtx, 7020 /* DeviceSetOnly */ false)) 7021 continue; 7022 7023 VMIs.push_back(VMI); 7024 Exprs.push_back(VariantRef); 7025 } 7026 7027 CalleeFnDecl = CalleeFnDecl->getPreviousDecl(); 7028 } 7029 7030 ExprResult NewCall; 7031 do { 7032 int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx); 7033 if (BestIdx < 0) 7034 return Call; 7035 Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]); 7036 Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl(); 7037 7038 { 7039 // Try to build a (member) call expression for the current best applicable 7040 // variant expression. We allow this to fail in which case we continue 7041 // with the next best variant expression. The fail case is part of the 7042 // implementation defined behavior in the OpenMP standard when it talks 7043 // about what differences in the function prototypes: "Any differences 7044 // that the specific OpenMP context requires in the prototype of the 7045 // variant from the base function prototype are implementation defined." 7046 // This wording is there to allow the specialized variant to have a 7047 // different type than the base function. This is intended and OK but if 7048 // we cannot create a call the difference is not in the "implementation 7049 // defined range" we allow. 7050 Sema::TentativeAnalysisScope Trap(*this); 7051 7052 if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) { 7053 auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE); 7054 BestExpr = MemberExpr::CreateImplicit( 7055 Context, MemberCall->getImplicitObjectArgument(), 7056 /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy, 7057 MemberCall->getValueKind(), MemberCall->getObjectKind()); 7058 } 7059 NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc, 7060 ExecConfig); 7061 if (NewCall.isUsable()) { 7062 if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) { 7063 FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee(); 7064 QualType NewType = Context.mergeFunctionTypes( 7065 CalleeFnType, NewCalleeFnDecl->getType(), 7066 /* OfBlockPointer */ false, 7067 /* Unqualified */ false, /* AllowCXX */ true); 7068 if (!NewType.isNull()) 7069 break; 7070 // Don't use the call if the function type was not compatible. 7071 NewCall = nullptr; 7072 } 7073 } 7074 } 7075 7076 VMIs.erase(VMIs.begin() + BestIdx); 7077 Exprs.erase(Exprs.begin() + BestIdx); 7078 } while (!VMIs.empty()); 7079 7080 if (!NewCall.isUsable()) 7081 return Call; 7082 return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0); 7083 } 7084 7085 Optional<std::pair<FunctionDecl *, Expr *>> 7086 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG, 7087 Expr *VariantRef, OMPTraitInfo &TI, 7088 unsigned NumAppendArgs, 7089 SourceRange SR) { 7090 if (!DG || DG.get().isNull()) 7091 return None; 7092 7093 const int VariantId = 1; 7094 // Must be applied only to single decl. 7095 if (!DG.get().isSingleDecl()) { 7096 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant) 7097 << VariantId << SR; 7098 return None; 7099 } 7100 Decl *ADecl = DG.get().getSingleDecl(); 7101 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 7102 ADecl = FTD->getTemplatedDecl(); 7103 7104 // Decl must be a function. 7105 auto *FD = dyn_cast<FunctionDecl>(ADecl); 7106 if (!FD) { 7107 Diag(ADecl->getLocation(), diag::err_omp_function_expected) 7108 << VariantId << SR; 7109 return None; 7110 } 7111 7112 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) { 7113 // The 'target' attribute needs to be separately checked because it does 7114 // not always signify a multiversion function declaration. 7115 return FD->isMultiVersion() || FD->hasAttr<TargetAttr>(); 7116 }; 7117 // OpenMP is not compatible with multiversion function attributes. 7118 if (HasMultiVersionAttributes(FD)) { 7119 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes) 7120 << SR; 7121 return None; 7122 } 7123 7124 // Allow #pragma omp declare variant only if the function is not used. 7125 if (FD->isUsed(false)) 7126 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used) 7127 << FD->getLocation(); 7128 7129 // Check if the function was emitted already. 7130 const FunctionDecl *Definition; 7131 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) && 7132 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition))) 7133 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted) 7134 << FD->getLocation(); 7135 7136 // The VariantRef must point to function. 7137 if (!VariantRef) { 7138 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId; 7139 return None; 7140 } 7141 7142 auto ShouldDelayChecks = [](Expr *&E, bool) { 7143 return E && (E->isTypeDependent() || E->isValueDependent() || 7144 E->containsUnexpandedParameterPack() || 7145 E->isInstantiationDependent()); 7146 }; 7147 // Do not check templates, wait until instantiation. 7148 if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) || 7149 TI.anyScoreOrCondition(ShouldDelayChecks)) 7150 return std::make_pair(FD, VariantRef); 7151 7152 // Deal with non-constant score and user condition expressions. 7153 auto HandleNonConstantScoresAndConditions = [this](Expr *&E, 7154 bool IsScore) -> bool { 7155 if (!E || E->isIntegerConstantExpr(Context)) 7156 return false; 7157 7158 if (IsScore) { 7159 // We warn on non-constant scores and pretend they were not present. 7160 Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant) 7161 << E; 7162 E = nullptr; 7163 } else { 7164 // We could replace a non-constant user condition with "false" but we 7165 // will soon need to handle these anyway for the dynamic version of 7166 // OpenMP context selectors. 7167 Diag(E->getExprLoc(), 7168 diag::err_omp_declare_variant_user_condition_not_constant) 7169 << E; 7170 } 7171 return true; 7172 }; 7173 if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions)) 7174 return None; 7175 7176 QualType AdjustedFnType = FD->getType(); 7177 if (NumAppendArgs) { 7178 const auto *PTy = AdjustedFnType->getAsAdjusted<FunctionProtoType>(); 7179 if (!PTy) { 7180 Diag(FD->getLocation(), diag::err_omp_declare_variant_prototype_required) 7181 << SR; 7182 return None; 7183 } 7184 // Adjust the function type to account for an extra omp_interop_t for each 7185 // specified in the append_args clause. 7186 const TypeDecl *TD = nullptr; 7187 LookupResult Result(*this, &Context.Idents.get("omp_interop_t"), 7188 SR.getBegin(), Sema::LookupOrdinaryName); 7189 if (LookupName(Result, getCurScope())) { 7190 NamedDecl *ND = Result.getFoundDecl(); 7191 TD = dyn_cast_or_null<TypeDecl>(ND); 7192 } 7193 if (!TD) { 7194 Diag(SR.getBegin(), diag::err_omp_interop_type_not_found) << SR; 7195 return None; 7196 } 7197 QualType InteropType = Context.getTypeDeclType(TD); 7198 if (PTy->isVariadic()) { 7199 Diag(FD->getLocation(), diag::err_omp_append_args_with_varargs) << SR; 7200 return None; 7201 } 7202 llvm::SmallVector<QualType, 8> Params; 7203 Params.append(PTy->param_type_begin(), PTy->param_type_end()); 7204 Params.insert(Params.end(), NumAppendArgs, InteropType); 7205 AdjustedFnType = Context.getFunctionType(PTy->getReturnType(), Params, 7206 PTy->getExtProtoInfo()); 7207 } 7208 7209 // Convert VariantRef expression to the type of the original function to 7210 // resolve possible conflicts. 7211 ExprResult VariantRefCast = VariantRef; 7212 if (LangOpts.CPlusPlus) { 7213 QualType FnPtrType; 7214 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7215 if (Method && !Method->isStatic()) { 7216 const Type *ClassType = 7217 Context.getTypeDeclType(Method->getParent()).getTypePtr(); 7218 FnPtrType = Context.getMemberPointerType(AdjustedFnType, ClassType); 7219 ExprResult ER; 7220 { 7221 // Build adrr_of unary op to correctly handle type checks for member 7222 // functions. 7223 Sema::TentativeAnalysisScope Trap(*this); 7224 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf, 7225 VariantRef); 7226 } 7227 if (!ER.isUsable()) { 7228 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7229 << VariantId << VariantRef->getSourceRange(); 7230 return None; 7231 } 7232 VariantRef = ER.get(); 7233 } else { 7234 FnPtrType = Context.getPointerType(AdjustedFnType); 7235 } 7236 QualType VarianPtrType = Context.getPointerType(VariantRef->getType()); 7237 if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) { 7238 ImplicitConversionSequence ICS = TryImplicitConversion( 7239 VariantRef, FnPtrType.getUnqualifiedType(), 7240 /*SuppressUserConversions=*/false, AllowedExplicit::None, 7241 /*InOverloadResolution=*/false, 7242 /*CStyle=*/false, 7243 /*AllowObjCWritebackConversion=*/false); 7244 if (ICS.isFailure()) { 7245 Diag(VariantRef->getExprLoc(), 7246 diag::err_omp_declare_variant_incompat_types) 7247 << VariantRef->getType() 7248 << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType()) 7249 << (NumAppendArgs ? 1 : 0) << VariantRef->getSourceRange(); 7250 return None; 7251 } 7252 VariantRefCast = PerformImplicitConversion( 7253 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting); 7254 if (!VariantRefCast.isUsable()) 7255 return None; 7256 } 7257 // Drop previously built artificial addr_of unary op for member functions. 7258 if (Method && !Method->isStatic()) { 7259 Expr *PossibleAddrOfVariantRef = VariantRefCast.get(); 7260 if (auto *UO = dyn_cast<UnaryOperator>( 7261 PossibleAddrOfVariantRef->IgnoreImplicit())) 7262 VariantRefCast = UO->getSubExpr(); 7263 } 7264 } 7265 7266 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get()); 7267 if (!ER.isUsable() || 7268 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) { 7269 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7270 << VariantId << VariantRef->getSourceRange(); 7271 return None; 7272 } 7273 7274 // The VariantRef must point to function. 7275 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts()); 7276 if (!DRE) { 7277 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7278 << VariantId << VariantRef->getSourceRange(); 7279 return None; 7280 } 7281 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl()); 7282 if (!NewFD) { 7283 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7284 << VariantId << VariantRef->getSourceRange(); 7285 return None; 7286 } 7287 7288 if (FD->getCanonicalDecl() == NewFD->getCanonicalDecl()) { 7289 Diag(VariantRef->getExprLoc(), 7290 diag::err_omp_declare_variant_same_base_function) 7291 << VariantRef->getSourceRange(); 7292 return None; 7293 } 7294 7295 // Check if function types are compatible in C. 7296 if (!LangOpts.CPlusPlus) { 7297 QualType NewType = 7298 Context.mergeFunctionTypes(AdjustedFnType, NewFD->getType()); 7299 if (NewType.isNull()) { 7300 Diag(VariantRef->getExprLoc(), 7301 diag::err_omp_declare_variant_incompat_types) 7302 << NewFD->getType() << FD->getType() << (NumAppendArgs ? 1 : 0) 7303 << VariantRef->getSourceRange(); 7304 return None; 7305 } 7306 if (NewType->isFunctionProtoType()) { 7307 if (FD->getType()->isFunctionNoProtoType()) 7308 setPrototype(*this, FD, NewFD, NewType); 7309 else if (NewFD->getType()->isFunctionNoProtoType()) 7310 setPrototype(*this, NewFD, FD, NewType); 7311 } 7312 } 7313 7314 // Check if variant function is not marked with declare variant directive. 7315 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) { 7316 Diag(VariantRef->getExprLoc(), 7317 diag::warn_omp_declare_variant_marked_as_declare_variant) 7318 << VariantRef->getSourceRange(); 7319 SourceRange SR = 7320 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange(); 7321 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR; 7322 return None; 7323 } 7324 7325 enum DoesntSupport { 7326 VirtFuncs = 1, 7327 Constructors = 3, 7328 Destructors = 4, 7329 DeletedFuncs = 5, 7330 DefaultedFuncs = 6, 7331 ConstexprFuncs = 7, 7332 ConstevalFuncs = 8, 7333 }; 7334 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) { 7335 if (CXXFD->isVirtual()) { 7336 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7337 << VirtFuncs; 7338 return None; 7339 } 7340 7341 if (isa<CXXConstructorDecl>(FD)) { 7342 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7343 << Constructors; 7344 return None; 7345 } 7346 7347 if (isa<CXXDestructorDecl>(FD)) { 7348 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7349 << Destructors; 7350 return None; 7351 } 7352 } 7353 7354 if (FD->isDeleted()) { 7355 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7356 << DeletedFuncs; 7357 return None; 7358 } 7359 7360 if (FD->isDefaulted()) { 7361 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7362 << DefaultedFuncs; 7363 return None; 7364 } 7365 7366 if (FD->isConstexpr()) { 7367 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7368 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 7369 return None; 7370 } 7371 7372 // Check general compatibility. 7373 if (areMultiversionVariantFunctionsCompatible( 7374 FD, NewFD, PartialDiagnostic::NullDiagnostic(), 7375 PartialDiagnosticAt(SourceLocation(), 7376 PartialDiagnostic::NullDiagnostic()), 7377 PartialDiagnosticAt( 7378 VariantRef->getExprLoc(), 7379 PDiag(diag::err_omp_declare_variant_doesnt_support)), 7380 PartialDiagnosticAt(VariantRef->getExprLoc(), 7381 PDiag(diag::err_omp_declare_variant_diff) 7382 << FD->getLocation()), 7383 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false, 7384 /*CLinkageMayDiffer=*/true)) 7385 return None; 7386 return std::make_pair(FD, cast<Expr>(DRE)); 7387 } 7388 7389 void Sema::ActOnOpenMPDeclareVariantDirective( 7390 FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, 7391 ArrayRef<Expr *> AdjustArgsNothing, 7392 ArrayRef<Expr *> AdjustArgsNeedDevicePtr, 7393 ArrayRef<OMPDeclareVariantAttr::InteropType> AppendArgs, 7394 SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc, 7395 SourceRange SR) { 7396 7397 // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions] 7398 // An adjust_args clause or append_args clause can only be specified if the 7399 // dispatch selector of the construct selector set appears in the match 7400 // clause. 7401 7402 SmallVector<Expr *, 8> AllAdjustArgs; 7403 llvm::append_range(AllAdjustArgs, AdjustArgsNothing); 7404 llvm::append_range(AllAdjustArgs, AdjustArgsNeedDevicePtr); 7405 7406 if (!AllAdjustArgs.empty() || !AppendArgs.empty()) { 7407 VariantMatchInfo VMI; 7408 TI.getAsVariantMatchInfo(Context, VMI); 7409 if (!llvm::is_contained( 7410 VMI.ConstructTraits, 7411 llvm::omp::TraitProperty::construct_dispatch_dispatch)) { 7412 if (!AllAdjustArgs.empty()) 7413 Diag(AdjustArgsLoc, diag::err_omp_clause_requires_dispatch_construct) 7414 << getOpenMPClauseName(OMPC_adjust_args); 7415 if (!AppendArgs.empty()) 7416 Diag(AppendArgsLoc, diag::err_omp_clause_requires_dispatch_construct) 7417 << getOpenMPClauseName(OMPC_append_args); 7418 return; 7419 } 7420 } 7421 7422 // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions] 7423 // Each argument can only appear in a single adjust_args clause for each 7424 // declare variant directive. 7425 llvm::SmallPtrSet<const VarDecl *, 4> AdjustVars; 7426 7427 for (Expr *E : AllAdjustArgs) { 7428 E = E->IgnoreParenImpCasts(); 7429 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) { 7430 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 7431 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 7432 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 7433 FD->getParamDecl(PVD->getFunctionScopeIndex()) 7434 ->getCanonicalDecl() == CanonPVD) { 7435 // It's a parameter of the function, check duplicates. 7436 if (!AdjustVars.insert(CanonPVD).second) { 7437 Diag(DRE->getLocation(), diag::err_omp_adjust_arg_multiple_clauses) 7438 << PVD; 7439 return; 7440 } 7441 continue; 7442 } 7443 } 7444 } 7445 // Anything that is not a function parameter is an error. 7446 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) << FD << 0; 7447 return; 7448 } 7449 7450 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit( 7451 Context, VariantRef, &TI, const_cast<Expr **>(AdjustArgsNothing.data()), 7452 AdjustArgsNothing.size(), 7453 const_cast<Expr **>(AdjustArgsNeedDevicePtr.data()), 7454 AdjustArgsNeedDevicePtr.size(), 7455 const_cast<OMPDeclareVariantAttr::InteropType *>(AppendArgs.data()), 7456 AppendArgs.size(), SR); 7457 FD->addAttr(NewAttr); 7458 } 7459 7460 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 7461 Stmt *AStmt, 7462 SourceLocation StartLoc, 7463 SourceLocation EndLoc) { 7464 if (!AStmt) 7465 return StmtError(); 7466 7467 auto *CS = cast<CapturedStmt>(AStmt); 7468 // 1.2.2 OpenMP Language Terminology 7469 // Structured block - An executable statement with a single entry at the 7470 // top and a single exit at the bottom. 7471 // The point of exit cannot be a branch out of the structured block. 7472 // longjmp() and throw() must not violate the entry/exit criteria. 7473 CS->getCapturedDecl()->setNothrow(); 7474 7475 setFunctionHasBranchProtectedScope(); 7476 7477 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 7478 DSAStack->getTaskgroupReductionRef(), 7479 DSAStack->isCancelRegion()); 7480 } 7481 7482 namespace { 7483 /// Iteration space of a single for loop. 7484 struct LoopIterationSpace final { 7485 /// True if the condition operator is the strict compare operator (<, > or 7486 /// !=). 7487 bool IsStrictCompare = false; 7488 /// Condition of the loop. 7489 Expr *PreCond = nullptr; 7490 /// This expression calculates the number of iterations in the loop. 7491 /// It is always possible to calculate it before starting the loop. 7492 Expr *NumIterations = nullptr; 7493 /// The loop counter variable. 7494 Expr *CounterVar = nullptr; 7495 /// Private loop counter variable. 7496 Expr *PrivateCounterVar = nullptr; 7497 /// This is initializer for the initial value of #CounterVar. 7498 Expr *CounterInit = nullptr; 7499 /// This is step for the #CounterVar used to generate its update: 7500 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 7501 Expr *CounterStep = nullptr; 7502 /// Should step be subtracted? 7503 bool Subtract = false; 7504 /// Source range of the loop init. 7505 SourceRange InitSrcRange; 7506 /// Source range of the loop condition. 7507 SourceRange CondSrcRange; 7508 /// Source range of the loop increment. 7509 SourceRange IncSrcRange; 7510 /// Minimum value that can have the loop control variable. Used to support 7511 /// non-rectangular loops. Applied only for LCV with the non-iterator types, 7512 /// since only such variables can be used in non-loop invariant expressions. 7513 Expr *MinValue = nullptr; 7514 /// Maximum value that can have the loop control variable. Used to support 7515 /// non-rectangular loops. Applied only for LCV with the non-iterator type, 7516 /// since only such variables can be used in non-loop invariant expressions. 7517 Expr *MaxValue = nullptr; 7518 /// true, if the lower bound depends on the outer loop control var. 7519 bool IsNonRectangularLB = false; 7520 /// true, if the upper bound depends on the outer loop control var. 7521 bool IsNonRectangularUB = false; 7522 /// Index of the loop this loop depends on and forms non-rectangular loop 7523 /// nest. 7524 unsigned LoopDependentIdx = 0; 7525 /// Final condition for the non-rectangular loop nest support. It is used to 7526 /// check that the number of iterations for this particular counter must be 7527 /// finished. 7528 Expr *FinalCondition = nullptr; 7529 }; 7530 7531 /// Helper class for checking canonical form of the OpenMP loops and 7532 /// extracting iteration space of each loop in the loop nest, that will be used 7533 /// for IR generation. 7534 class OpenMPIterationSpaceChecker { 7535 /// Reference to Sema. 7536 Sema &SemaRef; 7537 /// Does the loop associated directive support non-rectangular loops? 7538 bool SupportsNonRectangular; 7539 /// Data-sharing stack. 7540 DSAStackTy &Stack; 7541 /// A location for diagnostics (when there is no some better location). 7542 SourceLocation DefaultLoc; 7543 /// A location for diagnostics (when increment is not compatible). 7544 SourceLocation ConditionLoc; 7545 /// A source location for referring to loop init later. 7546 SourceRange InitSrcRange; 7547 /// A source location for referring to condition later. 7548 SourceRange ConditionSrcRange; 7549 /// A source location for referring to increment later. 7550 SourceRange IncrementSrcRange; 7551 /// Loop variable. 7552 ValueDecl *LCDecl = nullptr; 7553 /// Reference to loop variable. 7554 Expr *LCRef = nullptr; 7555 /// Lower bound (initializer for the var). 7556 Expr *LB = nullptr; 7557 /// Upper bound. 7558 Expr *UB = nullptr; 7559 /// Loop step (increment). 7560 Expr *Step = nullptr; 7561 /// This flag is true when condition is one of: 7562 /// Var < UB 7563 /// Var <= UB 7564 /// UB > Var 7565 /// UB >= Var 7566 /// This will have no value when the condition is != 7567 llvm::Optional<bool> TestIsLessOp; 7568 /// This flag is true when condition is strict ( < or > ). 7569 bool TestIsStrictOp = false; 7570 /// This flag is true when step is subtracted on each iteration. 7571 bool SubtractStep = false; 7572 /// The outer loop counter this loop depends on (if any). 7573 const ValueDecl *DepDecl = nullptr; 7574 /// Contains number of loop (starts from 1) on which loop counter init 7575 /// expression of this loop depends on. 7576 Optional<unsigned> InitDependOnLC; 7577 /// Contains number of loop (starts from 1) on which loop counter condition 7578 /// expression of this loop depends on. 7579 Optional<unsigned> CondDependOnLC; 7580 /// Checks if the provide statement depends on the loop counter. 7581 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer); 7582 /// Original condition required for checking of the exit condition for 7583 /// non-rectangular loop. 7584 Expr *Condition = nullptr; 7585 7586 public: 7587 OpenMPIterationSpaceChecker(Sema &SemaRef, bool SupportsNonRectangular, 7588 DSAStackTy &Stack, SourceLocation DefaultLoc) 7589 : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular), 7590 Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 7591 /// Check init-expr for canonical loop form and save loop counter 7592 /// variable - #Var and its initialization value - #LB. 7593 bool checkAndSetInit(Stmt *S, bool EmitDiags = true); 7594 /// Check test-expr for canonical form, save upper-bound (#UB), flags 7595 /// for less/greater and for strict/non-strict comparison. 7596 bool checkAndSetCond(Expr *S); 7597 /// Check incr-expr for canonical loop form and return true if it 7598 /// does not conform, otherwise save loop step (#Step). 7599 bool checkAndSetInc(Expr *S); 7600 /// Return the loop counter variable. 7601 ValueDecl *getLoopDecl() const { return LCDecl; } 7602 /// Return the reference expression to loop counter variable. 7603 Expr *getLoopDeclRefExpr() const { return LCRef; } 7604 /// Source range of the loop init. 7605 SourceRange getInitSrcRange() const { return InitSrcRange; } 7606 /// Source range of the loop condition. 7607 SourceRange getConditionSrcRange() const { return ConditionSrcRange; } 7608 /// Source range of the loop increment. 7609 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; } 7610 /// True if the step should be subtracted. 7611 bool shouldSubtractStep() const { return SubtractStep; } 7612 /// True, if the compare operator is strict (<, > or !=). 7613 bool isStrictTestOp() const { return TestIsStrictOp; } 7614 /// Build the expression to calculate the number of iterations. 7615 Expr *buildNumIterations( 7616 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType, 7617 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 7618 /// Build the precondition expression for the loops. 7619 Expr * 7620 buildPreCond(Scope *S, Expr *Cond, 7621 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 7622 /// Build reference expression to the counter be used for codegen. 7623 DeclRefExpr * 7624 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 7625 DSAStackTy &DSA) const; 7626 /// Build reference expression to the private counter be used for 7627 /// codegen. 7628 Expr *buildPrivateCounterVar() const; 7629 /// Build initialization of the counter be used for codegen. 7630 Expr *buildCounterInit() const; 7631 /// Build step of the counter be used for codegen. 7632 Expr *buildCounterStep() const; 7633 /// Build loop data with counter value for depend clauses in ordered 7634 /// directives. 7635 Expr * 7636 buildOrderedLoopData(Scope *S, Expr *Counter, 7637 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 7638 SourceLocation Loc, Expr *Inc = nullptr, 7639 OverloadedOperatorKind OOK = OO_Amp); 7640 /// Builds the minimum value for the loop counter. 7641 std::pair<Expr *, Expr *> buildMinMaxValues( 7642 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 7643 /// Builds final condition for the non-rectangular loops. 7644 Expr *buildFinalCondition(Scope *S) const; 7645 /// Return true if any expression is dependent. 7646 bool dependent() const; 7647 /// Returns true if the initializer forms non-rectangular loop. 7648 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); } 7649 /// Returns true if the condition forms non-rectangular loop. 7650 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); } 7651 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise. 7652 unsigned getLoopDependentIdx() const { 7653 return InitDependOnLC.value_or(CondDependOnLC.value_or(0)); 7654 } 7655 7656 private: 7657 /// Check the right-hand side of an assignment in the increment 7658 /// expression. 7659 bool checkAndSetIncRHS(Expr *RHS); 7660 /// Helper to set loop counter variable and its initializer. 7661 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB, 7662 bool EmitDiags); 7663 /// Helper to set upper bound. 7664 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp, 7665 SourceRange SR, SourceLocation SL); 7666 /// Helper to set loop increment. 7667 bool setStep(Expr *NewStep, bool Subtract); 7668 }; 7669 7670 bool OpenMPIterationSpaceChecker::dependent() const { 7671 if (!LCDecl) { 7672 assert(!LB && !UB && !Step); 7673 return false; 7674 } 7675 return LCDecl->getType()->isDependentType() || 7676 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 7677 (Step && Step->isValueDependent()); 7678 } 7679 7680 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl, 7681 Expr *NewLCRefExpr, 7682 Expr *NewLB, bool EmitDiags) { 7683 // State consistency checking to ensure correct usage. 7684 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 7685 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 7686 if (!NewLCDecl || !NewLB || NewLB->containsErrors()) 7687 return true; 7688 LCDecl = getCanonicalDecl(NewLCDecl); 7689 LCRef = NewLCRefExpr; 7690 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 7691 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 7692 if ((Ctor->isCopyOrMoveConstructor() || 7693 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 7694 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 7695 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 7696 LB = NewLB; 7697 if (EmitDiags) 7698 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true); 7699 return false; 7700 } 7701 7702 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, 7703 llvm::Optional<bool> LessOp, 7704 bool StrictOp, SourceRange SR, 7705 SourceLocation SL) { 7706 // State consistency checking to ensure correct usage. 7707 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 7708 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 7709 if (!NewUB || NewUB->containsErrors()) 7710 return true; 7711 UB = NewUB; 7712 if (LessOp) 7713 TestIsLessOp = LessOp; 7714 TestIsStrictOp = StrictOp; 7715 ConditionSrcRange = SR; 7716 ConditionLoc = SL; 7717 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false); 7718 return false; 7719 } 7720 7721 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) { 7722 // State consistency checking to ensure correct usage. 7723 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 7724 if (!NewStep || NewStep->containsErrors()) 7725 return true; 7726 if (!NewStep->isValueDependent()) { 7727 // Check that the step is integer expression. 7728 SourceLocation StepLoc = NewStep->getBeginLoc(); 7729 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( 7730 StepLoc, getExprAsWritten(NewStep)); 7731 if (Val.isInvalid()) 7732 return true; 7733 NewStep = Val.get(); 7734 7735 // OpenMP [2.6, Canonical Loop Form, Restrictions] 7736 // If test-expr is of form var relational-op b and relational-op is < or 7737 // <= then incr-expr must cause var to increase on each iteration of the 7738 // loop. If test-expr is of form var relational-op b and relational-op is 7739 // > or >= then incr-expr must cause var to decrease on each iteration of 7740 // the loop. 7741 // If test-expr is of form b relational-op var and relational-op is < or 7742 // <= then incr-expr must cause var to decrease on each iteration of the 7743 // loop. If test-expr is of form b relational-op var and relational-op is 7744 // > or >= then incr-expr must cause var to increase on each iteration of 7745 // the loop. 7746 Optional<llvm::APSInt> Result = 7747 NewStep->getIntegerConstantExpr(SemaRef.Context); 7748 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 7749 bool IsConstNeg = 7750 Result && Result->isSigned() && (Subtract != Result->isNegative()); 7751 bool IsConstPos = 7752 Result && Result->isSigned() && (Subtract == Result->isNegative()); 7753 bool IsConstZero = Result && !Result->getBoolValue(); 7754 7755 // != with increment is treated as <; != with decrement is treated as > 7756 if (!TestIsLessOp.hasValue()) 7757 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract); 7758 if (UB && 7759 (IsConstZero || (TestIsLessOp.getValue() 7760 ? (IsConstNeg || (IsUnsigned && Subtract)) 7761 : (IsConstPos || (IsUnsigned && !Subtract))))) { 7762 SemaRef.Diag(NewStep->getExprLoc(), 7763 diag::err_omp_loop_incr_not_compatible) 7764 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange(); 7765 SemaRef.Diag(ConditionLoc, 7766 diag::note_omp_loop_cond_requres_compatible_incr) 7767 << TestIsLessOp.getValue() << ConditionSrcRange; 7768 return true; 7769 } 7770 if (TestIsLessOp.getValue() == Subtract) { 7771 NewStep = 7772 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 7773 .get(); 7774 Subtract = !Subtract; 7775 } 7776 } 7777 7778 Step = NewStep; 7779 SubtractStep = Subtract; 7780 return false; 7781 } 7782 7783 namespace { 7784 /// Checker for the non-rectangular loops. Checks if the initializer or 7785 /// condition expression references loop counter variable. 7786 class LoopCounterRefChecker final 7787 : public ConstStmtVisitor<LoopCounterRefChecker, bool> { 7788 Sema &SemaRef; 7789 DSAStackTy &Stack; 7790 const ValueDecl *CurLCDecl = nullptr; 7791 const ValueDecl *DepDecl = nullptr; 7792 const ValueDecl *PrevDepDecl = nullptr; 7793 bool IsInitializer = true; 7794 bool SupportsNonRectangular; 7795 unsigned BaseLoopId = 0; 7796 bool checkDecl(const Expr *E, const ValueDecl *VD) { 7797 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) { 7798 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter) 7799 << (IsInitializer ? 0 : 1); 7800 return false; 7801 } 7802 const auto &&Data = Stack.isLoopControlVariable(VD); 7803 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions. 7804 // The type of the loop iterator on which we depend may not have a random 7805 // access iterator type. 7806 if (Data.first && VD->getType()->isRecordType()) { 7807 SmallString<128> Name; 7808 llvm::raw_svector_ostream OS(Name); 7809 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(), 7810 /*Qualified=*/true); 7811 SemaRef.Diag(E->getExprLoc(), 7812 diag::err_omp_wrong_dependency_iterator_type) 7813 << OS.str(); 7814 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD; 7815 return false; 7816 } 7817 if (Data.first && !SupportsNonRectangular) { 7818 SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency); 7819 return false; 7820 } 7821 if (Data.first && 7822 (DepDecl || (PrevDepDecl && 7823 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) { 7824 if (!DepDecl && PrevDepDecl) 7825 DepDecl = PrevDepDecl; 7826 SmallString<128> Name; 7827 llvm::raw_svector_ostream OS(Name); 7828 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(), 7829 /*Qualified=*/true); 7830 SemaRef.Diag(E->getExprLoc(), 7831 diag::err_omp_invariant_or_linear_dependency) 7832 << OS.str(); 7833 return false; 7834 } 7835 if (Data.first) { 7836 DepDecl = VD; 7837 BaseLoopId = Data.first; 7838 } 7839 return Data.first; 7840 } 7841 7842 public: 7843 bool VisitDeclRefExpr(const DeclRefExpr *E) { 7844 const ValueDecl *VD = E->getDecl(); 7845 if (isa<VarDecl>(VD)) 7846 return checkDecl(E, VD); 7847 return false; 7848 } 7849 bool VisitMemberExpr(const MemberExpr *E) { 7850 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 7851 const ValueDecl *VD = E->getMemberDecl(); 7852 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD)) 7853 return checkDecl(E, VD); 7854 } 7855 return false; 7856 } 7857 bool VisitStmt(const Stmt *S) { 7858 bool Res = false; 7859 for (const Stmt *Child : S->children()) 7860 Res = (Child && Visit(Child)) || Res; 7861 return Res; 7862 } 7863 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack, 7864 const ValueDecl *CurLCDecl, bool IsInitializer, 7865 const ValueDecl *PrevDepDecl = nullptr, 7866 bool SupportsNonRectangular = true) 7867 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl), 7868 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer), 7869 SupportsNonRectangular(SupportsNonRectangular) {} 7870 unsigned getBaseLoopId() const { 7871 assert(CurLCDecl && "Expected loop dependency."); 7872 return BaseLoopId; 7873 } 7874 const ValueDecl *getDepDecl() const { 7875 assert(CurLCDecl && "Expected loop dependency."); 7876 return DepDecl; 7877 } 7878 }; 7879 } // namespace 7880 7881 Optional<unsigned> 7882 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S, 7883 bool IsInitializer) { 7884 // Check for the non-rectangular loops. 7885 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer, 7886 DepDecl, SupportsNonRectangular); 7887 if (LoopStmtChecker.Visit(S)) { 7888 DepDecl = LoopStmtChecker.getDepDecl(); 7889 return LoopStmtChecker.getBaseLoopId(); 7890 } 7891 return llvm::None; 7892 } 7893 7894 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) { 7895 // Check init-expr for canonical loop form and save loop counter 7896 // variable - #Var and its initialization value - #LB. 7897 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 7898 // var = lb 7899 // integer-type var = lb 7900 // random-access-iterator-type var = lb 7901 // pointer-type var = lb 7902 // 7903 if (!S) { 7904 if (EmitDiags) { 7905 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 7906 } 7907 return true; 7908 } 7909 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 7910 if (!ExprTemp->cleanupsHaveSideEffects()) 7911 S = ExprTemp->getSubExpr(); 7912 7913 InitSrcRange = S->getSourceRange(); 7914 if (Expr *E = dyn_cast<Expr>(S)) 7915 S = E->IgnoreParens(); 7916 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 7917 if (BO->getOpcode() == BO_Assign) { 7918 Expr *LHS = BO->getLHS()->IgnoreParens(); 7919 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 7920 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 7921 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 7922 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7923 EmitDiags); 7924 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags); 7925 } 7926 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 7927 if (ME->isArrow() && 7928 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7929 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7930 EmitDiags); 7931 } 7932 } 7933 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 7934 if (DS->isSingleDecl()) { 7935 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 7936 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 7937 // Accept non-canonical init form here but emit ext. warning. 7938 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 7939 SemaRef.Diag(S->getBeginLoc(), 7940 diag::ext_omp_loop_not_canonical_init) 7941 << S->getSourceRange(); 7942 return setLCDeclAndLB( 7943 Var, 7944 buildDeclRefExpr(SemaRef, Var, 7945 Var->getType().getNonReferenceType(), 7946 DS->getBeginLoc()), 7947 Var->getInit(), EmitDiags); 7948 } 7949 } 7950 } 7951 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 7952 if (CE->getOperator() == OO_Equal) { 7953 Expr *LHS = CE->getArg(0); 7954 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 7955 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 7956 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 7957 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7958 EmitDiags); 7959 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags); 7960 } 7961 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 7962 if (ME->isArrow() && 7963 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7964 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7965 EmitDiags); 7966 } 7967 } 7968 } 7969 7970 if (dependent() || SemaRef.CurContext->isDependentContext()) 7971 return false; 7972 if (EmitDiags) { 7973 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init) 7974 << S->getSourceRange(); 7975 } 7976 return true; 7977 } 7978 7979 /// Ignore parenthesizes, implicit casts, copy constructor and return the 7980 /// variable (which may be the loop variable) if possible. 7981 static const ValueDecl *getInitLCDecl(const Expr *E) { 7982 if (!E) 7983 return nullptr; 7984 E = getExprAsWritten(E); 7985 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 7986 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 7987 if ((Ctor->isCopyOrMoveConstructor() || 7988 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 7989 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 7990 E = CE->getArg(0)->IgnoreParenImpCasts(); 7991 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 7992 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 7993 return getCanonicalDecl(VD); 7994 } 7995 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E)) 7996 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7997 return getCanonicalDecl(ME->getMemberDecl()); 7998 return nullptr; 7999 } 8000 8001 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) { 8002 // Check test-expr for canonical form, save upper-bound UB, flags for 8003 // less/greater and for strict/non-strict comparison. 8004 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following: 8005 // var relational-op b 8006 // b relational-op var 8007 // 8008 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50; 8009 if (!S) { 8010 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) 8011 << (IneqCondIsCanonical ? 1 : 0) << LCDecl; 8012 return true; 8013 } 8014 Condition = S; 8015 S = getExprAsWritten(S); 8016 SourceLocation CondLoc = S->getBeginLoc(); 8017 auto &&CheckAndSetCond = [this, IneqCondIsCanonical]( 8018 BinaryOperatorKind Opcode, const Expr *LHS, 8019 const Expr *RHS, SourceRange SR, 8020 SourceLocation OpLoc) -> llvm::Optional<bool> { 8021 if (BinaryOperator::isRelationalOp(Opcode)) { 8022 if (getInitLCDecl(LHS) == LCDecl) 8023 return setUB(const_cast<Expr *>(RHS), 8024 (Opcode == BO_LT || Opcode == BO_LE), 8025 (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc); 8026 if (getInitLCDecl(RHS) == LCDecl) 8027 return setUB(const_cast<Expr *>(LHS), 8028 (Opcode == BO_GT || Opcode == BO_GE), 8029 (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc); 8030 } else if (IneqCondIsCanonical && Opcode == BO_NE) { 8031 return setUB(const_cast<Expr *>(getInitLCDecl(LHS) == LCDecl ? RHS : LHS), 8032 /*LessOp=*/llvm::None, 8033 /*StrictOp=*/true, SR, OpLoc); 8034 } 8035 return llvm::None; 8036 }; 8037 llvm::Optional<bool> Res; 8038 if (auto *RBO = dyn_cast<CXXRewrittenBinaryOperator>(S)) { 8039 CXXRewrittenBinaryOperator::DecomposedForm DF = RBO->getDecomposedForm(); 8040 Res = CheckAndSetCond(DF.Opcode, DF.LHS, DF.RHS, RBO->getSourceRange(), 8041 RBO->getOperatorLoc()); 8042 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 8043 Res = CheckAndSetCond(BO->getOpcode(), BO->getLHS(), BO->getRHS(), 8044 BO->getSourceRange(), BO->getOperatorLoc()); 8045 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 8046 if (CE->getNumArgs() == 2) { 8047 Res = CheckAndSetCond( 8048 BinaryOperator::getOverloadedOpcode(CE->getOperator()), CE->getArg(0), 8049 CE->getArg(1), CE->getSourceRange(), CE->getOperatorLoc()); 8050 } 8051 } 8052 if (Res) 8053 return *Res; 8054 if (dependent() || SemaRef.CurContext->isDependentContext()) 8055 return false; 8056 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 8057 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl; 8058 return true; 8059 } 8060 8061 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) { 8062 // RHS of canonical loop form increment can be: 8063 // var + incr 8064 // incr + var 8065 // var - incr 8066 // 8067 RHS = RHS->IgnoreParenImpCasts(); 8068 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 8069 if (BO->isAdditiveOp()) { 8070 bool IsAdd = BO->getOpcode() == BO_Add; 8071 if (getInitLCDecl(BO->getLHS()) == LCDecl) 8072 return setStep(BO->getRHS(), !IsAdd); 8073 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl) 8074 return setStep(BO->getLHS(), /*Subtract=*/false); 8075 } 8076 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 8077 bool IsAdd = CE->getOperator() == OO_Plus; 8078 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 8079 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 8080 return setStep(CE->getArg(1), !IsAdd); 8081 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl) 8082 return setStep(CE->getArg(0), /*Subtract=*/false); 8083 } 8084 } 8085 if (dependent() || SemaRef.CurContext->isDependentContext()) 8086 return false; 8087 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 8088 << RHS->getSourceRange() << LCDecl; 8089 return true; 8090 } 8091 8092 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) { 8093 // Check incr-expr for canonical loop form and return true if it 8094 // does not conform. 8095 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 8096 // ++var 8097 // var++ 8098 // --var 8099 // var-- 8100 // var += incr 8101 // var -= incr 8102 // var = var + incr 8103 // var = incr + var 8104 // var = var - incr 8105 // 8106 if (!S) { 8107 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 8108 return true; 8109 } 8110 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 8111 if (!ExprTemp->cleanupsHaveSideEffects()) 8112 S = ExprTemp->getSubExpr(); 8113 8114 IncrementSrcRange = S->getSourceRange(); 8115 S = S->IgnoreParens(); 8116 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 8117 if (UO->isIncrementDecrementOp() && 8118 getInitLCDecl(UO->getSubExpr()) == LCDecl) 8119 return setStep(SemaRef 8120 .ActOnIntegerConstant(UO->getBeginLoc(), 8121 (UO->isDecrementOp() ? -1 : 1)) 8122 .get(), 8123 /*Subtract=*/false); 8124 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 8125 switch (BO->getOpcode()) { 8126 case BO_AddAssign: 8127 case BO_SubAssign: 8128 if (getInitLCDecl(BO->getLHS()) == LCDecl) 8129 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 8130 break; 8131 case BO_Assign: 8132 if (getInitLCDecl(BO->getLHS()) == LCDecl) 8133 return checkAndSetIncRHS(BO->getRHS()); 8134 break; 8135 default: 8136 break; 8137 } 8138 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 8139 switch (CE->getOperator()) { 8140 case OO_PlusPlus: 8141 case OO_MinusMinus: 8142 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 8143 return setStep(SemaRef 8144 .ActOnIntegerConstant( 8145 CE->getBeginLoc(), 8146 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 8147 .get(), 8148 /*Subtract=*/false); 8149 break; 8150 case OO_PlusEqual: 8151 case OO_MinusEqual: 8152 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 8153 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 8154 break; 8155 case OO_Equal: 8156 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 8157 return checkAndSetIncRHS(CE->getArg(1)); 8158 break; 8159 default: 8160 break; 8161 } 8162 } 8163 if (dependent() || SemaRef.CurContext->isDependentContext()) 8164 return false; 8165 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 8166 << S->getSourceRange() << LCDecl; 8167 return true; 8168 } 8169 8170 static ExprResult 8171 tryBuildCapture(Sema &SemaRef, Expr *Capture, 8172 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8173 if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors()) 8174 return Capture; 8175 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 8176 return SemaRef.PerformImplicitConversion( 8177 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 8178 /*AllowExplicit=*/true); 8179 auto I = Captures.find(Capture); 8180 if (I != Captures.end()) 8181 return buildCapture(SemaRef, Capture, I->second); 8182 DeclRefExpr *Ref = nullptr; 8183 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 8184 Captures[Capture] = Ref; 8185 return Res; 8186 } 8187 8188 /// Calculate number of iterations, transforming to unsigned, if number of 8189 /// iterations may be larger than the original type. 8190 static Expr * 8191 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc, 8192 Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy, 8193 bool TestIsStrictOp, bool RoundToStep, 8194 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8195 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 8196 if (!NewStep.isUsable()) 8197 return nullptr; 8198 llvm::APSInt LRes, SRes; 8199 bool IsLowerConst = false, IsStepConst = false; 8200 if (Optional<llvm::APSInt> Res = 8201 Lower->getIntegerConstantExpr(SemaRef.Context)) { 8202 LRes = *Res; 8203 IsLowerConst = true; 8204 } 8205 if (Optional<llvm::APSInt> Res = 8206 Step->getIntegerConstantExpr(SemaRef.Context)) { 8207 SRes = *Res; 8208 IsStepConst = true; 8209 } 8210 bool NoNeedToConvert = IsLowerConst && !RoundToStep && 8211 ((!TestIsStrictOp && LRes.isNonNegative()) || 8212 (TestIsStrictOp && LRes.isStrictlyPositive())); 8213 bool NeedToReorganize = false; 8214 // Check if any subexpressions in Lower -Step [+ 1] lead to overflow. 8215 if (!NoNeedToConvert && IsLowerConst && 8216 (TestIsStrictOp || (RoundToStep && IsStepConst))) { 8217 NoNeedToConvert = true; 8218 if (RoundToStep) { 8219 unsigned BW = LRes.getBitWidth() > SRes.getBitWidth() 8220 ? LRes.getBitWidth() 8221 : SRes.getBitWidth(); 8222 LRes = LRes.extend(BW + 1); 8223 LRes.setIsSigned(true); 8224 SRes = SRes.extend(BW + 1); 8225 SRes.setIsSigned(true); 8226 LRes -= SRes; 8227 NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes; 8228 LRes = LRes.trunc(BW); 8229 } 8230 if (TestIsStrictOp) { 8231 unsigned BW = LRes.getBitWidth(); 8232 LRes = LRes.extend(BW + 1); 8233 LRes.setIsSigned(true); 8234 ++LRes; 8235 NoNeedToConvert = 8236 NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes; 8237 // truncate to the original bitwidth. 8238 LRes = LRes.trunc(BW); 8239 } 8240 NeedToReorganize = NoNeedToConvert; 8241 } 8242 llvm::APSInt URes; 8243 bool IsUpperConst = false; 8244 if (Optional<llvm::APSInt> Res = 8245 Upper->getIntegerConstantExpr(SemaRef.Context)) { 8246 URes = *Res; 8247 IsUpperConst = true; 8248 } 8249 if (NoNeedToConvert && IsLowerConst && IsUpperConst && 8250 (!RoundToStep || IsStepConst)) { 8251 unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth() 8252 : URes.getBitWidth(); 8253 LRes = LRes.extend(BW + 1); 8254 LRes.setIsSigned(true); 8255 URes = URes.extend(BW + 1); 8256 URes.setIsSigned(true); 8257 URes -= LRes; 8258 NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes; 8259 NeedToReorganize = NoNeedToConvert; 8260 } 8261 // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant 8262 // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to 8263 // unsigned. 8264 if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) && 8265 !LCTy->isDependentType() && LCTy->isIntegerType()) { 8266 QualType LowerTy = Lower->getType(); 8267 QualType UpperTy = Upper->getType(); 8268 uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy); 8269 uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy); 8270 if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) || 8271 (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) { 8272 QualType CastType = SemaRef.Context.getIntTypeForBitwidth( 8273 LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0); 8274 Upper = 8275 SemaRef 8276 .PerformImplicitConversion( 8277 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(), 8278 CastType, Sema::AA_Converting) 8279 .get(); 8280 Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(); 8281 NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get()); 8282 } 8283 } 8284 if (!Lower || !Upper || NewStep.isInvalid()) 8285 return nullptr; 8286 8287 ExprResult Diff; 8288 // If need to reorganize, then calculate the form as Upper - (Lower - Step [+ 8289 // 1]). 8290 if (NeedToReorganize) { 8291 Diff = Lower; 8292 8293 if (RoundToStep) { 8294 // Lower - Step 8295 Diff = 8296 SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get()); 8297 if (!Diff.isUsable()) 8298 return nullptr; 8299 } 8300 8301 // Lower - Step [+ 1] 8302 if (TestIsStrictOp) 8303 Diff = SemaRef.BuildBinOp( 8304 S, DefaultLoc, BO_Add, Diff.get(), 8305 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 8306 if (!Diff.isUsable()) 8307 return nullptr; 8308 8309 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8310 if (!Diff.isUsable()) 8311 return nullptr; 8312 8313 // Upper - (Lower - Step [+ 1]). 8314 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get()); 8315 if (!Diff.isUsable()) 8316 return nullptr; 8317 } else { 8318 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 8319 8320 if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) { 8321 // BuildBinOp already emitted error, this one is to point user to upper 8322 // and lower bound, and to tell what is passed to 'operator-'. 8323 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx) 8324 << Upper->getSourceRange() << Lower->getSourceRange(); 8325 return nullptr; 8326 } 8327 8328 if (!Diff.isUsable()) 8329 return nullptr; 8330 8331 // Upper - Lower [- 1] 8332 if (TestIsStrictOp) 8333 Diff = SemaRef.BuildBinOp( 8334 S, DefaultLoc, BO_Sub, Diff.get(), 8335 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 8336 if (!Diff.isUsable()) 8337 return nullptr; 8338 8339 if (RoundToStep) { 8340 // Upper - Lower [- 1] + Step 8341 Diff = 8342 SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 8343 if (!Diff.isUsable()) 8344 return nullptr; 8345 } 8346 } 8347 8348 // Parentheses (for dumping/debugging purposes only). 8349 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8350 if (!Diff.isUsable()) 8351 return nullptr; 8352 8353 // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step 8354 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 8355 if (!Diff.isUsable()) 8356 return nullptr; 8357 8358 return Diff.get(); 8359 } 8360 8361 /// Build the expression to calculate the number of iterations. 8362 Expr *OpenMPIterationSpaceChecker::buildNumIterations( 8363 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType, 8364 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 8365 QualType VarType = LCDecl->getType().getNonReferenceType(); 8366 if (!VarType->isIntegerType() && !VarType->isPointerType() && 8367 !SemaRef.getLangOpts().CPlusPlus) 8368 return nullptr; 8369 Expr *LBVal = LB; 8370 Expr *UBVal = UB; 8371 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) : 8372 // max(LB(MinVal), LB(MaxVal)) 8373 if (InitDependOnLC) { 8374 const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1]; 8375 if (!IS.MinValue || !IS.MaxValue) 8376 return nullptr; 8377 // OuterVar = Min 8378 ExprResult MinValue = 8379 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue); 8380 if (!MinValue.isUsable()) 8381 return nullptr; 8382 8383 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8384 IS.CounterVar, MinValue.get()); 8385 if (!LBMinVal.isUsable()) 8386 return nullptr; 8387 // OuterVar = Min, LBVal 8388 LBMinVal = 8389 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal); 8390 if (!LBMinVal.isUsable()) 8391 return nullptr; 8392 // (OuterVar = Min, LBVal) 8393 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get()); 8394 if (!LBMinVal.isUsable()) 8395 return nullptr; 8396 8397 // OuterVar = Max 8398 ExprResult MaxValue = 8399 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue); 8400 if (!MaxValue.isUsable()) 8401 return nullptr; 8402 8403 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8404 IS.CounterVar, MaxValue.get()); 8405 if (!LBMaxVal.isUsable()) 8406 return nullptr; 8407 // OuterVar = Max, LBVal 8408 LBMaxVal = 8409 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal); 8410 if (!LBMaxVal.isUsable()) 8411 return nullptr; 8412 // (OuterVar = Max, LBVal) 8413 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get()); 8414 if (!LBMaxVal.isUsable()) 8415 return nullptr; 8416 8417 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get(); 8418 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get(); 8419 if (!LBMin || !LBMax) 8420 return nullptr; 8421 // LB(MinVal) < LB(MaxVal) 8422 ExprResult MinLessMaxRes = 8423 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax); 8424 if (!MinLessMaxRes.isUsable()) 8425 return nullptr; 8426 Expr *MinLessMax = 8427 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get(); 8428 if (!MinLessMax) 8429 return nullptr; 8430 if (*TestIsLessOp) { 8431 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal), 8432 // LB(MaxVal)) 8433 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc, 8434 MinLessMax, LBMin, LBMax); 8435 if (!MinLB.isUsable()) 8436 return nullptr; 8437 LBVal = MinLB.get(); 8438 } else { 8439 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal), 8440 // LB(MaxVal)) 8441 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc, 8442 MinLessMax, LBMax, LBMin); 8443 if (!MaxLB.isUsable()) 8444 return nullptr; 8445 LBVal = MaxLB.get(); 8446 } 8447 } 8448 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) : 8449 // min(UB(MinVal), UB(MaxVal)) 8450 if (CondDependOnLC) { 8451 const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1]; 8452 if (!IS.MinValue || !IS.MaxValue) 8453 return nullptr; 8454 // OuterVar = Min 8455 ExprResult MinValue = 8456 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue); 8457 if (!MinValue.isUsable()) 8458 return nullptr; 8459 8460 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8461 IS.CounterVar, MinValue.get()); 8462 if (!UBMinVal.isUsable()) 8463 return nullptr; 8464 // OuterVar = Min, UBVal 8465 UBMinVal = 8466 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal); 8467 if (!UBMinVal.isUsable()) 8468 return nullptr; 8469 // (OuterVar = Min, UBVal) 8470 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get()); 8471 if (!UBMinVal.isUsable()) 8472 return nullptr; 8473 8474 // OuterVar = Max 8475 ExprResult MaxValue = 8476 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue); 8477 if (!MaxValue.isUsable()) 8478 return nullptr; 8479 8480 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8481 IS.CounterVar, MaxValue.get()); 8482 if (!UBMaxVal.isUsable()) 8483 return nullptr; 8484 // OuterVar = Max, UBVal 8485 UBMaxVal = 8486 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal); 8487 if (!UBMaxVal.isUsable()) 8488 return nullptr; 8489 // (OuterVar = Max, UBVal) 8490 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get()); 8491 if (!UBMaxVal.isUsable()) 8492 return nullptr; 8493 8494 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get(); 8495 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get(); 8496 if (!UBMin || !UBMax) 8497 return nullptr; 8498 // UB(MinVal) > UB(MaxVal) 8499 ExprResult MinGreaterMaxRes = 8500 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax); 8501 if (!MinGreaterMaxRes.isUsable()) 8502 return nullptr; 8503 Expr *MinGreaterMax = 8504 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get(); 8505 if (!MinGreaterMax) 8506 return nullptr; 8507 if (*TestIsLessOp) { 8508 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal), 8509 // UB(MaxVal)) 8510 ExprResult MaxUB = SemaRef.ActOnConditionalOp( 8511 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax); 8512 if (!MaxUB.isUsable()) 8513 return nullptr; 8514 UBVal = MaxUB.get(); 8515 } else { 8516 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal), 8517 // UB(MaxVal)) 8518 ExprResult MinUB = SemaRef.ActOnConditionalOp( 8519 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin); 8520 if (!MinUB.isUsable()) 8521 return nullptr; 8522 UBVal = MinUB.get(); 8523 } 8524 } 8525 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal; 8526 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal; 8527 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 8528 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 8529 if (!Upper || !Lower) 8530 return nullptr; 8531 8532 ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, 8533 Step, VarType, TestIsStrictOp, 8534 /*RoundToStep=*/true, Captures); 8535 if (!Diff.isUsable()) 8536 return nullptr; 8537 8538 // OpenMP runtime requires 32-bit or 64-bit loop variables. 8539 QualType Type = Diff.get()->getType(); 8540 ASTContext &C = SemaRef.Context; 8541 bool UseVarType = VarType->hasIntegerRepresentation() && 8542 C.getTypeSize(Type) > C.getTypeSize(VarType); 8543 if (!Type->isIntegerType() || UseVarType) { 8544 unsigned NewSize = 8545 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 8546 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 8547 : Type->hasSignedIntegerRepresentation(); 8548 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 8549 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 8550 Diff = SemaRef.PerformImplicitConversion( 8551 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 8552 if (!Diff.isUsable()) 8553 return nullptr; 8554 } 8555 } 8556 if (LimitedType) { 8557 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 8558 if (NewSize != C.getTypeSize(Type)) { 8559 if (NewSize < C.getTypeSize(Type)) { 8560 assert(NewSize == 64 && "incorrect loop var size"); 8561 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 8562 << InitSrcRange << ConditionSrcRange; 8563 } 8564 QualType NewType = C.getIntTypeForBitwidth( 8565 NewSize, Type->hasSignedIntegerRepresentation() || 8566 C.getTypeSize(Type) < NewSize); 8567 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 8568 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 8569 Sema::AA_Converting, true); 8570 if (!Diff.isUsable()) 8571 return nullptr; 8572 } 8573 } 8574 } 8575 8576 return Diff.get(); 8577 } 8578 8579 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues( 8580 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 8581 // Do not build for iterators, they cannot be used in non-rectangular loop 8582 // nests. 8583 if (LCDecl->getType()->isRecordType()) 8584 return std::make_pair(nullptr, nullptr); 8585 // If we subtract, the min is in the condition, otherwise the min is in the 8586 // init value. 8587 Expr *MinExpr = nullptr; 8588 Expr *MaxExpr = nullptr; 8589 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB; 8590 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB; 8591 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue() 8592 : CondDependOnLC.hasValue(); 8593 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue() 8594 : InitDependOnLC.hasValue(); 8595 Expr *Lower = 8596 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get(); 8597 Expr *Upper = 8598 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get(); 8599 if (!Upper || !Lower) 8600 return std::make_pair(nullptr, nullptr); 8601 8602 if (*TestIsLessOp) 8603 MinExpr = Lower; 8604 else 8605 MaxExpr = Upper; 8606 8607 // Build minimum/maximum value based on number of iterations. 8608 QualType VarType = LCDecl->getType().getNonReferenceType(); 8609 8610 ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, 8611 Step, VarType, TestIsStrictOp, 8612 /*RoundToStep=*/false, Captures); 8613 if (!Diff.isUsable()) 8614 return std::make_pair(nullptr, nullptr); 8615 8616 // ((Upper - Lower [- 1]) / Step) * Step 8617 // Parentheses (for dumping/debugging purposes only). 8618 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8619 if (!Diff.isUsable()) 8620 return std::make_pair(nullptr, nullptr); 8621 8622 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 8623 if (!NewStep.isUsable()) 8624 return std::make_pair(nullptr, nullptr); 8625 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get()); 8626 if (!Diff.isUsable()) 8627 return std::make_pair(nullptr, nullptr); 8628 8629 // Parentheses (for dumping/debugging purposes only). 8630 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8631 if (!Diff.isUsable()) 8632 return std::make_pair(nullptr, nullptr); 8633 8634 // Convert to the ptrdiff_t, if original type is pointer. 8635 if (VarType->isAnyPointerType() && 8636 !SemaRef.Context.hasSameType( 8637 Diff.get()->getType(), 8638 SemaRef.Context.getUnsignedPointerDiffType())) { 8639 Diff = SemaRef.PerformImplicitConversion( 8640 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(), 8641 Sema::AA_Converting, /*AllowExplicit=*/true); 8642 } 8643 if (!Diff.isUsable()) 8644 return std::make_pair(nullptr, nullptr); 8645 8646 if (*TestIsLessOp) { 8647 // MinExpr = Lower; 8648 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step) 8649 Diff = SemaRef.BuildBinOp( 8650 S, DefaultLoc, BO_Add, 8651 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(), 8652 Diff.get()); 8653 if (!Diff.isUsable()) 8654 return std::make_pair(nullptr, nullptr); 8655 } else { 8656 // MaxExpr = Upper; 8657 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step) 8658 Diff = SemaRef.BuildBinOp( 8659 S, DefaultLoc, BO_Sub, 8660 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(), 8661 Diff.get()); 8662 if (!Diff.isUsable()) 8663 return std::make_pair(nullptr, nullptr); 8664 } 8665 8666 // Convert to the original type. 8667 if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) 8668 Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType, 8669 Sema::AA_Converting, 8670 /*AllowExplicit=*/true); 8671 if (!Diff.isUsable()) 8672 return std::make_pair(nullptr, nullptr); 8673 8674 Sema::TentativeAnalysisScope Trap(SemaRef); 8675 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false); 8676 if (!Diff.isUsable()) 8677 return std::make_pair(nullptr, nullptr); 8678 8679 if (*TestIsLessOp) 8680 MaxExpr = Diff.get(); 8681 else 8682 MinExpr = Diff.get(); 8683 8684 return std::make_pair(MinExpr, MaxExpr); 8685 } 8686 8687 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const { 8688 if (InitDependOnLC || CondDependOnLC) 8689 return Condition; 8690 return nullptr; 8691 } 8692 8693 Expr *OpenMPIterationSpaceChecker::buildPreCond( 8694 Scope *S, Expr *Cond, 8695 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 8696 // Do not build a precondition when the condition/initialization is dependent 8697 // to prevent pessimistic early loop exit. 8698 // TODO: this can be improved by calculating min/max values but not sure that 8699 // it will be very effective. 8700 if (CondDependOnLC || InitDependOnLC) 8701 return SemaRef 8702 .PerformImplicitConversion( 8703 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(), 8704 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 8705 /*AllowExplicit=*/true) 8706 .get(); 8707 8708 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 8709 Sema::TentativeAnalysisScope Trap(SemaRef); 8710 8711 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures); 8712 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures); 8713 if (!NewLB.isUsable() || !NewUB.isUsable()) 8714 return nullptr; 8715 8716 ExprResult CondExpr = SemaRef.BuildBinOp( 8717 S, DefaultLoc, 8718 TestIsLessOp.getValue() ? (TestIsStrictOp ? BO_LT : BO_LE) 8719 : (TestIsStrictOp ? BO_GT : BO_GE), 8720 NewLB.get(), NewUB.get()); 8721 if (CondExpr.isUsable()) { 8722 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 8723 SemaRef.Context.BoolTy)) 8724 CondExpr = SemaRef.PerformImplicitConversion( 8725 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 8726 /*AllowExplicit=*/true); 8727 } 8728 8729 // Otherwise use original loop condition and evaluate it in runtime. 8730 return CondExpr.isUsable() ? CondExpr.get() : Cond; 8731 } 8732 8733 /// Build reference expression to the counter be used for codegen. 8734 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar( 8735 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 8736 DSAStackTy &DSA) const { 8737 auto *VD = dyn_cast<VarDecl>(LCDecl); 8738 if (!VD) { 8739 VD = SemaRef.isOpenMPCapturedDecl(LCDecl); 8740 DeclRefExpr *Ref = buildDeclRefExpr( 8741 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 8742 const DSAStackTy::DSAVarData Data = 8743 DSA.getTopDSA(LCDecl, /*FromParent=*/false); 8744 // If the loop control decl is explicitly marked as private, do not mark it 8745 // as captured again. 8746 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 8747 Captures.insert(std::make_pair(LCRef, Ref)); 8748 return Ref; 8749 } 8750 return cast<DeclRefExpr>(LCRef); 8751 } 8752 8753 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const { 8754 if (LCDecl && !LCDecl->isInvalidDecl()) { 8755 QualType Type = LCDecl->getType().getNonReferenceType(); 8756 VarDecl *PrivateVar = buildVarDecl( 8757 SemaRef, DefaultLoc, Type, LCDecl->getName(), 8758 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr, 8759 isa<VarDecl>(LCDecl) 8760 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc) 8761 : nullptr); 8762 if (PrivateVar->isInvalidDecl()) 8763 return nullptr; 8764 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 8765 } 8766 return nullptr; 8767 } 8768 8769 /// Build initialization of the counter to be used for codegen. 8770 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; } 8771 8772 /// Build step of the counter be used for codegen. 8773 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; } 8774 8775 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData( 8776 Scope *S, Expr *Counter, 8777 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc, 8778 Expr *Inc, OverloadedOperatorKind OOK) { 8779 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get(); 8780 if (!Cnt) 8781 return nullptr; 8782 if (Inc) { 8783 assert((OOK == OO_Plus || OOK == OO_Minus) && 8784 "Expected only + or - operations for depend clauses."); 8785 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub; 8786 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get(); 8787 if (!Cnt) 8788 return nullptr; 8789 } 8790 QualType VarType = LCDecl->getType().getNonReferenceType(); 8791 if (!VarType->isIntegerType() && !VarType->isPointerType() && 8792 !SemaRef.getLangOpts().CPlusPlus) 8793 return nullptr; 8794 // Upper - Lower 8795 Expr *Upper = TestIsLessOp.getValue() 8796 ? Cnt 8797 : tryBuildCapture(SemaRef, LB, Captures).get(); 8798 Expr *Lower = TestIsLessOp.getValue() 8799 ? tryBuildCapture(SemaRef, LB, Captures).get() 8800 : Cnt; 8801 if (!Upper || !Lower) 8802 return nullptr; 8803 8804 ExprResult Diff = calculateNumIters( 8805 SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType, 8806 /*TestIsStrictOp=*/false, /*RoundToStep=*/false, Captures); 8807 if (!Diff.isUsable()) 8808 return nullptr; 8809 8810 return Diff.get(); 8811 } 8812 } // namespace 8813 8814 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 8815 assert(getLangOpts().OpenMP && "OpenMP is not active."); 8816 assert(Init && "Expected loop in canonical form."); 8817 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 8818 if (AssociatedLoops > 0 && 8819 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 8820 DSAStack->loopStart(); 8821 OpenMPIterationSpaceChecker ISC(*this, /*SupportsNonRectangular=*/true, 8822 *DSAStack, ForLoc); 8823 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) { 8824 if (ValueDecl *D = ISC.getLoopDecl()) { 8825 auto *VD = dyn_cast<VarDecl>(D); 8826 DeclRefExpr *PrivateRef = nullptr; 8827 if (!VD) { 8828 if (VarDecl *Private = isOpenMPCapturedDecl(D)) { 8829 VD = Private; 8830 } else { 8831 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(), 8832 /*WithInit=*/false); 8833 VD = cast<VarDecl>(PrivateRef->getDecl()); 8834 } 8835 } 8836 DSAStack->addLoopControlVariable(D, VD); 8837 const Decl *LD = DSAStack->getPossiblyLoopCunter(); 8838 if (LD != D->getCanonicalDecl()) { 8839 DSAStack->resetPossibleLoopCounter(); 8840 if (auto *Var = dyn_cast_or_null<VarDecl>(LD)) 8841 MarkDeclarationsReferencedInExpr( 8842 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var), 8843 Var->getType().getNonLValueExprType(Context), 8844 ForLoc, /*RefersToCapture=*/true)); 8845 } 8846 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 8847 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables 8848 // Referenced in a Construct, C/C++]. The loop iteration variable in the 8849 // associated for-loop of a simd construct with just one associated 8850 // for-loop may be listed in a linear clause with a constant-linear-step 8851 // that is the increment of the associated for-loop. The loop iteration 8852 // variable(s) in the associated for-loop(s) of a for or parallel for 8853 // construct may be listed in a private or lastprivate clause. 8854 DSAStackTy::DSAVarData DVar = 8855 DSAStack->getTopDSA(D, /*FromParent=*/false); 8856 // If LoopVarRefExpr is nullptr it means the corresponding loop variable 8857 // is declared in the loop and it is predetermined as a private. 8858 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr(); 8859 OpenMPClauseKind PredeterminedCKind = 8860 isOpenMPSimdDirective(DKind) 8861 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear) 8862 : OMPC_private; 8863 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 8864 DVar.CKind != PredeterminedCKind && DVar.RefExpr && 8865 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate && 8866 DVar.CKind != OMPC_private))) || 8867 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 8868 DKind == OMPD_master_taskloop || 8869 DKind == OMPD_parallel_master_taskloop || 8870 isOpenMPDistributeDirective(DKind)) && 8871 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 8872 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 8873 (DVar.CKind != OMPC_private || DVar.RefExpr)) { 8874 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa) 8875 << getOpenMPClauseName(DVar.CKind) 8876 << getOpenMPDirectiveName(DKind) 8877 << getOpenMPClauseName(PredeterminedCKind); 8878 if (DVar.RefExpr == nullptr) 8879 DVar.CKind = PredeterminedCKind; 8880 reportOriginalDsa(*this, DSAStack, D, DVar, 8881 /*IsLoopIterVar=*/true); 8882 } else if (LoopDeclRefExpr) { 8883 // Make the loop iteration variable private (for worksharing 8884 // constructs), linear (for simd directives with the only one 8885 // associated loop) or lastprivate (for simd directives with several 8886 // collapsed or ordered loops). 8887 if (DVar.CKind == OMPC_unknown) 8888 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind, 8889 PrivateRef); 8890 } 8891 } 8892 } 8893 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 8894 } 8895 } 8896 8897 /// Called on a for stmt to check and extract its iteration space 8898 /// for further processing (such as collapsing). 8899 static bool checkOpenMPIterationSpace( 8900 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 8901 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 8902 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr, 8903 Expr *OrderedLoopCountExpr, 8904 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 8905 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces, 8906 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8907 bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind); 8908 // OpenMP [2.9.1, Canonical Loop Form] 8909 // for (init-expr; test-expr; incr-expr) structured-block 8910 // for (range-decl: range-expr) structured-block 8911 if (auto *CanonLoop = dyn_cast_or_null<OMPCanonicalLoop>(S)) 8912 S = CanonLoop->getLoopStmt(); 8913 auto *For = dyn_cast_or_null<ForStmt>(S); 8914 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S); 8915 // Ranged for is supported only in OpenMP 5.0. 8916 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) { 8917 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for) 8918 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 8919 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount 8920 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 8921 if (TotalNestedLoopCount > 1) { 8922 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 8923 SemaRef.Diag(DSA.getConstructLoc(), 8924 diag::note_omp_collapse_ordered_expr) 8925 << 2 << CollapseLoopCountExpr->getSourceRange() 8926 << OrderedLoopCountExpr->getSourceRange(); 8927 else if (CollapseLoopCountExpr) 8928 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 8929 diag::note_omp_collapse_ordered_expr) 8930 << 0 << CollapseLoopCountExpr->getSourceRange(); 8931 else 8932 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 8933 diag::note_omp_collapse_ordered_expr) 8934 << 1 << OrderedLoopCountExpr->getSourceRange(); 8935 } 8936 return true; 8937 } 8938 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) && 8939 "No loop body."); 8940 // Postpone analysis in dependent contexts for ranged for loops. 8941 if (CXXFor && SemaRef.CurContext->isDependentContext()) 8942 return false; 8943 8944 OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA, 8945 For ? For->getForLoc() : CXXFor->getForLoc()); 8946 8947 // Check init. 8948 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt(); 8949 if (ISC.checkAndSetInit(Init)) 8950 return true; 8951 8952 bool HasErrors = false; 8953 8954 // Check loop variable's type. 8955 if (ValueDecl *LCDecl = ISC.getLoopDecl()) { 8956 // OpenMP [2.6, Canonical Loop Form] 8957 // Var is one of the following: 8958 // A variable of signed or unsigned integer type. 8959 // For C++, a variable of a random access iterator type. 8960 // For C, a variable of a pointer type. 8961 QualType VarType = LCDecl->getType().getNonReferenceType(); 8962 if (!VarType->isDependentType() && !VarType->isIntegerType() && 8963 !VarType->isPointerType() && 8964 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 8965 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type) 8966 << SemaRef.getLangOpts().CPlusPlus; 8967 HasErrors = true; 8968 } 8969 8970 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 8971 // a Construct 8972 // The loop iteration variable(s) in the associated for-loop(s) of a for or 8973 // parallel for construct is (are) private. 8974 // The loop iteration variable in the associated for-loop of a simd 8975 // construct with just one associated for-loop is linear with a 8976 // constant-linear-step that is the increment of the associated for-loop. 8977 // Exclude loop var from the list of variables with implicitly defined data 8978 // sharing attributes. 8979 VarsWithImplicitDSA.erase(LCDecl); 8980 8981 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 8982 8983 // Check test-expr. 8984 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond()); 8985 8986 // Check incr-expr. 8987 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc()); 8988 } 8989 8990 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 8991 return HasErrors; 8992 8993 // Build the loop's iteration space representation. 8994 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond( 8995 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures); 8996 ResultIterSpaces[CurrentNestedLoopCount].NumIterations = 8997 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces, 8998 (isOpenMPWorksharingDirective(DKind) || 8999 isOpenMPGenericLoopDirective(DKind) || 9000 isOpenMPTaskLoopDirective(DKind) || 9001 isOpenMPDistributeDirective(DKind) || 9002 isOpenMPLoopTransformationDirective(DKind)), 9003 Captures); 9004 ResultIterSpaces[CurrentNestedLoopCount].CounterVar = 9005 ISC.buildCounterVar(Captures, DSA); 9006 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar = 9007 ISC.buildPrivateCounterVar(); 9008 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit(); 9009 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep(); 9010 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange(); 9011 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange = 9012 ISC.getConditionSrcRange(); 9013 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange = 9014 ISC.getIncrementSrcRange(); 9015 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep(); 9016 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare = 9017 ISC.isStrictTestOp(); 9018 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue, 9019 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) = 9020 ISC.buildMinMaxValues(DSA.getCurScope(), Captures); 9021 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition = 9022 ISC.buildFinalCondition(DSA.getCurScope()); 9023 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB = 9024 ISC.doesInitDependOnLC(); 9025 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB = 9026 ISC.doesCondDependOnLC(); 9027 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx = 9028 ISC.getLoopDependentIdx(); 9029 9030 HasErrors |= 9031 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr || 9032 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr || 9033 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr || 9034 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr || 9035 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr || 9036 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr); 9037 if (!HasErrors && DSA.isOrderedRegion()) { 9038 if (DSA.getOrderedRegionParam().second->getNumForLoops()) { 9039 if (CurrentNestedLoopCount < 9040 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) { 9041 DSA.getOrderedRegionParam().second->setLoopNumIterations( 9042 CurrentNestedLoopCount, 9043 ResultIterSpaces[CurrentNestedLoopCount].NumIterations); 9044 DSA.getOrderedRegionParam().second->setLoopCounter( 9045 CurrentNestedLoopCount, 9046 ResultIterSpaces[CurrentNestedLoopCount].CounterVar); 9047 } 9048 } 9049 for (auto &Pair : DSA.getDoacrossDependClauses()) { 9050 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) { 9051 // Erroneous case - clause has some problems. 9052 continue; 9053 } 9054 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink && 9055 Pair.second.size() <= CurrentNestedLoopCount) { 9056 // Erroneous case - clause has some problems. 9057 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr); 9058 continue; 9059 } 9060 Expr *CntValue; 9061 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 9062 CntValue = ISC.buildOrderedLoopData( 9063 DSA.getCurScope(), 9064 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures, 9065 Pair.first->getDependencyLoc()); 9066 else 9067 CntValue = ISC.buildOrderedLoopData( 9068 DSA.getCurScope(), 9069 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures, 9070 Pair.first->getDependencyLoc(), 9071 Pair.second[CurrentNestedLoopCount].first, 9072 Pair.second[CurrentNestedLoopCount].second); 9073 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue); 9074 } 9075 } 9076 9077 return HasErrors; 9078 } 9079 9080 /// Build 'VarRef = Start. 9081 static ExprResult 9082 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 9083 ExprResult Start, bool IsNonRectangularLB, 9084 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 9085 // Build 'VarRef = Start. 9086 ExprResult NewStart = IsNonRectangularLB 9087 ? Start.get() 9088 : tryBuildCapture(SemaRef, Start.get(), Captures); 9089 if (!NewStart.isUsable()) 9090 return ExprError(); 9091 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 9092 VarRef.get()->getType())) { 9093 NewStart = SemaRef.PerformImplicitConversion( 9094 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 9095 /*AllowExplicit=*/true); 9096 if (!NewStart.isUsable()) 9097 return ExprError(); 9098 } 9099 9100 ExprResult Init = 9101 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 9102 return Init; 9103 } 9104 9105 /// Build 'VarRef = Start + Iter * Step'. 9106 static ExprResult buildCounterUpdate( 9107 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 9108 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract, 9109 bool IsNonRectangularLB, 9110 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) { 9111 // Add parentheses (for debugging purposes only). 9112 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 9113 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 9114 !Step.isUsable()) 9115 return ExprError(); 9116 9117 ExprResult NewStep = Step; 9118 if (Captures) 9119 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 9120 if (NewStep.isInvalid()) 9121 return ExprError(); 9122 ExprResult Update = 9123 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 9124 if (!Update.isUsable()) 9125 return ExprError(); 9126 9127 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 9128 // 'VarRef = Start (+|-) Iter * Step'. 9129 if (!Start.isUsable()) 9130 return ExprError(); 9131 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get()); 9132 if (!NewStart.isUsable()) 9133 return ExprError(); 9134 if (Captures && !IsNonRectangularLB) 9135 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 9136 if (NewStart.isInvalid()) 9137 return ExprError(); 9138 9139 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 9140 ExprResult SavedUpdate = Update; 9141 ExprResult UpdateVal; 9142 if (VarRef.get()->getType()->isOverloadableType() || 9143 NewStart.get()->getType()->isOverloadableType() || 9144 Update.get()->getType()->isOverloadableType()) { 9145 Sema::TentativeAnalysisScope Trap(SemaRef); 9146 9147 Update = 9148 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 9149 if (Update.isUsable()) { 9150 UpdateVal = 9151 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 9152 VarRef.get(), SavedUpdate.get()); 9153 if (UpdateVal.isUsable()) { 9154 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 9155 UpdateVal.get()); 9156 } 9157 } 9158 } 9159 9160 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 9161 if (!Update.isUsable() || !UpdateVal.isUsable()) { 9162 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 9163 NewStart.get(), SavedUpdate.get()); 9164 if (!Update.isUsable()) 9165 return ExprError(); 9166 9167 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 9168 VarRef.get()->getType())) { 9169 Update = SemaRef.PerformImplicitConversion( 9170 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 9171 if (!Update.isUsable()) 9172 return ExprError(); 9173 } 9174 9175 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 9176 } 9177 return Update; 9178 } 9179 9180 /// Convert integer expression \a E to make it have at least \a Bits 9181 /// bits. 9182 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 9183 if (E == nullptr) 9184 return ExprError(); 9185 ASTContext &C = SemaRef.Context; 9186 QualType OldType = E->getType(); 9187 unsigned HasBits = C.getTypeSize(OldType); 9188 if (HasBits >= Bits) 9189 return ExprResult(E); 9190 // OK to convert to signed, because new type has more bits than old. 9191 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 9192 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 9193 true); 9194 } 9195 9196 /// Check if the given expression \a E is a constant integer that fits 9197 /// into \a Bits bits. 9198 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) { 9199 if (E == nullptr) 9200 return false; 9201 if (Optional<llvm::APSInt> Result = 9202 E->getIntegerConstantExpr(SemaRef.Context)) 9203 return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits); 9204 return false; 9205 } 9206 9207 /// Build preinits statement for the given declarations. 9208 static Stmt *buildPreInits(ASTContext &Context, 9209 MutableArrayRef<Decl *> PreInits) { 9210 if (!PreInits.empty()) { 9211 return new (Context) DeclStmt( 9212 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 9213 SourceLocation(), SourceLocation()); 9214 } 9215 return nullptr; 9216 } 9217 9218 /// Build preinits statement for the given declarations. 9219 static Stmt * 9220 buildPreInits(ASTContext &Context, 9221 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 9222 if (!Captures.empty()) { 9223 SmallVector<Decl *, 16> PreInits; 9224 for (const auto &Pair : Captures) 9225 PreInits.push_back(Pair.second->getDecl()); 9226 return buildPreInits(Context, PreInits); 9227 } 9228 return nullptr; 9229 } 9230 9231 /// Build postupdate expression for the given list of postupdates expressions. 9232 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 9233 Expr *PostUpdate = nullptr; 9234 if (!PostUpdates.empty()) { 9235 for (Expr *E : PostUpdates) { 9236 Expr *ConvE = S.BuildCStyleCastExpr( 9237 E->getExprLoc(), 9238 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 9239 E->getExprLoc(), E) 9240 .get(); 9241 PostUpdate = PostUpdate 9242 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 9243 PostUpdate, ConvE) 9244 .get() 9245 : ConvE; 9246 } 9247 } 9248 return PostUpdate; 9249 } 9250 9251 /// Called on a for stmt to check itself and nested loops (if any). 9252 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 9253 /// number of collapsed loops otherwise. 9254 static unsigned 9255 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 9256 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 9257 DSAStackTy &DSA, 9258 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 9259 OMPLoopBasedDirective::HelperExprs &Built) { 9260 unsigned NestedLoopCount = 1; 9261 bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) && 9262 !isOpenMPLoopTransformationDirective(DKind); 9263 9264 if (CollapseLoopCountExpr) { 9265 // Found 'collapse' clause - calculate collapse number. 9266 Expr::EvalResult Result; 9267 if (!CollapseLoopCountExpr->isValueDependent() && 9268 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 9269 NestedLoopCount = Result.Val.getInt().getLimitedValue(); 9270 } else { 9271 Built.clear(/*Size=*/1); 9272 return 1; 9273 } 9274 } 9275 unsigned OrderedLoopCount = 1; 9276 if (OrderedLoopCountExpr) { 9277 // Found 'ordered' clause - calculate collapse number. 9278 Expr::EvalResult EVResult; 9279 if (!OrderedLoopCountExpr->isValueDependent() && 9280 OrderedLoopCountExpr->EvaluateAsInt(EVResult, 9281 SemaRef.getASTContext())) { 9282 llvm::APSInt Result = EVResult.Val.getInt(); 9283 if (Result.getLimitedValue() < NestedLoopCount) { 9284 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 9285 diag::err_omp_wrong_ordered_loop_count) 9286 << OrderedLoopCountExpr->getSourceRange(); 9287 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 9288 diag::note_collapse_loop_count) 9289 << CollapseLoopCountExpr->getSourceRange(); 9290 } 9291 OrderedLoopCount = Result.getLimitedValue(); 9292 } else { 9293 Built.clear(/*Size=*/1); 9294 return 1; 9295 } 9296 } 9297 // This is helper routine for loop directives (e.g., 'for', 'simd', 9298 // 'for simd', etc.). 9299 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 9300 unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount); 9301 SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops); 9302 if (!OMPLoopBasedDirective::doForAllLoops( 9303 AStmt->IgnoreContainers(!isOpenMPLoopTransformationDirective(DKind)), 9304 SupportsNonPerfectlyNested, NumLoops, 9305 [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount, 9306 CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA, 9307 &IterSpaces, &Captures](unsigned Cnt, Stmt *CurStmt) { 9308 if (checkOpenMPIterationSpace( 9309 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 9310 NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr, 9311 VarsWithImplicitDSA, IterSpaces, Captures)) 9312 return true; 9313 if (Cnt > 0 && Cnt >= NestedLoopCount && 9314 IterSpaces[Cnt].CounterVar) { 9315 // Handle initialization of captured loop iterator variables. 9316 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar); 9317 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) { 9318 Captures[DRE] = DRE; 9319 } 9320 } 9321 return false; 9322 }, 9323 [&SemaRef, &Captures](OMPLoopTransformationDirective *Transform) { 9324 Stmt *DependentPreInits = Transform->getPreInits(); 9325 if (!DependentPreInits) 9326 return; 9327 for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) { 9328 auto *D = cast<VarDecl>(C); 9329 DeclRefExpr *Ref = buildDeclRefExpr(SemaRef, D, D->getType(), 9330 Transform->getBeginLoc()); 9331 Captures[Ref] = Ref; 9332 } 9333 })) 9334 return 0; 9335 9336 Built.clear(/* size */ NestedLoopCount); 9337 9338 if (SemaRef.CurContext->isDependentContext()) 9339 return NestedLoopCount; 9340 9341 // An example of what is generated for the following code: 9342 // 9343 // #pragma omp simd collapse(2) ordered(2) 9344 // for (i = 0; i < NI; ++i) 9345 // for (k = 0; k < NK; ++k) 9346 // for (j = J0; j < NJ; j+=2) { 9347 // <loop body> 9348 // } 9349 // 9350 // We generate the code below. 9351 // Note: the loop body may be outlined in CodeGen. 9352 // Note: some counters may be C++ classes, operator- is used to find number of 9353 // iterations and operator+= to calculate counter value. 9354 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 9355 // or i64 is currently supported). 9356 // 9357 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 9358 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 9359 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 9360 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 9361 // // similar updates for vars in clauses (e.g. 'linear') 9362 // <loop body (using local i and j)> 9363 // } 9364 // i = NI; // assign final values of counters 9365 // j = NJ; 9366 // 9367 9368 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 9369 // the iteration counts of the collapsed for loops. 9370 // Precondition tests if there is at least one iteration (all conditions are 9371 // true). 9372 auto PreCond = ExprResult(IterSpaces[0].PreCond); 9373 Expr *N0 = IterSpaces[0].NumIterations; 9374 ExprResult LastIteration32 = 9375 widenIterationCount(/*Bits=*/32, 9376 SemaRef 9377 .PerformImplicitConversion( 9378 N0->IgnoreImpCasts(), N0->getType(), 9379 Sema::AA_Converting, /*AllowExplicit=*/true) 9380 .get(), 9381 SemaRef); 9382 ExprResult LastIteration64 = widenIterationCount( 9383 /*Bits=*/64, 9384 SemaRef 9385 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(), 9386 Sema::AA_Converting, 9387 /*AllowExplicit=*/true) 9388 .get(), 9389 SemaRef); 9390 9391 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 9392 return NestedLoopCount; 9393 9394 ASTContext &C = SemaRef.Context; 9395 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 9396 9397 Scope *CurScope = DSA.getCurScope(); 9398 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 9399 if (PreCond.isUsable()) { 9400 PreCond = 9401 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 9402 PreCond.get(), IterSpaces[Cnt].PreCond); 9403 } 9404 Expr *N = IterSpaces[Cnt].NumIterations; 9405 SourceLocation Loc = N->getExprLoc(); 9406 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 9407 if (LastIteration32.isUsable()) 9408 LastIteration32 = SemaRef.BuildBinOp( 9409 CurScope, Loc, BO_Mul, LastIteration32.get(), 9410 SemaRef 9411 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 9412 Sema::AA_Converting, 9413 /*AllowExplicit=*/true) 9414 .get()); 9415 if (LastIteration64.isUsable()) 9416 LastIteration64 = SemaRef.BuildBinOp( 9417 CurScope, Loc, BO_Mul, LastIteration64.get(), 9418 SemaRef 9419 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 9420 Sema::AA_Converting, 9421 /*AllowExplicit=*/true) 9422 .get()); 9423 } 9424 9425 // Choose either the 32-bit or 64-bit version. 9426 ExprResult LastIteration = LastIteration64; 9427 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse || 9428 (LastIteration32.isUsable() && 9429 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 9430 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 9431 fitsInto( 9432 /*Bits=*/32, 9433 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 9434 LastIteration64.get(), SemaRef)))) 9435 LastIteration = LastIteration32; 9436 QualType VType = LastIteration.get()->getType(); 9437 QualType RealVType = VType; 9438 QualType StrideVType = VType; 9439 if (isOpenMPTaskLoopDirective(DKind)) { 9440 VType = 9441 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 9442 StrideVType = 9443 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 9444 } 9445 9446 if (!LastIteration.isUsable()) 9447 return 0; 9448 9449 // Save the number of iterations. 9450 ExprResult NumIterations = LastIteration; 9451 { 9452 LastIteration = SemaRef.BuildBinOp( 9453 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 9454 LastIteration.get(), 9455 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 9456 if (!LastIteration.isUsable()) 9457 return 0; 9458 } 9459 9460 // Calculate the last iteration number beforehand instead of doing this on 9461 // each iteration. Do not do this if the number of iterations may be kfold-ed. 9462 bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context); 9463 ExprResult CalcLastIteration; 9464 if (!IsConstant) { 9465 ExprResult SaveRef = 9466 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 9467 LastIteration = SaveRef; 9468 9469 // Prepare SaveRef + 1. 9470 NumIterations = SemaRef.BuildBinOp( 9471 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 9472 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 9473 if (!NumIterations.isUsable()) 9474 return 0; 9475 } 9476 9477 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 9478 9479 // Build variables passed into runtime, necessary for worksharing directives. 9480 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 9481 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 9482 isOpenMPDistributeDirective(DKind) || 9483 isOpenMPGenericLoopDirective(DKind) || 9484 isOpenMPLoopTransformationDirective(DKind)) { 9485 // Lower bound variable, initialized with zero. 9486 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 9487 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 9488 SemaRef.AddInitializerToDecl(LBDecl, 9489 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 9490 /*DirectInit*/ false); 9491 9492 // Upper bound variable, initialized with last iteration number. 9493 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 9494 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 9495 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 9496 /*DirectInit*/ false); 9497 9498 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 9499 // This will be used to implement clause 'lastprivate'. 9500 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 9501 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 9502 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 9503 SemaRef.AddInitializerToDecl(ILDecl, 9504 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 9505 /*DirectInit*/ false); 9506 9507 // Stride variable returned by runtime (we initialize it to 1 by default). 9508 VarDecl *STDecl = 9509 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 9510 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 9511 SemaRef.AddInitializerToDecl(STDecl, 9512 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 9513 /*DirectInit*/ false); 9514 9515 // Build expression: UB = min(UB, LastIteration) 9516 // It is necessary for CodeGen of directives with static scheduling. 9517 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 9518 UB.get(), LastIteration.get()); 9519 ExprResult CondOp = SemaRef.ActOnConditionalOp( 9520 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(), 9521 LastIteration.get(), UB.get()); 9522 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 9523 CondOp.get()); 9524 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false); 9525 9526 // If we have a combined directive that combines 'distribute', 'for' or 9527 // 'simd' we need to be able to access the bounds of the schedule of the 9528 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 9529 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 9530 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9531 // Lower bound variable, initialized with zero. 9532 VarDecl *CombLBDecl = 9533 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 9534 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 9535 SemaRef.AddInitializerToDecl( 9536 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 9537 /*DirectInit*/ false); 9538 9539 // Upper bound variable, initialized with last iteration number. 9540 VarDecl *CombUBDecl = 9541 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 9542 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 9543 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 9544 /*DirectInit*/ false); 9545 9546 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 9547 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 9548 ExprResult CombCondOp = 9549 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 9550 LastIteration.get(), CombUB.get()); 9551 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 9552 CombCondOp.get()); 9553 CombEUB = 9554 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false); 9555 9556 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 9557 // We expect to have at least 2 more parameters than the 'parallel' 9558 // directive does - the lower and upper bounds of the previous schedule. 9559 assert(CD->getNumParams() >= 4 && 9560 "Unexpected number of parameters in loop combined directive"); 9561 9562 // Set the proper type for the bounds given what we learned from the 9563 // enclosed loops. 9564 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 9565 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 9566 9567 // Previous lower and upper bounds are obtained from the region 9568 // parameters. 9569 PrevLB = 9570 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 9571 PrevUB = 9572 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 9573 } 9574 } 9575 9576 // Build the iteration variable and its initialization before loop. 9577 ExprResult IV; 9578 ExprResult Init, CombInit; 9579 { 9580 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 9581 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 9582 Expr *RHS = (isOpenMPWorksharingDirective(DKind) || 9583 isOpenMPGenericLoopDirective(DKind) || 9584 isOpenMPTaskLoopDirective(DKind) || 9585 isOpenMPDistributeDirective(DKind) || 9586 isOpenMPLoopTransformationDirective(DKind)) 9587 ? LB.get() 9588 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 9589 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 9590 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false); 9591 9592 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9593 Expr *CombRHS = 9594 (isOpenMPWorksharingDirective(DKind) || 9595 isOpenMPGenericLoopDirective(DKind) || 9596 isOpenMPTaskLoopDirective(DKind) || 9597 isOpenMPDistributeDirective(DKind)) 9598 ? CombLB.get() 9599 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 9600 CombInit = 9601 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 9602 CombInit = 9603 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false); 9604 } 9605 } 9606 9607 bool UseStrictCompare = 9608 RealVType->hasUnsignedIntegerRepresentation() && 9609 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) { 9610 return LIS.IsStrictCompare; 9611 }); 9612 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for 9613 // unsigned IV)) for worksharing loops. 9614 SourceLocation CondLoc = AStmt->getBeginLoc(); 9615 Expr *BoundUB = UB.get(); 9616 if (UseStrictCompare) { 9617 BoundUB = 9618 SemaRef 9619 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB, 9620 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 9621 .get(); 9622 BoundUB = 9623 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get(); 9624 } 9625 ExprResult Cond = 9626 (isOpenMPWorksharingDirective(DKind) || 9627 isOpenMPGenericLoopDirective(DKind) || 9628 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind) || 9629 isOpenMPLoopTransformationDirective(DKind)) 9630 ? SemaRef.BuildBinOp(CurScope, CondLoc, 9631 UseStrictCompare ? BO_LT : BO_LE, IV.get(), 9632 BoundUB) 9633 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 9634 NumIterations.get()); 9635 ExprResult CombDistCond; 9636 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9637 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 9638 NumIterations.get()); 9639 } 9640 9641 ExprResult CombCond; 9642 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9643 Expr *BoundCombUB = CombUB.get(); 9644 if (UseStrictCompare) { 9645 BoundCombUB = 9646 SemaRef 9647 .BuildBinOp( 9648 CurScope, CondLoc, BO_Add, BoundCombUB, 9649 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 9650 .get(); 9651 BoundCombUB = 9652 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false) 9653 .get(); 9654 } 9655 CombCond = 9656 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 9657 IV.get(), BoundCombUB); 9658 } 9659 // Loop increment (IV = IV + 1) 9660 SourceLocation IncLoc = AStmt->getBeginLoc(); 9661 ExprResult Inc = 9662 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 9663 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 9664 if (!Inc.isUsable()) 9665 return 0; 9666 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 9667 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false); 9668 if (!Inc.isUsable()) 9669 return 0; 9670 9671 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 9672 // Used for directives with static scheduling. 9673 // In combined construct, add combined version that use CombLB and CombUB 9674 // base variables for the update 9675 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 9676 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 9677 isOpenMPGenericLoopDirective(DKind) || 9678 isOpenMPDistributeDirective(DKind) || 9679 isOpenMPLoopTransformationDirective(DKind)) { 9680 // LB + ST 9681 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 9682 if (!NextLB.isUsable()) 9683 return 0; 9684 // LB = LB + ST 9685 NextLB = 9686 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 9687 NextLB = 9688 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false); 9689 if (!NextLB.isUsable()) 9690 return 0; 9691 // UB + ST 9692 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 9693 if (!NextUB.isUsable()) 9694 return 0; 9695 // UB = UB + ST 9696 NextUB = 9697 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 9698 NextUB = 9699 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false); 9700 if (!NextUB.isUsable()) 9701 return 0; 9702 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9703 CombNextLB = 9704 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 9705 if (!NextLB.isUsable()) 9706 return 0; 9707 // LB = LB + ST 9708 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 9709 CombNextLB.get()); 9710 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(), 9711 /*DiscardedValue*/ false); 9712 if (!CombNextLB.isUsable()) 9713 return 0; 9714 // UB + ST 9715 CombNextUB = 9716 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 9717 if (!CombNextUB.isUsable()) 9718 return 0; 9719 // UB = UB + ST 9720 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 9721 CombNextUB.get()); 9722 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(), 9723 /*DiscardedValue*/ false); 9724 if (!CombNextUB.isUsable()) 9725 return 0; 9726 } 9727 } 9728 9729 // Create increment expression for distribute loop when combined in a same 9730 // directive with for as IV = IV + ST; ensure upper bound expression based 9731 // on PrevUB instead of NumIterations - used to implement 'for' when found 9732 // in combination with 'distribute', like in 'distribute parallel for' 9733 SourceLocation DistIncLoc = AStmt->getBeginLoc(); 9734 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond; 9735 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9736 DistCond = SemaRef.BuildBinOp( 9737 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB); 9738 assert(DistCond.isUsable() && "distribute cond expr was not built"); 9739 9740 DistInc = 9741 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 9742 assert(DistInc.isUsable() && "distribute inc expr was not built"); 9743 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 9744 DistInc.get()); 9745 DistInc = 9746 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false); 9747 assert(DistInc.isUsable() && "distribute inc expr was not built"); 9748 9749 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 9750 // construct 9751 ExprResult NewPrevUB = PrevUB; 9752 SourceLocation DistEUBLoc = AStmt->getBeginLoc(); 9753 if (!SemaRef.Context.hasSameType(UB.get()->getType(), 9754 PrevUB.get()->getType())) { 9755 NewPrevUB = SemaRef.BuildCStyleCastExpr( 9756 DistEUBLoc, 9757 SemaRef.Context.getTrivialTypeSourceInfo(UB.get()->getType()), 9758 DistEUBLoc, NewPrevUB.get()); 9759 if (!NewPrevUB.isUsable()) 9760 return 0; 9761 } 9762 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, 9763 UB.get(), NewPrevUB.get()); 9764 ExprResult CondOp = SemaRef.ActOnConditionalOp( 9765 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), NewPrevUB.get(), UB.get()); 9766 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 9767 CondOp.get()); 9768 PrevEUB = 9769 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false); 9770 9771 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in 9772 // parallel for is in combination with a distribute directive with 9773 // schedule(static, 1) 9774 Expr *BoundPrevUB = PrevUB.get(); 9775 if (UseStrictCompare) { 9776 BoundPrevUB = 9777 SemaRef 9778 .BuildBinOp( 9779 CurScope, CondLoc, BO_Add, BoundPrevUB, 9780 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 9781 .get(); 9782 BoundPrevUB = 9783 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false) 9784 .get(); 9785 } 9786 ParForInDistCond = 9787 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 9788 IV.get(), BoundPrevUB); 9789 } 9790 9791 // Build updates and final values of the loop counters. 9792 bool HasErrors = false; 9793 Built.Counters.resize(NestedLoopCount); 9794 Built.Inits.resize(NestedLoopCount); 9795 Built.Updates.resize(NestedLoopCount); 9796 Built.Finals.resize(NestedLoopCount); 9797 Built.DependentCounters.resize(NestedLoopCount); 9798 Built.DependentInits.resize(NestedLoopCount); 9799 Built.FinalsConditions.resize(NestedLoopCount); 9800 { 9801 // We implement the following algorithm for obtaining the 9802 // original loop iteration variable values based on the 9803 // value of the collapsed loop iteration variable IV. 9804 // 9805 // Let n+1 be the number of collapsed loops in the nest. 9806 // Iteration variables (I0, I1, .... In) 9807 // Iteration counts (N0, N1, ... Nn) 9808 // 9809 // Acc = IV; 9810 // 9811 // To compute Ik for loop k, 0 <= k <= n, generate: 9812 // Prod = N(k+1) * N(k+2) * ... * Nn; 9813 // Ik = Acc / Prod; 9814 // Acc -= Ik * Prod; 9815 // 9816 ExprResult Acc = IV; 9817 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 9818 LoopIterationSpace &IS = IterSpaces[Cnt]; 9819 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 9820 ExprResult Iter; 9821 9822 // Compute prod 9823 ExprResult Prod = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 9824 for (unsigned int K = Cnt + 1; K < NestedLoopCount; ++K) 9825 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(), 9826 IterSpaces[K].NumIterations); 9827 9828 // Iter = Acc / Prod 9829 // If there is at least one more inner loop to avoid 9830 // multiplication by 1. 9831 if (Cnt + 1 < NestedLoopCount) 9832 Iter = 9833 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, Acc.get(), Prod.get()); 9834 else 9835 Iter = Acc; 9836 if (!Iter.isUsable()) { 9837 HasErrors = true; 9838 break; 9839 } 9840 9841 // Update Acc: 9842 // Acc -= Iter * Prod 9843 // Check if there is at least one more inner loop to avoid 9844 // multiplication by 1. 9845 if (Cnt + 1 < NestedLoopCount) 9846 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Iter.get(), 9847 Prod.get()); 9848 else 9849 Prod = Iter; 9850 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, Acc.get(), Prod.get()); 9851 9852 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 9853 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 9854 DeclRefExpr *CounterVar = buildDeclRefExpr( 9855 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(), 9856 /*RefersToCapture=*/true); 9857 ExprResult Init = 9858 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 9859 IS.CounterInit, IS.IsNonRectangularLB, Captures); 9860 if (!Init.isUsable()) { 9861 HasErrors = true; 9862 break; 9863 } 9864 ExprResult Update = buildCounterUpdate( 9865 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 9866 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures); 9867 if (!Update.isUsable()) { 9868 HasErrors = true; 9869 break; 9870 } 9871 9872 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 9873 ExprResult Final = 9874 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar, 9875 IS.CounterInit, IS.NumIterations, IS.CounterStep, 9876 IS.Subtract, IS.IsNonRectangularLB, &Captures); 9877 if (!Final.isUsable()) { 9878 HasErrors = true; 9879 break; 9880 } 9881 9882 if (!Update.isUsable() || !Final.isUsable()) { 9883 HasErrors = true; 9884 break; 9885 } 9886 // Save results 9887 Built.Counters[Cnt] = IS.CounterVar; 9888 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 9889 Built.Inits[Cnt] = Init.get(); 9890 Built.Updates[Cnt] = Update.get(); 9891 Built.Finals[Cnt] = Final.get(); 9892 Built.DependentCounters[Cnt] = nullptr; 9893 Built.DependentInits[Cnt] = nullptr; 9894 Built.FinalsConditions[Cnt] = nullptr; 9895 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) { 9896 Built.DependentCounters[Cnt] = 9897 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx]; 9898 Built.DependentInits[Cnt] = 9899 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx]; 9900 Built.FinalsConditions[Cnt] = IS.FinalCondition; 9901 } 9902 } 9903 } 9904 9905 if (HasErrors) 9906 return 0; 9907 9908 // Save results 9909 Built.IterationVarRef = IV.get(); 9910 Built.LastIteration = LastIteration.get(); 9911 Built.NumIterations = NumIterations.get(); 9912 Built.CalcLastIteration = SemaRef 9913 .ActOnFinishFullExpr(CalcLastIteration.get(), 9914 /*DiscardedValue=*/false) 9915 .get(); 9916 Built.PreCond = PreCond.get(); 9917 Built.PreInits = buildPreInits(C, Captures); 9918 Built.Cond = Cond.get(); 9919 Built.Init = Init.get(); 9920 Built.Inc = Inc.get(); 9921 Built.LB = LB.get(); 9922 Built.UB = UB.get(); 9923 Built.IL = IL.get(); 9924 Built.ST = ST.get(); 9925 Built.EUB = EUB.get(); 9926 Built.NLB = NextLB.get(); 9927 Built.NUB = NextUB.get(); 9928 Built.PrevLB = PrevLB.get(); 9929 Built.PrevUB = PrevUB.get(); 9930 Built.DistInc = DistInc.get(); 9931 Built.PrevEUB = PrevEUB.get(); 9932 Built.DistCombinedFields.LB = CombLB.get(); 9933 Built.DistCombinedFields.UB = CombUB.get(); 9934 Built.DistCombinedFields.EUB = CombEUB.get(); 9935 Built.DistCombinedFields.Init = CombInit.get(); 9936 Built.DistCombinedFields.Cond = CombCond.get(); 9937 Built.DistCombinedFields.NLB = CombNextLB.get(); 9938 Built.DistCombinedFields.NUB = CombNextUB.get(); 9939 Built.DistCombinedFields.DistCond = CombDistCond.get(); 9940 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get(); 9941 9942 return NestedLoopCount; 9943 } 9944 9945 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 9946 auto CollapseClauses = 9947 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 9948 if (CollapseClauses.begin() != CollapseClauses.end()) 9949 return (*CollapseClauses.begin())->getNumForLoops(); 9950 return nullptr; 9951 } 9952 9953 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 9954 auto OrderedClauses = 9955 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 9956 if (OrderedClauses.begin() != OrderedClauses.end()) 9957 return (*OrderedClauses.begin())->getNumForLoops(); 9958 return nullptr; 9959 } 9960 9961 static bool checkSimdlenSafelenSpecified(Sema &S, 9962 const ArrayRef<OMPClause *> Clauses) { 9963 const OMPSafelenClause *Safelen = nullptr; 9964 const OMPSimdlenClause *Simdlen = nullptr; 9965 9966 for (const OMPClause *Clause : Clauses) { 9967 if (Clause->getClauseKind() == OMPC_safelen) 9968 Safelen = cast<OMPSafelenClause>(Clause); 9969 else if (Clause->getClauseKind() == OMPC_simdlen) 9970 Simdlen = cast<OMPSimdlenClause>(Clause); 9971 if (Safelen && Simdlen) 9972 break; 9973 } 9974 9975 if (Simdlen && Safelen) { 9976 const Expr *SimdlenLength = Simdlen->getSimdlen(); 9977 const Expr *SafelenLength = Safelen->getSafelen(); 9978 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 9979 SimdlenLength->isInstantiationDependent() || 9980 SimdlenLength->containsUnexpandedParameterPack()) 9981 return false; 9982 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 9983 SafelenLength->isInstantiationDependent() || 9984 SafelenLength->containsUnexpandedParameterPack()) 9985 return false; 9986 Expr::EvalResult SimdlenResult, SafelenResult; 9987 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context); 9988 SafelenLength->EvaluateAsInt(SafelenResult, S.Context); 9989 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt(); 9990 llvm::APSInt SafelenRes = SafelenResult.Val.getInt(); 9991 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 9992 // If both simdlen and safelen clauses are specified, the value of the 9993 // simdlen parameter must be less than or equal to the value of the safelen 9994 // parameter. 9995 if (SimdlenRes > SafelenRes) { 9996 S.Diag(SimdlenLength->getExprLoc(), 9997 diag::err_omp_wrong_simdlen_safelen_values) 9998 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 9999 return true; 10000 } 10001 } 10002 return false; 10003 } 10004 10005 StmtResult 10006 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10007 SourceLocation StartLoc, SourceLocation EndLoc, 10008 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10009 if (!AStmt) 10010 return StmtError(); 10011 10012 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10013 OMPLoopBasedDirective::HelperExprs B; 10014 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10015 // define the nested loops number. 10016 unsigned NestedLoopCount = checkOpenMPLoop( 10017 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 10018 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 10019 if (NestedLoopCount == 0) 10020 return StmtError(); 10021 10022 assert((CurContext->isDependentContext() || B.builtAll()) && 10023 "omp simd loop exprs were not built"); 10024 10025 if (!CurContext->isDependentContext()) { 10026 // Finalize the clauses that need pre-built expressions for CodeGen. 10027 for (OMPClause *C : Clauses) { 10028 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10029 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10030 B.NumIterations, *this, CurScope, 10031 DSAStack)) 10032 return StmtError(); 10033 } 10034 } 10035 10036 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10037 return StmtError(); 10038 10039 setFunctionHasBranchProtectedScope(); 10040 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 10041 Clauses, AStmt, B); 10042 } 10043 10044 StmtResult 10045 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 10046 SourceLocation StartLoc, SourceLocation EndLoc, 10047 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10048 if (!AStmt) 10049 return StmtError(); 10050 10051 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10052 OMPLoopBasedDirective::HelperExprs B; 10053 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10054 // define the nested loops number. 10055 unsigned NestedLoopCount = checkOpenMPLoop( 10056 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 10057 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 10058 if (NestedLoopCount == 0) 10059 return StmtError(); 10060 10061 assert((CurContext->isDependentContext() || B.builtAll()) && 10062 "omp for loop exprs were not built"); 10063 10064 if (!CurContext->isDependentContext()) { 10065 // Finalize the clauses that need pre-built expressions for CodeGen. 10066 for (OMPClause *C : Clauses) { 10067 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10068 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10069 B.NumIterations, *this, CurScope, 10070 DSAStack)) 10071 return StmtError(); 10072 } 10073 } 10074 10075 setFunctionHasBranchProtectedScope(); 10076 return OMPForDirective::Create( 10077 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 10078 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 10079 } 10080 10081 StmtResult Sema::ActOnOpenMPForSimdDirective( 10082 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10083 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10084 if (!AStmt) 10085 return StmtError(); 10086 10087 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10088 OMPLoopBasedDirective::HelperExprs B; 10089 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10090 // define the nested loops number. 10091 unsigned NestedLoopCount = 10092 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 10093 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 10094 VarsWithImplicitDSA, B); 10095 if (NestedLoopCount == 0) 10096 return StmtError(); 10097 10098 assert((CurContext->isDependentContext() || B.builtAll()) && 10099 "omp for simd loop exprs were not built"); 10100 10101 if (!CurContext->isDependentContext()) { 10102 // Finalize the clauses that need pre-built expressions for CodeGen. 10103 for (OMPClause *C : Clauses) { 10104 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10105 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10106 B.NumIterations, *this, CurScope, 10107 DSAStack)) 10108 return StmtError(); 10109 } 10110 } 10111 10112 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10113 return StmtError(); 10114 10115 setFunctionHasBranchProtectedScope(); 10116 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 10117 Clauses, AStmt, B); 10118 } 10119 10120 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 10121 Stmt *AStmt, 10122 SourceLocation StartLoc, 10123 SourceLocation EndLoc) { 10124 if (!AStmt) 10125 return StmtError(); 10126 10127 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10128 auto BaseStmt = AStmt; 10129 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 10130 BaseStmt = CS->getCapturedStmt(); 10131 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 10132 auto S = C->children(); 10133 if (S.begin() == S.end()) 10134 return StmtError(); 10135 // All associated statements must be '#pragma omp section' except for 10136 // the first one. 10137 for (Stmt *SectionStmt : llvm::drop_begin(S)) { 10138 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 10139 if (SectionStmt) 10140 Diag(SectionStmt->getBeginLoc(), 10141 diag::err_omp_sections_substmt_not_section); 10142 return StmtError(); 10143 } 10144 cast<OMPSectionDirective>(SectionStmt) 10145 ->setHasCancel(DSAStack->isCancelRegion()); 10146 } 10147 } else { 10148 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt); 10149 return StmtError(); 10150 } 10151 10152 setFunctionHasBranchProtectedScope(); 10153 10154 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 10155 DSAStack->getTaskgroupReductionRef(), 10156 DSAStack->isCancelRegion()); 10157 } 10158 10159 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 10160 SourceLocation StartLoc, 10161 SourceLocation EndLoc) { 10162 if (!AStmt) 10163 return StmtError(); 10164 10165 setFunctionHasBranchProtectedScope(); 10166 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 10167 10168 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 10169 DSAStack->isCancelRegion()); 10170 } 10171 10172 static Expr *getDirectCallExpr(Expr *E) { 10173 E = E->IgnoreParenCasts()->IgnoreImplicit(); 10174 if (auto *CE = dyn_cast<CallExpr>(E)) 10175 if (CE->getDirectCallee()) 10176 return E; 10177 return nullptr; 10178 } 10179 10180 StmtResult Sema::ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses, 10181 Stmt *AStmt, 10182 SourceLocation StartLoc, 10183 SourceLocation EndLoc) { 10184 if (!AStmt) 10185 return StmtError(); 10186 10187 Stmt *S = cast<CapturedStmt>(AStmt)->getCapturedStmt(); 10188 10189 // 5.1 OpenMP 10190 // expression-stmt : an expression statement with one of the following forms: 10191 // expression = target-call ( [expression-list] ); 10192 // target-call ( [expression-list] ); 10193 10194 SourceLocation TargetCallLoc; 10195 10196 if (!CurContext->isDependentContext()) { 10197 Expr *TargetCall = nullptr; 10198 10199 auto *E = dyn_cast<Expr>(S); 10200 if (!E) { 10201 Diag(S->getBeginLoc(), diag::err_omp_dispatch_statement_call); 10202 return StmtError(); 10203 } 10204 10205 E = E->IgnoreParenCasts()->IgnoreImplicit(); 10206 10207 if (auto *BO = dyn_cast<BinaryOperator>(E)) { 10208 if (BO->getOpcode() == BO_Assign) 10209 TargetCall = getDirectCallExpr(BO->getRHS()); 10210 } else { 10211 if (auto *COCE = dyn_cast<CXXOperatorCallExpr>(E)) 10212 if (COCE->getOperator() == OO_Equal) 10213 TargetCall = getDirectCallExpr(COCE->getArg(1)); 10214 if (!TargetCall) 10215 TargetCall = getDirectCallExpr(E); 10216 } 10217 if (!TargetCall) { 10218 Diag(E->getBeginLoc(), diag::err_omp_dispatch_statement_call); 10219 return StmtError(); 10220 } 10221 TargetCallLoc = TargetCall->getExprLoc(); 10222 } 10223 10224 setFunctionHasBranchProtectedScope(); 10225 10226 return OMPDispatchDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 10227 TargetCallLoc); 10228 } 10229 10230 static bool checkGenericLoopLastprivate(Sema &S, ArrayRef<OMPClause *> Clauses, 10231 OpenMPDirectiveKind K, 10232 DSAStackTy *Stack) { 10233 bool ErrorFound = false; 10234 for (OMPClause *C : Clauses) { 10235 if (auto *LPC = dyn_cast<OMPLastprivateClause>(C)) { 10236 for (Expr *RefExpr : LPC->varlists()) { 10237 SourceLocation ELoc; 10238 SourceRange ERange; 10239 Expr *SimpleRefExpr = RefExpr; 10240 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange); 10241 if (ValueDecl *D = Res.first) { 10242 auto &&Info = Stack->isLoopControlVariable(D); 10243 if (!Info.first) { 10244 S.Diag(ELoc, diag::err_omp_lastprivate_loop_var_non_loop_iteration) 10245 << getOpenMPDirectiveName(K); 10246 ErrorFound = true; 10247 } 10248 } 10249 } 10250 } 10251 } 10252 return ErrorFound; 10253 } 10254 10255 StmtResult Sema::ActOnOpenMPGenericLoopDirective( 10256 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10257 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10258 if (!AStmt) 10259 return StmtError(); 10260 10261 // OpenMP 5.1 [2.11.7, loop construct, Restrictions] 10262 // A list item may not appear in a lastprivate clause unless it is the 10263 // loop iteration variable of a loop that is associated with the construct. 10264 if (checkGenericLoopLastprivate(*this, Clauses, OMPD_loop, DSAStack)) 10265 return StmtError(); 10266 10267 auto *CS = cast<CapturedStmt>(AStmt); 10268 // 1.2.2 OpenMP Language Terminology 10269 // Structured block - An executable statement with a single entry at the 10270 // top and a single exit at the bottom. 10271 // The point of exit cannot be a branch out of the structured block. 10272 // longjmp() and throw() must not violate the entry/exit criteria. 10273 CS->getCapturedDecl()->setNothrow(); 10274 10275 OMPLoopDirective::HelperExprs B; 10276 // In presence of clause 'collapse', it will define the nested loops number. 10277 unsigned NestedLoopCount = checkOpenMPLoop( 10278 OMPD_loop, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 10279 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 10280 if (NestedLoopCount == 0) 10281 return StmtError(); 10282 10283 assert((CurContext->isDependentContext() || B.builtAll()) && 10284 "omp loop exprs were not built"); 10285 10286 setFunctionHasBranchProtectedScope(); 10287 return OMPGenericLoopDirective::Create(Context, StartLoc, EndLoc, 10288 NestedLoopCount, Clauses, AStmt, B); 10289 } 10290 10291 StmtResult Sema::ActOnOpenMPTeamsGenericLoopDirective( 10292 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10293 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10294 if (!AStmt) 10295 return StmtError(); 10296 10297 // OpenMP 5.1 [2.11.7, loop construct, Restrictions] 10298 // A list item may not appear in a lastprivate clause unless it is the 10299 // loop iteration variable of a loop that is associated with the construct. 10300 if (checkGenericLoopLastprivate(*this, Clauses, OMPD_teams_loop, DSAStack)) 10301 return StmtError(); 10302 10303 auto *CS = cast<CapturedStmt>(AStmt); 10304 // 1.2.2 OpenMP Language Terminology 10305 // Structured block - An executable statement with a single entry at the 10306 // top and a single exit at the bottom. 10307 // The point of exit cannot be a branch out of the structured block. 10308 // longjmp() and throw() must not violate the entry/exit criteria. 10309 CS->getCapturedDecl()->setNothrow(); 10310 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_loop); 10311 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10312 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10313 // 1.2.2 OpenMP Language Terminology 10314 // Structured block - An executable statement with a single entry at the 10315 // top and a single exit at the bottom. 10316 // The point of exit cannot be a branch out of the structured block. 10317 // longjmp() and throw() must not violate the entry/exit criteria. 10318 CS->getCapturedDecl()->setNothrow(); 10319 } 10320 10321 OMPLoopDirective::HelperExprs B; 10322 // In presence of clause 'collapse', it will define the nested loops number. 10323 unsigned NestedLoopCount = 10324 checkOpenMPLoop(OMPD_teams_loop, getCollapseNumberExpr(Clauses), 10325 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 10326 VarsWithImplicitDSA, B); 10327 if (NestedLoopCount == 0) 10328 return StmtError(); 10329 10330 assert((CurContext->isDependentContext() || B.builtAll()) && 10331 "omp loop exprs were not built"); 10332 10333 setFunctionHasBranchProtectedScope(); 10334 DSAStack->setParentTeamsRegionLoc(StartLoc); 10335 10336 return OMPTeamsGenericLoopDirective::Create( 10337 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 10338 } 10339 10340 StmtResult Sema::ActOnOpenMPTargetTeamsGenericLoopDirective( 10341 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10342 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10343 if (!AStmt) 10344 return StmtError(); 10345 10346 // OpenMP 5.1 [2.11.7, loop construct, Restrictions] 10347 // A list item may not appear in a lastprivate clause unless it is the 10348 // loop iteration variable of a loop that is associated with the construct. 10349 if (checkGenericLoopLastprivate(*this, Clauses, OMPD_target_teams_loop, 10350 DSAStack)) 10351 return StmtError(); 10352 10353 auto *CS = cast<CapturedStmt>(AStmt); 10354 // 1.2.2 OpenMP Language Terminology 10355 // Structured block - An executable statement with a single entry at the 10356 // top and a single exit at the bottom. 10357 // The point of exit cannot be a branch out of the structured block. 10358 // longjmp() and throw() must not violate the entry/exit criteria. 10359 CS->getCapturedDecl()->setNothrow(); 10360 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams_loop); 10361 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10362 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10363 // 1.2.2 OpenMP Language Terminology 10364 // Structured block - An executable statement with a single entry at the 10365 // top and a single exit at the bottom. 10366 // The point of exit cannot be a branch out of the structured block. 10367 // longjmp() and throw() must not violate the entry/exit criteria. 10368 CS->getCapturedDecl()->setNothrow(); 10369 } 10370 10371 OMPLoopDirective::HelperExprs B; 10372 // In presence of clause 'collapse', it will define the nested loops number. 10373 unsigned NestedLoopCount = 10374 checkOpenMPLoop(OMPD_target_teams_loop, getCollapseNumberExpr(Clauses), 10375 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 10376 VarsWithImplicitDSA, B); 10377 if (NestedLoopCount == 0) 10378 return StmtError(); 10379 10380 assert((CurContext->isDependentContext() || B.builtAll()) && 10381 "omp loop exprs were not built"); 10382 10383 setFunctionHasBranchProtectedScope(); 10384 10385 return OMPTargetTeamsGenericLoopDirective::Create( 10386 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 10387 } 10388 10389 StmtResult Sema::ActOnOpenMPParallelGenericLoopDirective( 10390 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10391 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10392 if (!AStmt) 10393 return StmtError(); 10394 10395 // OpenMP 5.1 [2.11.7, loop construct, Restrictions] 10396 // A list item may not appear in a lastprivate clause unless it is the 10397 // loop iteration variable of a loop that is associated with the construct. 10398 if (checkGenericLoopLastprivate(*this, Clauses, OMPD_parallel_loop, DSAStack)) 10399 return StmtError(); 10400 10401 auto *CS = cast<CapturedStmt>(AStmt); 10402 // 1.2.2 OpenMP Language Terminology 10403 // Structured block - An executable statement with a single entry at the 10404 // top and a single exit at the bottom. 10405 // The point of exit cannot be a branch out of the structured block. 10406 // longjmp() and throw() must not violate the entry/exit criteria. 10407 CS->getCapturedDecl()->setNothrow(); 10408 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_parallel_loop); 10409 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10410 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10411 // 1.2.2 OpenMP Language Terminology 10412 // Structured block - An executable statement with a single entry at the 10413 // top and a single exit at the bottom. 10414 // The point of exit cannot be a branch out of the structured block. 10415 // longjmp() and throw() must not violate the entry/exit criteria. 10416 CS->getCapturedDecl()->setNothrow(); 10417 } 10418 10419 OMPLoopDirective::HelperExprs B; 10420 // In presence of clause 'collapse', it will define the nested loops number. 10421 unsigned NestedLoopCount = 10422 checkOpenMPLoop(OMPD_parallel_loop, getCollapseNumberExpr(Clauses), 10423 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 10424 VarsWithImplicitDSA, B); 10425 if (NestedLoopCount == 0) 10426 return StmtError(); 10427 10428 assert((CurContext->isDependentContext() || B.builtAll()) && 10429 "omp loop exprs were not built"); 10430 10431 setFunctionHasBranchProtectedScope(); 10432 10433 return OMPParallelGenericLoopDirective::Create( 10434 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 10435 } 10436 10437 StmtResult Sema::ActOnOpenMPTargetParallelGenericLoopDirective( 10438 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10439 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10440 if (!AStmt) 10441 return StmtError(); 10442 10443 // OpenMP 5.1 [2.11.7, loop construct, Restrictions] 10444 // A list item may not appear in a lastprivate clause unless it is the 10445 // loop iteration variable of a loop that is associated with the construct. 10446 if (checkGenericLoopLastprivate(*this, Clauses, OMPD_target_parallel_loop, 10447 DSAStack)) 10448 return StmtError(); 10449 10450 auto *CS = cast<CapturedStmt>(AStmt); 10451 // 1.2.2 OpenMP Language Terminology 10452 // Structured block - An executable statement with a single entry at the 10453 // top and a single exit at the bottom. 10454 // The point of exit cannot be a branch out of the structured block. 10455 // longjmp() and throw() must not violate the entry/exit criteria. 10456 CS->getCapturedDecl()->setNothrow(); 10457 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_loop); 10458 ThisCaptureLevel > 1; --ThisCaptureLevel) { 10459 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 10460 // 1.2.2 OpenMP Language Terminology 10461 // Structured block - An executable statement with a single entry at the 10462 // top and a single exit at the bottom. 10463 // The point of exit cannot be a branch out of the structured block. 10464 // longjmp() and throw() must not violate the entry/exit criteria. 10465 CS->getCapturedDecl()->setNothrow(); 10466 } 10467 10468 OMPLoopDirective::HelperExprs B; 10469 // In presence of clause 'collapse', it will define the nested loops number. 10470 unsigned NestedLoopCount = 10471 checkOpenMPLoop(OMPD_target_parallel_loop, getCollapseNumberExpr(Clauses), 10472 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 10473 VarsWithImplicitDSA, B); 10474 if (NestedLoopCount == 0) 10475 return StmtError(); 10476 10477 assert((CurContext->isDependentContext() || B.builtAll()) && 10478 "omp loop exprs were not built"); 10479 10480 setFunctionHasBranchProtectedScope(); 10481 10482 return OMPTargetParallelGenericLoopDirective::Create( 10483 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 10484 } 10485 10486 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 10487 Stmt *AStmt, 10488 SourceLocation StartLoc, 10489 SourceLocation EndLoc) { 10490 if (!AStmt) 10491 return StmtError(); 10492 10493 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10494 10495 setFunctionHasBranchProtectedScope(); 10496 10497 // OpenMP [2.7.3, single Construct, Restrictions] 10498 // The copyprivate clause must not be used with the nowait clause. 10499 const OMPClause *Nowait = nullptr; 10500 const OMPClause *Copyprivate = nullptr; 10501 for (const OMPClause *Clause : Clauses) { 10502 if (Clause->getClauseKind() == OMPC_nowait) 10503 Nowait = Clause; 10504 else if (Clause->getClauseKind() == OMPC_copyprivate) 10505 Copyprivate = Clause; 10506 if (Copyprivate && Nowait) { 10507 Diag(Copyprivate->getBeginLoc(), 10508 diag::err_omp_single_copyprivate_with_nowait); 10509 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here); 10510 return StmtError(); 10511 } 10512 } 10513 10514 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10515 } 10516 10517 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 10518 SourceLocation StartLoc, 10519 SourceLocation EndLoc) { 10520 if (!AStmt) 10521 return StmtError(); 10522 10523 setFunctionHasBranchProtectedScope(); 10524 10525 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 10526 } 10527 10528 StmtResult Sema::ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses, 10529 Stmt *AStmt, 10530 SourceLocation StartLoc, 10531 SourceLocation EndLoc) { 10532 if (!AStmt) 10533 return StmtError(); 10534 10535 setFunctionHasBranchProtectedScope(); 10536 10537 return OMPMaskedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10538 } 10539 10540 StmtResult Sema::ActOnOpenMPCriticalDirective( 10541 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 10542 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 10543 if (!AStmt) 10544 return StmtError(); 10545 10546 bool ErrorFound = false; 10547 llvm::APSInt Hint; 10548 SourceLocation HintLoc; 10549 bool DependentHint = false; 10550 for (const OMPClause *C : Clauses) { 10551 if (C->getClauseKind() == OMPC_hint) { 10552 if (!DirName.getName()) { 10553 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name); 10554 ErrorFound = true; 10555 } 10556 Expr *E = cast<OMPHintClause>(C)->getHint(); 10557 if (E->isTypeDependent() || E->isValueDependent() || 10558 E->isInstantiationDependent()) { 10559 DependentHint = true; 10560 } else { 10561 Hint = E->EvaluateKnownConstInt(Context); 10562 HintLoc = C->getBeginLoc(); 10563 } 10564 } 10565 } 10566 if (ErrorFound) 10567 return StmtError(); 10568 const auto Pair = DSAStack->getCriticalWithHint(DirName); 10569 if (Pair.first && DirName.getName() && !DependentHint) { 10570 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 10571 Diag(StartLoc, diag::err_omp_critical_with_hint); 10572 if (HintLoc.isValid()) 10573 Diag(HintLoc, diag::note_omp_critical_hint_here) 10574 << 0 << toString(Hint, /*Radix=*/10, /*Signed=*/false); 10575 else 10576 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 10577 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 10578 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here) 10579 << 1 10580 << toString(C->getHint()->EvaluateKnownConstInt(Context), 10581 /*Radix=*/10, /*Signed=*/false); 10582 } else { 10583 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1; 10584 } 10585 } 10586 } 10587 10588 setFunctionHasBranchProtectedScope(); 10589 10590 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 10591 Clauses, AStmt); 10592 if (!Pair.first && DirName.getName() && !DependentHint) 10593 DSAStack->addCriticalWithHint(Dir, Hint); 10594 return Dir; 10595 } 10596 10597 StmtResult Sema::ActOnOpenMPParallelForDirective( 10598 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10599 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10600 if (!AStmt) 10601 return StmtError(); 10602 10603 auto *CS = cast<CapturedStmt>(AStmt); 10604 // 1.2.2 OpenMP Language Terminology 10605 // Structured block - An executable statement with a single entry at the 10606 // top and a single exit at the bottom. 10607 // The point of exit cannot be a branch out of the structured block. 10608 // longjmp() and throw() must not violate the entry/exit criteria. 10609 CS->getCapturedDecl()->setNothrow(); 10610 10611 OMPLoopBasedDirective::HelperExprs B; 10612 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10613 // define the nested loops number. 10614 unsigned NestedLoopCount = 10615 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 10616 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 10617 VarsWithImplicitDSA, B); 10618 if (NestedLoopCount == 0) 10619 return StmtError(); 10620 10621 assert((CurContext->isDependentContext() || B.builtAll()) && 10622 "omp parallel for loop exprs were not built"); 10623 10624 if (!CurContext->isDependentContext()) { 10625 // Finalize the clauses that need pre-built expressions for CodeGen. 10626 for (OMPClause *C : Clauses) { 10627 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10628 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10629 B.NumIterations, *this, CurScope, 10630 DSAStack)) 10631 return StmtError(); 10632 } 10633 } 10634 10635 setFunctionHasBranchProtectedScope(); 10636 return OMPParallelForDirective::Create( 10637 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 10638 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 10639 } 10640 10641 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 10642 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10643 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10644 if (!AStmt) 10645 return StmtError(); 10646 10647 auto *CS = cast<CapturedStmt>(AStmt); 10648 // 1.2.2 OpenMP Language Terminology 10649 // Structured block - An executable statement with a single entry at the 10650 // top and a single exit at the bottom. 10651 // The point of exit cannot be a branch out of the structured block. 10652 // longjmp() and throw() must not violate the entry/exit criteria. 10653 CS->getCapturedDecl()->setNothrow(); 10654 10655 OMPLoopBasedDirective::HelperExprs B; 10656 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10657 // define the nested loops number. 10658 unsigned NestedLoopCount = 10659 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 10660 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 10661 VarsWithImplicitDSA, B); 10662 if (NestedLoopCount == 0) 10663 return StmtError(); 10664 10665 if (!CurContext->isDependentContext()) { 10666 // Finalize the clauses that need pre-built expressions for CodeGen. 10667 for (OMPClause *C : Clauses) { 10668 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10669 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10670 B.NumIterations, *this, CurScope, 10671 DSAStack)) 10672 return StmtError(); 10673 } 10674 } 10675 10676 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10677 return StmtError(); 10678 10679 setFunctionHasBranchProtectedScope(); 10680 return OMPParallelForSimdDirective::Create( 10681 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 10682 } 10683 10684 StmtResult 10685 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, 10686 Stmt *AStmt, SourceLocation StartLoc, 10687 SourceLocation EndLoc) { 10688 if (!AStmt) 10689 return StmtError(); 10690 10691 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10692 auto *CS = cast<CapturedStmt>(AStmt); 10693 // 1.2.2 OpenMP Language Terminology 10694 // Structured block - An executable statement with a single entry at the 10695 // top and a single exit at the bottom. 10696 // The point of exit cannot be a branch out of the structured block. 10697 // longjmp() and throw() must not violate the entry/exit criteria. 10698 CS->getCapturedDecl()->setNothrow(); 10699 10700 setFunctionHasBranchProtectedScope(); 10701 10702 return OMPParallelMasterDirective::Create( 10703 Context, StartLoc, EndLoc, Clauses, AStmt, 10704 DSAStack->getTaskgroupReductionRef()); 10705 } 10706 10707 StmtResult 10708 Sema::ActOnOpenMPParallelMaskedDirective(ArrayRef<OMPClause *> Clauses, 10709 Stmt *AStmt, SourceLocation StartLoc, 10710 SourceLocation EndLoc) { 10711 if (!AStmt) 10712 return StmtError(); 10713 10714 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10715 auto *CS = cast<CapturedStmt>(AStmt); 10716 // 1.2.2 OpenMP Language Terminology 10717 // Structured block - An executable statement with a single entry at the 10718 // top and a single exit at the bottom. 10719 // The point of exit cannot be a branch out of the structured block. 10720 // longjmp() and throw() must not violate the entry/exit criteria. 10721 CS->getCapturedDecl()->setNothrow(); 10722 10723 setFunctionHasBranchProtectedScope(); 10724 10725 return OMPParallelMaskedDirective::Create( 10726 Context, StartLoc, EndLoc, Clauses, AStmt, 10727 DSAStack->getTaskgroupReductionRef()); 10728 } 10729 10730 StmtResult 10731 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 10732 Stmt *AStmt, SourceLocation StartLoc, 10733 SourceLocation EndLoc) { 10734 if (!AStmt) 10735 return StmtError(); 10736 10737 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10738 auto BaseStmt = AStmt; 10739 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 10740 BaseStmt = CS->getCapturedStmt(); 10741 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 10742 auto S = C->children(); 10743 if (S.begin() == S.end()) 10744 return StmtError(); 10745 // All associated statements must be '#pragma omp section' except for 10746 // the first one. 10747 for (Stmt *SectionStmt : llvm::drop_begin(S)) { 10748 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 10749 if (SectionStmt) 10750 Diag(SectionStmt->getBeginLoc(), 10751 diag::err_omp_parallel_sections_substmt_not_section); 10752 return StmtError(); 10753 } 10754 cast<OMPSectionDirective>(SectionStmt) 10755 ->setHasCancel(DSAStack->isCancelRegion()); 10756 } 10757 } else { 10758 Diag(AStmt->getBeginLoc(), 10759 diag::err_omp_parallel_sections_not_compound_stmt); 10760 return StmtError(); 10761 } 10762 10763 setFunctionHasBranchProtectedScope(); 10764 10765 return OMPParallelSectionsDirective::Create( 10766 Context, StartLoc, EndLoc, Clauses, AStmt, 10767 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 10768 } 10769 10770 /// Find and diagnose mutually exclusive clause kinds. 10771 static bool checkMutuallyExclusiveClauses( 10772 Sema &S, ArrayRef<OMPClause *> Clauses, 10773 ArrayRef<OpenMPClauseKind> MutuallyExclusiveClauses) { 10774 const OMPClause *PrevClause = nullptr; 10775 bool ErrorFound = false; 10776 for (const OMPClause *C : Clauses) { 10777 if (llvm::is_contained(MutuallyExclusiveClauses, C->getClauseKind())) { 10778 if (!PrevClause) { 10779 PrevClause = C; 10780 } else if (PrevClause->getClauseKind() != C->getClauseKind()) { 10781 S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive) 10782 << getOpenMPClauseName(C->getClauseKind()) 10783 << getOpenMPClauseName(PrevClause->getClauseKind()); 10784 S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause) 10785 << getOpenMPClauseName(PrevClause->getClauseKind()); 10786 ErrorFound = true; 10787 } 10788 } 10789 } 10790 return ErrorFound; 10791 } 10792 10793 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 10794 Stmt *AStmt, SourceLocation StartLoc, 10795 SourceLocation EndLoc) { 10796 if (!AStmt) 10797 return StmtError(); 10798 10799 // OpenMP 5.0, 2.10.1 task Construct 10800 // If a detach clause appears on the directive, then a mergeable clause cannot 10801 // appear on the same directive. 10802 if (checkMutuallyExclusiveClauses(*this, Clauses, 10803 {OMPC_detach, OMPC_mergeable})) 10804 return StmtError(); 10805 10806 auto *CS = cast<CapturedStmt>(AStmt); 10807 // 1.2.2 OpenMP Language Terminology 10808 // Structured block - An executable statement with a single entry at the 10809 // top and a single exit at the bottom. 10810 // The point of exit cannot be a branch out of the structured block. 10811 // longjmp() and throw() must not violate the entry/exit criteria. 10812 CS->getCapturedDecl()->setNothrow(); 10813 10814 setFunctionHasBranchProtectedScope(); 10815 10816 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 10817 DSAStack->isCancelRegion()); 10818 } 10819 10820 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 10821 SourceLocation EndLoc) { 10822 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 10823 } 10824 10825 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 10826 SourceLocation EndLoc) { 10827 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 10828 } 10829 10830 StmtResult Sema::ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses, 10831 SourceLocation StartLoc, 10832 SourceLocation EndLoc) { 10833 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc, Clauses); 10834 } 10835 10836 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 10837 Stmt *AStmt, 10838 SourceLocation StartLoc, 10839 SourceLocation EndLoc) { 10840 if (!AStmt) 10841 return StmtError(); 10842 10843 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10844 10845 setFunctionHasBranchProtectedScope(); 10846 10847 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, 10848 AStmt, 10849 DSAStack->getTaskgroupReductionRef()); 10850 } 10851 10852 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 10853 SourceLocation StartLoc, 10854 SourceLocation EndLoc) { 10855 OMPFlushClause *FC = nullptr; 10856 OMPClause *OrderClause = nullptr; 10857 for (OMPClause *C : Clauses) { 10858 if (C->getClauseKind() == OMPC_flush) 10859 FC = cast<OMPFlushClause>(C); 10860 else 10861 OrderClause = C; 10862 } 10863 OpenMPClauseKind MemOrderKind = OMPC_unknown; 10864 SourceLocation MemOrderLoc; 10865 for (const OMPClause *C : Clauses) { 10866 if (C->getClauseKind() == OMPC_acq_rel || 10867 C->getClauseKind() == OMPC_acquire || 10868 C->getClauseKind() == OMPC_release) { 10869 if (MemOrderKind != OMPC_unknown) { 10870 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses) 10871 << getOpenMPDirectiveName(OMPD_flush) << 1 10872 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 10873 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 10874 << getOpenMPClauseName(MemOrderKind); 10875 } else { 10876 MemOrderKind = C->getClauseKind(); 10877 MemOrderLoc = C->getBeginLoc(); 10878 } 10879 } 10880 } 10881 if (FC && OrderClause) { 10882 Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list) 10883 << getOpenMPClauseName(OrderClause->getClauseKind()); 10884 Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here) 10885 << getOpenMPClauseName(OrderClause->getClauseKind()); 10886 return StmtError(); 10887 } 10888 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 10889 } 10890 10891 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, 10892 SourceLocation StartLoc, 10893 SourceLocation EndLoc) { 10894 if (Clauses.empty()) { 10895 Diag(StartLoc, diag::err_omp_depobj_expected); 10896 return StmtError(); 10897 } else if (Clauses[0]->getClauseKind() != OMPC_depobj) { 10898 Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected); 10899 return StmtError(); 10900 } 10901 // Only depobj expression and another single clause is allowed. 10902 if (Clauses.size() > 2) { 10903 Diag(Clauses[2]->getBeginLoc(), 10904 diag::err_omp_depobj_single_clause_expected); 10905 return StmtError(); 10906 } else if (Clauses.size() < 1) { 10907 Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected); 10908 return StmtError(); 10909 } 10910 return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses); 10911 } 10912 10913 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, 10914 SourceLocation StartLoc, 10915 SourceLocation EndLoc) { 10916 // Check that exactly one clause is specified. 10917 if (Clauses.size() != 1) { 10918 Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(), 10919 diag::err_omp_scan_single_clause_expected); 10920 return StmtError(); 10921 } 10922 // Check that scan directive is used in the scopeof the OpenMP loop body. 10923 if (Scope *S = DSAStack->getCurScope()) { 10924 Scope *ParentS = S->getParent(); 10925 if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() || 10926 !ParentS->getBreakParent()->isOpenMPLoopScope()) 10927 return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive) 10928 << getOpenMPDirectiveName(OMPD_scan) << 5); 10929 } 10930 // Check that only one instance of scan directives is used in the same outer 10931 // region. 10932 if (DSAStack->doesParentHasScanDirective()) { 10933 Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan"; 10934 Diag(DSAStack->getParentScanDirectiveLoc(), 10935 diag::note_omp_previous_directive) 10936 << "scan"; 10937 return StmtError(); 10938 } 10939 DSAStack->setParentHasScanDirective(StartLoc); 10940 return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses); 10941 } 10942 10943 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 10944 Stmt *AStmt, 10945 SourceLocation StartLoc, 10946 SourceLocation EndLoc) { 10947 const OMPClause *DependFound = nullptr; 10948 const OMPClause *DependSourceClause = nullptr; 10949 const OMPClause *DependSinkClause = nullptr; 10950 bool ErrorFound = false; 10951 const OMPThreadsClause *TC = nullptr; 10952 const OMPSIMDClause *SC = nullptr; 10953 for (const OMPClause *C : Clauses) { 10954 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 10955 DependFound = C; 10956 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 10957 if (DependSourceClause) { 10958 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 10959 << getOpenMPDirectiveName(OMPD_ordered) 10960 << getOpenMPClauseName(OMPC_depend) << 2; 10961 ErrorFound = true; 10962 } else { 10963 DependSourceClause = C; 10964 } 10965 if (DependSinkClause) { 10966 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 10967 << 0; 10968 ErrorFound = true; 10969 } 10970 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 10971 if (DependSourceClause) { 10972 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 10973 << 1; 10974 ErrorFound = true; 10975 } 10976 DependSinkClause = C; 10977 } 10978 } else if (C->getClauseKind() == OMPC_threads) { 10979 TC = cast<OMPThreadsClause>(C); 10980 } else if (C->getClauseKind() == OMPC_simd) { 10981 SC = cast<OMPSIMDClause>(C); 10982 } 10983 } 10984 if (!ErrorFound && !SC && 10985 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 10986 // OpenMP [2.8.1,simd Construct, Restrictions] 10987 // An ordered construct with the simd clause is the only OpenMP construct 10988 // that can appear in the simd region. 10989 Diag(StartLoc, diag::err_omp_prohibited_region_simd) 10990 << (LangOpts.OpenMP >= 50 ? 1 : 0); 10991 ErrorFound = true; 10992 } else if (DependFound && (TC || SC)) { 10993 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd) 10994 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 10995 ErrorFound = true; 10996 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) { 10997 Diag(DependFound->getBeginLoc(), 10998 diag::err_omp_ordered_directive_without_param); 10999 ErrorFound = true; 11000 } else if (TC || Clauses.empty()) { 11001 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) { 11002 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc; 11003 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 11004 << (TC != nullptr); 11005 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1; 11006 ErrorFound = true; 11007 } 11008 } 11009 if ((!AStmt && !DependFound) || ErrorFound) 11010 return StmtError(); 11011 11012 // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions. 11013 // During execution of an iteration of a worksharing-loop or a loop nest 11014 // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread 11015 // must not execute more than one ordered region corresponding to an ordered 11016 // construct without a depend clause. 11017 if (!DependFound) { 11018 if (DSAStack->doesParentHasOrderedDirective()) { 11019 Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered"; 11020 Diag(DSAStack->getParentOrderedDirectiveLoc(), 11021 diag::note_omp_previous_directive) 11022 << "ordered"; 11023 return StmtError(); 11024 } 11025 DSAStack->setParentHasOrderedDirective(StartLoc); 11026 } 11027 11028 if (AStmt) { 11029 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11030 11031 setFunctionHasBranchProtectedScope(); 11032 } 11033 11034 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 11035 } 11036 11037 namespace { 11038 /// Helper class for checking expression in 'omp atomic [update]' 11039 /// construct. 11040 class OpenMPAtomicUpdateChecker { 11041 /// Error results for atomic update expressions. 11042 enum ExprAnalysisErrorCode { 11043 /// A statement is not an expression statement. 11044 NotAnExpression, 11045 /// Expression is not builtin binary or unary operation. 11046 NotABinaryOrUnaryExpression, 11047 /// Unary operation is not post-/pre- increment/decrement operation. 11048 NotAnUnaryIncDecExpression, 11049 /// An expression is not of scalar type. 11050 NotAScalarType, 11051 /// A binary operation is not an assignment operation. 11052 NotAnAssignmentOp, 11053 /// RHS part of the binary operation is not a binary expression. 11054 NotABinaryExpression, 11055 /// RHS part is not additive/multiplicative/shift/biwise binary 11056 /// expression. 11057 NotABinaryOperator, 11058 /// RHS binary operation does not have reference to the updated LHS 11059 /// part. 11060 NotAnUpdateExpression, 11061 /// No errors is found. 11062 NoError 11063 }; 11064 /// Reference to Sema. 11065 Sema &SemaRef; 11066 /// A location for note diagnostics (when error is found). 11067 SourceLocation NoteLoc; 11068 /// 'x' lvalue part of the source atomic expression. 11069 Expr *X; 11070 /// 'expr' rvalue part of the source atomic expression. 11071 Expr *E; 11072 /// Helper expression of the form 11073 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 11074 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 11075 Expr *UpdateExpr; 11076 /// Is 'x' a LHS in a RHS part of full update expression. It is 11077 /// important for non-associative operations. 11078 bool IsXLHSInRHSPart; 11079 BinaryOperatorKind Op; 11080 SourceLocation OpLoc; 11081 /// true if the source expression is a postfix unary operation, false 11082 /// if it is a prefix unary operation. 11083 bool IsPostfixUpdate; 11084 11085 public: 11086 OpenMPAtomicUpdateChecker(Sema &SemaRef) 11087 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 11088 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 11089 /// Check specified statement that it is suitable for 'atomic update' 11090 /// constructs and extract 'x', 'expr' and Operation from the original 11091 /// expression. If DiagId and NoteId == 0, then only check is performed 11092 /// without error notification. 11093 /// \param DiagId Diagnostic which should be emitted if error is found. 11094 /// \param NoteId Diagnostic note for the main error message. 11095 /// \return true if statement is not an update expression, false otherwise. 11096 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 11097 /// Return the 'x' lvalue part of the source atomic expression. 11098 Expr *getX() const { return X; } 11099 /// Return the 'expr' rvalue part of the source atomic expression. 11100 Expr *getExpr() const { return E; } 11101 /// Return the update expression used in calculation of the updated 11102 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 11103 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 11104 Expr *getUpdateExpr() const { return UpdateExpr; } 11105 /// Return true if 'x' is LHS in RHS part of full update expression, 11106 /// false otherwise. 11107 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 11108 11109 /// true if the source expression is a postfix unary operation, false 11110 /// if it is a prefix unary operation. 11111 bool isPostfixUpdate() const { return IsPostfixUpdate; } 11112 11113 private: 11114 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 11115 unsigned NoteId = 0); 11116 }; 11117 11118 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 11119 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 11120 ExprAnalysisErrorCode ErrorFound = NoError; 11121 SourceLocation ErrorLoc, NoteLoc; 11122 SourceRange ErrorRange, NoteRange; 11123 // Allowed constructs are: 11124 // x = x binop expr; 11125 // x = expr binop x; 11126 if (AtomicBinOp->getOpcode() == BO_Assign) { 11127 X = AtomicBinOp->getLHS(); 11128 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 11129 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 11130 if (AtomicInnerBinOp->isMultiplicativeOp() || 11131 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 11132 AtomicInnerBinOp->isBitwiseOp()) { 11133 Op = AtomicInnerBinOp->getOpcode(); 11134 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 11135 Expr *LHS = AtomicInnerBinOp->getLHS(); 11136 Expr *RHS = AtomicInnerBinOp->getRHS(); 11137 llvm::FoldingSetNodeID XId, LHSId, RHSId; 11138 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 11139 /*Canonical=*/true); 11140 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 11141 /*Canonical=*/true); 11142 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 11143 /*Canonical=*/true); 11144 if (XId == LHSId) { 11145 E = RHS; 11146 IsXLHSInRHSPart = true; 11147 } else if (XId == RHSId) { 11148 E = LHS; 11149 IsXLHSInRHSPart = false; 11150 } else { 11151 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 11152 ErrorRange = AtomicInnerBinOp->getSourceRange(); 11153 NoteLoc = X->getExprLoc(); 11154 NoteRange = X->getSourceRange(); 11155 ErrorFound = NotAnUpdateExpression; 11156 } 11157 } else { 11158 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 11159 ErrorRange = AtomicInnerBinOp->getSourceRange(); 11160 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 11161 NoteRange = SourceRange(NoteLoc, NoteLoc); 11162 ErrorFound = NotABinaryOperator; 11163 } 11164 } else { 11165 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 11166 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 11167 ErrorFound = NotABinaryExpression; 11168 } 11169 } else { 11170 ErrorLoc = AtomicBinOp->getExprLoc(); 11171 ErrorRange = AtomicBinOp->getSourceRange(); 11172 NoteLoc = AtomicBinOp->getOperatorLoc(); 11173 NoteRange = SourceRange(NoteLoc, NoteLoc); 11174 ErrorFound = NotAnAssignmentOp; 11175 } 11176 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 11177 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 11178 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 11179 return true; 11180 } 11181 if (SemaRef.CurContext->isDependentContext()) 11182 E = X = UpdateExpr = nullptr; 11183 return ErrorFound != NoError; 11184 } 11185 11186 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 11187 unsigned NoteId) { 11188 ExprAnalysisErrorCode ErrorFound = NoError; 11189 SourceLocation ErrorLoc, NoteLoc; 11190 SourceRange ErrorRange, NoteRange; 11191 // Allowed constructs are: 11192 // x++; 11193 // x--; 11194 // ++x; 11195 // --x; 11196 // x binop= expr; 11197 // x = x binop expr; 11198 // x = expr binop x; 11199 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 11200 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 11201 if (AtomicBody->getType()->isScalarType() || 11202 AtomicBody->isInstantiationDependent()) { 11203 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 11204 AtomicBody->IgnoreParenImpCasts())) { 11205 // Check for Compound Assignment Operation 11206 Op = BinaryOperator::getOpForCompoundAssignment( 11207 AtomicCompAssignOp->getOpcode()); 11208 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 11209 E = AtomicCompAssignOp->getRHS(); 11210 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 11211 IsXLHSInRHSPart = true; 11212 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 11213 AtomicBody->IgnoreParenImpCasts())) { 11214 // Check for Binary Operation 11215 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 11216 return true; 11217 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 11218 AtomicBody->IgnoreParenImpCasts())) { 11219 // Check for Unary Operation 11220 if (AtomicUnaryOp->isIncrementDecrementOp()) { 11221 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 11222 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 11223 OpLoc = AtomicUnaryOp->getOperatorLoc(); 11224 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 11225 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 11226 IsXLHSInRHSPart = true; 11227 } else { 11228 ErrorFound = NotAnUnaryIncDecExpression; 11229 ErrorLoc = AtomicUnaryOp->getExprLoc(); 11230 ErrorRange = AtomicUnaryOp->getSourceRange(); 11231 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 11232 NoteRange = SourceRange(NoteLoc, NoteLoc); 11233 } 11234 } else if (!AtomicBody->isInstantiationDependent()) { 11235 ErrorFound = NotABinaryOrUnaryExpression; 11236 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 11237 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 11238 } 11239 } else { 11240 ErrorFound = NotAScalarType; 11241 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc(); 11242 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 11243 } 11244 } else { 11245 ErrorFound = NotAnExpression; 11246 NoteLoc = ErrorLoc = S->getBeginLoc(); 11247 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 11248 } 11249 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 11250 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 11251 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 11252 return true; 11253 } 11254 if (SemaRef.CurContext->isDependentContext()) 11255 E = X = UpdateExpr = nullptr; 11256 if (ErrorFound == NoError && E && X) { 11257 // Build an update expression of form 'OpaqueValueExpr(x) binop 11258 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 11259 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 11260 auto *OVEX = new (SemaRef.getASTContext()) 11261 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_PRValue); 11262 auto *OVEExpr = new (SemaRef.getASTContext()) 11263 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_PRValue); 11264 ExprResult Update = 11265 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 11266 IsXLHSInRHSPart ? OVEExpr : OVEX); 11267 if (Update.isInvalid()) 11268 return true; 11269 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 11270 Sema::AA_Casting); 11271 if (Update.isInvalid()) 11272 return true; 11273 UpdateExpr = Update.get(); 11274 } 11275 return ErrorFound != NoError; 11276 } 11277 11278 /// Get the node id of the fixed point of an expression \a S. 11279 llvm::FoldingSetNodeID getNodeId(ASTContext &Context, const Expr *S) { 11280 llvm::FoldingSetNodeID Id; 11281 S->IgnoreParenImpCasts()->Profile(Id, Context, true); 11282 return Id; 11283 } 11284 11285 /// Check if two expressions are same. 11286 bool checkIfTwoExprsAreSame(ASTContext &Context, const Expr *LHS, 11287 const Expr *RHS) { 11288 return getNodeId(Context, LHS) == getNodeId(Context, RHS); 11289 } 11290 11291 class OpenMPAtomicCompareChecker { 11292 public: 11293 /// All kinds of errors that can occur in `atomic compare` 11294 enum ErrorTy { 11295 /// Empty compound statement. 11296 NoStmt = 0, 11297 /// More than one statement in a compound statement. 11298 MoreThanOneStmt, 11299 /// Not an assignment binary operator. 11300 NotAnAssignment, 11301 /// Not a conditional operator. 11302 NotCondOp, 11303 /// Wrong false expr. According to the spec, 'x' should be at the false 11304 /// expression of a conditional expression. 11305 WrongFalseExpr, 11306 /// The condition of a conditional expression is not a binary operator. 11307 NotABinaryOp, 11308 /// Invalid binary operator (not <, >, or ==). 11309 InvalidBinaryOp, 11310 /// Invalid comparison (not x == e, e == x, x ordop expr, or expr ordop x). 11311 InvalidComparison, 11312 /// X is not a lvalue. 11313 XNotLValue, 11314 /// Not a scalar. 11315 NotScalar, 11316 /// Not an integer. 11317 NotInteger, 11318 /// 'else' statement is not expected. 11319 UnexpectedElse, 11320 /// Not an equality operator. 11321 NotEQ, 11322 /// Invalid assignment (not v == x). 11323 InvalidAssignment, 11324 /// Not if statement 11325 NotIfStmt, 11326 /// More than two statements in a compund statement. 11327 MoreThanTwoStmts, 11328 /// Not a compound statement. 11329 NotCompoundStmt, 11330 /// No else statement. 11331 NoElse, 11332 /// Not 'if (r)'. 11333 InvalidCondition, 11334 /// No error. 11335 NoError, 11336 }; 11337 11338 struct ErrorInfoTy { 11339 ErrorTy Error; 11340 SourceLocation ErrorLoc; 11341 SourceRange ErrorRange; 11342 SourceLocation NoteLoc; 11343 SourceRange NoteRange; 11344 }; 11345 11346 OpenMPAtomicCompareChecker(Sema &S) : ContextRef(S.getASTContext()) {} 11347 11348 /// Check if statement \a S is valid for <tt>atomic compare</tt>. 11349 bool checkStmt(Stmt *S, ErrorInfoTy &ErrorInfo); 11350 11351 Expr *getX() const { return X; } 11352 Expr *getE() const { return E; } 11353 Expr *getD() const { return D; } 11354 Expr *getCond() const { return C; } 11355 bool isXBinopExpr() const { return IsXBinopExpr; } 11356 11357 protected: 11358 /// Reference to ASTContext 11359 ASTContext &ContextRef; 11360 /// 'x' lvalue part of the source atomic expression. 11361 Expr *X = nullptr; 11362 /// 'expr' or 'e' rvalue part of the source atomic expression. 11363 Expr *E = nullptr; 11364 /// 'd' rvalue part of the source atomic expression. 11365 Expr *D = nullptr; 11366 /// 'cond' part of the source atomic expression. It is in one of the following 11367 /// forms: 11368 /// expr ordop x 11369 /// x ordop expr 11370 /// x == e 11371 /// e == x 11372 Expr *C = nullptr; 11373 /// True if the cond expr is in the form of 'x ordop expr'. 11374 bool IsXBinopExpr = true; 11375 11376 /// Check if it is a valid conditional update statement (cond-update-stmt). 11377 bool checkCondUpdateStmt(IfStmt *S, ErrorInfoTy &ErrorInfo); 11378 11379 /// Check if it is a valid conditional expression statement (cond-expr-stmt). 11380 bool checkCondExprStmt(Stmt *S, ErrorInfoTy &ErrorInfo); 11381 11382 /// Check if all captured values have right type. 11383 bool checkType(ErrorInfoTy &ErrorInfo) const; 11384 11385 static bool CheckValue(const Expr *E, ErrorInfoTy &ErrorInfo, 11386 bool ShouldBeLValue) { 11387 if (ShouldBeLValue && !E->isLValue()) { 11388 ErrorInfo.Error = ErrorTy::XNotLValue; 11389 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc(); 11390 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange(); 11391 return false; 11392 } 11393 11394 if (!E->isInstantiationDependent()) { 11395 QualType QTy = E->getType(); 11396 if (!QTy->isScalarType()) { 11397 ErrorInfo.Error = ErrorTy::NotScalar; 11398 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc(); 11399 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange(); 11400 return false; 11401 } 11402 11403 if (!QTy->isIntegerType()) { 11404 ErrorInfo.Error = ErrorTy::NotInteger; 11405 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc(); 11406 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange(); 11407 return false; 11408 } 11409 } 11410 11411 return true; 11412 } 11413 }; 11414 11415 bool OpenMPAtomicCompareChecker::checkCondUpdateStmt(IfStmt *S, 11416 ErrorInfoTy &ErrorInfo) { 11417 auto *Then = S->getThen(); 11418 if (auto *CS = dyn_cast<CompoundStmt>(Then)) { 11419 if (CS->body_empty()) { 11420 ErrorInfo.Error = ErrorTy::NoStmt; 11421 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc(); 11422 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange(); 11423 return false; 11424 } 11425 if (CS->size() > 1) { 11426 ErrorInfo.Error = ErrorTy::MoreThanOneStmt; 11427 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc(); 11428 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange(); 11429 return false; 11430 } 11431 Then = CS->body_front(); 11432 } 11433 11434 auto *BO = dyn_cast<BinaryOperator>(Then); 11435 if (!BO) { 11436 ErrorInfo.Error = ErrorTy::NotAnAssignment; 11437 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Then->getBeginLoc(); 11438 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Then->getSourceRange(); 11439 return false; 11440 } 11441 if (BO->getOpcode() != BO_Assign) { 11442 ErrorInfo.Error = ErrorTy::NotAnAssignment; 11443 ErrorInfo.ErrorLoc = BO->getExprLoc(); 11444 ErrorInfo.NoteLoc = BO->getOperatorLoc(); 11445 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange(); 11446 return false; 11447 } 11448 11449 X = BO->getLHS(); 11450 11451 auto *Cond = dyn_cast<BinaryOperator>(S->getCond()); 11452 if (!Cond) { 11453 ErrorInfo.Error = ErrorTy::NotABinaryOp; 11454 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getCond()->getExprLoc(); 11455 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getCond()->getSourceRange(); 11456 return false; 11457 } 11458 11459 switch (Cond->getOpcode()) { 11460 case BO_EQ: { 11461 C = Cond; 11462 D = BO->getRHS(); 11463 if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS())) { 11464 E = Cond->getRHS(); 11465 } else if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) { 11466 E = Cond->getLHS(); 11467 } else { 11468 ErrorInfo.Error = ErrorTy::InvalidComparison; 11469 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc(); 11470 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange(); 11471 return false; 11472 } 11473 break; 11474 } 11475 case BO_LT: 11476 case BO_GT: { 11477 E = BO->getRHS(); 11478 if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS()) && 11479 checkIfTwoExprsAreSame(ContextRef, E, Cond->getRHS())) { 11480 C = Cond; 11481 } else if (checkIfTwoExprsAreSame(ContextRef, E, Cond->getLHS()) && 11482 checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) { 11483 C = Cond; 11484 IsXBinopExpr = false; 11485 } else { 11486 ErrorInfo.Error = ErrorTy::InvalidComparison; 11487 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc(); 11488 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange(); 11489 return false; 11490 } 11491 break; 11492 } 11493 default: 11494 ErrorInfo.Error = ErrorTy::InvalidBinaryOp; 11495 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc(); 11496 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange(); 11497 return false; 11498 } 11499 11500 if (S->getElse()) { 11501 ErrorInfo.Error = ErrorTy::UnexpectedElse; 11502 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getElse()->getBeginLoc(); 11503 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getElse()->getSourceRange(); 11504 return false; 11505 } 11506 11507 return true; 11508 } 11509 11510 bool OpenMPAtomicCompareChecker::checkCondExprStmt(Stmt *S, 11511 ErrorInfoTy &ErrorInfo) { 11512 auto *BO = dyn_cast<BinaryOperator>(S); 11513 if (!BO) { 11514 ErrorInfo.Error = ErrorTy::NotAnAssignment; 11515 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getBeginLoc(); 11516 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange(); 11517 return false; 11518 } 11519 if (BO->getOpcode() != BO_Assign) { 11520 ErrorInfo.Error = ErrorTy::NotAnAssignment; 11521 ErrorInfo.ErrorLoc = BO->getExprLoc(); 11522 ErrorInfo.NoteLoc = BO->getOperatorLoc(); 11523 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange(); 11524 return false; 11525 } 11526 11527 X = BO->getLHS(); 11528 11529 auto *CO = dyn_cast<ConditionalOperator>(BO->getRHS()->IgnoreParenImpCasts()); 11530 if (!CO) { 11531 ErrorInfo.Error = ErrorTy::NotCondOp; 11532 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = BO->getRHS()->getExprLoc(); 11533 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getRHS()->getSourceRange(); 11534 return false; 11535 } 11536 11537 if (!checkIfTwoExprsAreSame(ContextRef, X, CO->getFalseExpr())) { 11538 ErrorInfo.Error = ErrorTy::WrongFalseExpr; 11539 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CO->getFalseExpr()->getExprLoc(); 11540 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = 11541 CO->getFalseExpr()->getSourceRange(); 11542 return false; 11543 } 11544 11545 auto *Cond = dyn_cast<BinaryOperator>(CO->getCond()); 11546 if (!Cond) { 11547 ErrorInfo.Error = ErrorTy::NotABinaryOp; 11548 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CO->getCond()->getExprLoc(); 11549 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = 11550 CO->getCond()->getSourceRange(); 11551 return false; 11552 } 11553 11554 switch (Cond->getOpcode()) { 11555 case BO_EQ: { 11556 C = Cond; 11557 D = CO->getTrueExpr(); 11558 if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS())) { 11559 E = Cond->getRHS(); 11560 } else if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) { 11561 E = Cond->getLHS(); 11562 } else { 11563 ErrorInfo.Error = ErrorTy::InvalidComparison; 11564 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc(); 11565 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange(); 11566 return false; 11567 } 11568 break; 11569 } 11570 case BO_LT: 11571 case BO_GT: { 11572 E = CO->getTrueExpr(); 11573 if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS()) && 11574 checkIfTwoExprsAreSame(ContextRef, E, Cond->getRHS())) { 11575 C = Cond; 11576 } else if (checkIfTwoExprsAreSame(ContextRef, E, Cond->getLHS()) && 11577 checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) { 11578 C = Cond; 11579 IsXBinopExpr = false; 11580 } else { 11581 ErrorInfo.Error = ErrorTy::InvalidComparison; 11582 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc(); 11583 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange(); 11584 return false; 11585 } 11586 break; 11587 } 11588 default: 11589 ErrorInfo.Error = ErrorTy::InvalidBinaryOp; 11590 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc(); 11591 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange(); 11592 return false; 11593 } 11594 11595 return true; 11596 } 11597 11598 bool OpenMPAtomicCompareChecker::checkType(ErrorInfoTy &ErrorInfo) const { 11599 // 'x' and 'e' cannot be nullptr 11600 assert(X && E && "X and E cannot be nullptr"); 11601 11602 if (!CheckValue(X, ErrorInfo, true)) 11603 return false; 11604 11605 if (!CheckValue(E, ErrorInfo, false)) 11606 return false; 11607 11608 if (D && !CheckValue(D, ErrorInfo, false)) 11609 return false; 11610 11611 return true; 11612 } 11613 11614 bool OpenMPAtomicCompareChecker::checkStmt( 11615 Stmt *S, OpenMPAtomicCompareChecker::ErrorInfoTy &ErrorInfo) { 11616 auto *CS = dyn_cast<CompoundStmt>(S); 11617 if (CS) { 11618 if (CS->body_empty()) { 11619 ErrorInfo.Error = ErrorTy::NoStmt; 11620 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc(); 11621 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange(); 11622 return false; 11623 } 11624 11625 if (CS->size() != 1) { 11626 ErrorInfo.Error = ErrorTy::MoreThanOneStmt; 11627 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc(); 11628 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange(); 11629 return false; 11630 } 11631 S = CS->body_front(); 11632 } 11633 11634 auto Res = false; 11635 11636 if (auto *IS = dyn_cast<IfStmt>(S)) { 11637 // Check if the statement is in one of the following forms 11638 // (cond-update-stmt): 11639 // if (expr ordop x) { x = expr; } 11640 // if (x ordop expr) { x = expr; } 11641 // if (x == e) { x = d; } 11642 Res = checkCondUpdateStmt(IS, ErrorInfo); 11643 } else { 11644 // Check if the statement is in one of the following forms (cond-expr-stmt): 11645 // x = expr ordop x ? expr : x; 11646 // x = x ordop expr ? expr : x; 11647 // x = x == e ? d : x; 11648 Res = checkCondExprStmt(S, ErrorInfo); 11649 } 11650 11651 if (!Res) 11652 return false; 11653 11654 return checkType(ErrorInfo); 11655 } 11656 11657 class OpenMPAtomicCompareCaptureChecker final 11658 : public OpenMPAtomicCompareChecker { 11659 public: 11660 OpenMPAtomicCompareCaptureChecker(Sema &S) : OpenMPAtomicCompareChecker(S) {} 11661 11662 Expr *getV() const { return V; } 11663 Expr *getR() const { return R; } 11664 bool isFailOnly() const { return IsFailOnly; } 11665 bool isPostfixUpdate() const { return IsPostfixUpdate; } 11666 11667 /// Check if statement \a S is valid for <tt>atomic compare capture</tt>. 11668 bool checkStmt(Stmt *S, ErrorInfoTy &ErrorInfo); 11669 11670 private: 11671 bool checkType(ErrorInfoTy &ErrorInfo); 11672 11673 // NOTE: Form 3, 4, 5 in the following comments mean the 3rd, 4th, and 5th 11674 // form of 'conditional-update-capture-atomic' structured block on the v5.2 11675 // spec p.p. 82: 11676 // (1) { v = x; cond-update-stmt } 11677 // (2) { cond-update-stmt v = x; } 11678 // (3) if(x == e) { x = d; } else { v = x; } 11679 // (4) { r = x == e; if(r) { x = d; } } 11680 // (5) { r = x == e; if(r) { x = d; } else { v = x; } } 11681 11682 /// Check if it is valid 'if(x == e) { x = d; } else { v = x; }' (form 3) 11683 bool checkForm3(IfStmt *S, ErrorInfoTy &ErrorInfo); 11684 11685 /// Check if it is valid '{ r = x == e; if(r) { x = d; } }', 11686 /// or '{ r = x == e; if(r) { x = d; } else { v = x; } }' (form 4 and 5) 11687 bool checkForm45(Stmt *S, ErrorInfoTy &ErrorInfo); 11688 11689 /// 'v' lvalue part of the source atomic expression. 11690 Expr *V = nullptr; 11691 /// 'r' lvalue part of the source atomic expression. 11692 Expr *R = nullptr; 11693 /// If 'v' is only updated when the comparison fails. 11694 bool IsFailOnly = false; 11695 /// If original value of 'x' must be stored in 'v', not an updated one. 11696 bool IsPostfixUpdate = false; 11697 }; 11698 11699 bool OpenMPAtomicCompareCaptureChecker::checkType(ErrorInfoTy &ErrorInfo) { 11700 if (!OpenMPAtomicCompareChecker::checkType(ErrorInfo)) 11701 return false; 11702 11703 if (V && !CheckValue(V, ErrorInfo, true)) 11704 return false; 11705 11706 if (R && !CheckValue(R, ErrorInfo, true)) 11707 return false; 11708 11709 return true; 11710 } 11711 11712 bool OpenMPAtomicCompareCaptureChecker::checkForm3(IfStmt *S, 11713 ErrorInfoTy &ErrorInfo) { 11714 IsFailOnly = true; 11715 11716 auto *Then = S->getThen(); 11717 if (auto *CS = dyn_cast<CompoundStmt>(Then)) { 11718 if (CS->body_empty()) { 11719 ErrorInfo.Error = ErrorTy::NoStmt; 11720 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc(); 11721 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange(); 11722 return false; 11723 } 11724 if (CS->size() > 1) { 11725 ErrorInfo.Error = ErrorTy::MoreThanOneStmt; 11726 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc(); 11727 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange(); 11728 return false; 11729 } 11730 Then = CS->body_front(); 11731 } 11732 11733 auto *BO = dyn_cast<BinaryOperator>(Then); 11734 if (!BO) { 11735 ErrorInfo.Error = ErrorTy::NotAnAssignment; 11736 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Then->getBeginLoc(); 11737 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Then->getSourceRange(); 11738 return false; 11739 } 11740 if (BO->getOpcode() != BO_Assign) { 11741 ErrorInfo.Error = ErrorTy::NotAnAssignment; 11742 ErrorInfo.ErrorLoc = BO->getExprLoc(); 11743 ErrorInfo.NoteLoc = BO->getOperatorLoc(); 11744 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange(); 11745 return false; 11746 } 11747 11748 X = BO->getLHS(); 11749 D = BO->getRHS(); 11750 11751 auto *Cond = dyn_cast<BinaryOperator>(S->getCond()); 11752 if (!Cond) { 11753 ErrorInfo.Error = ErrorTy::NotABinaryOp; 11754 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getCond()->getExprLoc(); 11755 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getCond()->getSourceRange(); 11756 return false; 11757 } 11758 if (Cond->getOpcode() != BO_EQ) { 11759 ErrorInfo.Error = ErrorTy::NotEQ; 11760 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc(); 11761 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange(); 11762 return false; 11763 } 11764 11765 if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS())) { 11766 E = Cond->getRHS(); 11767 } else if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) { 11768 E = Cond->getLHS(); 11769 } else { 11770 ErrorInfo.Error = ErrorTy::InvalidComparison; 11771 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc(); 11772 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange(); 11773 return false; 11774 } 11775 11776 C = Cond; 11777 11778 if (!S->getElse()) { 11779 ErrorInfo.Error = ErrorTy::NoElse; 11780 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getBeginLoc(); 11781 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange(); 11782 return false; 11783 } 11784 11785 auto *Else = S->getElse(); 11786 if (auto *CS = dyn_cast<CompoundStmt>(Else)) { 11787 if (CS->body_empty()) { 11788 ErrorInfo.Error = ErrorTy::NoStmt; 11789 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc(); 11790 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange(); 11791 return false; 11792 } 11793 if (CS->size() > 1) { 11794 ErrorInfo.Error = ErrorTy::MoreThanOneStmt; 11795 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc(); 11796 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange(); 11797 return false; 11798 } 11799 Else = CS->body_front(); 11800 } 11801 11802 auto *ElseBO = dyn_cast<BinaryOperator>(Else); 11803 if (!ElseBO) { 11804 ErrorInfo.Error = ErrorTy::NotAnAssignment; 11805 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Else->getBeginLoc(); 11806 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Else->getSourceRange(); 11807 return false; 11808 } 11809 if (ElseBO->getOpcode() != BO_Assign) { 11810 ErrorInfo.Error = ErrorTy::NotAnAssignment; 11811 ErrorInfo.ErrorLoc = ElseBO->getExprLoc(); 11812 ErrorInfo.NoteLoc = ElseBO->getOperatorLoc(); 11813 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ElseBO->getSourceRange(); 11814 return false; 11815 } 11816 11817 if (!checkIfTwoExprsAreSame(ContextRef, X, ElseBO->getRHS())) { 11818 ErrorInfo.Error = ErrorTy::InvalidAssignment; 11819 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ElseBO->getRHS()->getExprLoc(); 11820 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = 11821 ElseBO->getRHS()->getSourceRange(); 11822 return false; 11823 } 11824 11825 V = ElseBO->getLHS(); 11826 11827 return checkType(ErrorInfo); 11828 } 11829 11830 bool OpenMPAtomicCompareCaptureChecker::checkForm45(Stmt *S, 11831 ErrorInfoTy &ErrorInfo) { 11832 // We don't check here as they should be already done before call this 11833 // function. 11834 auto *CS = cast<CompoundStmt>(S); 11835 assert(CS->size() == 2 && "CompoundStmt size is not expected"); 11836 auto *S1 = cast<BinaryOperator>(CS->body_front()); 11837 auto *S2 = cast<IfStmt>(CS->body_back()); 11838 assert(S1->getOpcode() == BO_Assign && "unexpected binary operator"); 11839 11840 if (!checkIfTwoExprsAreSame(ContextRef, S1->getLHS(), S2->getCond())) { 11841 ErrorInfo.Error = ErrorTy::InvalidCondition; 11842 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S2->getCond()->getExprLoc(); 11843 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S1->getLHS()->getSourceRange(); 11844 return false; 11845 } 11846 11847 R = S1->getLHS(); 11848 11849 auto *Then = S2->getThen(); 11850 if (auto *ThenCS = dyn_cast<CompoundStmt>(Then)) { 11851 if (ThenCS->body_empty()) { 11852 ErrorInfo.Error = ErrorTy::NoStmt; 11853 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ThenCS->getBeginLoc(); 11854 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ThenCS->getSourceRange(); 11855 return false; 11856 } 11857 if (ThenCS->size() > 1) { 11858 ErrorInfo.Error = ErrorTy::MoreThanOneStmt; 11859 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ThenCS->getBeginLoc(); 11860 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ThenCS->getSourceRange(); 11861 return false; 11862 } 11863 Then = ThenCS->body_front(); 11864 } 11865 11866 auto *ThenBO = dyn_cast<BinaryOperator>(Then); 11867 if (!ThenBO) { 11868 ErrorInfo.Error = ErrorTy::NotAnAssignment; 11869 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S2->getBeginLoc(); 11870 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S2->getSourceRange(); 11871 return false; 11872 } 11873 if (ThenBO->getOpcode() != BO_Assign) { 11874 ErrorInfo.Error = ErrorTy::NotAnAssignment; 11875 ErrorInfo.ErrorLoc = ThenBO->getExprLoc(); 11876 ErrorInfo.NoteLoc = ThenBO->getOperatorLoc(); 11877 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ThenBO->getSourceRange(); 11878 return false; 11879 } 11880 11881 X = ThenBO->getLHS(); 11882 D = ThenBO->getRHS(); 11883 11884 auto *BO = cast<BinaryOperator>(S1->getRHS()->IgnoreImpCasts()); 11885 if (BO->getOpcode() != BO_EQ) { 11886 ErrorInfo.Error = ErrorTy::NotEQ; 11887 ErrorInfo.ErrorLoc = BO->getExprLoc(); 11888 ErrorInfo.NoteLoc = BO->getOperatorLoc(); 11889 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange(); 11890 return false; 11891 } 11892 11893 C = BO; 11894 11895 if (checkIfTwoExprsAreSame(ContextRef, X, BO->getLHS())) { 11896 E = BO->getRHS(); 11897 } else if (checkIfTwoExprsAreSame(ContextRef, X, BO->getRHS())) { 11898 E = BO->getLHS(); 11899 } else { 11900 ErrorInfo.Error = ErrorTy::InvalidComparison; 11901 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = BO->getExprLoc(); 11902 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange(); 11903 return false; 11904 } 11905 11906 if (S2->getElse()) { 11907 IsFailOnly = true; 11908 11909 auto *Else = S2->getElse(); 11910 if (auto *ElseCS = dyn_cast<CompoundStmt>(Else)) { 11911 if (ElseCS->body_empty()) { 11912 ErrorInfo.Error = ErrorTy::NoStmt; 11913 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ElseCS->getBeginLoc(); 11914 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ElseCS->getSourceRange(); 11915 return false; 11916 } 11917 if (ElseCS->size() > 1) { 11918 ErrorInfo.Error = ErrorTy::MoreThanOneStmt; 11919 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = ElseCS->getBeginLoc(); 11920 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ElseCS->getSourceRange(); 11921 return false; 11922 } 11923 Else = ElseCS->body_front(); 11924 } 11925 11926 auto *ElseBO = dyn_cast<BinaryOperator>(Else); 11927 if (!ElseBO) { 11928 ErrorInfo.Error = ErrorTy::NotAnAssignment; 11929 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Else->getBeginLoc(); 11930 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Else->getSourceRange(); 11931 return false; 11932 } 11933 if (ElseBO->getOpcode() != BO_Assign) { 11934 ErrorInfo.Error = ErrorTy::NotAnAssignment; 11935 ErrorInfo.ErrorLoc = ElseBO->getExprLoc(); 11936 ErrorInfo.NoteLoc = ElseBO->getOperatorLoc(); 11937 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = ElseBO->getSourceRange(); 11938 return false; 11939 } 11940 if (!checkIfTwoExprsAreSame(ContextRef, X, ElseBO->getRHS())) { 11941 ErrorInfo.Error = ErrorTy::InvalidAssignment; 11942 ErrorInfo.ErrorLoc = ElseBO->getRHS()->getExprLoc(); 11943 ErrorInfo.NoteLoc = X->getExprLoc(); 11944 ErrorInfo.ErrorRange = ElseBO->getRHS()->getSourceRange(); 11945 ErrorInfo.NoteRange = X->getSourceRange(); 11946 return false; 11947 } 11948 11949 V = ElseBO->getLHS(); 11950 } 11951 11952 return checkType(ErrorInfo); 11953 } 11954 11955 bool OpenMPAtomicCompareCaptureChecker::checkStmt(Stmt *S, 11956 ErrorInfoTy &ErrorInfo) { 11957 // if(x == e) { x = d; } else { v = x; } 11958 if (auto *IS = dyn_cast<IfStmt>(S)) 11959 return checkForm3(IS, ErrorInfo); 11960 11961 auto *CS = dyn_cast<CompoundStmt>(S); 11962 if (!CS) { 11963 ErrorInfo.Error = ErrorTy::NotCompoundStmt; 11964 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getBeginLoc(); 11965 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange(); 11966 return false; 11967 } 11968 if (CS->body_empty()) { 11969 ErrorInfo.Error = ErrorTy::NoStmt; 11970 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc(); 11971 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange(); 11972 return false; 11973 } 11974 11975 // { if(x == e) { x = d; } else { v = x; } } 11976 if (CS->size() == 1) { 11977 auto *IS = dyn_cast<IfStmt>(CS->body_front()); 11978 if (!IS) { 11979 ErrorInfo.Error = ErrorTy::NotIfStmt; 11980 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->body_front()->getBeginLoc(); 11981 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = 11982 CS->body_front()->getSourceRange(); 11983 return false; 11984 } 11985 11986 return checkForm3(IS, ErrorInfo); 11987 } else if (CS->size() == 2) { 11988 auto *S1 = CS->body_front(); 11989 auto *S2 = CS->body_back(); 11990 11991 Stmt *UpdateStmt = nullptr; 11992 Stmt *CondUpdateStmt = nullptr; 11993 11994 if (auto *BO = dyn_cast<BinaryOperator>(S1)) { 11995 // { v = x; cond-update-stmt } or form 45. 11996 UpdateStmt = S1; 11997 CondUpdateStmt = S2; 11998 // Check if form 45. 11999 if (isa<BinaryOperator>(BO->getRHS()->IgnoreImpCasts()) && 12000 isa<IfStmt>(S2)) 12001 return checkForm45(CS, ErrorInfo); 12002 // It cannot be set before we the check for form45. 12003 IsPostfixUpdate = true; 12004 } else { 12005 // { cond-update-stmt v = x; } 12006 UpdateStmt = S2; 12007 CondUpdateStmt = S1; 12008 } 12009 12010 auto CheckCondUpdateStmt = [this, &ErrorInfo](Stmt *CUS) { 12011 auto *IS = dyn_cast<IfStmt>(CUS); 12012 if (!IS) { 12013 ErrorInfo.Error = ErrorTy::NotIfStmt; 12014 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CUS->getBeginLoc(); 12015 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CUS->getSourceRange(); 12016 return false; 12017 } 12018 12019 if (!checkCondUpdateStmt(IS, ErrorInfo)) 12020 return false; 12021 12022 return true; 12023 }; 12024 12025 // CheckUpdateStmt has to be called *after* CheckCondUpdateStmt. 12026 auto CheckUpdateStmt = [this, &ErrorInfo](Stmt *US) { 12027 auto *BO = dyn_cast<BinaryOperator>(US); 12028 if (!BO) { 12029 ErrorInfo.Error = ErrorTy::NotAnAssignment; 12030 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = US->getBeginLoc(); 12031 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = US->getSourceRange(); 12032 return false; 12033 } 12034 if (BO->getOpcode() != BO_Assign) { 12035 ErrorInfo.Error = ErrorTy::NotAnAssignment; 12036 ErrorInfo.ErrorLoc = BO->getExprLoc(); 12037 ErrorInfo.NoteLoc = BO->getOperatorLoc(); 12038 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange(); 12039 return false; 12040 } 12041 if (!checkIfTwoExprsAreSame(ContextRef, this->X, BO->getRHS())) { 12042 ErrorInfo.Error = ErrorTy::InvalidAssignment; 12043 ErrorInfo.ErrorLoc = BO->getRHS()->getExprLoc(); 12044 ErrorInfo.NoteLoc = this->X->getExprLoc(); 12045 ErrorInfo.ErrorRange = BO->getRHS()->getSourceRange(); 12046 ErrorInfo.NoteRange = this->X->getSourceRange(); 12047 return false; 12048 } 12049 12050 this->V = BO->getLHS(); 12051 12052 return true; 12053 }; 12054 12055 if (!CheckCondUpdateStmt(CondUpdateStmt)) 12056 return false; 12057 if (!CheckUpdateStmt(UpdateStmt)) 12058 return false; 12059 } else { 12060 ErrorInfo.Error = ErrorTy::MoreThanTwoStmts; 12061 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc(); 12062 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange(); 12063 return false; 12064 } 12065 12066 return checkType(ErrorInfo); 12067 } 12068 } // namespace 12069 12070 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 12071 Stmt *AStmt, 12072 SourceLocation StartLoc, 12073 SourceLocation EndLoc) { 12074 // Register location of the first atomic directive. 12075 DSAStack->addAtomicDirectiveLoc(StartLoc); 12076 if (!AStmt) 12077 return StmtError(); 12078 12079 // 1.2.2 OpenMP Language Terminology 12080 // Structured block - An executable statement with a single entry at the 12081 // top and a single exit at the bottom. 12082 // The point of exit cannot be a branch out of the structured block. 12083 // longjmp() and throw() must not violate the entry/exit criteria. 12084 OpenMPClauseKind AtomicKind = OMPC_unknown; 12085 SourceLocation AtomicKindLoc; 12086 OpenMPClauseKind MemOrderKind = OMPC_unknown; 12087 SourceLocation MemOrderLoc; 12088 bool MutexClauseEncountered = false; 12089 llvm::SmallSet<OpenMPClauseKind, 2> EncounteredAtomicKinds; 12090 for (const OMPClause *C : Clauses) { 12091 switch (C->getClauseKind()) { 12092 case OMPC_read: 12093 case OMPC_write: 12094 case OMPC_update: 12095 MutexClauseEncountered = true; 12096 LLVM_FALLTHROUGH; 12097 case OMPC_capture: 12098 case OMPC_compare: { 12099 if (AtomicKind != OMPC_unknown && MutexClauseEncountered) { 12100 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses) 12101 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 12102 Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause) 12103 << getOpenMPClauseName(AtomicKind); 12104 } else { 12105 AtomicKind = C->getClauseKind(); 12106 AtomicKindLoc = C->getBeginLoc(); 12107 if (!EncounteredAtomicKinds.insert(C->getClauseKind()).second) { 12108 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses) 12109 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 12110 Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause) 12111 << getOpenMPClauseName(AtomicKind); 12112 } 12113 } 12114 break; 12115 } 12116 case OMPC_seq_cst: 12117 case OMPC_acq_rel: 12118 case OMPC_acquire: 12119 case OMPC_release: 12120 case OMPC_relaxed: { 12121 if (MemOrderKind != OMPC_unknown) { 12122 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses) 12123 << getOpenMPDirectiveName(OMPD_atomic) << 0 12124 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 12125 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 12126 << getOpenMPClauseName(MemOrderKind); 12127 } else { 12128 MemOrderKind = C->getClauseKind(); 12129 MemOrderLoc = C->getBeginLoc(); 12130 } 12131 break; 12132 } 12133 // The following clauses are allowed, but we don't need to do anything here. 12134 case OMPC_hint: 12135 break; 12136 default: 12137 llvm_unreachable("unknown clause is encountered"); 12138 } 12139 } 12140 bool IsCompareCapture = false; 12141 if (EncounteredAtomicKinds.contains(OMPC_compare) && 12142 EncounteredAtomicKinds.contains(OMPC_capture)) { 12143 IsCompareCapture = true; 12144 AtomicKind = OMPC_compare; 12145 } 12146 // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions 12147 // If atomic-clause is read then memory-order-clause must not be acq_rel or 12148 // release. 12149 // If atomic-clause is write then memory-order-clause must not be acq_rel or 12150 // acquire. 12151 // If atomic-clause is update or not present then memory-order-clause must not 12152 // be acq_rel or acquire. 12153 if ((AtomicKind == OMPC_read && 12154 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) || 12155 ((AtomicKind == OMPC_write || AtomicKind == OMPC_update || 12156 AtomicKind == OMPC_unknown) && 12157 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) { 12158 SourceLocation Loc = AtomicKindLoc; 12159 if (AtomicKind == OMPC_unknown) 12160 Loc = StartLoc; 12161 Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause) 12162 << getOpenMPClauseName(AtomicKind) 12163 << (AtomicKind == OMPC_unknown ? 1 : 0) 12164 << getOpenMPClauseName(MemOrderKind); 12165 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 12166 << getOpenMPClauseName(MemOrderKind); 12167 } 12168 12169 Stmt *Body = AStmt; 12170 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 12171 Body = EWC->getSubExpr(); 12172 12173 Expr *X = nullptr; 12174 Expr *V = nullptr; 12175 Expr *E = nullptr; 12176 Expr *UE = nullptr; 12177 Expr *D = nullptr; 12178 Expr *CE = nullptr; 12179 Expr *R = nullptr; 12180 bool IsXLHSInRHSPart = false; 12181 bool IsPostfixUpdate = false; 12182 bool IsFailOnly = false; 12183 // OpenMP [2.12.6, atomic Construct] 12184 // In the next expressions: 12185 // * x and v (as applicable) are both l-value expressions with scalar type. 12186 // * During the execution of an atomic region, multiple syntactic 12187 // occurrences of x must designate the same storage location. 12188 // * Neither of v and expr (as applicable) may access the storage location 12189 // designated by x. 12190 // * Neither of x and expr (as applicable) may access the storage location 12191 // designated by v. 12192 // * expr is an expression with scalar type. 12193 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 12194 // * binop, binop=, ++, and -- are not overloaded operators. 12195 // * The expression x binop expr must be numerically equivalent to x binop 12196 // (expr). This requirement is satisfied if the operators in expr have 12197 // precedence greater than binop, or by using parentheses around expr or 12198 // subexpressions of expr. 12199 // * The expression expr binop x must be numerically equivalent to (expr) 12200 // binop x. This requirement is satisfied if the operators in expr have 12201 // precedence equal to or greater than binop, or by using parentheses around 12202 // expr or subexpressions of expr. 12203 // * For forms that allow multiple occurrences of x, the number of times 12204 // that x is evaluated is unspecified. 12205 if (AtomicKind == OMPC_read) { 12206 enum { 12207 NotAnExpression, 12208 NotAnAssignmentOp, 12209 NotAScalarType, 12210 NotAnLValue, 12211 NoError 12212 } ErrorFound = NoError; 12213 SourceLocation ErrorLoc, NoteLoc; 12214 SourceRange ErrorRange, NoteRange; 12215 // If clause is read: 12216 // v = x; 12217 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 12218 const auto *AtomicBinOp = 12219 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 12220 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 12221 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 12222 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 12223 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 12224 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 12225 if (!X->isLValue() || !V->isLValue()) { 12226 const Expr *NotLValueExpr = X->isLValue() ? V : X; 12227 ErrorFound = NotAnLValue; 12228 ErrorLoc = AtomicBinOp->getExprLoc(); 12229 ErrorRange = AtomicBinOp->getSourceRange(); 12230 NoteLoc = NotLValueExpr->getExprLoc(); 12231 NoteRange = NotLValueExpr->getSourceRange(); 12232 } 12233 } else if (!X->isInstantiationDependent() || 12234 !V->isInstantiationDependent()) { 12235 const Expr *NotScalarExpr = 12236 (X->isInstantiationDependent() || X->getType()->isScalarType()) 12237 ? V 12238 : X; 12239 ErrorFound = NotAScalarType; 12240 ErrorLoc = AtomicBinOp->getExprLoc(); 12241 ErrorRange = AtomicBinOp->getSourceRange(); 12242 NoteLoc = NotScalarExpr->getExprLoc(); 12243 NoteRange = NotScalarExpr->getSourceRange(); 12244 } 12245 } else if (!AtomicBody->isInstantiationDependent()) { 12246 ErrorFound = NotAnAssignmentOp; 12247 ErrorLoc = AtomicBody->getExprLoc(); 12248 ErrorRange = AtomicBody->getSourceRange(); 12249 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 12250 : AtomicBody->getExprLoc(); 12251 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 12252 : AtomicBody->getSourceRange(); 12253 } 12254 } else { 12255 ErrorFound = NotAnExpression; 12256 NoteLoc = ErrorLoc = Body->getBeginLoc(); 12257 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 12258 } 12259 if (ErrorFound != NoError) { 12260 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 12261 << ErrorRange; 12262 Diag(NoteLoc, diag::note_omp_atomic_read_write) 12263 << ErrorFound << NoteRange; 12264 return StmtError(); 12265 } 12266 if (CurContext->isDependentContext()) 12267 V = X = nullptr; 12268 } else if (AtomicKind == OMPC_write) { 12269 enum { 12270 NotAnExpression, 12271 NotAnAssignmentOp, 12272 NotAScalarType, 12273 NotAnLValue, 12274 NoError 12275 } ErrorFound = NoError; 12276 SourceLocation ErrorLoc, NoteLoc; 12277 SourceRange ErrorRange, NoteRange; 12278 // If clause is write: 12279 // x = expr; 12280 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 12281 const auto *AtomicBinOp = 12282 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 12283 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 12284 X = AtomicBinOp->getLHS(); 12285 E = AtomicBinOp->getRHS(); 12286 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 12287 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 12288 if (!X->isLValue()) { 12289 ErrorFound = NotAnLValue; 12290 ErrorLoc = AtomicBinOp->getExprLoc(); 12291 ErrorRange = AtomicBinOp->getSourceRange(); 12292 NoteLoc = X->getExprLoc(); 12293 NoteRange = X->getSourceRange(); 12294 } 12295 } else if (!X->isInstantiationDependent() || 12296 !E->isInstantiationDependent()) { 12297 const Expr *NotScalarExpr = 12298 (X->isInstantiationDependent() || X->getType()->isScalarType()) 12299 ? E 12300 : X; 12301 ErrorFound = NotAScalarType; 12302 ErrorLoc = AtomicBinOp->getExprLoc(); 12303 ErrorRange = AtomicBinOp->getSourceRange(); 12304 NoteLoc = NotScalarExpr->getExprLoc(); 12305 NoteRange = NotScalarExpr->getSourceRange(); 12306 } 12307 } else if (!AtomicBody->isInstantiationDependent()) { 12308 ErrorFound = NotAnAssignmentOp; 12309 ErrorLoc = AtomicBody->getExprLoc(); 12310 ErrorRange = AtomicBody->getSourceRange(); 12311 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 12312 : AtomicBody->getExprLoc(); 12313 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 12314 : AtomicBody->getSourceRange(); 12315 } 12316 } else { 12317 ErrorFound = NotAnExpression; 12318 NoteLoc = ErrorLoc = Body->getBeginLoc(); 12319 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 12320 } 12321 if (ErrorFound != NoError) { 12322 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 12323 << ErrorRange; 12324 Diag(NoteLoc, diag::note_omp_atomic_read_write) 12325 << ErrorFound << NoteRange; 12326 return StmtError(); 12327 } 12328 if (CurContext->isDependentContext()) 12329 E = X = nullptr; 12330 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 12331 // If clause is update: 12332 // x++; 12333 // x--; 12334 // ++x; 12335 // --x; 12336 // x binop= expr; 12337 // x = x binop expr; 12338 // x = expr binop x; 12339 OpenMPAtomicUpdateChecker Checker(*this); 12340 if (Checker.checkStatement( 12341 Body, 12342 (AtomicKind == OMPC_update) 12343 ? diag::err_omp_atomic_update_not_expression_statement 12344 : diag::err_omp_atomic_not_expression_statement, 12345 diag::note_omp_atomic_update)) 12346 return StmtError(); 12347 if (!CurContext->isDependentContext()) { 12348 E = Checker.getExpr(); 12349 X = Checker.getX(); 12350 UE = Checker.getUpdateExpr(); 12351 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 12352 } 12353 } else if (AtomicKind == OMPC_capture) { 12354 enum { 12355 NotAnAssignmentOp, 12356 NotACompoundStatement, 12357 NotTwoSubstatements, 12358 NotASpecificExpression, 12359 NoError 12360 } ErrorFound = NoError; 12361 SourceLocation ErrorLoc, NoteLoc; 12362 SourceRange ErrorRange, NoteRange; 12363 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 12364 // If clause is a capture: 12365 // v = x++; 12366 // v = x--; 12367 // v = ++x; 12368 // v = --x; 12369 // v = x binop= expr; 12370 // v = x = x binop expr; 12371 // v = x = expr binop x; 12372 const auto *AtomicBinOp = 12373 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 12374 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 12375 V = AtomicBinOp->getLHS(); 12376 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 12377 OpenMPAtomicUpdateChecker Checker(*this); 12378 if (Checker.checkStatement( 12379 Body, diag::err_omp_atomic_capture_not_expression_statement, 12380 diag::note_omp_atomic_update)) 12381 return StmtError(); 12382 E = Checker.getExpr(); 12383 X = Checker.getX(); 12384 UE = Checker.getUpdateExpr(); 12385 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 12386 IsPostfixUpdate = Checker.isPostfixUpdate(); 12387 } else if (!AtomicBody->isInstantiationDependent()) { 12388 ErrorLoc = AtomicBody->getExprLoc(); 12389 ErrorRange = AtomicBody->getSourceRange(); 12390 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 12391 : AtomicBody->getExprLoc(); 12392 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 12393 : AtomicBody->getSourceRange(); 12394 ErrorFound = NotAnAssignmentOp; 12395 } 12396 if (ErrorFound != NoError) { 12397 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 12398 << ErrorRange; 12399 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 12400 return StmtError(); 12401 } 12402 if (CurContext->isDependentContext()) 12403 UE = V = E = X = nullptr; 12404 } else { 12405 // If clause is a capture: 12406 // { v = x; x = expr; } 12407 // { v = x; x++; } 12408 // { v = x; x--; } 12409 // { v = x; ++x; } 12410 // { v = x; --x; } 12411 // { v = x; x binop= expr; } 12412 // { v = x; x = x binop expr; } 12413 // { v = x; x = expr binop x; } 12414 // { x++; v = x; } 12415 // { x--; v = x; } 12416 // { ++x; v = x; } 12417 // { --x; v = x; } 12418 // { x binop= expr; v = x; } 12419 // { x = x binop expr; v = x; } 12420 // { x = expr binop x; v = x; } 12421 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 12422 // Check that this is { expr1; expr2; } 12423 if (CS->size() == 2) { 12424 Stmt *First = CS->body_front(); 12425 Stmt *Second = CS->body_back(); 12426 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 12427 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 12428 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 12429 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 12430 // Need to find what subexpression is 'v' and what is 'x'. 12431 OpenMPAtomicUpdateChecker Checker(*this); 12432 bool IsUpdateExprFound = !Checker.checkStatement(Second); 12433 BinaryOperator *BinOp = nullptr; 12434 if (IsUpdateExprFound) { 12435 BinOp = dyn_cast<BinaryOperator>(First); 12436 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 12437 } 12438 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 12439 // { v = x; x++; } 12440 // { v = x; x--; } 12441 // { v = x; ++x; } 12442 // { v = x; --x; } 12443 // { v = x; x binop= expr; } 12444 // { v = x; x = x binop expr; } 12445 // { v = x; x = expr binop x; } 12446 // Check that the first expression has form v = x. 12447 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 12448 llvm::FoldingSetNodeID XId, PossibleXId; 12449 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 12450 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 12451 IsUpdateExprFound = XId == PossibleXId; 12452 if (IsUpdateExprFound) { 12453 V = BinOp->getLHS(); 12454 X = Checker.getX(); 12455 E = Checker.getExpr(); 12456 UE = Checker.getUpdateExpr(); 12457 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 12458 IsPostfixUpdate = true; 12459 } 12460 } 12461 if (!IsUpdateExprFound) { 12462 IsUpdateExprFound = !Checker.checkStatement(First); 12463 BinOp = nullptr; 12464 if (IsUpdateExprFound) { 12465 BinOp = dyn_cast<BinaryOperator>(Second); 12466 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 12467 } 12468 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 12469 // { x++; v = x; } 12470 // { x--; v = x; } 12471 // { ++x; v = x; } 12472 // { --x; v = x; } 12473 // { x binop= expr; v = x; } 12474 // { x = x binop expr; v = x; } 12475 // { x = expr binop x; v = x; } 12476 // Check that the second expression has form v = x. 12477 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 12478 llvm::FoldingSetNodeID XId, PossibleXId; 12479 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 12480 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 12481 IsUpdateExprFound = XId == PossibleXId; 12482 if (IsUpdateExprFound) { 12483 V = BinOp->getLHS(); 12484 X = Checker.getX(); 12485 E = Checker.getExpr(); 12486 UE = Checker.getUpdateExpr(); 12487 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 12488 IsPostfixUpdate = false; 12489 } 12490 } 12491 } 12492 if (!IsUpdateExprFound) { 12493 // { v = x; x = expr; } 12494 auto *FirstExpr = dyn_cast<Expr>(First); 12495 auto *SecondExpr = dyn_cast<Expr>(Second); 12496 if (!FirstExpr || !SecondExpr || 12497 !(FirstExpr->isInstantiationDependent() || 12498 SecondExpr->isInstantiationDependent())) { 12499 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 12500 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 12501 ErrorFound = NotAnAssignmentOp; 12502 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 12503 : First->getBeginLoc(); 12504 NoteRange = ErrorRange = FirstBinOp 12505 ? FirstBinOp->getSourceRange() 12506 : SourceRange(ErrorLoc, ErrorLoc); 12507 } else { 12508 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 12509 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 12510 ErrorFound = NotAnAssignmentOp; 12511 NoteLoc = ErrorLoc = SecondBinOp 12512 ? SecondBinOp->getOperatorLoc() 12513 : Second->getBeginLoc(); 12514 NoteRange = ErrorRange = 12515 SecondBinOp ? SecondBinOp->getSourceRange() 12516 : SourceRange(ErrorLoc, ErrorLoc); 12517 } else { 12518 Expr *PossibleXRHSInFirst = 12519 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 12520 Expr *PossibleXLHSInSecond = 12521 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 12522 llvm::FoldingSetNodeID X1Id, X2Id; 12523 PossibleXRHSInFirst->Profile(X1Id, Context, 12524 /*Canonical=*/true); 12525 PossibleXLHSInSecond->Profile(X2Id, Context, 12526 /*Canonical=*/true); 12527 IsUpdateExprFound = X1Id == X2Id; 12528 if (IsUpdateExprFound) { 12529 V = FirstBinOp->getLHS(); 12530 X = SecondBinOp->getLHS(); 12531 E = SecondBinOp->getRHS(); 12532 UE = nullptr; 12533 IsXLHSInRHSPart = false; 12534 IsPostfixUpdate = true; 12535 } else { 12536 ErrorFound = NotASpecificExpression; 12537 ErrorLoc = FirstBinOp->getExprLoc(); 12538 ErrorRange = FirstBinOp->getSourceRange(); 12539 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 12540 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 12541 } 12542 } 12543 } 12544 } 12545 } 12546 } else { 12547 NoteLoc = ErrorLoc = Body->getBeginLoc(); 12548 NoteRange = ErrorRange = 12549 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 12550 ErrorFound = NotTwoSubstatements; 12551 } 12552 } else { 12553 NoteLoc = ErrorLoc = Body->getBeginLoc(); 12554 NoteRange = ErrorRange = 12555 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 12556 ErrorFound = NotACompoundStatement; 12557 } 12558 } 12559 if (ErrorFound != NoError) { 12560 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 12561 << ErrorRange; 12562 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 12563 return StmtError(); 12564 } 12565 if (CurContext->isDependentContext()) 12566 UE = V = E = X = nullptr; 12567 } else if (AtomicKind == OMPC_compare) { 12568 if (IsCompareCapture) { 12569 OpenMPAtomicCompareCaptureChecker::ErrorInfoTy ErrorInfo; 12570 OpenMPAtomicCompareCaptureChecker Checker(*this); 12571 if (!Checker.checkStmt(Body, ErrorInfo)) { 12572 Diag(ErrorInfo.ErrorLoc, diag::err_omp_atomic_compare_capture) 12573 << ErrorInfo.ErrorRange; 12574 Diag(ErrorInfo.NoteLoc, diag::note_omp_atomic_compare) 12575 << ErrorInfo.Error << ErrorInfo.NoteRange; 12576 return StmtError(); 12577 } 12578 X = Checker.getX(); 12579 E = Checker.getE(); 12580 D = Checker.getD(); 12581 CE = Checker.getCond(); 12582 V = Checker.getV(); 12583 R = Checker.getR(); 12584 // We reuse IsXLHSInRHSPart to tell if it is in the form 'x ordop expr'. 12585 IsXLHSInRHSPart = Checker.isXBinopExpr(); 12586 IsFailOnly = Checker.isFailOnly(); 12587 IsPostfixUpdate = Checker.isPostfixUpdate(); 12588 } else { 12589 OpenMPAtomicCompareChecker::ErrorInfoTy ErrorInfo; 12590 OpenMPAtomicCompareChecker Checker(*this); 12591 if (!Checker.checkStmt(Body, ErrorInfo)) { 12592 Diag(ErrorInfo.ErrorLoc, diag::err_omp_atomic_compare) 12593 << ErrorInfo.ErrorRange; 12594 Diag(ErrorInfo.NoteLoc, diag::note_omp_atomic_compare) 12595 << ErrorInfo.Error << ErrorInfo.NoteRange; 12596 return StmtError(); 12597 } 12598 X = Checker.getX(); 12599 E = Checker.getE(); 12600 D = Checker.getD(); 12601 CE = Checker.getCond(); 12602 // We reuse IsXLHSInRHSPart to tell if it is in the form 'x ordop expr'. 12603 IsXLHSInRHSPart = Checker.isXBinopExpr(); 12604 } 12605 } 12606 12607 setFunctionHasBranchProtectedScope(); 12608 12609 return OMPAtomicDirective::Create( 12610 Context, StartLoc, EndLoc, Clauses, AStmt, 12611 {X, V, R, E, UE, D, CE, IsXLHSInRHSPart, IsPostfixUpdate, IsFailOnly}); 12612 } 12613 12614 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 12615 Stmt *AStmt, 12616 SourceLocation StartLoc, 12617 SourceLocation EndLoc) { 12618 if (!AStmt) 12619 return StmtError(); 12620 12621 auto *CS = cast<CapturedStmt>(AStmt); 12622 // 1.2.2 OpenMP Language Terminology 12623 // Structured block - An executable statement with a single entry at the 12624 // top and a single exit at the bottom. 12625 // The point of exit cannot be a branch out of the structured block. 12626 // longjmp() and throw() must not violate the entry/exit criteria. 12627 CS->getCapturedDecl()->setNothrow(); 12628 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target); 12629 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12630 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12631 // 1.2.2 OpenMP Language Terminology 12632 // Structured block - An executable statement with a single entry at the 12633 // top and a single exit at the bottom. 12634 // The point of exit cannot be a branch out of the structured block. 12635 // longjmp() and throw() must not violate the entry/exit criteria. 12636 CS->getCapturedDecl()->setNothrow(); 12637 } 12638 12639 // OpenMP [2.16, Nesting of Regions] 12640 // If specified, a teams construct must be contained within a target 12641 // construct. That target construct must contain no statements or directives 12642 // outside of the teams construct. 12643 if (DSAStack->hasInnerTeamsRegion()) { 12644 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true); 12645 bool OMPTeamsFound = true; 12646 if (const auto *CS = dyn_cast<CompoundStmt>(S)) { 12647 auto I = CS->body_begin(); 12648 while (I != CS->body_end()) { 12649 const auto *OED = dyn_cast<OMPExecutableDirective>(*I); 12650 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) || 12651 OMPTeamsFound) { 12652 12653 OMPTeamsFound = false; 12654 break; 12655 } 12656 ++I; 12657 } 12658 assert(I != CS->body_end() && "Not found statement"); 12659 S = *I; 12660 } else { 12661 const auto *OED = dyn_cast<OMPExecutableDirective>(S); 12662 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 12663 } 12664 if (!OMPTeamsFound) { 12665 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 12666 Diag(DSAStack->getInnerTeamsRegionLoc(), 12667 diag::note_omp_nested_teams_construct_here); 12668 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here) 12669 << isa<OMPExecutableDirective>(S); 12670 return StmtError(); 12671 } 12672 } 12673 12674 setFunctionHasBranchProtectedScope(); 12675 12676 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 12677 } 12678 12679 StmtResult 12680 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 12681 Stmt *AStmt, SourceLocation StartLoc, 12682 SourceLocation EndLoc) { 12683 if (!AStmt) 12684 return StmtError(); 12685 12686 auto *CS = cast<CapturedStmt>(AStmt); 12687 // 1.2.2 OpenMP Language Terminology 12688 // Structured block - An executable statement with a single entry at the 12689 // top and a single exit at the bottom. 12690 // The point of exit cannot be a branch out of the structured block. 12691 // longjmp() and throw() must not violate the entry/exit criteria. 12692 CS->getCapturedDecl()->setNothrow(); 12693 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel); 12694 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12695 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12696 // 1.2.2 OpenMP Language Terminology 12697 // Structured block - An executable statement with a single entry at the 12698 // top and a single exit at the bottom. 12699 // The point of exit cannot be a branch out of the structured block. 12700 // longjmp() and throw() must not violate the entry/exit criteria. 12701 CS->getCapturedDecl()->setNothrow(); 12702 } 12703 12704 setFunctionHasBranchProtectedScope(); 12705 12706 return OMPTargetParallelDirective::Create( 12707 Context, StartLoc, EndLoc, Clauses, AStmt, 12708 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 12709 } 12710 12711 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 12712 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12713 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12714 if (!AStmt) 12715 return StmtError(); 12716 12717 auto *CS = cast<CapturedStmt>(AStmt); 12718 // 1.2.2 OpenMP Language Terminology 12719 // Structured block - An executable statement with a single entry at the 12720 // top and a single exit at the bottom. 12721 // The point of exit cannot be a branch out of the structured block. 12722 // longjmp() and throw() must not violate the entry/exit criteria. 12723 CS->getCapturedDecl()->setNothrow(); 12724 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 12725 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12726 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12727 // 1.2.2 OpenMP Language Terminology 12728 // Structured block - An executable statement with a single entry at the 12729 // top and a single exit at the bottom. 12730 // The point of exit cannot be a branch out of the structured block. 12731 // longjmp() and throw() must not violate the entry/exit criteria. 12732 CS->getCapturedDecl()->setNothrow(); 12733 } 12734 12735 OMPLoopBasedDirective::HelperExprs B; 12736 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 12737 // define the nested loops number. 12738 unsigned NestedLoopCount = 12739 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 12740 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 12741 VarsWithImplicitDSA, B); 12742 if (NestedLoopCount == 0) 12743 return StmtError(); 12744 12745 assert((CurContext->isDependentContext() || B.builtAll()) && 12746 "omp target parallel for loop exprs were not built"); 12747 12748 if (!CurContext->isDependentContext()) { 12749 // Finalize the clauses that need pre-built expressions for CodeGen. 12750 for (OMPClause *C : Clauses) { 12751 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12752 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12753 B.NumIterations, *this, CurScope, 12754 DSAStack)) 12755 return StmtError(); 12756 } 12757 } 12758 12759 setFunctionHasBranchProtectedScope(); 12760 return OMPTargetParallelForDirective::Create( 12761 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 12762 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 12763 } 12764 12765 /// Check for existence of a map clause in the list of clauses. 12766 static bool hasClauses(ArrayRef<OMPClause *> Clauses, 12767 const OpenMPClauseKind K) { 12768 return llvm::any_of( 12769 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); 12770 } 12771 12772 template <typename... Params> 12773 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, 12774 const Params... ClauseTypes) { 12775 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); 12776 } 12777 12778 /// Check if the variables in the mapping clause are externally visible. 12779 static bool isClauseMappable(ArrayRef<OMPClause *> Clauses) { 12780 for (const OMPClause *C : Clauses) { 12781 if (auto *TC = dyn_cast<OMPToClause>(C)) 12782 return llvm::all_of(TC->all_decls(), [](ValueDecl *VD) { 12783 return !VD || !VD->hasAttr<OMPDeclareTargetDeclAttr>() || 12784 (VD->isExternallyVisible() && 12785 VD->getVisibility() != HiddenVisibility); 12786 }); 12787 else if (auto *FC = dyn_cast<OMPFromClause>(C)) 12788 return llvm::all_of(FC->all_decls(), [](ValueDecl *VD) { 12789 return !VD || !VD->hasAttr<OMPDeclareTargetDeclAttr>() || 12790 (VD->isExternallyVisible() && 12791 VD->getVisibility() != HiddenVisibility); 12792 }); 12793 } 12794 12795 return true; 12796 } 12797 12798 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 12799 Stmt *AStmt, 12800 SourceLocation StartLoc, 12801 SourceLocation EndLoc) { 12802 if (!AStmt) 12803 return StmtError(); 12804 12805 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 12806 12807 // OpenMP [2.12.2, target data Construct, Restrictions] 12808 // At least one map, use_device_addr or use_device_ptr clause must appear on 12809 // the directive. 12810 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) && 12811 (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) { 12812 StringRef Expected; 12813 if (LangOpts.OpenMP < 50) 12814 Expected = "'map' or 'use_device_ptr'"; 12815 else 12816 Expected = "'map', 'use_device_ptr', or 'use_device_addr'"; 12817 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 12818 << Expected << getOpenMPDirectiveName(OMPD_target_data); 12819 return StmtError(); 12820 } 12821 12822 setFunctionHasBranchProtectedScope(); 12823 12824 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 12825 AStmt); 12826 } 12827 12828 StmtResult 12829 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 12830 SourceLocation StartLoc, 12831 SourceLocation EndLoc, Stmt *AStmt) { 12832 if (!AStmt) 12833 return StmtError(); 12834 12835 auto *CS = cast<CapturedStmt>(AStmt); 12836 // 1.2.2 OpenMP Language Terminology 12837 // Structured block - An executable statement with a single entry at the 12838 // top and a single exit at the bottom. 12839 // The point of exit cannot be a branch out of the structured block. 12840 // longjmp() and throw() must not violate the entry/exit criteria. 12841 CS->getCapturedDecl()->setNothrow(); 12842 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data); 12843 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12844 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12845 // 1.2.2 OpenMP Language Terminology 12846 // Structured block - An executable statement with a single entry at the 12847 // top and a single exit at the bottom. 12848 // The point of exit cannot be a branch out of the structured block. 12849 // longjmp() and throw() must not violate the entry/exit criteria. 12850 CS->getCapturedDecl()->setNothrow(); 12851 } 12852 12853 // OpenMP [2.10.2, Restrictions, p. 99] 12854 // At least one map clause must appear on the directive. 12855 if (!hasClauses(Clauses, OMPC_map)) { 12856 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 12857 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); 12858 return StmtError(); 12859 } 12860 12861 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 12862 AStmt); 12863 } 12864 12865 StmtResult 12866 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 12867 SourceLocation StartLoc, 12868 SourceLocation EndLoc, Stmt *AStmt) { 12869 if (!AStmt) 12870 return StmtError(); 12871 12872 auto *CS = cast<CapturedStmt>(AStmt); 12873 // 1.2.2 OpenMP Language Terminology 12874 // Structured block - An executable statement with a single entry at the 12875 // top and a single exit at the bottom. 12876 // The point of exit cannot be a branch out of the structured block. 12877 // longjmp() and throw() must not violate the entry/exit criteria. 12878 CS->getCapturedDecl()->setNothrow(); 12879 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data); 12880 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12881 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12882 // 1.2.2 OpenMP Language Terminology 12883 // Structured block - An executable statement with a single entry at the 12884 // top and a single exit at the bottom. 12885 // The point of exit cannot be a branch out of the structured block. 12886 // longjmp() and throw() must not violate the entry/exit criteria. 12887 CS->getCapturedDecl()->setNothrow(); 12888 } 12889 12890 // OpenMP [2.10.3, Restrictions, p. 102] 12891 // At least one map clause must appear on the directive. 12892 if (!hasClauses(Clauses, OMPC_map)) { 12893 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 12894 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data); 12895 return StmtError(); 12896 } 12897 12898 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 12899 AStmt); 12900 } 12901 12902 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 12903 SourceLocation StartLoc, 12904 SourceLocation EndLoc, 12905 Stmt *AStmt) { 12906 if (!AStmt) 12907 return StmtError(); 12908 12909 auto *CS = cast<CapturedStmt>(AStmt); 12910 // 1.2.2 OpenMP Language Terminology 12911 // Structured block - An executable statement with a single entry at the 12912 // top and a single exit at the bottom. 12913 // The point of exit cannot be a branch out of the structured block. 12914 // longjmp() and throw() must not violate the entry/exit criteria. 12915 CS->getCapturedDecl()->setNothrow(); 12916 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update); 12917 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12918 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12919 // 1.2.2 OpenMP Language Terminology 12920 // Structured block - An executable statement with a single entry at the 12921 // top and a single exit at the bottom. 12922 // The point of exit cannot be a branch out of the structured block. 12923 // longjmp() and throw() must not violate the entry/exit criteria. 12924 CS->getCapturedDecl()->setNothrow(); 12925 } 12926 12927 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { 12928 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 12929 return StmtError(); 12930 } 12931 12932 if (!isClauseMappable(Clauses)) { 12933 Diag(StartLoc, diag::err_omp_cannot_update_with_internal_linkage); 12934 return StmtError(); 12935 } 12936 12937 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses, 12938 AStmt); 12939 } 12940 12941 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 12942 Stmt *AStmt, SourceLocation StartLoc, 12943 SourceLocation EndLoc) { 12944 if (!AStmt) 12945 return StmtError(); 12946 12947 auto *CS = cast<CapturedStmt>(AStmt); 12948 // 1.2.2 OpenMP Language Terminology 12949 // Structured block - An executable statement with a single entry at the 12950 // top and a single exit at the bottom. 12951 // The point of exit cannot be a branch out of the structured block. 12952 // longjmp() and throw() must not violate the entry/exit criteria. 12953 CS->getCapturedDecl()->setNothrow(); 12954 12955 setFunctionHasBranchProtectedScope(); 12956 12957 DSAStack->setParentTeamsRegionLoc(StartLoc); 12958 12959 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 12960 } 12961 12962 StmtResult 12963 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 12964 SourceLocation EndLoc, 12965 OpenMPDirectiveKind CancelRegion) { 12966 if (DSAStack->isParentNowaitRegion()) { 12967 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 12968 return StmtError(); 12969 } 12970 if (DSAStack->isParentOrderedRegion()) { 12971 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 12972 return StmtError(); 12973 } 12974 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 12975 CancelRegion); 12976 } 12977 12978 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 12979 SourceLocation StartLoc, 12980 SourceLocation EndLoc, 12981 OpenMPDirectiveKind CancelRegion) { 12982 if (DSAStack->isParentNowaitRegion()) { 12983 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 12984 return StmtError(); 12985 } 12986 if (DSAStack->isParentOrderedRegion()) { 12987 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 12988 return StmtError(); 12989 } 12990 DSAStack->setParentCancelRegion(/*Cancel=*/true); 12991 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 12992 CancelRegion); 12993 } 12994 12995 static bool checkReductionClauseWithNogroup(Sema &S, 12996 ArrayRef<OMPClause *> Clauses) { 12997 const OMPClause *ReductionClause = nullptr; 12998 const OMPClause *NogroupClause = nullptr; 12999 for (const OMPClause *C : Clauses) { 13000 if (C->getClauseKind() == OMPC_reduction) { 13001 ReductionClause = C; 13002 if (NogroupClause) 13003 break; 13004 continue; 13005 } 13006 if (C->getClauseKind() == OMPC_nogroup) { 13007 NogroupClause = C; 13008 if (ReductionClause) 13009 break; 13010 continue; 13011 } 13012 } 13013 if (ReductionClause && NogroupClause) { 13014 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup) 13015 << SourceRange(NogroupClause->getBeginLoc(), 13016 NogroupClause->getEndLoc()); 13017 return true; 13018 } 13019 return false; 13020 } 13021 13022 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 13023 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13024 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13025 if (!AStmt) 13026 return StmtError(); 13027 13028 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 13029 OMPLoopBasedDirective::HelperExprs B; 13030 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 13031 // define the nested loops number. 13032 unsigned NestedLoopCount = 13033 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 13034 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 13035 VarsWithImplicitDSA, B); 13036 if (NestedLoopCount == 0) 13037 return StmtError(); 13038 13039 assert((CurContext->isDependentContext() || B.builtAll()) && 13040 "omp for loop exprs were not built"); 13041 13042 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 13043 // The grainsize clause and num_tasks clause are mutually exclusive and may 13044 // not appear on the same taskloop directive. 13045 if (checkMutuallyExclusiveClauses(*this, Clauses, 13046 {OMPC_grainsize, OMPC_num_tasks})) 13047 return StmtError(); 13048 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 13049 // If a reduction clause is present on the taskloop directive, the nogroup 13050 // clause must not be specified. 13051 if (checkReductionClauseWithNogroup(*this, Clauses)) 13052 return StmtError(); 13053 13054 setFunctionHasBranchProtectedScope(); 13055 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 13056 NestedLoopCount, Clauses, AStmt, B, 13057 DSAStack->isCancelRegion()); 13058 } 13059 13060 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 13061 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13062 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13063 if (!AStmt) 13064 return StmtError(); 13065 13066 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 13067 OMPLoopBasedDirective::HelperExprs B; 13068 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 13069 // define the nested loops number. 13070 unsigned NestedLoopCount = 13071 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 13072 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 13073 VarsWithImplicitDSA, B); 13074 if (NestedLoopCount == 0) 13075 return StmtError(); 13076 13077 assert((CurContext->isDependentContext() || B.builtAll()) && 13078 "omp for loop exprs were not built"); 13079 13080 if (!CurContext->isDependentContext()) { 13081 // Finalize the clauses that need pre-built expressions for CodeGen. 13082 for (OMPClause *C : Clauses) { 13083 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 13084 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 13085 B.NumIterations, *this, CurScope, 13086 DSAStack)) 13087 return StmtError(); 13088 } 13089 } 13090 13091 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 13092 // The grainsize clause and num_tasks clause are mutually exclusive and may 13093 // not appear on the same taskloop directive. 13094 if (checkMutuallyExclusiveClauses(*this, Clauses, 13095 {OMPC_grainsize, OMPC_num_tasks})) 13096 return StmtError(); 13097 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 13098 // If a reduction clause is present on the taskloop directive, the nogroup 13099 // clause must not be specified. 13100 if (checkReductionClauseWithNogroup(*this, Clauses)) 13101 return StmtError(); 13102 if (checkSimdlenSafelenSpecified(*this, Clauses)) 13103 return StmtError(); 13104 13105 setFunctionHasBranchProtectedScope(); 13106 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 13107 NestedLoopCount, Clauses, AStmt, B); 13108 } 13109 13110 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective( 13111 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13112 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13113 if (!AStmt) 13114 return StmtError(); 13115 13116 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 13117 OMPLoopBasedDirective::HelperExprs B; 13118 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 13119 // define the nested loops number. 13120 unsigned NestedLoopCount = 13121 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses), 13122 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 13123 VarsWithImplicitDSA, B); 13124 if (NestedLoopCount == 0) 13125 return StmtError(); 13126 13127 assert((CurContext->isDependentContext() || B.builtAll()) && 13128 "omp for loop exprs were not built"); 13129 13130 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 13131 // The grainsize clause and num_tasks clause are mutually exclusive and may 13132 // not appear on the same taskloop directive. 13133 if (checkMutuallyExclusiveClauses(*this, Clauses, 13134 {OMPC_grainsize, OMPC_num_tasks})) 13135 return StmtError(); 13136 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 13137 // If a reduction clause is present on the taskloop directive, the nogroup 13138 // clause must not be specified. 13139 if (checkReductionClauseWithNogroup(*this, Clauses)) 13140 return StmtError(); 13141 13142 setFunctionHasBranchProtectedScope(); 13143 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc, 13144 NestedLoopCount, Clauses, AStmt, B, 13145 DSAStack->isCancelRegion()); 13146 } 13147 13148 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective( 13149 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13150 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13151 if (!AStmt) 13152 return StmtError(); 13153 13154 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 13155 OMPLoopBasedDirective::HelperExprs B; 13156 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 13157 // define the nested loops number. 13158 unsigned NestedLoopCount = 13159 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses), 13160 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 13161 VarsWithImplicitDSA, B); 13162 if (NestedLoopCount == 0) 13163 return StmtError(); 13164 13165 assert((CurContext->isDependentContext() || B.builtAll()) && 13166 "omp for loop exprs were not built"); 13167 13168 if (!CurContext->isDependentContext()) { 13169 // Finalize the clauses that need pre-built expressions for CodeGen. 13170 for (OMPClause *C : Clauses) { 13171 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 13172 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 13173 B.NumIterations, *this, CurScope, 13174 DSAStack)) 13175 return StmtError(); 13176 } 13177 } 13178 13179 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 13180 // The grainsize clause and num_tasks clause are mutually exclusive and may 13181 // not appear on the same taskloop directive. 13182 if (checkMutuallyExclusiveClauses(*this, Clauses, 13183 {OMPC_grainsize, OMPC_num_tasks})) 13184 return StmtError(); 13185 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 13186 // If a reduction clause is present on the taskloop directive, the nogroup 13187 // clause must not be specified. 13188 if (checkReductionClauseWithNogroup(*this, Clauses)) 13189 return StmtError(); 13190 if (checkSimdlenSafelenSpecified(*this, Clauses)) 13191 return StmtError(); 13192 13193 setFunctionHasBranchProtectedScope(); 13194 return OMPMasterTaskLoopSimdDirective::Create( 13195 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 13196 } 13197 13198 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective( 13199 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13200 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13201 if (!AStmt) 13202 return StmtError(); 13203 13204 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 13205 auto *CS = cast<CapturedStmt>(AStmt); 13206 // 1.2.2 OpenMP Language Terminology 13207 // Structured block - An executable statement with a single entry at the 13208 // top and a single exit at the bottom. 13209 // The point of exit cannot be a branch out of the structured block. 13210 // longjmp() and throw() must not violate the entry/exit criteria. 13211 CS->getCapturedDecl()->setNothrow(); 13212 for (int ThisCaptureLevel = 13213 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop); 13214 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13215 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13216 // 1.2.2 OpenMP Language Terminology 13217 // Structured block - An executable statement with a single entry at the 13218 // top and a single exit at the bottom. 13219 // The point of exit cannot be a branch out of the structured block. 13220 // longjmp() and throw() must not violate the entry/exit criteria. 13221 CS->getCapturedDecl()->setNothrow(); 13222 } 13223 13224 OMPLoopBasedDirective::HelperExprs B; 13225 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 13226 // define the nested loops number. 13227 unsigned NestedLoopCount = checkOpenMPLoop( 13228 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses), 13229 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 13230 VarsWithImplicitDSA, B); 13231 if (NestedLoopCount == 0) 13232 return StmtError(); 13233 13234 assert((CurContext->isDependentContext() || B.builtAll()) && 13235 "omp for loop exprs were not built"); 13236 13237 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 13238 // The grainsize clause and num_tasks clause are mutually exclusive and may 13239 // not appear on the same taskloop directive. 13240 if (checkMutuallyExclusiveClauses(*this, Clauses, 13241 {OMPC_grainsize, OMPC_num_tasks})) 13242 return StmtError(); 13243 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 13244 // If a reduction clause is present on the taskloop directive, the nogroup 13245 // clause must not be specified. 13246 if (checkReductionClauseWithNogroup(*this, Clauses)) 13247 return StmtError(); 13248 13249 setFunctionHasBranchProtectedScope(); 13250 return OMPParallelMasterTaskLoopDirective::Create( 13251 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 13252 DSAStack->isCancelRegion()); 13253 } 13254 13255 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective( 13256 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13257 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13258 if (!AStmt) 13259 return StmtError(); 13260 13261 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 13262 auto *CS = cast<CapturedStmt>(AStmt); 13263 // 1.2.2 OpenMP Language Terminology 13264 // Structured block - An executable statement with a single entry at the 13265 // top and a single exit at the bottom. 13266 // The point of exit cannot be a branch out of the structured block. 13267 // longjmp() and throw() must not violate the entry/exit criteria. 13268 CS->getCapturedDecl()->setNothrow(); 13269 for (int ThisCaptureLevel = 13270 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd); 13271 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13272 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13273 // 1.2.2 OpenMP Language Terminology 13274 // Structured block - An executable statement with a single entry at the 13275 // top and a single exit at the bottom. 13276 // The point of exit cannot be a branch out of the structured block. 13277 // longjmp() and throw() must not violate the entry/exit criteria. 13278 CS->getCapturedDecl()->setNothrow(); 13279 } 13280 13281 OMPLoopBasedDirective::HelperExprs B; 13282 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 13283 // define the nested loops number. 13284 unsigned NestedLoopCount = checkOpenMPLoop( 13285 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses), 13286 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 13287 VarsWithImplicitDSA, B); 13288 if (NestedLoopCount == 0) 13289 return StmtError(); 13290 13291 assert((CurContext->isDependentContext() || B.builtAll()) && 13292 "omp for loop exprs were not built"); 13293 13294 if (!CurContext->isDependentContext()) { 13295 // Finalize the clauses that need pre-built expressions for CodeGen. 13296 for (OMPClause *C : Clauses) { 13297 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 13298 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 13299 B.NumIterations, *this, CurScope, 13300 DSAStack)) 13301 return StmtError(); 13302 } 13303 } 13304 13305 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 13306 // The grainsize clause and num_tasks clause are mutually exclusive and may 13307 // not appear on the same taskloop directive. 13308 if (checkMutuallyExclusiveClauses(*this, Clauses, 13309 {OMPC_grainsize, OMPC_num_tasks})) 13310 return StmtError(); 13311 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 13312 // If a reduction clause is present on the taskloop directive, the nogroup 13313 // clause must not be specified. 13314 if (checkReductionClauseWithNogroup(*this, Clauses)) 13315 return StmtError(); 13316 if (checkSimdlenSafelenSpecified(*this, Clauses)) 13317 return StmtError(); 13318 13319 setFunctionHasBranchProtectedScope(); 13320 return OMPParallelMasterTaskLoopSimdDirective::Create( 13321 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 13322 } 13323 13324 StmtResult Sema::ActOnOpenMPDistributeDirective( 13325 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13326 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13327 if (!AStmt) 13328 return StmtError(); 13329 13330 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 13331 OMPLoopBasedDirective::HelperExprs B; 13332 // In presence of clause 'collapse' with number of loops, it will 13333 // define the nested loops number. 13334 unsigned NestedLoopCount = 13335 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 13336 nullptr /*ordered not a clause on distribute*/, AStmt, 13337 *this, *DSAStack, VarsWithImplicitDSA, B); 13338 if (NestedLoopCount == 0) 13339 return StmtError(); 13340 13341 assert((CurContext->isDependentContext() || B.builtAll()) && 13342 "omp for loop exprs were not built"); 13343 13344 setFunctionHasBranchProtectedScope(); 13345 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 13346 NestedLoopCount, Clauses, AStmt, B); 13347 } 13348 13349 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 13350 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13351 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13352 if (!AStmt) 13353 return StmtError(); 13354 13355 auto *CS = cast<CapturedStmt>(AStmt); 13356 // 1.2.2 OpenMP Language Terminology 13357 // Structured block - An executable statement with a single entry at the 13358 // top and a single exit at the bottom. 13359 // The point of exit cannot be a branch out of the structured block. 13360 // longjmp() and throw() must not violate the entry/exit criteria. 13361 CS->getCapturedDecl()->setNothrow(); 13362 for (int ThisCaptureLevel = 13363 getOpenMPCaptureLevels(OMPD_distribute_parallel_for); 13364 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13365 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13366 // 1.2.2 OpenMP Language Terminology 13367 // Structured block - An executable statement with a single entry at the 13368 // top and a single exit at the bottom. 13369 // The point of exit cannot be a branch out of the structured block. 13370 // longjmp() and throw() must not violate the entry/exit criteria. 13371 CS->getCapturedDecl()->setNothrow(); 13372 } 13373 13374 OMPLoopBasedDirective::HelperExprs B; 13375 // In presence of clause 'collapse' with number of loops, it will 13376 // define the nested loops number. 13377 unsigned NestedLoopCount = checkOpenMPLoop( 13378 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 13379 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 13380 VarsWithImplicitDSA, B); 13381 if (NestedLoopCount == 0) 13382 return StmtError(); 13383 13384 assert((CurContext->isDependentContext() || B.builtAll()) && 13385 "omp for loop exprs were not built"); 13386 13387 setFunctionHasBranchProtectedScope(); 13388 return OMPDistributeParallelForDirective::Create( 13389 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 13390 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 13391 } 13392 13393 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 13394 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13395 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13396 if (!AStmt) 13397 return StmtError(); 13398 13399 auto *CS = cast<CapturedStmt>(AStmt); 13400 // 1.2.2 OpenMP Language Terminology 13401 // Structured block - An executable statement with a single entry at the 13402 // top and a single exit at the bottom. 13403 // The point of exit cannot be a branch out of the structured block. 13404 // longjmp() and throw() must not violate the entry/exit criteria. 13405 CS->getCapturedDecl()->setNothrow(); 13406 for (int ThisCaptureLevel = 13407 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd); 13408 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13409 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13410 // 1.2.2 OpenMP Language Terminology 13411 // Structured block - An executable statement with a single entry at the 13412 // top and a single exit at the bottom. 13413 // The point of exit cannot be a branch out of the structured block. 13414 // longjmp() and throw() must not violate the entry/exit criteria. 13415 CS->getCapturedDecl()->setNothrow(); 13416 } 13417 13418 OMPLoopBasedDirective::HelperExprs B; 13419 // In presence of clause 'collapse' with number of loops, it will 13420 // define the nested loops number. 13421 unsigned NestedLoopCount = checkOpenMPLoop( 13422 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 13423 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 13424 VarsWithImplicitDSA, B); 13425 if (NestedLoopCount == 0) 13426 return StmtError(); 13427 13428 assert((CurContext->isDependentContext() || B.builtAll()) && 13429 "omp for loop exprs were not built"); 13430 13431 if (!CurContext->isDependentContext()) { 13432 // Finalize the clauses that need pre-built expressions for CodeGen. 13433 for (OMPClause *C : Clauses) { 13434 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 13435 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 13436 B.NumIterations, *this, CurScope, 13437 DSAStack)) 13438 return StmtError(); 13439 } 13440 } 13441 13442 if (checkSimdlenSafelenSpecified(*this, Clauses)) 13443 return StmtError(); 13444 13445 setFunctionHasBranchProtectedScope(); 13446 return OMPDistributeParallelForSimdDirective::Create( 13447 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 13448 } 13449 13450 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 13451 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13452 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13453 if (!AStmt) 13454 return StmtError(); 13455 13456 auto *CS = cast<CapturedStmt>(AStmt); 13457 // 1.2.2 OpenMP Language Terminology 13458 // Structured block - An executable statement with a single entry at the 13459 // top and a single exit at the bottom. 13460 // The point of exit cannot be a branch out of the structured block. 13461 // longjmp() and throw() must not violate the entry/exit criteria. 13462 CS->getCapturedDecl()->setNothrow(); 13463 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd); 13464 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13465 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13466 // 1.2.2 OpenMP Language Terminology 13467 // Structured block - An executable statement with a single entry at the 13468 // top and a single exit at the bottom. 13469 // The point of exit cannot be a branch out of the structured block. 13470 // longjmp() and throw() must not violate the entry/exit criteria. 13471 CS->getCapturedDecl()->setNothrow(); 13472 } 13473 13474 OMPLoopBasedDirective::HelperExprs B; 13475 // In presence of clause 'collapse' with number of loops, it will 13476 // define the nested loops number. 13477 unsigned NestedLoopCount = 13478 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 13479 nullptr /*ordered not a clause on distribute*/, CS, *this, 13480 *DSAStack, VarsWithImplicitDSA, B); 13481 if (NestedLoopCount == 0) 13482 return StmtError(); 13483 13484 assert((CurContext->isDependentContext() || B.builtAll()) && 13485 "omp for loop exprs were not built"); 13486 13487 if (!CurContext->isDependentContext()) { 13488 // Finalize the clauses that need pre-built expressions for CodeGen. 13489 for (OMPClause *C : Clauses) { 13490 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 13491 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 13492 B.NumIterations, *this, CurScope, 13493 DSAStack)) 13494 return StmtError(); 13495 } 13496 } 13497 13498 if (checkSimdlenSafelenSpecified(*this, Clauses)) 13499 return StmtError(); 13500 13501 setFunctionHasBranchProtectedScope(); 13502 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 13503 NestedLoopCount, Clauses, AStmt, B); 13504 } 13505 13506 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 13507 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13508 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13509 if (!AStmt) 13510 return StmtError(); 13511 13512 auto *CS = cast<CapturedStmt>(AStmt); 13513 // 1.2.2 OpenMP Language Terminology 13514 // Structured block - An executable statement with a single entry at the 13515 // top and a single exit at the bottom. 13516 // The point of exit cannot be a branch out of the structured block. 13517 // longjmp() and throw() must not violate the entry/exit criteria. 13518 CS->getCapturedDecl()->setNothrow(); 13519 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 13520 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13521 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13522 // 1.2.2 OpenMP Language Terminology 13523 // Structured block - An executable statement with a single entry at the 13524 // top and a single exit at the bottom. 13525 // The point of exit cannot be a branch out of the structured block. 13526 // longjmp() and throw() must not violate the entry/exit criteria. 13527 CS->getCapturedDecl()->setNothrow(); 13528 } 13529 13530 OMPLoopBasedDirective::HelperExprs B; 13531 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 13532 // define the nested loops number. 13533 unsigned NestedLoopCount = checkOpenMPLoop( 13534 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 13535 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, VarsWithImplicitDSA, 13536 B); 13537 if (NestedLoopCount == 0) 13538 return StmtError(); 13539 13540 assert((CurContext->isDependentContext() || B.builtAll()) && 13541 "omp target parallel for simd loop exprs were not built"); 13542 13543 if (!CurContext->isDependentContext()) { 13544 // Finalize the clauses that need pre-built expressions for CodeGen. 13545 for (OMPClause *C : Clauses) { 13546 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 13547 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 13548 B.NumIterations, *this, CurScope, 13549 DSAStack)) 13550 return StmtError(); 13551 } 13552 } 13553 if (checkSimdlenSafelenSpecified(*this, Clauses)) 13554 return StmtError(); 13555 13556 setFunctionHasBranchProtectedScope(); 13557 return OMPTargetParallelForSimdDirective::Create( 13558 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 13559 } 13560 13561 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 13562 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13563 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13564 if (!AStmt) 13565 return StmtError(); 13566 13567 auto *CS = cast<CapturedStmt>(AStmt); 13568 // 1.2.2 OpenMP Language Terminology 13569 // Structured block - An executable statement with a single entry at the 13570 // top and a single exit at the bottom. 13571 // The point of exit cannot be a branch out of the structured block. 13572 // longjmp() and throw() must not violate the entry/exit criteria. 13573 CS->getCapturedDecl()->setNothrow(); 13574 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd); 13575 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13576 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13577 // 1.2.2 OpenMP Language Terminology 13578 // Structured block - An executable statement with a single entry at the 13579 // top and a single exit at the bottom. 13580 // The point of exit cannot be a branch out of the structured block. 13581 // longjmp() and throw() must not violate the entry/exit criteria. 13582 CS->getCapturedDecl()->setNothrow(); 13583 } 13584 13585 OMPLoopBasedDirective::HelperExprs B; 13586 // In presence of clause 'collapse' with number of loops, it will define the 13587 // nested loops number. 13588 unsigned NestedLoopCount = 13589 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 13590 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 13591 VarsWithImplicitDSA, B); 13592 if (NestedLoopCount == 0) 13593 return StmtError(); 13594 13595 assert((CurContext->isDependentContext() || B.builtAll()) && 13596 "omp target simd loop exprs were not built"); 13597 13598 if (!CurContext->isDependentContext()) { 13599 // Finalize the clauses that need pre-built expressions for CodeGen. 13600 for (OMPClause *C : Clauses) { 13601 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 13602 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 13603 B.NumIterations, *this, CurScope, 13604 DSAStack)) 13605 return StmtError(); 13606 } 13607 } 13608 13609 if (checkSimdlenSafelenSpecified(*this, Clauses)) 13610 return StmtError(); 13611 13612 setFunctionHasBranchProtectedScope(); 13613 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 13614 NestedLoopCount, Clauses, AStmt, B); 13615 } 13616 13617 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 13618 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13619 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13620 if (!AStmt) 13621 return StmtError(); 13622 13623 auto *CS = cast<CapturedStmt>(AStmt); 13624 // 1.2.2 OpenMP Language Terminology 13625 // Structured block - An executable statement with a single entry at the 13626 // top and a single exit at the bottom. 13627 // The point of exit cannot be a branch out of the structured block. 13628 // longjmp() and throw() must not violate the entry/exit criteria. 13629 CS->getCapturedDecl()->setNothrow(); 13630 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute); 13631 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13632 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13633 // 1.2.2 OpenMP Language Terminology 13634 // Structured block - An executable statement with a single entry at the 13635 // top and a single exit at the bottom. 13636 // The point of exit cannot be a branch out of the structured block. 13637 // longjmp() and throw() must not violate the entry/exit criteria. 13638 CS->getCapturedDecl()->setNothrow(); 13639 } 13640 13641 OMPLoopBasedDirective::HelperExprs B; 13642 // In presence of clause 'collapse' with number of loops, it will 13643 // define the nested loops number. 13644 unsigned NestedLoopCount = 13645 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 13646 nullptr /*ordered not a clause on distribute*/, CS, *this, 13647 *DSAStack, VarsWithImplicitDSA, B); 13648 if (NestedLoopCount == 0) 13649 return StmtError(); 13650 13651 assert((CurContext->isDependentContext() || B.builtAll()) && 13652 "omp teams distribute loop exprs were not built"); 13653 13654 setFunctionHasBranchProtectedScope(); 13655 13656 DSAStack->setParentTeamsRegionLoc(StartLoc); 13657 13658 return OMPTeamsDistributeDirective::Create( 13659 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 13660 } 13661 13662 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 13663 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13664 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13665 if (!AStmt) 13666 return StmtError(); 13667 13668 auto *CS = cast<CapturedStmt>(AStmt); 13669 // 1.2.2 OpenMP Language Terminology 13670 // Structured block - An executable statement with a single entry at the 13671 // top and a single exit at the bottom. 13672 // The point of exit cannot be a branch out of the structured block. 13673 // longjmp() and throw() must not violate the entry/exit criteria. 13674 CS->getCapturedDecl()->setNothrow(); 13675 for (int ThisCaptureLevel = 13676 getOpenMPCaptureLevels(OMPD_teams_distribute_simd); 13677 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13678 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13679 // 1.2.2 OpenMP Language Terminology 13680 // Structured block - An executable statement with a single entry at the 13681 // top and a single exit at the bottom. 13682 // The point of exit cannot be a branch out of the structured block. 13683 // longjmp() and throw() must not violate the entry/exit criteria. 13684 CS->getCapturedDecl()->setNothrow(); 13685 } 13686 13687 OMPLoopBasedDirective::HelperExprs B; 13688 // In presence of clause 'collapse' with number of loops, it will 13689 // define the nested loops number. 13690 unsigned NestedLoopCount = checkOpenMPLoop( 13691 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 13692 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 13693 VarsWithImplicitDSA, B); 13694 13695 if (NestedLoopCount == 0) 13696 return StmtError(); 13697 13698 assert((CurContext->isDependentContext() || B.builtAll()) && 13699 "omp teams distribute simd loop exprs were not built"); 13700 13701 if (!CurContext->isDependentContext()) { 13702 // Finalize the clauses that need pre-built expressions for CodeGen. 13703 for (OMPClause *C : Clauses) { 13704 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 13705 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 13706 B.NumIterations, *this, CurScope, 13707 DSAStack)) 13708 return StmtError(); 13709 } 13710 } 13711 13712 if (checkSimdlenSafelenSpecified(*this, Clauses)) 13713 return StmtError(); 13714 13715 setFunctionHasBranchProtectedScope(); 13716 13717 DSAStack->setParentTeamsRegionLoc(StartLoc); 13718 13719 return OMPTeamsDistributeSimdDirective::Create( 13720 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 13721 } 13722 13723 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 13724 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13725 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13726 if (!AStmt) 13727 return StmtError(); 13728 13729 auto *CS = cast<CapturedStmt>(AStmt); 13730 // 1.2.2 OpenMP Language Terminology 13731 // Structured block - An executable statement with a single entry at the 13732 // top and a single exit at the bottom. 13733 // The point of exit cannot be a branch out of the structured block. 13734 // longjmp() and throw() must not violate the entry/exit criteria. 13735 CS->getCapturedDecl()->setNothrow(); 13736 13737 for (int ThisCaptureLevel = 13738 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd); 13739 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13740 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13741 // 1.2.2 OpenMP Language Terminology 13742 // Structured block - An executable statement with a single entry at the 13743 // top and a single exit at the bottom. 13744 // The point of exit cannot be a branch out of the structured block. 13745 // longjmp() and throw() must not violate the entry/exit criteria. 13746 CS->getCapturedDecl()->setNothrow(); 13747 } 13748 13749 OMPLoopBasedDirective::HelperExprs B; 13750 // In presence of clause 'collapse' with number of loops, it will 13751 // define the nested loops number. 13752 unsigned NestedLoopCount = checkOpenMPLoop( 13753 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 13754 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 13755 VarsWithImplicitDSA, B); 13756 13757 if (NestedLoopCount == 0) 13758 return StmtError(); 13759 13760 assert((CurContext->isDependentContext() || B.builtAll()) && 13761 "omp for loop exprs were not built"); 13762 13763 if (!CurContext->isDependentContext()) { 13764 // Finalize the clauses that need pre-built expressions for CodeGen. 13765 for (OMPClause *C : Clauses) { 13766 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 13767 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 13768 B.NumIterations, *this, CurScope, 13769 DSAStack)) 13770 return StmtError(); 13771 } 13772 } 13773 13774 if (checkSimdlenSafelenSpecified(*this, Clauses)) 13775 return StmtError(); 13776 13777 setFunctionHasBranchProtectedScope(); 13778 13779 DSAStack->setParentTeamsRegionLoc(StartLoc); 13780 13781 return OMPTeamsDistributeParallelForSimdDirective::Create( 13782 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 13783 } 13784 13785 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 13786 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13787 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13788 if (!AStmt) 13789 return StmtError(); 13790 13791 auto *CS = cast<CapturedStmt>(AStmt); 13792 // 1.2.2 OpenMP Language Terminology 13793 // Structured block - An executable statement with a single entry at the 13794 // top and a single exit at the bottom. 13795 // The point of exit cannot be a branch out of the structured block. 13796 // longjmp() and throw() must not violate the entry/exit criteria. 13797 CS->getCapturedDecl()->setNothrow(); 13798 13799 for (int ThisCaptureLevel = 13800 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for); 13801 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13802 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13803 // 1.2.2 OpenMP Language Terminology 13804 // Structured block - An executable statement with a single entry at the 13805 // top and a single exit at the bottom. 13806 // The point of exit cannot be a branch out of the structured block. 13807 // longjmp() and throw() must not violate the entry/exit criteria. 13808 CS->getCapturedDecl()->setNothrow(); 13809 } 13810 13811 OMPLoopBasedDirective::HelperExprs B; 13812 // In presence of clause 'collapse' with number of loops, it will 13813 // define the nested loops number. 13814 unsigned NestedLoopCount = checkOpenMPLoop( 13815 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 13816 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 13817 VarsWithImplicitDSA, B); 13818 13819 if (NestedLoopCount == 0) 13820 return StmtError(); 13821 13822 assert((CurContext->isDependentContext() || B.builtAll()) && 13823 "omp for loop exprs were not built"); 13824 13825 setFunctionHasBranchProtectedScope(); 13826 13827 DSAStack->setParentTeamsRegionLoc(StartLoc); 13828 13829 return OMPTeamsDistributeParallelForDirective::Create( 13830 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 13831 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 13832 } 13833 13834 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 13835 Stmt *AStmt, 13836 SourceLocation StartLoc, 13837 SourceLocation EndLoc) { 13838 if (!AStmt) 13839 return StmtError(); 13840 13841 auto *CS = cast<CapturedStmt>(AStmt); 13842 // 1.2.2 OpenMP Language Terminology 13843 // Structured block - An executable statement with a single entry at the 13844 // top and a single exit at the bottom. 13845 // The point of exit cannot be a branch out of the structured block. 13846 // longjmp() and throw() must not violate the entry/exit criteria. 13847 CS->getCapturedDecl()->setNothrow(); 13848 13849 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams); 13850 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13851 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13852 // 1.2.2 OpenMP Language Terminology 13853 // Structured block - An executable statement with a single entry at the 13854 // top and a single exit at the bottom. 13855 // The point of exit cannot be a branch out of the structured block. 13856 // longjmp() and throw() must not violate the entry/exit criteria. 13857 CS->getCapturedDecl()->setNothrow(); 13858 } 13859 setFunctionHasBranchProtectedScope(); 13860 13861 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 13862 AStmt); 13863 } 13864 13865 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 13866 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13867 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13868 if (!AStmt) 13869 return StmtError(); 13870 13871 auto *CS = cast<CapturedStmt>(AStmt); 13872 // 1.2.2 OpenMP Language Terminology 13873 // Structured block - An executable statement with a single entry at the 13874 // top and a single exit at the bottom. 13875 // The point of exit cannot be a branch out of the structured block. 13876 // longjmp() and throw() must not violate the entry/exit criteria. 13877 CS->getCapturedDecl()->setNothrow(); 13878 for (int ThisCaptureLevel = 13879 getOpenMPCaptureLevels(OMPD_target_teams_distribute); 13880 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13881 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13882 // 1.2.2 OpenMP Language Terminology 13883 // Structured block - An executable statement with a single entry at the 13884 // top and a single exit at the bottom. 13885 // The point of exit cannot be a branch out of the structured block. 13886 // longjmp() and throw() must not violate the entry/exit criteria. 13887 CS->getCapturedDecl()->setNothrow(); 13888 } 13889 13890 OMPLoopBasedDirective::HelperExprs B; 13891 // In presence of clause 'collapse' with number of loops, it will 13892 // define the nested loops number. 13893 unsigned NestedLoopCount = checkOpenMPLoop( 13894 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses), 13895 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 13896 VarsWithImplicitDSA, B); 13897 if (NestedLoopCount == 0) 13898 return StmtError(); 13899 13900 assert((CurContext->isDependentContext() || B.builtAll()) && 13901 "omp target teams distribute loop exprs were not built"); 13902 13903 setFunctionHasBranchProtectedScope(); 13904 return OMPTargetTeamsDistributeDirective::Create( 13905 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 13906 } 13907 13908 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 13909 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13910 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13911 if (!AStmt) 13912 return StmtError(); 13913 13914 auto *CS = cast<CapturedStmt>(AStmt); 13915 // 1.2.2 OpenMP Language Terminology 13916 // Structured block - An executable statement with a single entry at the 13917 // top and a single exit at the bottom. 13918 // The point of exit cannot be a branch out of the structured block. 13919 // longjmp() and throw() must not violate the entry/exit criteria. 13920 CS->getCapturedDecl()->setNothrow(); 13921 for (int ThisCaptureLevel = 13922 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for); 13923 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13924 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13925 // 1.2.2 OpenMP Language Terminology 13926 // Structured block - An executable statement with a single entry at the 13927 // top and a single exit at the bottom. 13928 // The point of exit cannot be a branch out of the structured block. 13929 // longjmp() and throw() must not violate the entry/exit criteria. 13930 CS->getCapturedDecl()->setNothrow(); 13931 } 13932 13933 OMPLoopBasedDirective::HelperExprs B; 13934 // In presence of clause 'collapse' with number of loops, it will 13935 // define the nested loops number. 13936 unsigned NestedLoopCount = checkOpenMPLoop( 13937 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 13938 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 13939 VarsWithImplicitDSA, B); 13940 if (NestedLoopCount == 0) 13941 return StmtError(); 13942 13943 assert((CurContext->isDependentContext() || B.builtAll()) && 13944 "omp target teams distribute parallel for loop exprs were not built"); 13945 13946 if (!CurContext->isDependentContext()) { 13947 // Finalize the clauses that need pre-built expressions for CodeGen. 13948 for (OMPClause *C : Clauses) { 13949 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 13950 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 13951 B.NumIterations, *this, CurScope, 13952 DSAStack)) 13953 return StmtError(); 13954 } 13955 } 13956 13957 setFunctionHasBranchProtectedScope(); 13958 return OMPTargetTeamsDistributeParallelForDirective::Create( 13959 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 13960 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 13961 } 13962 13963 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 13964 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13965 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13966 if (!AStmt) 13967 return StmtError(); 13968 13969 auto *CS = cast<CapturedStmt>(AStmt); 13970 // 1.2.2 OpenMP Language Terminology 13971 // Structured block - An executable statement with a single entry at the 13972 // top and a single exit at the bottom. 13973 // The point of exit cannot be a branch out of the structured block. 13974 // longjmp() and throw() must not violate the entry/exit criteria. 13975 CS->getCapturedDecl()->setNothrow(); 13976 for (int ThisCaptureLevel = getOpenMPCaptureLevels( 13977 OMPD_target_teams_distribute_parallel_for_simd); 13978 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13979 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13980 // 1.2.2 OpenMP Language Terminology 13981 // Structured block - An executable statement with a single entry at the 13982 // top and a single exit at the bottom. 13983 // The point of exit cannot be a branch out of the structured block. 13984 // longjmp() and throw() must not violate the entry/exit criteria. 13985 CS->getCapturedDecl()->setNothrow(); 13986 } 13987 13988 OMPLoopBasedDirective::HelperExprs B; 13989 // In presence of clause 'collapse' with number of loops, it will 13990 // define the nested loops number. 13991 unsigned NestedLoopCount = 13992 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd, 13993 getCollapseNumberExpr(Clauses), 13994 nullptr /*ordered not a clause on distribute*/, CS, *this, 13995 *DSAStack, VarsWithImplicitDSA, B); 13996 if (NestedLoopCount == 0) 13997 return StmtError(); 13998 13999 assert((CurContext->isDependentContext() || B.builtAll()) && 14000 "omp target teams distribute parallel for simd loop exprs were not " 14001 "built"); 14002 14003 if (!CurContext->isDependentContext()) { 14004 // Finalize the clauses that need pre-built expressions for CodeGen. 14005 for (OMPClause *C : Clauses) { 14006 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 14007 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 14008 B.NumIterations, *this, CurScope, 14009 DSAStack)) 14010 return StmtError(); 14011 } 14012 } 14013 14014 if (checkSimdlenSafelenSpecified(*this, Clauses)) 14015 return StmtError(); 14016 14017 setFunctionHasBranchProtectedScope(); 14018 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 14019 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 14020 } 14021 14022 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 14023 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 14024 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 14025 if (!AStmt) 14026 return StmtError(); 14027 14028 auto *CS = cast<CapturedStmt>(AStmt); 14029 // 1.2.2 OpenMP Language Terminology 14030 // Structured block - An executable statement with a single entry at the 14031 // top and a single exit at the bottom. 14032 // The point of exit cannot be a branch out of the structured block. 14033 // longjmp() and throw() must not violate the entry/exit criteria. 14034 CS->getCapturedDecl()->setNothrow(); 14035 for (int ThisCaptureLevel = 14036 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd); 14037 ThisCaptureLevel > 1; --ThisCaptureLevel) { 14038 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 14039 // 1.2.2 OpenMP Language Terminology 14040 // Structured block - An executable statement with a single entry at the 14041 // top and a single exit at the bottom. 14042 // The point of exit cannot be a branch out of the structured block. 14043 // longjmp() and throw() must not violate the entry/exit criteria. 14044 CS->getCapturedDecl()->setNothrow(); 14045 } 14046 14047 OMPLoopBasedDirective::HelperExprs B; 14048 // In presence of clause 'collapse' with number of loops, it will 14049 // define the nested loops number. 14050 unsigned NestedLoopCount = checkOpenMPLoop( 14051 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 14052 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 14053 VarsWithImplicitDSA, B); 14054 if (NestedLoopCount == 0) 14055 return StmtError(); 14056 14057 assert((CurContext->isDependentContext() || B.builtAll()) && 14058 "omp target teams distribute simd loop exprs were not built"); 14059 14060 if (!CurContext->isDependentContext()) { 14061 // Finalize the clauses that need pre-built expressions for CodeGen. 14062 for (OMPClause *C : Clauses) { 14063 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 14064 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 14065 B.NumIterations, *this, CurScope, 14066 DSAStack)) 14067 return StmtError(); 14068 } 14069 } 14070 14071 if (checkSimdlenSafelenSpecified(*this, Clauses)) 14072 return StmtError(); 14073 14074 setFunctionHasBranchProtectedScope(); 14075 return OMPTargetTeamsDistributeSimdDirective::Create( 14076 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 14077 } 14078 14079 bool Sema::checkTransformableLoopNest( 14080 OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops, 14081 SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers, 14082 Stmt *&Body, 14083 SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>> 14084 &OriginalInits) { 14085 OriginalInits.emplace_back(); 14086 bool Result = OMPLoopBasedDirective::doForAllLoops( 14087 AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false, NumLoops, 14088 [this, &LoopHelpers, &Body, &OriginalInits, Kind](unsigned Cnt, 14089 Stmt *CurStmt) { 14090 VarsWithInheritedDSAType TmpDSA; 14091 unsigned SingleNumLoops = 14092 checkOpenMPLoop(Kind, nullptr, nullptr, CurStmt, *this, *DSAStack, 14093 TmpDSA, LoopHelpers[Cnt]); 14094 if (SingleNumLoops == 0) 14095 return true; 14096 assert(SingleNumLoops == 1 && "Expect single loop iteration space"); 14097 if (auto *For = dyn_cast<ForStmt>(CurStmt)) { 14098 OriginalInits.back().push_back(For->getInit()); 14099 Body = For->getBody(); 14100 } else { 14101 assert(isa<CXXForRangeStmt>(CurStmt) && 14102 "Expected canonical for or range-based for loops."); 14103 auto *CXXFor = cast<CXXForRangeStmt>(CurStmt); 14104 OriginalInits.back().push_back(CXXFor->getBeginStmt()); 14105 Body = CXXFor->getBody(); 14106 } 14107 OriginalInits.emplace_back(); 14108 return false; 14109 }, 14110 [&OriginalInits](OMPLoopBasedDirective *Transform) { 14111 Stmt *DependentPreInits; 14112 if (auto *Dir = dyn_cast<OMPTileDirective>(Transform)) 14113 DependentPreInits = Dir->getPreInits(); 14114 else if (auto *Dir = dyn_cast<OMPUnrollDirective>(Transform)) 14115 DependentPreInits = Dir->getPreInits(); 14116 else 14117 llvm_unreachable("Unhandled loop transformation"); 14118 if (!DependentPreInits) 14119 return; 14120 llvm::append_range(OriginalInits.back(), 14121 cast<DeclStmt>(DependentPreInits)->getDeclGroup()); 14122 }); 14123 assert(OriginalInits.back().empty() && "No preinit after innermost loop"); 14124 OriginalInits.pop_back(); 14125 return Result; 14126 } 14127 14128 StmtResult Sema::ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses, 14129 Stmt *AStmt, SourceLocation StartLoc, 14130 SourceLocation EndLoc) { 14131 auto SizesClauses = 14132 OMPExecutableDirective::getClausesOfKind<OMPSizesClause>(Clauses); 14133 if (SizesClauses.empty()) { 14134 // A missing 'sizes' clause is already reported by the parser. 14135 return StmtError(); 14136 } 14137 const OMPSizesClause *SizesClause = *SizesClauses.begin(); 14138 unsigned NumLoops = SizesClause->getNumSizes(); 14139 14140 // Empty statement should only be possible if there already was an error. 14141 if (!AStmt) 14142 return StmtError(); 14143 14144 // Verify and diagnose loop nest. 14145 SmallVector<OMPLoopBasedDirective::HelperExprs, 4> LoopHelpers(NumLoops); 14146 Stmt *Body = nullptr; 14147 SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, 4> 14148 OriginalInits; 14149 if (!checkTransformableLoopNest(OMPD_tile, AStmt, NumLoops, LoopHelpers, Body, 14150 OriginalInits)) 14151 return StmtError(); 14152 14153 // Delay tiling to when template is completely instantiated. 14154 if (CurContext->isDependentContext()) 14155 return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, 14156 NumLoops, AStmt, nullptr, nullptr); 14157 14158 SmallVector<Decl *, 4> PreInits; 14159 14160 // Create iteration variables for the generated loops. 14161 SmallVector<VarDecl *, 4> FloorIndVars; 14162 SmallVector<VarDecl *, 4> TileIndVars; 14163 FloorIndVars.resize(NumLoops); 14164 TileIndVars.resize(NumLoops); 14165 for (unsigned I = 0; I < NumLoops; ++I) { 14166 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I]; 14167 14168 assert(LoopHelper.Counters.size() == 1 && 14169 "Expect single-dimensional loop iteration space"); 14170 auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front()); 14171 std::string OrigVarName = OrigCntVar->getNameInfo().getAsString(); 14172 DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef); 14173 QualType CntTy = IterVarRef->getType(); 14174 14175 // Iteration variable for the floor (i.e. outer) loop. 14176 { 14177 std::string FloorCntName = 14178 (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str(); 14179 VarDecl *FloorCntDecl = 14180 buildVarDecl(*this, {}, CntTy, FloorCntName, nullptr, OrigCntVar); 14181 FloorIndVars[I] = FloorCntDecl; 14182 } 14183 14184 // Iteration variable for the tile (i.e. inner) loop. 14185 { 14186 std::string TileCntName = 14187 (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str(); 14188 14189 // Reuse the iteration variable created by checkOpenMPLoop. It is also 14190 // used by the expressions to derive the original iteration variable's 14191 // value from the logical iteration number. 14192 auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl()); 14193 TileCntDecl->setDeclName(&PP.getIdentifierTable().get(TileCntName)); 14194 TileIndVars[I] = TileCntDecl; 14195 } 14196 for (auto &P : OriginalInits[I]) { 14197 if (auto *D = P.dyn_cast<Decl *>()) 14198 PreInits.push_back(D); 14199 else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>())) 14200 PreInits.append(PI->decl_begin(), PI->decl_end()); 14201 } 14202 if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits)) 14203 PreInits.append(PI->decl_begin(), PI->decl_end()); 14204 // Gather declarations for the data members used as counters. 14205 for (Expr *CounterRef : LoopHelper.Counters) { 14206 auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl(); 14207 if (isa<OMPCapturedExprDecl>(CounterDecl)) 14208 PreInits.push_back(CounterDecl); 14209 } 14210 } 14211 14212 // Once the original iteration values are set, append the innermost body. 14213 Stmt *Inner = Body; 14214 14215 // Create tile loops from the inside to the outside. 14216 for (int I = NumLoops - 1; I >= 0; --I) { 14217 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I]; 14218 Expr *NumIterations = LoopHelper.NumIterations; 14219 auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]); 14220 QualType CntTy = OrigCntVar->getType(); 14221 Expr *DimTileSize = SizesClause->getSizesRefs()[I]; 14222 Scope *CurScope = getCurScope(); 14223 14224 // Commonly used variables. 14225 DeclRefExpr *TileIV = buildDeclRefExpr(*this, TileIndVars[I], CntTy, 14226 OrigCntVar->getExprLoc()); 14227 DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy, 14228 OrigCntVar->getExprLoc()); 14229 14230 // For init-statement: auto .tile.iv = .floor.iv 14231 AddInitializerToDecl(TileIndVars[I], DefaultLvalueConversion(FloorIV).get(), 14232 /*DirectInit=*/false); 14233 Decl *CounterDecl = TileIndVars[I]; 14234 StmtResult InitStmt = new (Context) 14235 DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1), 14236 OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc()); 14237 if (!InitStmt.isUsable()) 14238 return StmtError(); 14239 14240 // For cond-expression: .tile.iv < min(.floor.iv + DimTileSize, 14241 // NumIterations) 14242 ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 14243 BO_Add, FloorIV, DimTileSize); 14244 if (!EndOfTile.isUsable()) 14245 return StmtError(); 14246 ExprResult IsPartialTile = 14247 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, 14248 NumIterations, EndOfTile.get()); 14249 if (!IsPartialTile.isUsable()) 14250 return StmtError(); 14251 ExprResult MinTileAndIterSpace = ActOnConditionalOp( 14252 LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(), 14253 IsPartialTile.get(), NumIterations, EndOfTile.get()); 14254 if (!MinTileAndIterSpace.isUsable()) 14255 return StmtError(); 14256 ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 14257 BO_LT, TileIV, MinTileAndIterSpace.get()); 14258 if (!CondExpr.isUsable()) 14259 return StmtError(); 14260 14261 // For incr-statement: ++.tile.iv 14262 ExprResult IncrStmt = 14263 BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV); 14264 if (!IncrStmt.isUsable()) 14265 return StmtError(); 14266 14267 // Statements to set the original iteration variable's value from the 14268 // logical iteration number. 14269 // Generated for loop is: 14270 // Original_for_init; 14271 // for (auto .tile.iv = .floor.iv; .tile.iv < min(.floor.iv + DimTileSize, 14272 // NumIterations); ++.tile.iv) { 14273 // Original_Body; 14274 // Original_counter_update; 14275 // } 14276 // FIXME: If the innermost body is an loop itself, inserting these 14277 // statements stops it being recognized as a perfectly nested loop (e.g. 14278 // for applying tiling again). If this is the case, sink the expressions 14279 // further into the inner loop. 14280 SmallVector<Stmt *, 4> BodyParts; 14281 BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end()); 14282 BodyParts.push_back(Inner); 14283 Inner = CompoundStmt::Create(Context, BodyParts, Inner->getBeginLoc(), 14284 Inner->getEndLoc()); 14285 Inner = new (Context) 14286 ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr, 14287 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(), 14288 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 14289 } 14290 14291 // Create floor loops from the inside to the outside. 14292 for (int I = NumLoops - 1; I >= 0; --I) { 14293 auto &LoopHelper = LoopHelpers[I]; 14294 Expr *NumIterations = LoopHelper.NumIterations; 14295 DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]); 14296 QualType CntTy = OrigCntVar->getType(); 14297 Expr *DimTileSize = SizesClause->getSizesRefs()[I]; 14298 Scope *CurScope = getCurScope(); 14299 14300 // Commonly used variables. 14301 DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy, 14302 OrigCntVar->getExprLoc()); 14303 14304 // For init-statement: auto .floor.iv = 0 14305 AddInitializerToDecl( 14306 FloorIndVars[I], 14307 ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(), 14308 /*DirectInit=*/false); 14309 Decl *CounterDecl = FloorIndVars[I]; 14310 StmtResult InitStmt = new (Context) 14311 DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1), 14312 OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc()); 14313 if (!InitStmt.isUsable()) 14314 return StmtError(); 14315 14316 // For cond-expression: .floor.iv < NumIterations 14317 ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 14318 BO_LT, FloorIV, NumIterations); 14319 if (!CondExpr.isUsable()) 14320 return StmtError(); 14321 14322 // For incr-statement: .floor.iv += DimTileSize 14323 ExprResult IncrStmt = BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), 14324 BO_AddAssign, FloorIV, DimTileSize); 14325 if (!IncrStmt.isUsable()) 14326 return StmtError(); 14327 14328 Inner = new (Context) 14329 ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr, 14330 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(), 14331 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 14332 } 14333 14334 return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, NumLoops, 14335 AStmt, Inner, 14336 buildPreInits(Context, PreInits)); 14337 } 14338 14339 StmtResult Sema::ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses, 14340 Stmt *AStmt, 14341 SourceLocation StartLoc, 14342 SourceLocation EndLoc) { 14343 // Empty statement should only be possible if there already was an error. 14344 if (!AStmt) 14345 return StmtError(); 14346 14347 if (checkMutuallyExclusiveClauses(*this, Clauses, {OMPC_partial, OMPC_full})) 14348 return StmtError(); 14349 14350 const OMPFullClause *FullClause = 14351 OMPExecutableDirective::getSingleClause<OMPFullClause>(Clauses); 14352 const OMPPartialClause *PartialClause = 14353 OMPExecutableDirective::getSingleClause<OMPPartialClause>(Clauses); 14354 assert(!(FullClause && PartialClause) && 14355 "mutual exclusivity must have been checked before"); 14356 14357 constexpr unsigned NumLoops = 1; 14358 Stmt *Body = nullptr; 14359 SmallVector<OMPLoopBasedDirective::HelperExprs, NumLoops> LoopHelpers( 14360 NumLoops); 14361 SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, NumLoops + 1> 14362 OriginalInits; 14363 if (!checkTransformableLoopNest(OMPD_unroll, AStmt, NumLoops, LoopHelpers, 14364 Body, OriginalInits)) 14365 return StmtError(); 14366 14367 unsigned NumGeneratedLoops = PartialClause ? 1 : 0; 14368 14369 // Delay unrolling to when template is completely instantiated. 14370 if (CurContext->isDependentContext()) 14371 return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 14372 NumGeneratedLoops, nullptr, nullptr); 14373 14374 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers.front(); 14375 14376 if (FullClause) { 14377 if (!VerifyPositiveIntegerConstantInClause( 14378 LoopHelper.NumIterations, OMPC_full, /*StrictlyPositive=*/false, 14379 /*SuppressExprDiags=*/true) 14380 .isUsable()) { 14381 Diag(AStmt->getBeginLoc(), diag::err_omp_unroll_full_variable_trip_count); 14382 Diag(FullClause->getBeginLoc(), diag::note_omp_directive_here) 14383 << "#pragma omp unroll full"; 14384 return StmtError(); 14385 } 14386 } 14387 14388 // The generated loop may only be passed to other loop-associated directive 14389 // when a partial clause is specified. Without the requirement it is 14390 // sufficient to generate loop unroll metadata at code-generation. 14391 if (NumGeneratedLoops == 0) 14392 return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 14393 NumGeneratedLoops, nullptr, nullptr); 14394 14395 // Otherwise, we need to provide a de-sugared/transformed AST that can be 14396 // associated with another loop directive. 14397 // 14398 // The canonical loop analysis return by checkTransformableLoopNest assumes 14399 // the following structure to be the same loop without transformations or 14400 // directives applied: \code OriginalInits; LoopHelper.PreInits; 14401 // LoopHelper.Counters; 14402 // for (; IV < LoopHelper.NumIterations; ++IV) { 14403 // LoopHelper.Updates; 14404 // Body; 14405 // } 14406 // \endcode 14407 // where IV is a variable declared and initialized to 0 in LoopHelper.PreInits 14408 // and referenced by LoopHelper.IterationVarRef. 14409 // 14410 // The unrolling directive transforms this into the following loop: 14411 // \code 14412 // OriginalInits; \ 14413 // LoopHelper.PreInits; > NewPreInits 14414 // LoopHelper.Counters; / 14415 // for (auto UIV = 0; UIV < LoopHelper.NumIterations; UIV+=Factor) { 14416 // #pragma clang loop unroll_count(Factor) 14417 // for (IV = UIV; IV < UIV + Factor && UIV < LoopHelper.NumIterations; ++IV) 14418 // { 14419 // LoopHelper.Updates; 14420 // Body; 14421 // } 14422 // } 14423 // \endcode 14424 // where UIV is a new logical iteration counter. IV must be the same VarDecl 14425 // as the original LoopHelper.IterationVarRef because LoopHelper.Updates 14426 // references it. If the partially unrolled loop is associated with another 14427 // loop directive (like an OMPForDirective), it will use checkOpenMPLoop to 14428 // analyze this loop, i.e. the outer loop must fulfill the constraints of an 14429 // OpenMP canonical loop. The inner loop is not an associable canonical loop 14430 // and only exists to defer its unrolling to LLVM's LoopUnroll instead of 14431 // doing it in the frontend (by adding loop metadata). NewPreInits becomes a 14432 // property of the OMPLoopBasedDirective instead of statements in 14433 // CompoundStatement. This is to allow the loop to become a non-outermost loop 14434 // of a canonical loop nest where these PreInits are emitted before the 14435 // outermost directive. 14436 14437 // Determine the PreInit declarations. 14438 SmallVector<Decl *, 4> PreInits; 14439 assert(OriginalInits.size() == 1 && 14440 "Expecting a single-dimensional loop iteration space"); 14441 for (auto &P : OriginalInits[0]) { 14442 if (auto *D = P.dyn_cast<Decl *>()) 14443 PreInits.push_back(D); 14444 else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>())) 14445 PreInits.append(PI->decl_begin(), PI->decl_end()); 14446 } 14447 if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits)) 14448 PreInits.append(PI->decl_begin(), PI->decl_end()); 14449 // Gather declarations for the data members used as counters. 14450 for (Expr *CounterRef : LoopHelper.Counters) { 14451 auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl(); 14452 if (isa<OMPCapturedExprDecl>(CounterDecl)) 14453 PreInits.push_back(CounterDecl); 14454 } 14455 14456 auto *IterationVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef); 14457 QualType IVTy = IterationVarRef->getType(); 14458 assert(LoopHelper.Counters.size() == 1 && 14459 "Expecting a single-dimensional loop iteration space"); 14460 auto *OrigVar = cast<DeclRefExpr>(LoopHelper.Counters.front()); 14461 14462 // Determine the unroll factor. 14463 uint64_t Factor; 14464 SourceLocation FactorLoc; 14465 if (Expr *FactorVal = PartialClause->getFactor()) { 14466 Factor = FactorVal->getIntegerConstantExpr(Context)->getZExtValue(); 14467 FactorLoc = FactorVal->getExprLoc(); 14468 } else { 14469 // TODO: Use a better profitability model. 14470 Factor = 2; 14471 } 14472 assert(Factor > 0 && "Expected positive unroll factor"); 14473 auto MakeFactorExpr = [this, Factor, IVTy, FactorLoc]() { 14474 return IntegerLiteral::Create( 14475 Context, llvm::APInt(Context.getIntWidth(IVTy), Factor), IVTy, 14476 FactorLoc); 14477 }; 14478 14479 // Iteration variable SourceLocations. 14480 SourceLocation OrigVarLoc = OrigVar->getExprLoc(); 14481 SourceLocation OrigVarLocBegin = OrigVar->getBeginLoc(); 14482 SourceLocation OrigVarLocEnd = OrigVar->getEndLoc(); 14483 14484 // Internal variable names. 14485 std::string OrigVarName = OrigVar->getNameInfo().getAsString(); 14486 std::string OuterIVName = (Twine(".unrolled.iv.") + OrigVarName).str(); 14487 std::string InnerIVName = (Twine(".unroll_inner.iv.") + OrigVarName).str(); 14488 std::string InnerTripCountName = 14489 (Twine(".unroll_inner.tripcount.") + OrigVarName).str(); 14490 14491 // Create the iteration variable for the unrolled loop. 14492 VarDecl *OuterIVDecl = 14493 buildVarDecl(*this, {}, IVTy, OuterIVName, nullptr, OrigVar); 14494 auto MakeOuterRef = [this, OuterIVDecl, IVTy, OrigVarLoc]() { 14495 return buildDeclRefExpr(*this, OuterIVDecl, IVTy, OrigVarLoc); 14496 }; 14497 14498 // Iteration variable for the inner loop: Reuse the iteration variable created 14499 // by checkOpenMPLoop. 14500 auto *InnerIVDecl = cast<VarDecl>(IterationVarRef->getDecl()); 14501 InnerIVDecl->setDeclName(&PP.getIdentifierTable().get(InnerIVName)); 14502 auto MakeInnerRef = [this, InnerIVDecl, IVTy, OrigVarLoc]() { 14503 return buildDeclRefExpr(*this, InnerIVDecl, IVTy, OrigVarLoc); 14504 }; 14505 14506 // Make a copy of the NumIterations expression for each use: By the AST 14507 // constraints, every expression object in a DeclContext must be unique. 14508 CaptureVars CopyTransformer(*this); 14509 auto MakeNumIterations = [&CopyTransformer, &LoopHelper]() -> Expr * { 14510 return AssertSuccess( 14511 CopyTransformer.TransformExpr(LoopHelper.NumIterations)); 14512 }; 14513 14514 // Inner For init-statement: auto .unroll_inner.iv = .unrolled.iv 14515 ExprResult LValueConv = DefaultLvalueConversion(MakeOuterRef()); 14516 AddInitializerToDecl(InnerIVDecl, LValueConv.get(), /*DirectInit=*/false); 14517 StmtResult InnerInit = new (Context) 14518 DeclStmt(DeclGroupRef(InnerIVDecl), OrigVarLocBegin, OrigVarLocEnd); 14519 if (!InnerInit.isUsable()) 14520 return StmtError(); 14521 14522 // Inner For cond-expression: 14523 // \code 14524 // .unroll_inner.iv < .unrolled.iv + Factor && 14525 // .unroll_inner.iv < NumIterations 14526 // \endcode 14527 // This conjunction of two conditions allows ScalarEvolution to derive the 14528 // maximum trip count of the inner loop. 14529 ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 14530 BO_Add, MakeOuterRef(), MakeFactorExpr()); 14531 if (!EndOfTile.isUsable()) 14532 return StmtError(); 14533 ExprResult InnerCond1 = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 14534 BO_LT, MakeInnerRef(), EndOfTile.get()); 14535 if (!InnerCond1.isUsable()) 14536 return StmtError(); 14537 ExprResult InnerCond2 = 14538 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, MakeInnerRef(), 14539 MakeNumIterations()); 14540 if (!InnerCond2.isUsable()) 14541 return StmtError(); 14542 ExprResult InnerCond = 14543 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LAnd, 14544 InnerCond1.get(), InnerCond2.get()); 14545 if (!InnerCond.isUsable()) 14546 return StmtError(); 14547 14548 // Inner For incr-statement: ++.unroll_inner.iv 14549 ExprResult InnerIncr = BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), 14550 UO_PreInc, MakeInnerRef()); 14551 if (!InnerIncr.isUsable()) 14552 return StmtError(); 14553 14554 // Inner For statement. 14555 SmallVector<Stmt *> InnerBodyStmts; 14556 InnerBodyStmts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end()); 14557 InnerBodyStmts.push_back(Body); 14558 CompoundStmt *InnerBody = CompoundStmt::Create( 14559 Context, InnerBodyStmts, Body->getBeginLoc(), Body->getEndLoc()); 14560 ForStmt *InnerFor = new (Context) 14561 ForStmt(Context, InnerInit.get(), InnerCond.get(), nullptr, 14562 InnerIncr.get(), InnerBody, LoopHelper.Init->getBeginLoc(), 14563 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 14564 14565 // Unroll metadata for the inner loop. 14566 // This needs to take into account the remainder portion of the unrolled loop, 14567 // hence `unroll(full)` does not apply here, even though the LoopUnroll pass 14568 // supports multiple loop exits. Instead, unroll using a factor equivalent to 14569 // the maximum trip count, which will also generate a remainder loop. Just 14570 // `unroll(enable)` (which could have been useful if the user has not 14571 // specified a concrete factor; even though the outer loop cannot be 14572 // influenced anymore, would avoid more code bloat than necessary) will refuse 14573 // the loop because "Won't unroll; remainder loop could not be generated when 14574 // assuming runtime trip count". Even if it did work, it must not choose a 14575 // larger unroll factor than the maximum loop length, or it would always just 14576 // execute the remainder loop. 14577 LoopHintAttr *UnrollHintAttr = 14578 LoopHintAttr::CreateImplicit(Context, LoopHintAttr::UnrollCount, 14579 LoopHintAttr::Numeric, MakeFactorExpr()); 14580 AttributedStmt *InnerUnrolled = 14581 AttributedStmt::Create(Context, StartLoc, {UnrollHintAttr}, InnerFor); 14582 14583 // Outer For init-statement: auto .unrolled.iv = 0 14584 AddInitializerToDecl( 14585 OuterIVDecl, ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(), 14586 /*DirectInit=*/false); 14587 StmtResult OuterInit = new (Context) 14588 DeclStmt(DeclGroupRef(OuterIVDecl), OrigVarLocBegin, OrigVarLocEnd); 14589 if (!OuterInit.isUsable()) 14590 return StmtError(); 14591 14592 // Outer For cond-expression: .unrolled.iv < NumIterations 14593 ExprResult OuterConde = 14594 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, MakeOuterRef(), 14595 MakeNumIterations()); 14596 if (!OuterConde.isUsable()) 14597 return StmtError(); 14598 14599 // Outer For incr-statement: .unrolled.iv += Factor 14600 ExprResult OuterIncr = 14601 BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), BO_AddAssign, 14602 MakeOuterRef(), MakeFactorExpr()); 14603 if (!OuterIncr.isUsable()) 14604 return StmtError(); 14605 14606 // Outer For statement. 14607 ForStmt *OuterFor = new (Context) 14608 ForStmt(Context, OuterInit.get(), OuterConde.get(), nullptr, 14609 OuterIncr.get(), InnerUnrolled, LoopHelper.Init->getBeginLoc(), 14610 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 14611 14612 return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 14613 NumGeneratedLoops, OuterFor, 14614 buildPreInits(Context, PreInits)); 14615 } 14616 14617 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 14618 SourceLocation StartLoc, 14619 SourceLocation LParenLoc, 14620 SourceLocation EndLoc) { 14621 OMPClause *Res = nullptr; 14622 switch (Kind) { 14623 case OMPC_final: 14624 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 14625 break; 14626 case OMPC_num_threads: 14627 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 14628 break; 14629 case OMPC_safelen: 14630 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 14631 break; 14632 case OMPC_simdlen: 14633 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 14634 break; 14635 case OMPC_allocator: 14636 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc); 14637 break; 14638 case OMPC_collapse: 14639 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 14640 break; 14641 case OMPC_ordered: 14642 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 14643 break; 14644 case OMPC_num_teams: 14645 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 14646 break; 14647 case OMPC_thread_limit: 14648 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 14649 break; 14650 case OMPC_priority: 14651 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 14652 break; 14653 case OMPC_grainsize: 14654 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 14655 break; 14656 case OMPC_num_tasks: 14657 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 14658 break; 14659 case OMPC_hint: 14660 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 14661 break; 14662 case OMPC_depobj: 14663 Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc); 14664 break; 14665 case OMPC_detach: 14666 Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc); 14667 break; 14668 case OMPC_novariants: 14669 Res = ActOnOpenMPNovariantsClause(Expr, StartLoc, LParenLoc, EndLoc); 14670 break; 14671 case OMPC_nocontext: 14672 Res = ActOnOpenMPNocontextClause(Expr, StartLoc, LParenLoc, EndLoc); 14673 break; 14674 case OMPC_filter: 14675 Res = ActOnOpenMPFilterClause(Expr, StartLoc, LParenLoc, EndLoc); 14676 break; 14677 case OMPC_partial: 14678 Res = ActOnOpenMPPartialClause(Expr, StartLoc, LParenLoc, EndLoc); 14679 break; 14680 case OMPC_align: 14681 Res = ActOnOpenMPAlignClause(Expr, StartLoc, LParenLoc, EndLoc); 14682 break; 14683 case OMPC_device: 14684 case OMPC_if: 14685 case OMPC_default: 14686 case OMPC_proc_bind: 14687 case OMPC_schedule: 14688 case OMPC_private: 14689 case OMPC_firstprivate: 14690 case OMPC_lastprivate: 14691 case OMPC_shared: 14692 case OMPC_reduction: 14693 case OMPC_task_reduction: 14694 case OMPC_in_reduction: 14695 case OMPC_linear: 14696 case OMPC_aligned: 14697 case OMPC_copyin: 14698 case OMPC_copyprivate: 14699 case OMPC_nowait: 14700 case OMPC_untied: 14701 case OMPC_mergeable: 14702 case OMPC_threadprivate: 14703 case OMPC_sizes: 14704 case OMPC_allocate: 14705 case OMPC_flush: 14706 case OMPC_read: 14707 case OMPC_write: 14708 case OMPC_update: 14709 case OMPC_capture: 14710 case OMPC_compare: 14711 case OMPC_seq_cst: 14712 case OMPC_acq_rel: 14713 case OMPC_acquire: 14714 case OMPC_release: 14715 case OMPC_relaxed: 14716 case OMPC_depend: 14717 case OMPC_threads: 14718 case OMPC_simd: 14719 case OMPC_map: 14720 case OMPC_nogroup: 14721 case OMPC_dist_schedule: 14722 case OMPC_defaultmap: 14723 case OMPC_unknown: 14724 case OMPC_uniform: 14725 case OMPC_to: 14726 case OMPC_from: 14727 case OMPC_use_device_ptr: 14728 case OMPC_use_device_addr: 14729 case OMPC_is_device_ptr: 14730 case OMPC_unified_address: 14731 case OMPC_unified_shared_memory: 14732 case OMPC_reverse_offload: 14733 case OMPC_dynamic_allocators: 14734 case OMPC_atomic_default_mem_order: 14735 case OMPC_device_type: 14736 case OMPC_match: 14737 case OMPC_nontemporal: 14738 case OMPC_order: 14739 case OMPC_destroy: 14740 case OMPC_inclusive: 14741 case OMPC_exclusive: 14742 case OMPC_uses_allocators: 14743 case OMPC_affinity: 14744 case OMPC_when: 14745 case OMPC_bind: 14746 default: 14747 llvm_unreachable("Clause is not allowed."); 14748 } 14749 return Res; 14750 } 14751 14752 // An OpenMP directive such as 'target parallel' has two captured regions: 14753 // for the 'target' and 'parallel' respectively. This function returns 14754 // the region in which to capture expressions associated with a clause. 14755 // A return value of OMPD_unknown signifies that the expression should not 14756 // be captured. 14757 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 14758 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion, 14759 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 14760 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 14761 switch (CKind) { 14762 case OMPC_if: 14763 switch (DKind) { 14764 case OMPD_target_parallel_for_simd: 14765 if (OpenMPVersion >= 50 && 14766 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 14767 CaptureRegion = OMPD_parallel; 14768 break; 14769 } 14770 LLVM_FALLTHROUGH; 14771 case OMPD_target_parallel: 14772 case OMPD_target_parallel_for: 14773 case OMPD_target_parallel_loop: 14774 // If this clause applies to the nested 'parallel' region, capture within 14775 // the 'target' region, otherwise do not capture. 14776 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 14777 CaptureRegion = OMPD_target; 14778 break; 14779 case OMPD_target_teams_distribute_parallel_for_simd: 14780 if (OpenMPVersion >= 50 && 14781 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 14782 CaptureRegion = OMPD_parallel; 14783 break; 14784 } 14785 LLVM_FALLTHROUGH; 14786 case OMPD_target_teams_distribute_parallel_for: 14787 // If this clause applies to the nested 'parallel' region, capture within 14788 // the 'teams' region, otherwise do not capture. 14789 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 14790 CaptureRegion = OMPD_teams; 14791 break; 14792 case OMPD_teams_distribute_parallel_for_simd: 14793 if (OpenMPVersion >= 50 && 14794 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 14795 CaptureRegion = OMPD_parallel; 14796 break; 14797 } 14798 LLVM_FALLTHROUGH; 14799 case OMPD_teams_distribute_parallel_for: 14800 CaptureRegion = OMPD_teams; 14801 break; 14802 case OMPD_target_update: 14803 case OMPD_target_enter_data: 14804 case OMPD_target_exit_data: 14805 CaptureRegion = OMPD_task; 14806 break; 14807 case OMPD_parallel_master_taskloop: 14808 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop) 14809 CaptureRegion = OMPD_parallel; 14810 break; 14811 case OMPD_parallel_master_taskloop_simd: 14812 if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) || 14813 NameModifier == OMPD_taskloop) { 14814 CaptureRegion = OMPD_parallel; 14815 break; 14816 } 14817 if (OpenMPVersion <= 45) 14818 break; 14819 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 14820 CaptureRegion = OMPD_taskloop; 14821 break; 14822 case OMPD_parallel_for_simd: 14823 if (OpenMPVersion <= 45) 14824 break; 14825 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 14826 CaptureRegion = OMPD_parallel; 14827 break; 14828 case OMPD_taskloop_simd: 14829 case OMPD_master_taskloop_simd: 14830 if (OpenMPVersion <= 45) 14831 break; 14832 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 14833 CaptureRegion = OMPD_taskloop; 14834 break; 14835 case OMPD_distribute_parallel_for_simd: 14836 if (OpenMPVersion <= 45) 14837 break; 14838 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 14839 CaptureRegion = OMPD_parallel; 14840 break; 14841 case OMPD_target_simd: 14842 if (OpenMPVersion >= 50 && 14843 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) 14844 CaptureRegion = OMPD_target; 14845 break; 14846 case OMPD_teams_distribute_simd: 14847 case OMPD_target_teams_distribute_simd: 14848 if (OpenMPVersion >= 50 && 14849 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) 14850 CaptureRegion = OMPD_teams; 14851 break; 14852 case OMPD_cancel: 14853 case OMPD_parallel: 14854 case OMPD_parallel_master: 14855 case OMPD_parallel_masked: 14856 case OMPD_parallel_sections: 14857 case OMPD_parallel_for: 14858 case OMPD_parallel_loop: 14859 case OMPD_target: 14860 case OMPD_target_teams: 14861 case OMPD_target_teams_distribute: 14862 case OMPD_target_teams_loop: 14863 case OMPD_distribute_parallel_for: 14864 case OMPD_task: 14865 case OMPD_taskloop: 14866 case OMPD_master_taskloop: 14867 case OMPD_target_data: 14868 case OMPD_simd: 14869 case OMPD_for_simd: 14870 case OMPD_distribute_simd: 14871 // Do not capture if-clause expressions. 14872 break; 14873 case OMPD_threadprivate: 14874 case OMPD_allocate: 14875 case OMPD_taskyield: 14876 case OMPD_barrier: 14877 case OMPD_taskwait: 14878 case OMPD_cancellation_point: 14879 case OMPD_flush: 14880 case OMPD_depobj: 14881 case OMPD_scan: 14882 case OMPD_declare_reduction: 14883 case OMPD_declare_mapper: 14884 case OMPD_declare_simd: 14885 case OMPD_declare_variant: 14886 case OMPD_begin_declare_variant: 14887 case OMPD_end_declare_variant: 14888 case OMPD_declare_target: 14889 case OMPD_end_declare_target: 14890 case OMPD_loop: 14891 case OMPD_teams_loop: 14892 case OMPD_teams: 14893 case OMPD_tile: 14894 case OMPD_unroll: 14895 case OMPD_for: 14896 case OMPD_sections: 14897 case OMPD_section: 14898 case OMPD_single: 14899 case OMPD_master: 14900 case OMPD_masked: 14901 case OMPD_critical: 14902 case OMPD_taskgroup: 14903 case OMPD_distribute: 14904 case OMPD_ordered: 14905 case OMPD_atomic: 14906 case OMPD_teams_distribute: 14907 case OMPD_requires: 14908 case OMPD_metadirective: 14909 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 14910 case OMPD_unknown: 14911 default: 14912 llvm_unreachable("Unknown OpenMP directive"); 14913 } 14914 break; 14915 case OMPC_num_threads: 14916 switch (DKind) { 14917 case OMPD_target_parallel: 14918 case OMPD_target_parallel_for: 14919 case OMPD_target_parallel_for_simd: 14920 case OMPD_target_parallel_loop: 14921 CaptureRegion = OMPD_target; 14922 break; 14923 case OMPD_teams_distribute_parallel_for: 14924 case OMPD_teams_distribute_parallel_for_simd: 14925 case OMPD_target_teams_distribute_parallel_for: 14926 case OMPD_target_teams_distribute_parallel_for_simd: 14927 CaptureRegion = OMPD_teams; 14928 break; 14929 case OMPD_parallel: 14930 case OMPD_parallel_master: 14931 case OMPD_parallel_masked: 14932 case OMPD_parallel_sections: 14933 case OMPD_parallel_for: 14934 case OMPD_parallel_for_simd: 14935 case OMPD_parallel_loop: 14936 case OMPD_distribute_parallel_for: 14937 case OMPD_distribute_parallel_for_simd: 14938 case OMPD_parallel_master_taskloop: 14939 case OMPD_parallel_master_taskloop_simd: 14940 // Do not capture num_threads-clause expressions. 14941 break; 14942 case OMPD_target_data: 14943 case OMPD_target_enter_data: 14944 case OMPD_target_exit_data: 14945 case OMPD_target_update: 14946 case OMPD_target: 14947 case OMPD_target_simd: 14948 case OMPD_target_teams: 14949 case OMPD_target_teams_distribute: 14950 case OMPD_target_teams_distribute_simd: 14951 case OMPD_cancel: 14952 case OMPD_task: 14953 case OMPD_taskloop: 14954 case OMPD_taskloop_simd: 14955 case OMPD_master_taskloop: 14956 case OMPD_master_taskloop_simd: 14957 case OMPD_threadprivate: 14958 case OMPD_allocate: 14959 case OMPD_taskyield: 14960 case OMPD_barrier: 14961 case OMPD_taskwait: 14962 case OMPD_cancellation_point: 14963 case OMPD_flush: 14964 case OMPD_depobj: 14965 case OMPD_scan: 14966 case OMPD_declare_reduction: 14967 case OMPD_declare_mapper: 14968 case OMPD_declare_simd: 14969 case OMPD_declare_variant: 14970 case OMPD_begin_declare_variant: 14971 case OMPD_end_declare_variant: 14972 case OMPD_declare_target: 14973 case OMPD_end_declare_target: 14974 case OMPD_loop: 14975 case OMPD_teams_loop: 14976 case OMPD_target_teams_loop: 14977 case OMPD_teams: 14978 case OMPD_simd: 14979 case OMPD_tile: 14980 case OMPD_unroll: 14981 case OMPD_for: 14982 case OMPD_for_simd: 14983 case OMPD_sections: 14984 case OMPD_section: 14985 case OMPD_single: 14986 case OMPD_master: 14987 case OMPD_masked: 14988 case OMPD_critical: 14989 case OMPD_taskgroup: 14990 case OMPD_distribute: 14991 case OMPD_ordered: 14992 case OMPD_atomic: 14993 case OMPD_distribute_simd: 14994 case OMPD_teams_distribute: 14995 case OMPD_teams_distribute_simd: 14996 case OMPD_requires: 14997 case OMPD_metadirective: 14998 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 14999 case OMPD_unknown: 15000 default: 15001 llvm_unreachable("Unknown OpenMP directive"); 15002 } 15003 break; 15004 case OMPC_num_teams: 15005 switch (DKind) { 15006 case OMPD_target_teams: 15007 case OMPD_target_teams_distribute: 15008 case OMPD_target_teams_distribute_simd: 15009 case OMPD_target_teams_distribute_parallel_for: 15010 case OMPD_target_teams_distribute_parallel_for_simd: 15011 case OMPD_target_teams_loop: 15012 CaptureRegion = OMPD_target; 15013 break; 15014 case OMPD_teams_distribute_parallel_for: 15015 case OMPD_teams_distribute_parallel_for_simd: 15016 case OMPD_teams: 15017 case OMPD_teams_distribute: 15018 case OMPD_teams_distribute_simd: 15019 case OMPD_teams_loop: 15020 // Do not capture num_teams-clause expressions. 15021 break; 15022 case OMPD_distribute_parallel_for: 15023 case OMPD_distribute_parallel_for_simd: 15024 case OMPD_task: 15025 case OMPD_taskloop: 15026 case OMPD_taskloop_simd: 15027 case OMPD_master_taskloop: 15028 case OMPD_master_taskloop_simd: 15029 case OMPD_parallel_master_taskloop: 15030 case OMPD_parallel_master_taskloop_simd: 15031 case OMPD_target_data: 15032 case OMPD_target_enter_data: 15033 case OMPD_target_exit_data: 15034 case OMPD_target_update: 15035 case OMPD_cancel: 15036 case OMPD_parallel: 15037 case OMPD_parallel_master: 15038 case OMPD_parallel_masked: 15039 case OMPD_parallel_sections: 15040 case OMPD_parallel_for: 15041 case OMPD_parallel_for_simd: 15042 case OMPD_parallel_loop: 15043 case OMPD_target: 15044 case OMPD_target_simd: 15045 case OMPD_target_parallel: 15046 case OMPD_target_parallel_for: 15047 case OMPD_target_parallel_for_simd: 15048 case OMPD_target_parallel_loop: 15049 case OMPD_threadprivate: 15050 case OMPD_allocate: 15051 case OMPD_taskyield: 15052 case OMPD_barrier: 15053 case OMPD_taskwait: 15054 case OMPD_cancellation_point: 15055 case OMPD_flush: 15056 case OMPD_depobj: 15057 case OMPD_scan: 15058 case OMPD_declare_reduction: 15059 case OMPD_declare_mapper: 15060 case OMPD_declare_simd: 15061 case OMPD_declare_variant: 15062 case OMPD_begin_declare_variant: 15063 case OMPD_end_declare_variant: 15064 case OMPD_declare_target: 15065 case OMPD_end_declare_target: 15066 case OMPD_loop: 15067 case OMPD_simd: 15068 case OMPD_tile: 15069 case OMPD_unroll: 15070 case OMPD_for: 15071 case OMPD_for_simd: 15072 case OMPD_sections: 15073 case OMPD_section: 15074 case OMPD_single: 15075 case OMPD_master: 15076 case OMPD_masked: 15077 case OMPD_critical: 15078 case OMPD_taskgroup: 15079 case OMPD_distribute: 15080 case OMPD_ordered: 15081 case OMPD_atomic: 15082 case OMPD_distribute_simd: 15083 case OMPD_requires: 15084 case OMPD_metadirective: 15085 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 15086 case OMPD_unknown: 15087 default: 15088 llvm_unreachable("Unknown OpenMP directive"); 15089 } 15090 break; 15091 case OMPC_thread_limit: 15092 switch (DKind) { 15093 case OMPD_target_teams: 15094 case OMPD_target_teams_distribute: 15095 case OMPD_target_teams_distribute_simd: 15096 case OMPD_target_teams_distribute_parallel_for: 15097 case OMPD_target_teams_distribute_parallel_for_simd: 15098 case OMPD_target_teams_loop: 15099 CaptureRegion = OMPD_target; 15100 break; 15101 case OMPD_teams_distribute_parallel_for: 15102 case OMPD_teams_distribute_parallel_for_simd: 15103 case OMPD_teams: 15104 case OMPD_teams_distribute: 15105 case OMPD_teams_distribute_simd: 15106 case OMPD_teams_loop: 15107 // Do not capture thread_limit-clause expressions. 15108 break; 15109 case OMPD_distribute_parallel_for: 15110 case OMPD_distribute_parallel_for_simd: 15111 case OMPD_task: 15112 case OMPD_taskloop: 15113 case OMPD_taskloop_simd: 15114 case OMPD_master_taskloop: 15115 case OMPD_master_taskloop_simd: 15116 case OMPD_parallel_master_taskloop: 15117 case OMPD_parallel_master_taskloop_simd: 15118 case OMPD_target_data: 15119 case OMPD_target_enter_data: 15120 case OMPD_target_exit_data: 15121 case OMPD_target_update: 15122 case OMPD_cancel: 15123 case OMPD_parallel: 15124 case OMPD_parallel_master: 15125 case OMPD_parallel_masked: 15126 case OMPD_parallel_sections: 15127 case OMPD_parallel_for: 15128 case OMPD_parallel_for_simd: 15129 case OMPD_parallel_loop: 15130 case OMPD_target: 15131 case OMPD_target_simd: 15132 case OMPD_target_parallel: 15133 case OMPD_target_parallel_for: 15134 case OMPD_target_parallel_for_simd: 15135 case OMPD_target_parallel_loop: 15136 case OMPD_threadprivate: 15137 case OMPD_allocate: 15138 case OMPD_taskyield: 15139 case OMPD_barrier: 15140 case OMPD_taskwait: 15141 case OMPD_cancellation_point: 15142 case OMPD_flush: 15143 case OMPD_depobj: 15144 case OMPD_scan: 15145 case OMPD_declare_reduction: 15146 case OMPD_declare_mapper: 15147 case OMPD_declare_simd: 15148 case OMPD_declare_variant: 15149 case OMPD_begin_declare_variant: 15150 case OMPD_end_declare_variant: 15151 case OMPD_declare_target: 15152 case OMPD_end_declare_target: 15153 case OMPD_loop: 15154 case OMPD_simd: 15155 case OMPD_tile: 15156 case OMPD_unroll: 15157 case OMPD_for: 15158 case OMPD_for_simd: 15159 case OMPD_sections: 15160 case OMPD_section: 15161 case OMPD_single: 15162 case OMPD_master: 15163 case OMPD_masked: 15164 case OMPD_critical: 15165 case OMPD_taskgroup: 15166 case OMPD_distribute: 15167 case OMPD_ordered: 15168 case OMPD_atomic: 15169 case OMPD_distribute_simd: 15170 case OMPD_requires: 15171 case OMPD_metadirective: 15172 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 15173 case OMPD_unknown: 15174 default: 15175 llvm_unreachable("Unknown OpenMP directive"); 15176 } 15177 break; 15178 case OMPC_schedule: 15179 switch (DKind) { 15180 case OMPD_parallel_for: 15181 case OMPD_parallel_for_simd: 15182 case OMPD_distribute_parallel_for: 15183 case OMPD_distribute_parallel_for_simd: 15184 case OMPD_teams_distribute_parallel_for: 15185 case OMPD_teams_distribute_parallel_for_simd: 15186 case OMPD_target_parallel_for: 15187 case OMPD_target_parallel_for_simd: 15188 case OMPD_target_teams_distribute_parallel_for: 15189 case OMPD_target_teams_distribute_parallel_for_simd: 15190 CaptureRegion = OMPD_parallel; 15191 break; 15192 case OMPD_for: 15193 case OMPD_for_simd: 15194 // Do not capture schedule-clause expressions. 15195 break; 15196 case OMPD_task: 15197 case OMPD_taskloop: 15198 case OMPD_taskloop_simd: 15199 case OMPD_master_taskloop: 15200 case OMPD_master_taskloop_simd: 15201 case OMPD_parallel_master_taskloop: 15202 case OMPD_parallel_master_taskloop_simd: 15203 case OMPD_target_data: 15204 case OMPD_target_enter_data: 15205 case OMPD_target_exit_data: 15206 case OMPD_target_update: 15207 case OMPD_teams: 15208 case OMPD_teams_distribute: 15209 case OMPD_teams_distribute_simd: 15210 case OMPD_target_teams_distribute: 15211 case OMPD_target_teams_distribute_simd: 15212 case OMPD_target: 15213 case OMPD_target_simd: 15214 case OMPD_target_parallel: 15215 case OMPD_cancel: 15216 case OMPD_parallel: 15217 case OMPD_parallel_master: 15218 case OMPD_parallel_masked: 15219 case OMPD_parallel_sections: 15220 case OMPD_threadprivate: 15221 case OMPD_allocate: 15222 case OMPD_taskyield: 15223 case OMPD_barrier: 15224 case OMPD_taskwait: 15225 case OMPD_cancellation_point: 15226 case OMPD_flush: 15227 case OMPD_depobj: 15228 case OMPD_scan: 15229 case OMPD_declare_reduction: 15230 case OMPD_declare_mapper: 15231 case OMPD_declare_simd: 15232 case OMPD_declare_variant: 15233 case OMPD_begin_declare_variant: 15234 case OMPD_end_declare_variant: 15235 case OMPD_declare_target: 15236 case OMPD_end_declare_target: 15237 case OMPD_loop: 15238 case OMPD_teams_loop: 15239 case OMPD_target_teams_loop: 15240 case OMPD_parallel_loop: 15241 case OMPD_target_parallel_loop: 15242 case OMPD_simd: 15243 case OMPD_tile: 15244 case OMPD_unroll: 15245 case OMPD_sections: 15246 case OMPD_section: 15247 case OMPD_single: 15248 case OMPD_master: 15249 case OMPD_masked: 15250 case OMPD_critical: 15251 case OMPD_taskgroup: 15252 case OMPD_distribute: 15253 case OMPD_ordered: 15254 case OMPD_atomic: 15255 case OMPD_distribute_simd: 15256 case OMPD_target_teams: 15257 case OMPD_requires: 15258 case OMPD_metadirective: 15259 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 15260 case OMPD_unknown: 15261 default: 15262 llvm_unreachable("Unknown OpenMP directive"); 15263 } 15264 break; 15265 case OMPC_dist_schedule: 15266 switch (DKind) { 15267 case OMPD_teams_distribute_parallel_for: 15268 case OMPD_teams_distribute_parallel_for_simd: 15269 case OMPD_teams_distribute: 15270 case OMPD_teams_distribute_simd: 15271 case OMPD_target_teams_distribute_parallel_for: 15272 case OMPD_target_teams_distribute_parallel_for_simd: 15273 case OMPD_target_teams_distribute: 15274 case OMPD_target_teams_distribute_simd: 15275 CaptureRegion = OMPD_teams; 15276 break; 15277 case OMPD_distribute_parallel_for: 15278 case OMPD_distribute_parallel_for_simd: 15279 case OMPD_distribute: 15280 case OMPD_distribute_simd: 15281 // Do not capture dist_schedule-clause expressions. 15282 break; 15283 case OMPD_parallel_for: 15284 case OMPD_parallel_for_simd: 15285 case OMPD_target_parallel_for_simd: 15286 case OMPD_target_parallel_for: 15287 case OMPD_task: 15288 case OMPD_taskloop: 15289 case OMPD_taskloop_simd: 15290 case OMPD_master_taskloop: 15291 case OMPD_master_taskloop_simd: 15292 case OMPD_parallel_master_taskloop: 15293 case OMPD_parallel_master_taskloop_simd: 15294 case OMPD_target_data: 15295 case OMPD_target_enter_data: 15296 case OMPD_target_exit_data: 15297 case OMPD_target_update: 15298 case OMPD_teams: 15299 case OMPD_target: 15300 case OMPD_target_simd: 15301 case OMPD_target_parallel: 15302 case OMPD_cancel: 15303 case OMPD_parallel: 15304 case OMPD_parallel_master: 15305 case OMPD_parallel_masked: 15306 case OMPD_parallel_sections: 15307 case OMPD_threadprivate: 15308 case OMPD_allocate: 15309 case OMPD_taskyield: 15310 case OMPD_barrier: 15311 case OMPD_taskwait: 15312 case OMPD_cancellation_point: 15313 case OMPD_flush: 15314 case OMPD_depobj: 15315 case OMPD_scan: 15316 case OMPD_declare_reduction: 15317 case OMPD_declare_mapper: 15318 case OMPD_declare_simd: 15319 case OMPD_declare_variant: 15320 case OMPD_begin_declare_variant: 15321 case OMPD_end_declare_variant: 15322 case OMPD_declare_target: 15323 case OMPD_end_declare_target: 15324 case OMPD_loop: 15325 case OMPD_teams_loop: 15326 case OMPD_target_teams_loop: 15327 case OMPD_parallel_loop: 15328 case OMPD_target_parallel_loop: 15329 case OMPD_simd: 15330 case OMPD_tile: 15331 case OMPD_unroll: 15332 case OMPD_for: 15333 case OMPD_for_simd: 15334 case OMPD_sections: 15335 case OMPD_section: 15336 case OMPD_single: 15337 case OMPD_master: 15338 case OMPD_masked: 15339 case OMPD_critical: 15340 case OMPD_taskgroup: 15341 case OMPD_ordered: 15342 case OMPD_atomic: 15343 case OMPD_target_teams: 15344 case OMPD_requires: 15345 case OMPD_metadirective: 15346 llvm_unreachable("Unexpected OpenMP directive with dist_schedule clause"); 15347 case OMPD_unknown: 15348 default: 15349 llvm_unreachable("Unknown OpenMP directive"); 15350 } 15351 break; 15352 case OMPC_device: 15353 switch (DKind) { 15354 case OMPD_target_update: 15355 case OMPD_target_enter_data: 15356 case OMPD_target_exit_data: 15357 case OMPD_target: 15358 case OMPD_target_simd: 15359 case OMPD_target_teams: 15360 case OMPD_target_parallel: 15361 case OMPD_target_teams_distribute: 15362 case OMPD_target_teams_distribute_simd: 15363 case OMPD_target_parallel_for: 15364 case OMPD_target_parallel_for_simd: 15365 case OMPD_target_parallel_loop: 15366 case OMPD_target_teams_distribute_parallel_for: 15367 case OMPD_target_teams_distribute_parallel_for_simd: 15368 case OMPD_target_teams_loop: 15369 case OMPD_dispatch: 15370 CaptureRegion = OMPD_task; 15371 break; 15372 case OMPD_target_data: 15373 case OMPD_interop: 15374 // Do not capture device-clause expressions. 15375 break; 15376 case OMPD_teams_distribute_parallel_for: 15377 case OMPD_teams_distribute_parallel_for_simd: 15378 case OMPD_teams: 15379 case OMPD_teams_distribute: 15380 case OMPD_teams_distribute_simd: 15381 case OMPD_distribute_parallel_for: 15382 case OMPD_distribute_parallel_for_simd: 15383 case OMPD_task: 15384 case OMPD_taskloop: 15385 case OMPD_taskloop_simd: 15386 case OMPD_master_taskloop: 15387 case OMPD_master_taskloop_simd: 15388 case OMPD_parallel_master_taskloop: 15389 case OMPD_parallel_master_taskloop_simd: 15390 case OMPD_cancel: 15391 case OMPD_parallel: 15392 case OMPD_parallel_master: 15393 case OMPD_parallel_masked: 15394 case OMPD_parallel_sections: 15395 case OMPD_parallel_for: 15396 case OMPD_parallel_for_simd: 15397 case OMPD_threadprivate: 15398 case OMPD_allocate: 15399 case OMPD_taskyield: 15400 case OMPD_barrier: 15401 case OMPD_taskwait: 15402 case OMPD_cancellation_point: 15403 case OMPD_flush: 15404 case OMPD_depobj: 15405 case OMPD_scan: 15406 case OMPD_declare_reduction: 15407 case OMPD_declare_mapper: 15408 case OMPD_declare_simd: 15409 case OMPD_declare_variant: 15410 case OMPD_begin_declare_variant: 15411 case OMPD_end_declare_variant: 15412 case OMPD_declare_target: 15413 case OMPD_end_declare_target: 15414 case OMPD_loop: 15415 case OMPD_teams_loop: 15416 case OMPD_parallel_loop: 15417 case OMPD_simd: 15418 case OMPD_tile: 15419 case OMPD_unroll: 15420 case OMPD_for: 15421 case OMPD_for_simd: 15422 case OMPD_sections: 15423 case OMPD_section: 15424 case OMPD_single: 15425 case OMPD_master: 15426 case OMPD_masked: 15427 case OMPD_critical: 15428 case OMPD_taskgroup: 15429 case OMPD_distribute: 15430 case OMPD_ordered: 15431 case OMPD_atomic: 15432 case OMPD_distribute_simd: 15433 case OMPD_requires: 15434 case OMPD_metadirective: 15435 llvm_unreachable("Unexpected OpenMP directive with device-clause"); 15436 case OMPD_unknown: 15437 default: 15438 llvm_unreachable("Unknown OpenMP directive"); 15439 } 15440 break; 15441 case OMPC_grainsize: 15442 case OMPC_num_tasks: 15443 case OMPC_final: 15444 case OMPC_priority: 15445 switch (DKind) { 15446 case OMPD_task: 15447 case OMPD_taskloop: 15448 case OMPD_taskloop_simd: 15449 case OMPD_master_taskloop: 15450 case OMPD_master_taskloop_simd: 15451 break; 15452 case OMPD_parallel_master_taskloop: 15453 case OMPD_parallel_master_taskloop_simd: 15454 CaptureRegion = OMPD_parallel; 15455 break; 15456 case OMPD_target_update: 15457 case OMPD_target_enter_data: 15458 case OMPD_target_exit_data: 15459 case OMPD_target: 15460 case OMPD_target_simd: 15461 case OMPD_target_teams: 15462 case OMPD_target_parallel: 15463 case OMPD_target_teams_distribute: 15464 case OMPD_target_teams_distribute_simd: 15465 case OMPD_target_parallel_for: 15466 case OMPD_target_parallel_for_simd: 15467 case OMPD_target_teams_distribute_parallel_for: 15468 case OMPD_target_teams_distribute_parallel_for_simd: 15469 case OMPD_target_data: 15470 case OMPD_teams_distribute_parallel_for: 15471 case OMPD_teams_distribute_parallel_for_simd: 15472 case OMPD_teams: 15473 case OMPD_teams_distribute: 15474 case OMPD_teams_distribute_simd: 15475 case OMPD_distribute_parallel_for: 15476 case OMPD_distribute_parallel_for_simd: 15477 case OMPD_cancel: 15478 case OMPD_parallel: 15479 case OMPD_parallel_master: 15480 case OMPD_parallel_masked: 15481 case OMPD_parallel_sections: 15482 case OMPD_parallel_for: 15483 case OMPD_parallel_for_simd: 15484 case OMPD_threadprivate: 15485 case OMPD_allocate: 15486 case OMPD_taskyield: 15487 case OMPD_barrier: 15488 case OMPD_taskwait: 15489 case OMPD_cancellation_point: 15490 case OMPD_flush: 15491 case OMPD_depobj: 15492 case OMPD_scan: 15493 case OMPD_declare_reduction: 15494 case OMPD_declare_mapper: 15495 case OMPD_declare_simd: 15496 case OMPD_declare_variant: 15497 case OMPD_begin_declare_variant: 15498 case OMPD_end_declare_variant: 15499 case OMPD_declare_target: 15500 case OMPD_end_declare_target: 15501 case OMPD_loop: 15502 case OMPD_teams_loop: 15503 case OMPD_target_teams_loop: 15504 case OMPD_parallel_loop: 15505 case OMPD_target_parallel_loop: 15506 case OMPD_simd: 15507 case OMPD_tile: 15508 case OMPD_unroll: 15509 case OMPD_for: 15510 case OMPD_for_simd: 15511 case OMPD_sections: 15512 case OMPD_section: 15513 case OMPD_single: 15514 case OMPD_master: 15515 case OMPD_masked: 15516 case OMPD_critical: 15517 case OMPD_taskgroup: 15518 case OMPD_distribute: 15519 case OMPD_ordered: 15520 case OMPD_atomic: 15521 case OMPD_distribute_simd: 15522 case OMPD_requires: 15523 case OMPD_metadirective: 15524 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause"); 15525 case OMPD_unknown: 15526 default: 15527 llvm_unreachable("Unknown OpenMP directive"); 15528 } 15529 break; 15530 case OMPC_novariants: 15531 case OMPC_nocontext: 15532 switch (DKind) { 15533 case OMPD_dispatch: 15534 CaptureRegion = OMPD_task; 15535 break; 15536 default: 15537 llvm_unreachable("Unexpected OpenMP directive"); 15538 } 15539 break; 15540 case OMPC_filter: 15541 // Do not capture filter-clause expressions. 15542 break; 15543 case OMPC_when: 15544 if (DKind == OMPD_metadirective) { 15545 CaptureRegion = OMPD_metadirective; 15546 } else if (DKind == OMPD_unknown) { 15547 llvm_unreachable("Unknown OpenMP directive"); 15548 } else { 15549 llvm_unreachable("Unexpected OpenMP directive with when clause"); 15550 } 15551 break; 15552 case OMPC_firstprivate: 15553 case OMPC_lastprivate: 15554 case OMPC_reduction: 15555 case OMPC_task_reduction: 15556 case OMPC_in_reduction: 15557 case OMPC_linear: 15558 case OMPC_default: 15559 case OMPC_proc_bind: 15560 case OMPC_safelen: 15561 case OMPC_simdlen: 15562 case OMPC_sizes: 15563 case OMPC_allocator: 15564 case OMPC_collapse: 15565 case OMPC_private: 15566 case OMPC_shared: 15567 case OMPC_aligned: 15568 case OMPC_copyin: 15569 case OMPC_copyprivate: 15570 case OMPC_ordered: 15571 case OMPC_nowait: 15572 case OMPC_untied: 15573 case OMPC_mergeable: 15574 case OMPC_threadprivate: 15575 case OMPC_allocate: 15576 case OMPC_flush: 15577 case OMPC_depobj: 15578 case OMPC_read: 15579 case OMPC_write: 15580 case OMPC_update: 15581 case OMPC_capture: 15582 case OMPC_compare: 15583 case OMPC_seq_cst: 15584 case OMPC_acq_rel: 15585 case OMPC_acquire: 15586 case OMPC_release: 15587 case OMPC_relaxed: 15588 case OMPC_depend: 15589 case OMPC_threads: 15590 case OMPC_simd: 15591 case OMPC_map: 15592 case OMPC_nogroup: 15593 case OMPC_hint: 15594 case OMPC_defaultmap: 15595 case OMPC_unknown: 15596 case OMPC_uniform: 15597 case OMPC_to: 15598 case OMPC_from: 15599 case OMPC_use_device_ptr: 15600 case OMPC_use_device_addr: 15601 case OMPC_is_device_ptr: 15602 case OMPC_unified_address: 15603 case OMPC_unified_shared_memory: 15604 case OMPC_reverse_offload: 15605 case OMPC_dynamic_allocators: 15606 case OMPC_atomic_default_mem_order: 15607 case OMPC_device_type: 15608 case OMPC_match: 15609 case OMPC_nontemporal: 15610 case OMPC_order: 15611 case OMPC_destroy: 15612 case OMPC_detach: 15613 case OMPC_inclusive: 15614 case OMPC_exclusive: 15615 case OMPC_uses_allocators: 15616 case OMPC_affinity: 15617 case OMPC_bind: 15618 default: 15619 llvm_unreachable("Unexpected OpenMP clause."); 15620 } 15621 return CaptureRegion; 15622 } 15623 15624 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 15625 Expr *Condition, SourceLocation StartLoc, 15626 SourceLocation LParenLoc, 15627 SourceLocation NameModifierLoc, 15628 SourceLocation ColonLoc, 15629 SourceLocation EndLoc) { 15630 Expr *ValExpr = Condition; 15631 Stmt *HelperValStmt = nullptr; 15632 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 15633 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 15634 !Condition->isInstantiationDependent() && 15635 !Condition->containsUnexpandedParameterPack()) { 15636 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 15637 if (Val.isInvalid()) 15638 return nullptr; 15639 15640 ValExpr = Val.get(); 15641 15642 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 15643 CaptureRegion = getOpenMPCaptureRegionForClause( 15644 DKind, OMPC_if, LangOpts.OpenMP, NameModifier); 15645 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 15646 ValExpr = MakeFullExpr(ValExpr).get(); 15647 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 15648 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 15649 HelperValStmt = buildPreInits(Context, Captures); 15650 } 15651 } 15652 15653 return new (Context) 15654 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 15655 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 15656 } 15657 15658 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 15659 SourceLocation StartLoc, 15660 SourceLocation LParenLoc, 15661 SourceLocation EndLoc) { 15662 Expr *ValExpr = Condition; 15663 Stmt *HelperValStmt = nullptr; 15664 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 15665 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 15666 !Condition->isInstantiationDependent() && 15667 !Condition->containsUnexpandedParameterPack()) { 15668 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 15669 if (Val.isInvalid()) 15670 return nullptr; 15671 15672 ValExpr = MakeFullExpr(Val.get()).get(); 15673 15674 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 15675 CaptureRegion = 15676 getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP); 15677 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 15678 ValExpr = MakeFullExpr(ValExpr).get(); 15679 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 15680 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 15681 HelperValStmt = buildPreInits(Context, Captures); 15682 } 15683 } 15684 15685 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion, 15686 StartLoc, LParenLoc, EndLoc); 15687 } 15688 15689 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 15690 Expr *Op) { 15691 if (!Op) 15692 return ExprError(); 15693 15694 class IntConvertDiagnoser : public ICEConvertDiagnoser { 15695 public: 15696 IntConvertDiagnoser() 15697 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 15698 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 15699 QualType T) override { 15700 return S.Diag(Loc, diag::err_omp_not_integral) << T; 15701 } 15702 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 15703 QualType T) override { 15704 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 15705 } 15706 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 15707 QualType T, 15708 QualType ConvTy) override { 15709 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 15710 } 15711 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 15712 QualType ConvTy) override { 15713 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 15714 << ConvTy->isEnumeralType() << ConvTy; 15715 } 15716 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 15717 QualType T) override { 15718 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 15719 } 15720 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 15721 QualType ConvTy) override { 15722 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 15723 << ConvTy->isEnumeralType() << ConvTy; 15724 } 15725 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 15726 QualType) override { 15727 llvm_unreachable("conversion functions are permitted"); 15728 } 15729 } ConvertDiagnoser; 15730 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 15731 } 15732 15733 static bool 15734 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind, 15735 bool StrictlyPositive, bool BuildCapture = false, 15736 OpenMPDirectiveKind DKind = OMPD_unknown, 15737 OpenMPDirectiveKind *CaptureRegion = nullptr, 15738 Stmt **HelperValStmt = nullptr) { 15739 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 15740 !ValExpr->isInstantiationDependent()) { 15741 SourceLocation Loc = ValExpr->getExprLoc(); 15742 ExprResult Value = 15743 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 15744 if (Value.isInvalid()) 15745 return false; 15746 15747 ValExpr = Value.get(); 15748 // The expression must evaluate to a non-negative integer value. 15749 if (Optional<llvm::APSInt> Result = 15750 ValExpr->getIntegerConstantExpr(SemaRef.Context)) { 15751 if (Result->isSigned() && 15752 !((!StrictlyPositive && Result->isNonNegative()) || 15753 (StrictlyPositive && Result->isStrictlyPositive()))) { 15754 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 15755 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 15756 << ValExpr->getSourceRange(); 15757 return false; 15758 } 15759 } 15760 if (!BuildCapture) 15761 return true; 15762 *CaptureRegion = 15763 getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP); 15764 if (*CaptureRegion != OMPD_unknown && 15765 !SemaRef.CurContext->isDependentContext()) { 15766 ValExpr = SemaRef.MakeFullExpr(ValExpr).get(); 15767 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 15768 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get(); 15769 *HelperValStmt = buildPreInits(SemaRef.Context, Captures); 15770 } 15771 } 15772 return true; 15773 } 15774 15775 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 15776 SourceLocation StartLoc, 15777 SourceLocation LParenLoc, 15778 SourceLocation EndLoc) { 15779 Expr *ValExpr = NumThreads; 15780 Stmt *HelperValStmt = nullptr; 15781 15782 // OpenMP [2.5, Restrictions] 15783 // The num_threads expression must evaluate to a positive integer value. 15784 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 15785 /*StrictlyPositive=*/true)) 15786 return nullptr; 15787 15788 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 15789 OpenMPDirectiveKind CaptureRegion = 15790 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP); 15791 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 15792 ValExpr = MakeFullExpr(ValExpr).get(); 15793 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 15794 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 15795 HelperValStmt = buildPreInits(Context, Captures); 15796 } 15797 15798 return new (Context) OMPNumThreadsClause( 15799 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 15800 } 15801 15802 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 15803 OpenMPClauseKind CKind, 15804 bool StrictlyPositive, 15805 bool SuppressExprDiags) { 15806 if (!E) 15807 return ExprError(); 15808 if (E->isValueDependent() || E->isTypeDependent() || 15809 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 15810 return E; 15811 15812 llvm::APSInt Result; 15813 ExprResult ICE; 15814 if (SuppressExprDiags) { 15815 // Use a custom diagnoser that suppresses 'note' diagnostics about the 15816 // expression. 15817 struct SuppressedDiagnoser : public Sema::VerifyICEDiagnoser { 15818 SuppressedDiagnoser() : VerifyICEDiagnoser(/*Suppress=*/true) {} 15819 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 15820 SourceLocation Loc) override { 15821 llvm_unreachable("Diagnostic suppressed"); 15822 } 15823 } Diagnoser; 15824 ICE = VerifyIntegerConstantExpression(E, &Result, Diagnoser, AllowFold); 15825 } else { 15826 ICE = VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold); 15827 } 15828 if (ICE.isInvalid()) 15829 return ExprError(); 15830 15831 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 15832 (!StrictlyPositive && !Result.isNonNegative())) { 15833 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 15834 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 15835 << E->getSourceRange(); 15836 return ExprError(); 15837 } 15838 if ((CKind == OMPC_aligned || CKind == OMPC_align) && !Result.isPowerOf2()) { 15839 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 15840 << E->getSourceRange(); 15841 return ExprError(); 15842 } 15843 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 15844 DSAStack->setAssociatedLoops(Result.getExtValue()); 15845 else if (CKind == OMPC_ordered) 15846 DSAStack->setAssociatedLoops(Result.getExtValue()); 15847 return ICE; 15848 } 15849 15850 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 15851 SourceLocation LParenLoc, 15852 SourceLocation EndLoc) { 15853 // OpenMP [2.8.1, simd construct, Description] 15854 // The parameter of the safelen clause must be a constant 15855 // positive integer expression. 15856 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 15857 if (Safelen.isInvalid()) 15858 return nullptr; 15859 return new (Context) 15860 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 15861 } 15862 15863 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 15864 SourceLocation LParenLoc, 15865 SourceLocation EndLoc) { 15866 // OpenMP [2.8.1, simd construct, Description] 15867 // The parameter of the simdlen clause must be a constant 15868 // positive integer expression. 15869 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 15870 if (Simdlen.isInvalid()) 15871 return nullptr; 15872 return new (Context) 15873 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 15874 } 15875 15876 /// Tries to find omp_allocator_handle_t type. 15877 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc, 15878 DSAStackTy *Stack) { 15879 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT(); 15880 if (!OMPAllocatorHandleT.isNull()) 15881 return true; 15882 // Build the predefined allocator expressions. 15883 bool ErrorFound = false; 15884 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 15885 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 15886 StringRef Allocator = 15887 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind); 15888 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator); 15889 auto *VD = dyn_cast_or_null<ValueDecl>( 15890 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName)); 15891 if (!VD) { 15892 ErrorFound = true; 15893 break; 15894 } 15895 QualType AllocatorType = 15896 VD->getType().getNonLValueExprType(S.getASTContext()); 15897 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc); 15898 if (!Res.isUsable()) { 15899 ErrorFound = true; 15900 break; 15901 } 15902 if (OMPAllocatorHandleT.isNull()) 15903 OMPAllocatorHandleT = AllocatorType; 15904 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) { 15905 ErrorFound = true; 15906 break; 15907 } 15908 Stack->setAllocator(AllocatorKind, Res.get()); 15909 } 15910 if (ErrorFound) { 15911 S.Diag(Loc, diag::err_omp_implied_type_not_found) 15912 << "omp_allocator_handle_t"; 15913 return false; 15914 } 15915 OMPAllocatorHandleT.addConst(); 15916 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT); 15917 return true; 15918 } 15919 15920 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc, 15921 SourceLocation LParenLoc, 15922 SourceLocation EndLoc) { 15923 // OpenMP [2.11.3, allocate Directive, Description] 15924 // allocator is an expression of omp_allocator_handle_t type. 15925 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack)) 15926 return nullptr; 15927 15928 ExprResult Allocator = DefaultLvalueConversion(A); 15929 if (Allocator.isInvalid()) 15930 return nullptr; 15931 Allocator = PerformImplicitConversion(Allocator.get(), 15932 DSAStack->getOMPAllocatorHandleT(), 15933 Sema::AA_Initializing, 15934 /*AllowExplicit=*/true); 15935 if (Allocator.isInvalid()) 15936 return nullptr; 15937 return new (Context) 15938 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc); 15939 } 15940 15941 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 15942 SourceLocation StartLoc, 15943 SourceLocation LParenLoc, 15944 SourceLocation EndLoc) { 15945 // OpenMP [2.7.1, loop construct, Description] 15946 // OpenMP [2.8.1, simd construct, Description] 15947 // OpenMP [2.9.6, distribute construct, Description] 15948 // The parameter of the collapse clause must be a constant 15949 // positive integer expression. 15950 ExprResult NumForLoopsResult = 15951 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 15952 if (NumForLoopsResult.isInvalid()) 15953 return nullptr; 15954 return new (Context) 15955 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 15956 } 15957 15958 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 15959 SourceLocation EndLoc, 15960 SourceLocation LParenLoc, 15961 Expr *NumForLoops) { 15962 // OpenMP [2.7.1, loop construct, Description] 15963 // OpenMP [2.8.1, simd construct, Description] 15964 // OpenMP [2.9.6, distribute construct, Description] 15965 // The parameter of the ordered clause must be a constant 15966 // positive integer expression if any. 15967 if (NumForLoops && LParenLoc.isValid()) { 15968 ExprResult NumForLoopsResult = 15969 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 15970 if (NumForLoopsResult.isInvalid()) 15971 return nullptr; 15972 NumForLoops = NumForLoopsResult.get(); 15973 } else { 15974 NumForLoops = nullptr; 15975 } 15976 auto *Clause = OMPOrderedClause::Create( 15977 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0, 15978 StartLoc, LParenLoc, EndLoc); 15979 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause); 15980 return Clause; 15981 } 15982 15983 OMPClause *Sema::ActOnOpenMPSimpleClause( 15984 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 15985 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 15986 OMPClause *Res = nullptr; 15987 switch (Kind) { 15988 case OMPC_default: 15989 Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument), 15990 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 15991 break; 15992 case OMPC_proc_bind: 15993 Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument), 15994 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 15995 break; 15996 case OMPC_atomic_default_mem_order: 15997 Res = ActOnOpenMPAtomicDefaultMemOrderClause( 15998 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument), 15999 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 16000 break; 16001 case OMPC_order: 16002 Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument), 16003 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 16004 break; 16005 case OMPC_update: 16006 Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument), 16007 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 16008 break; 16009 case OMPC_bind: 16010 Res = ActOnOpenMPBindClause(static_cast<OpenMPBindClauseKind>(Argument), 16011 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 16012 break; 16013 case OMPC_if: 16014 case OMPC_final: 16015 case OMPC_num_threads: 16016 case OMPC_safelen: 16017 case OMPC_simdlen: 16018 case OMPC_sizes: 16019 case OMPC_allocator: 16020 case OMPC_collapse: 16021 case OMPC_schedule: 16022 case OMPC_private: 16023 case OMPC_firstprivate: 16024 case OMPC_lastprivate: 16025 case OMPC_shared: 16026 case OMPC_reduction: 16027 case OMPC_task_reduction: 16028 case OMPC_in_reduction: 16029 case OMPC_linear: 16030 case OMPC_aligned: 16031 case OMPC_copyin: 16032 case OMPC_copyprivate: 16033 case OMPC_ordered: 16034 case OMPC_nowait: 16035 case OMPC_untied: 16036 case OMPC_mergeable: 16037 case OMPC_threadprivate: 16038 case OMPC_allocate: 16039 case OMPC_flush: 16040 case OMPC_depobj: 16041 case OMPC_read: 16042 case OMPC_write: 16043 case OMPC_capture: 16044 case OMPC_compare: 16045 case OMPC_seq_cst: 16046 case OMPC_acq_rel: 16047 case OMPC_acquire: 16048 case OMPC_release: 16049 case OMPC_relaxed: 16050 case OMPC_depend: 16051 case OMPC_device: 16052 case OMPC_threads: 16053 case OMPC_simd: 16054 case OMPC_map: 16055 case OMPC_num_teams: 16056 case OMPC_thread_limit: 16057 case OMPC_priority: 16058 case OMPC_grainsize: 16059 case OMPC_nogroup: 16060 case OMPC_num_tasks: 16061 case OMPC_hint: 16062 case OMPC_dist_schedule: 16063 case OMPC_defaultmap: 16064 case OMPC_unknown: 16065 case OMPC_uniform: 16066 case OMPC_to: 16067 case OMPC_from: 16068 case OMPC_use_device_ptr: 16069 case OMPC_use_device_addr: 16070 case OMPC_is_device_ptr: 16071 case OMPC_has_device_addr: 16072 case OMPC_unified_address: 16073 case OMPC_unified_shared_memory: 16074 case OMPC_reverse_offload: 16075 case OMPC_dynamic_allocators: 16076 case OMPC_device_type: 16077 case OMPC_match: 16078 case OMPC_nontemporal: 16079 case OMPC_destroy: 16080 case OMPC_novariants: 16081 case OMPC_nocontext: 16082 case OMPC_detach: 16083 case OMPC_inclusive: 16084 case OMPC_exclusive: 16085 case OMPC_uses_allocators: 16086 case OMPC_affinity: 16087 case OMPC_when: 16088 default: 16089 llvm_unreachable("Clause is not allowed."); 16090 } 16091 return Res; 16092 } 16093 16094 static std::string 16095 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 16096 ArrayRef<unsigned> Exclude = llvm::None) { 16097 SmallString<256> Buffer; 16098 llvm::raw_svector_ostream Out(Buffer); 16099 unsigned Skipped = Exclude.size(); 16100 auto S = Exclude.begin(), E = Exclude.end(); 16101 for (unsigned I = First; I < Last; ++I) { 16102 if (std::find(S, E, I) != E) { 16103 --Skipped; 16104 continue; 16105 } 16106 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'"; 16107 if (I + Skipped + 2 == Last) 16108 Out << " or "; 16109 else if (I + Skipped + 1 != Last) 16110 Out << ", "; 16111 } 16112 return std::string(Out.str()); 16113 } 16114 16115 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind, 16116 SourceLocation KindKwLoc, 16117 SourceLocation StartLoc, 16118 SourceLocation LParenLoc, 16119 SourceLocation EndLoc) { 16120 if (Kind == OMP_DEFAULT_unknown) { 16121 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 16122 << getListOfPossibleValues(OMPC_default, /*First=*/0, 16123 /*Last=*/unsigned(OMP_DEFAULT_unknown)) 16124 << getOpenMPClauseName(OMPC_default); 16125 return nullptr; 16126 } 16127 16128 switch (Kind) { 16129 case OMP_DEFAULT_none: 16130 DSAStack->setDefaultDSANone(KindKwLoc); 16131 break; 16132 case OMP_DEFAULT_shared: 16133 DSAStack->setDefaultDSAShared(KindKwLoc); 16134 break; 16135 case OMP_DEFAULT_firstprivate: 16136 DSAStack->setDefaultDSAFirstPrivate(KindKwLoc); 16137 break; 16138 case OMP_DEFAULT_private: 16139 DSAStack->setDefaultDSAPrivate(KindKwLoc); 16140 break; 16141 default: 16142 llvm_unreachable("DSA unexpected in OpenMP default clause"); 16143 } 16144 16145 return new (Context) 16146 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 16147 } 16148 16149 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind, 16150 SourceLocation KindKwLoc, 16151 SourceLocation StartLoc, 16152 SourceLocation LParenLoc, 16153 SourceLocation EndLoc) { 16154 if (Kind == OMP_PROC_BIND_unknown) { 16155 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 16156 << getListOfPossibleValues(OMPC_proc_bind, 16157 /*First=*/unsigned(OMP_PROC_BIND_master), 16158 /*Last=*/ 16159 unsigned(LangOpts.OpenMP > 50 16160 ? OMP_PROC_BIND_primary 16161 : OMP_PROC_BIND_spread) + 16162 1) 16163 << getOpenMPClauseName(OMPC_proc_bind); 16164 return nullptr; 16165 } 16166 if (Kind == OMP_PROC_BIND_primary && LangOpts.OpenMP < 51) 16167 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 16168 << getListOfPossibleValues(OMPC_proc_bind, 16169 /*First=*/unsigned(OMP_PROC_BIND_master), 16170 /*Last=*/ 16171 unsigned(OMP_PROC_BIND_spread) + 1) 16172 << getOpenMPClauseName(OMPC_proc_bind); 16173 return new (Context) 16174 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 16175 } 16176 16177 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause( 16178 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc, 16179 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 16180 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) { 16181 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 16182 << getListOfPossibleValues( 16183 OMPC_atomic_default_mem_order, /*First=*/0, 16184 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) 16185 << getOpenMPClauseName(OMPC_atomic_default_mem_order); 16186 return nullptr; 16187 } 16188 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc, 16189 LParenLoc, EndLoc); 16190 } 16191 16192 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, 16193 SourceLocation KindKwLoc, 16194 SourceLocation StartLoc, 16195 SourceLocation LParenLoc, 16196 SourceLocation EndLoc) { 16197 if (Kind == OMPC_ORDER_unknown) { 16198 static_assert(OMPC_ORDER_unknown > 0, 16199 "OMPC_ORDER_unknown not greater than 0"); 16200 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 16201 << getListOfPossibleValues(OMPC_order, /*First=*/0, 16202 /*Last=*/OMPC_ORDER_unknown) 16203 << getOpenMPClauseName(OMPC_order); 16204 return nullptr; 16205 } 16206 return new (Context) 16207 OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 16208 } 16209 16210 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, 16211 SourceLocation KindKwLoc, 16212 SourceLocation StartLoc, 16213 SourceLocation LParenLoc, 16214 SourceLocation EndLoc) { 16215 if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source || 16216 Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) { 16217 SmallVector<unsigned> Except = { 16218 OMPC_DEPEND_source, OMPC_DEPEND_sink, OMPC_DEPEND_depobj, 16219 OMPC_DEPEND_outallmemory, OMPC_DEPEND_inoutallmemory}; 16220 if (LangOpts.OpenMP < 51) 16221 Except.push_back(OMPC_DEPEND_inoutset); 16222 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 16223 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 16224 /*Last=*/OMPC_DEPEND_unknown, Except) 16225 << getOpenMPClauseName(OMPC_update); 16226 return nullptr; 16227 } 16228 return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind, 16229 EndLoc); 16230 } 16231 16232 OMPClause *Sema::ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs, 16233 SourceLocation StartLoc, 16234 SourceLocation LParenLoc, 16235 SourceLocation EndLoc) { 16236 for (Expr *SizeExpr : SizeExprs) { 16237 ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause( 16238 SizeExpr, OMPC_sizes, /*StrictlyPositive=*/true); 16239 if (!NumForLoopsResult.isUsable()) 16240 return nullptr; 16241 } 16242 16243 DSAStack->setAssociatedLoops(SizeExprs.size()); 16244 return OMPSizesClause::Create(Context, StartLoc, LParenLoc, EndLoc, 16245 SizeExprs); 16246 } 16247 16248 OMPClause *Sema::ActOnOpenMPFullClause(SourceLocation StartLoc, 16249 SourceLocation EndLoc) { 16250 return OMPFullClause::Create(Context, StartLoc, EndLoc); 16251 } 16252 16253 OMPClause *Sema::ActOnOpenMPPartialClause(Expr *FactorExpr, 16254 SourceLocation StartLoc, 16255 SourceLocation LParenLoc, 16256 SourceLocation EndLoc) { 16257 if (FactorExpr) { 16258 // If an argument is specified, it must be a constant (or an unevaluated 16259 // template expression). 16260 ExprResult FactorResult = VerifyPositiveIntegerConstantInClause( 16261 FactorExpr, OMPC_partial, /*StrictlyPositive=*/true); 16262 if (FactorResult.isInvalid()) 16263 return nullptr; 16264 FactorExpr = FactorResult.get(); 16265 } 16266 16267 return OMPPartialClause::Create(Context, StartLoc, LParenLoc, EndLoc, 16268 FactorExpr); 16269 } 16270 16271 OMPClause *Sema::ActOnOpenMPAlignClause(Expr *A, SourceLocation StartLoc, 16272 SourceLocation LParenLoc, 16273 SourceLocation EndLoc) { 16274 ExprResult AlignVal; 16275 AlignVal = VerifyPositiveIntegerConstantInClause(A, OMPC_align); 16276 if (AlignVal.isInvalid()) 16277 return nullptr; 16278 return OMPAlignClause::Create(Context, AlignVal.get(), StartLoc, LParenLoc, 16279 EndLoc); 16280 } 16281 16282 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 16283 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 16284 SourceLocation StartLoc, SourceLocation LParenLoc, 16285 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 16286 SourceLocation EndLoc) { 16287 OMPClause *Res = nullptr; 16288 switch (Kind) { 16289 case OMPC_schedule: 16290 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 16291 assert(Argument.size() == NumberOfElements && 16292 ArgumentLoc.size() == NumberOfElements); 16293 Res = ActOnOpenMPScheduleClause( 16294 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 16295 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 16296 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 16297 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 16298 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 16299 break; 16300 case OMPC_if: 16301 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 16302 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 16303 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 16304 DelimLoc, EndLoc); 16305 break; 16306 case OMPC_dist_schedule: 16307 Res = ActOnOpenMPDistScheduleClause( 16308 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 16309 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 16310 break; 16311 case OMPC_defaultmap: 16312 enum { Modifier, DefaultmapKind }; 16313 Res = ActOnOpenMPDefaultmapClause( 16314 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 16315 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 16316 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 16317 EndLoc); 16318 break; 16319 case OMPC_device: 16320 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 16321 Res = ActOnOpenMPDeviceClause( 16322 static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr, 16323 StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc); 16324 break; 16325 case OMPC_final: 16326 case OMPC_num_threads: 16327 case OMPC_safelen: 16328 case OMPC_simdlen: 16329 case OMPC_sizes: 16330 case OMPC_allocator: 16331 case OMPC_collapse: 16332 case OMPC_default: 16333 case OMPC_proc_bind: 16334 case OMPC_private: 16335 case OMPC_firstprivate: 16336 case OMPC_lastprivate: 16337 case OMPC_shared: 16338 case OMPC_reduction: 16339 case OMPC_task_reduction: 16340 case OMPC_in_reduction: 16341 case OMPC_linear: 16342 case OMPC_aligned: 16343 case OMPC_copyin: 16344 case OMPC_copyprivate: 16345 case OMPC_ordered: 16346 case OMPC_nowait: 16347 case OMPC_untied: 16348 case OMPC_mergeable: 16349 case OMPC_threadprivate: 16350 case OMPC_allocate: 16351 case OMPC_flush: 16352 case OMPC_depobj: 16353 case OMPC_read: 16354 case OMPC_write: 16355 case OMPC_update: 16356 case OMPC_capture: 16357 case OMPC_compare: 16358 case OMPC_seq_cst: 16359 case OMPC_acq_rel: 16360 case OMPC_acquire: 16361 case OMPC_release: 16362 case OMPC_relaxed: 16363 case OMPC_depend: 16364 case OMPC_threads: 16365 case OMPC_simd: 16366 case OMPC_map: 16367 case OMPC_num_teams: 16368 case OMPC_thread_limit: 16369 case OMPC_priority: 16370 case OMPC_grainsize: 16371 case OMPC_nogroup: 16372 case OMPC_num_tasks: 16373 case OMPC_hint: 16374 case OMPC_unknown: 16375 case OMPC_uniform: 16376 case OMPC_to: 16377 case OMPC_from: 16378 case OMPC_use_device_ptr: 16379 case OMPC_use_device_addr: 16380 case OMPC_is_device_ptr: 16381 case OMPC_has_device_addr: 16382 case OMPC_unified_address: 16383 case OMPC_unified_shared_memory: 16384 case OMPC_reverse_offload: 16385 case OMPC_dynamic_allocators: 16386 case OMPC_atomic_default_mem_order: 16387 case OMPC_device_type: 16388 case OMPC_match: 16389 case OMPC_nontemporal: 16390 case OMPC_order: 16391 case OMPC_destroy: 16392 case OMPC_novariants: 16393 case OMPC_nocontext: 16394 case OMPC_detach: 16395 case OMPC_inclusive: 16396 case OMPC_exclusive: 16397 case OMPC_uses_allocators: 16398 case OMPC_affinity: 16399 case OMPC_when: 16400 case OMPC_bind: 16401 default: 16402 llvm_unreachable("Clause is not allowed."); 16403 } 16404 return Res; 16405 } 16406 16407 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 16408 OpenMPScheduleClauseModifier M2, 16409 SourceLocation M1Loc, SourceLocation M2Loc) { 16410 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 16411 SmallVector<unsigned, 2> Excluded; 16412 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 16413 Excluded.push_back(M2); 16414 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 16415 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 16416 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 16417 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 16418 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 16419 << getListOfPossibleValues(OMPC_schedule, 16420 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 16421 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 16422 Excluded) 16423 << getOpenMPClauseName(OMPC_schedule); 16424 return true; 16425 } 16426 return false; 16427 } 16428 16429 OMPClause *Sema::ActOnOpenMPScheduleClause( 16430 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 16431 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 16432 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 16433 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 16434 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 16435 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 16436 return nullptr; 16437 // OpenMP, 2.7.1, Loop Construct, Restrictions 16438 // Either the monotonic modifier or the nonmonotonic modifier can be specified 16439 // but not both. 16440 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 16441 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 16442 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 16443 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 16444 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 16445 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 16446 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 16447 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 16448 return nullptr; 16449 } 16450 if (Kind == OMPC_SCHEDULE_unknown) { 16451 std::string Values; 16452 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 16453 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 16454 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 16455 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 16456 Exclude); 16457 } else { 16458 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 16459 /*Last=*/OMPC_SCHEDULE_unknown); 16460 } 16461 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 16462 << Values << getOpenMPClauseName(OMPC_schedule); 16463 return nullptr; 16464 } 16465 // OpenMP, 2.7.1, Loop Construct, Restrictions 16466 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 16467 // schedule(guided). 16468 // OpenMP 5.0 does not have this restriction. 16469 if (LangOpts.OpenMP < 50 && 16470 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 16471 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 16472 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 16473 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 16474 diag::err_omp_schedule_nonmonotonic_static); 16475 return nullptr; 16476 } 16477 Expr *ValExpr = ChunkSize; 16478 Stmt *HelperValStmt = nullptr; 16479 if (ChunkSize) { 16480 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 16481 !ChunkSize->isInstantiationDependent() && 16482 !ChunkSize->containsUnexpandedParameterPack()) { 16483 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 16484 ExprResult Val = 16485 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 16486 if (Val.isInvalid()) 16487 return nullptr; 16488 16489 ValExpr = Val.get(); 16490 16491 // OpenMP [2.7.1, Restrictions] 16492 // chunk_size must be a loop invariant integer expression with a positive 16493 // value. 16494 if (Optional<llvm::APSInt> Result = 16495 ValExpr->getIntegerConstantExpr(Context)) { 16496 if (Result->isSigned() && !Result->isStrictlyPositive()) { 16497 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 16498 << "schedule" << 1 << ChunkSize->getSourceRange(); 16499 return nullptr; 16500 } 16501 } else if (getOpenMPCaptureRegionForClause( 16502 DSAStack->getCurrentDirective(), OMPC_schedule, 16503 LangOpts.OpenMP) != OMPD_unknown && 16504 !CurContext->isDependentContext()) { 16505 ValExpr = MakeFullExpr(ValExpr).get(); 16506 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 16507 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 16508 HelperValStmt = buildPreInits(Context, Captures); 16509 } 16510 } 16511 } 16512 16513 return new (Context) 16514 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 16515 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 16516 } 16517 16518 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 16519 SourceLocation StartLoc, 16520 SourceLocation EndLoc) { 16521 OMPClause *Res = nullptr; 16522 switch (Kind) { 16523 case OMPC_ordered: 16524 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 16525 break; 16526 case OMPC_nowait: 16527 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 16528 break; 16529 case OMPC_untied: 16530 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 16531 break; 16532 case OMPC_mergeable: 16533 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 16534 break; 16535 case OMPC_read: 16536 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 16537 break; 16538 case OMPC_write: 16539 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 16540 break; 16541 case OMPC_update: 16542 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 16543 break; 16544 case OMPC_capture: 16545 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 16546 break; 16547 case OMPC_compare: 16548 Res = ActOnOpenMPCompareClause(StartLoc, EndLoc); 16549 break; 16550 case OMPC_seq_cst: 16551 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 16552 break; 16553 case OMPC_acq_rel: 16554 Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc); 16555 break; 16556 case OMPC_acquire: 16557 Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc); 16558 break; 16559 case OMPC_release: 16560 Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc); 16561 break; 16562 case OMPC_relaxed: 16563 Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc); 16564 break; 16565 case OMPC_threads: 16566 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 16567 break; 16568 case OMPC_simd: 16569 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 16570 break; 16571 case OMPC_nogroup: 16572 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 16573 break; 16574 case OMPC_unified_address: 16575 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc); 16576 break; 16577 case OMPC_unified_shared_memory: 16578 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 16579 break; 16580 case OMPC_reverse_offload: 16581 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc); 16582 break; 16583 case OMPC_dynamic_allocators: 16584 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc); 16585 break; 16586 case OMPC_destroy: 16587 Res = ActOnOpenMPDestroyClause(/*InteropVar=*/nullptr, StartLoc, 16588 /*LParenLoc=*/SourceLocation(), 16589 /*VarLoc=*/SourceLocation(), EndLoc); 16590 break; 16591 case OMPC_full: 16592 Res = ActOnOpenMPFullClause(StartLoc, EndLoc); 16593 break; 16594 case OMPC_partial: 16595 Res = ActOnOpenMPPartialClause(nullptr, StartLoc, /*LParenLoc=*/{}, EndLoc); 16596 break; 16597 case OMPC_if: 16598 case OMPC_final: 16599 case OMPC_num_threads: 16600 case OMPC_safelen: 16601 case OMPC_simdlen: 16602 case OMPC_sizes: 16603 case OMPC_allocator: 16604 case OMPC_collapse: 16605 case OMPC_schedule: 16606 case OMPC_private: 16607 case OMPC_firstprivate: 16608 case OMPC_lastprivate: 16609 case OMPC_shared: 16610 case OMPC_reduction: 16611 case OMPC_task_reduction: 16612 case OMPC_in_reduction: 16613 case OMPC_linear: 16614 case OMPC_aligned: 16615 case OMPC_copyin: 16616 case OMPC_copyprivate: 16617 case OMPC_default: 16618 case OMPC_proc_bind: 16619 case OMPC_threadprivate: 16620 case OMPC_allocate: 16621 case OMPC_flush: 16622 case OMPC_depobj: 16623 case OMPC_depend: 16624 case OMPC_device: 16625 case OMPC_map: 16626 case OMPC_num_teams: 16627 case OMPC_thread_limit: 16628 case OMPC_priority: 16629 case OMPC_grainsize: 16630 case OMPC_num_tasks: 16631 case OMPC_hint: 16632 case OMPC_dist_schedule: 16633 case OMPC_defaultmap: 16634 case OMPC_unknown: 16635 case OMPC_uniform: 16636 case OMPC_to: 16637 case OMPC_from: 16638 case OMPC_use_device_ptr: 16639 case OMPC_use_device_addr: 16640 case OMPC_is_device_ptr: 16641 case OMPC_has_device_addr: 16642 case OMPC_atomic_default_mem_order: 16643 case OMPC_device_type: 16644 case OMPC_match: 16645 case OMPC_nontemporal: 16646 case OMPC_order: 16647 case OMPC_novariants: 16648 case OMPC_nocontext: 16649 case OMPC_detach: 16650 case OMPC_inclusive: 16651 case OMPC_exclusive: 16652 case OMPC_uses_allocators: 16653 case OMPC_affinity: 16654 case OMPC_when: 16655 default: 16656 llvm_unreachable("Clause is not allowed."); 16657 } 16658 return Res; 16659 } 16660 16661 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 16662 SourceLocation EndLoc) { 16663 DSAStack->setNowaitRegion(); 16664 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 16665 } 16666 16667 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 16668 SourceLocation EndLoc) { 16669 DSAStack->setUntiedRegion(); 16670 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 16671 } 16672 16673 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 16674 SourceLocation EndLoc) { 16675 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 16676 } 16677 16678 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 16679 SourceLocation EndLoc) { 16680 return new (Context) OMPReadClause(StartLoc, EndLoc); 16681 } 16682 16683 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 16684 SourceLocation EndLoc) { 16685 return new (Context) OMPWriteClause(StartLoc, EndLoc); 16686 } 16687 16688 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 16689 SourceLocation EndLoc) { 16690 return OMPUpdateClause::Create(Context, StartLoc, EndLoc); 16691 } 16692 16693 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 16694 SourceLocation EndLoc) { 16695 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 16696 } 16697 16698 OMPClause *Sema::ActOnOpenMPCompareClause(SourceLocation StartLoc, 16699 SourceLocation EndLoc) { 16700 return new (Context) OMPCompareClause(StartLoc, EndLoc); 16701 } 16702 16703 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 16704 SourceLocation EndLoc) { 16705 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 16706 } 16707 16708 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc, 16709 SourceLocation EndLoc) { 16710 return new (Context) OMPAcqRelClause(StartLoc, EndLoc); 16711 } 16712 16713 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc, 16714 SourceLocation EndLoc) { 16715 return new (Context) OMPAcquireClause(StartLoc, EndLoc); 16716 } 16717 16718 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc, 16719 SourceLocation EndLoc) { 16720 return new (Context) OMPReleaseClause(StartLoc, EndLoc); 16721 } 16722 16723 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc, 16724 SourceLocation EndLoc) { 16725 return new (Context) OMPRelaxedClause(StartLoc, EndLoc); 16726 } 16727 16728 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 16729 SourceLocation EndLoc) { 16730 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 16731 } 16732 16733 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 16734 SourceLocation EndLoc) { 16735 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 16736 } 16737 16738 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 16739 SourceLocation EndLoc) { 16740 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 16741 } 16742 16743 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, 16744 SourceLocation EndLoc) { 16745 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc); 16746 } 16747 16748 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, 16749 SourceLocation EndLoc) { 16750 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 16751 } 16752 16753 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, 16754 SourceLocation EndLoc) { 16755 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc); 16756 } 16757 16758 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, 16759 SourceLocation EndLoc) { 16760 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc); 16761 } 16762 16763 StmtResult Sema::ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses, 16764 SourceLocation StartLoc, 16765 SourceLocation EndLoc) { 16766 16767 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 16768 // At least one action-clause must appear on a directive. 16769 if (!hasClauses(Clauses, OMPC_init, OMPC_use, OMPC_destroy, OMPC_nowait)) { 16770 StringRef Expected = "'init', 'use', 'destroy', or 'nowait'"; 16771 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 16772 << Expected << getOpenMPDirectiveName(OMPD_interop); 16773 return StmtError(); 16774 } 16775 16776 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 16777 // A depend clause can only appear on the directive if a targetsync 16778 // interop-type is present or the interop-var was initialized with 16779 // the targetsync interop-type. 16780 16781 // If there is any 'init' clause diagnose if there is no 'init' clause with 16782 // interop-type of 'targetsync'. Cases involving other directives cannot be 16783 // diagnosed. 16784 const OMPDependClause *DependClause = nullptr; 16785 bool HasInitClause = false; 16786 bool IsTargetSync = false; 16787 for (const OMPClause *C : Clauses) { 16788 if (IsTargetSync) 16789 break; 16790 if (const auto *InitClause = dyn_cast<OMPInitClause>(C)) { 16791 HasInitClause = true; 16792 if (InitClause->getIsTargetSync()) 16793 IsTargetSync = true; 16794 } else if (const auto *DC = dyn_cast<OMPDependClause>(C)) { 16795 DependClause = DC; 16796 } 16797 } 16798 if (DependClause && HasInitClause && !IsTargetSync) { 16799 Diag(DependClause->getBeginLoc(), diag::err_omp_interop_bad_depend_clause); 16800 return StmtError(); 16801 } 16802 16803 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 16804 // Each interop-var may be specified for at most one action-clause of each 16805 // interop construct. 16806 llvm::SmallPtrSet<const VarDecl *, 4> InteropVars; 16807 for (const OMPClause *C : Clauses) { 16808 OpenMPClauseKind ClauseKind = C->getClauseKind(); 16809 const DeclRefExpr *DRE = nullptr; 16810 SourceLocation VarLoc; 16811 16812 if (ClauseKind == OMPC_init) { 16813 const auto *IC = cast<OMPInitClause>(C); 16814 VarLoc = IC->getVarLoc(); 16815 DRE = dyn_cast_or_null<DeclRefExpr>(IC->getInteropVar()); 16816 } else if (ClauseKind == OMPC_use) { 16817 const auto *UC = cast<OMPUseClause>(C); 16818 VarLoc = UC->getVarLoc(); 16819 DRE = dyn_cast_or_null<DeclRefExpr>(UC->getInteropVar()); 16820 } else if (ClauseKind == OMPC_destroy) { 16821 const auto *DC = cast<OMPDestroyClause>(C); 16822 VarLoc = DC->getVarLoc(); 16823 DRE = dyn_cast_or_null<DeclRefExpr>(DC->getInteropVar()); 16824 } 16825 16826 if (!DRE) 16827 continue; 16828 16829 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 16830 if (!InteropVars.insert(VD->getCanonicalDecl()).second) { 16831 Diag(VarLoc, diag::err_omp_interop_var_multiple_actions) << VD; 16832 return StmtError(); 16833 } 16834 } 16835 } 16836 16837 return OMPInteropDirective::Create(Context, StartLoc, EndLoc, Clauses); 16838 } 16839 16840 static bool isValidInteropVariable(Sema &SemaRef, Expr *InteropVarExpr, 16841 SourceLocation VarLoc, 16842 OpenMPClauseKind Kind) { 16843 if (InteropVarExpr->isValueDependent() || InteropVarExpr->isTypeDependent() || 16844 InteropVarExpr->isInstantiationDependent() || 16845 InteropVarExpr->containsUnexpandedParameterPack()) 16846 return true; 16847 16848 const auto *DRE = dyn_cast<DeclRefExpr>(InteropVarExpr); 16849 if (!DRE || !isa<VarDecl>(DRE->getDecl())) { 16850 SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) << 0; 16851 return false; 16852 } 16853 16854 // Interop variable should be of type omp_interop_t. 16855 bool HasError = false; 16856 QualType InteropType; 16857 LookupResult Result(SemaRef, &SemaRef.Context.Idents.get("omp_interop_t"), 16858 VarLoc, Sema::LookupOrdinaryName); 16859 if (SemaRef.LookupName(Result, SemaRef.getCurScope())) { 16860 NamedDecl *ND = Result.getFoundDecl(); 16861 if (const auto *TD = dyn_cast<TypeDecl>(ND)) { 16862 InteropType = QualType(TD->getTypeForDecl(), 0); 16863 } else { 16864 HasError = true; 16865 } 16866 } else { 16867 HasError = true; 16868 } 16869 16870 if (HasError) { 16871 SemaRef.Diag(VarLoc, diag::err_omp_implied_type_not_found) 16872 << "omp_interop_t"; 16873 return false; 16874 } 16875 16876 QualType VarType = InteropVarExpr->getType().getUnqualifiedType(); 16877 if (!SemaRef.Context.hasSameType(InteropType, VarType)) { 16878 SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_wrong_type); 16879 return false; 16880 } 16881 16882 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 16883 // The interop-var passed to init or destroy must be non-const. 16884 if ((Kind == OMPC_init || Kind == OMPC_destroy) && 16885 isConstNotMutableType(SemaRef, InteropVarExpr->getType())) { 16886 SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) 16887 << /*non-const*/ 1; 16888 return false; 16889 } 16890 return true; 16891 } 16892 16893 OMPClause * 16894 Sema::ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs, 16895 bool IsTarget, bool IsTargetSync, 16896 SourceLocation StartLoc, SourceLocation LParenLoc, 16897 SourceLocation VarLoc, SourceLocation EndLoc) { 16898 16899 if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_init)) 16900 return nullptr; 16901 16902 // Check prefer_type values. These foreign-runtime-id values are either 16903 // string literals or constant integral expressions. 16904 for (const Expr *E : PrefExprs) { 16905 if (E->isValueDependent() || E->isTypeDependent() || 16906 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 16907 continue; 16908 if (E->isIntegerConstantExpr(Context)) 16909 continue; 16910 if (isa<StringLiteral>(E)) 16911 continue; 16912 Diag(E->getExprLoc(), diag::err_omp_interop_prefer_type); 16913 return nullptr; 16914 } 16915 16916 return OMPInitClause::Create(Context, InteropVar, PrefExprs, IsTarget, 16917 IsTargetSync, StartLoc, LParenLoc, VarLoc, 16918 EndLoc); 16919 } 16920 16921 OMPClause *Sema::ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc, 16922 SourceLocation LParenLoc, 16923 SourceLocation VarLoc, 16924 SourceLocation EndLoc) { 16925 16926 if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_use)) 16927 return nullptr; 16928 16929 return new (Context) 16930 OMPUseClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc); 16931 } 16932 16933 OMPClause *Sema::ActOnOpenMPDestroyClause(Expr *InteropVar, 16934 SourceLocation StartLoc, 16935 SourceLocation LParenLoc, 16936 SourceLocation VarLoc, 16937 SourceLocation EndLoc) { 16938 if (InteropVar && 16939 !isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_destroy)) 16940 return nullptr; 16941 16942 return new (Context) 16943 OMPDestroyClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc); 16944 } 16945 16946 OMPClause *Sema::ActOnOpenMPNovariantsClause(Expr *Condition, 16947 SourceLocation StartLoc, 16948 SourceLocation LParenLoc, 16949 SourceLocation EndLoc) { 16950 Expr *ValExpr = Condition; 16951 Stmt *HelperValStmt = nullptr; 16952 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 16953 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 16954 !Condition->isInstantiationDependent() && 16955 !Condition->containsUnexpandedParameterPack()) { 16956 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 16957 if (Val.isInvalid()) 16958 return nullptr; 16959 16960 ValExpr = MakeFullExpr(Val.get()).get(); 16961 16962 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 16963 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_novariants, 16964 LangOpts.OpenMP); 16965 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 16966 ValExpr = MakeFullExpr(ValExpr).get(); 16967 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 16968 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 16969 HelperValStmt = buildPreInits(Context, Captures); 16970 } 16971 } 16972 16973 return new (Context) OMPNovariantsClause( 16974 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 16975 } 16976 16977 OMPClause *Sema::ActOnOpenMPNocontextClause(Expr *Condition, 16978 SourceLocation StartLoc, 16979 SourceLocation LParenLoc, 16980 SourceLocation EndLoc) { 16981 Expr *ValExpr = Condition; 16982 Stmt *HelperValStmt = nullptr; 16983 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 16984 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 16985 !Condition->isInstantiationDependent() && 16986 !Condition->containsUnexpandedParameterPack()) { 16987 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 16988 if (Val.isInvalid()) 16989 return nullptr; 16990 16991 ValExpr = MakeFullExpr(Val.get()).get(); 16992 16993 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 16994 CaptureRegion = 16995 getOpenMPCaptureRegionForClause(DKind, OMPC_nocontext, LangOpts.OpenMP); 16996 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 16997 ValExpr = MakeFullExpr(ValExpr).get(); 16998 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 16999 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 17000 HelperValStmt = buildPreInits(Context, Captures); 17001 } 17002 } 17003 17004 return new (Context) OMPNocontextClause(ValExpr, HelperValStmt, CaptureRegion, 17005 StartLoc, LParenLoc, EndLoc); 17006 } 17007 17008 OMPClause *Sema::ActOnOpenMPFilterClause(Expr *ThreadID, 17009 SourceLocation StartLoc, 17010 SourceLocation LParenLoc, 17011 SourceLocation EndLoc) { 17012 Expr *ValExpr = ThreadID; 17013 Stmt *HelperValStmt = nullptr; 17014 17015 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 17016 OpenMPDirectiveKind CaptureRegion = 17017 getOpenMPCaptureRegionForClause(DKind, OMPC_filter, LangOpts.OpenMP); 17018 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 17019 ValExpr = MakeFullExpr(ValExpr).get(); 17020 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 17021 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 17022 HelperValStmt = buildPreInits(Context, Captures); 17023 } 17024 17025 return new (Context) OMPFilterClause(ValExpr, HelperValStmt, CaptureRegion, 17026 StartLoc, LParenLoc, EndLoc); 17027 } 17028 17029 OMPClause *Sema::ActOnOpenMPVarListClause(OpenMPClauseKind Kind, 17030 ArrayRef<Expr *> VarList, 17031 const OMPVarListLocTy &Locs, 17032 OpenMPVarListDataTy &Data) { 17033 SourceLocation StartLoc = Locs.StartLoc; 17034 SourceLocation LParenLoc = Locs.LParenLoc; 17035 SourceLocation EndLoc = Locs.EndLoc; 17036 OMPClause *Res = nullptr; 17037 int ExtraModifier = Data.ExtraModifier; 17038 SourceLocation ExtraModifierLoc = Data.ExtraModifierLoc; 17039 SourceLocation ColonLoc = Data.ColonLoc; 17040 switch (Kind) { 17041 case OMPC_private: 17042 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 17043 break; 17044 case OMPC_firstprivate: 17045 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 17046 break; 17047 case OMPC_lastprivate: 17048 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown && 17049 "Unexpected lastprivate modifier."); 17050 Res = ActOnOpenMPLastprivateClause( 17051 VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier), 17052 ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc); 17053 break; 17054 case OMPC_shared: 17055 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 17056 break; 17057 case OMPC_reduction: 17058 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown && 17059 "Unexpected lastprivate modifier."); 17060 Res = ActOnOpenMPReductionClause( 17061 VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier), 17062 StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc, 17063 Data.ReductionOrMapperIdScopeSpec, Data.ReductionOrMapperId); 17064 break; 17065 case OMPC_task_reduction: 17066 Res = ActOnOpenMPTaskReductionClause( 17067 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, 17068 Data.ReductionOrMapperIdScopeSpec, Data.ReductionOrMapperId); 17069 break; 17070 case OMPC_in_reduction: 17071 Res = ActOnOpenMPInReductionClause( 17072 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, 17073 Data.ReductionOrMapperIdScopeSpec, Data.ReductionOrMapperId); 17074 break; 17075 case OMPC_linear: 17076 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown && 17077 "Unexpected linear modifier."); 17078 Res = ActOnOpenMPLinearClause( 17079 VarList, Data.DepModOrTailExpr, StartLoc, LParenLoc, 17080 static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc, 17081 ColonLoc, EndLoc); 17082 break; 17083 case OMPC_aligned: 17084 Res = ActOnOpenMPAlignedClause(VarList, Data.DepModOrTailExpr, StartLoc, 17085 LParenLoc, ColonLoc, EndLoc); 17086 break; 17087 case OMPC_copyin: 17088 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 17089 break; 17090 case OMPC_copyprivate: 17091 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 17092 break; 17093 case OMPC_flush: 17094 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 17095 break; 17096 case OMPC_depend: 17097 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown && 17098 "Unexpected depend modifier."); 17099 Res = ActOnOpenMPDependClause( 17100 {static_cast<OpenMPDependClauseKind>(ExtraModifier), ExtraModifierLoc, 17101 ColonLoc, Data.OmpAllMemoryLoc}, 17102 Data.DepModOrTailExpr, VarList, StartLoc, LParenLoc, EndLoc); 17103 break; 17104 case OMPC_map: 17105 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown && 17106 "Unexpected map modifier."); 17107 Res = ActOnOpenMPMapClause( 17108 Data.MapTypeModifiers, Data.MapTypeModifiersLoc, 17109 Data.ReductionOrMapperIdScopeSpec, Data.ReductionOrMapperId, 17110 static_cast<OpenMPMapClauseKind>(ExtraModifier), Data.IsMapTypeImplicit, 17111 ExtraModifierLoc, ColonLoc, VarList, Locs); 17112 break; 17113 case OMPC_to: 17114 Res = 17115 ActOnOpenMPToClause(Data.MotionModifiers, Data.MotionModifiersLoc, 17116 Data.ReductionOrMapperIdScopeSpec, 17117 Data.ReductionOrMapperId, ColonLoc, VarList, Locs); 17118 break; 17119 case OMPC_from: 17120 Res = ActOnOpenMPFromClause(Data.MotionModifiers, Data.MotionModifiersLoc, 17121 Data.ReductionOrMapperIdScopeSpec, 17122 Data.ReductionOrMapperId, ColonLoc, VarList, 17123 Locs); 17124 break; 17125 case OMPC_use_device_ptr: 17126 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs); 17127 break; 17128 case OMPC_use_device_addr: 17129 Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs); 17130 break; 17131 case OMPC_is_device_ptr: 17132 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs); 17133 break; 17134 case OMPC_has_device_addr: 17135 Res = ActOnOpenMPHasDeviceAddrClause(VarList, Locs); 17136 break; 17137 case OMPC_allocate: 17138 Res = ActOnOpenMPAllocateClause(Data.DepModOrTailExpr, VarList, StartLoc, 17139 LParenLoc, ColonLoc, EndLoc); 17140 break; 17141 case OMPC_nontemporal: 17142 Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc); 17143 break; 17144 case OMPC_inclusive: 17145 Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc); 17146 break; 17147 case OMPC_exclusive: 17148 Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc); 17149 break; 17150 case OMPC_affinity: 17151 Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc, 17152 Data.DepModOrTailExpr, VarList); 17153 break; 17154 case OMPC_if: 17155 case OMPC_depobj: 17156 case OMPC_final: 17157 case OMPC_num_threads: 17158 case OMPC_safelen: 17159 case OMPC_simdlen: 17160 case OMPC_sizes: 17161 case OMPC_allocator: 17162 case OMPC_collapse: 17163 case OMPC_default: 17164 case OMPC_proc_bind: 17165 case OMPC_schedule: 17166 case OMPC_ordered: 17167 case OMPC_nowait: 17168 case OMPC_untied: 17169 case OMPC_mergeable: 17170 case OMPC_threadprivate: 17171 case OMPC_read: 17172 case OMPC_write: 17173 case OMPC_update: 17174 case OMPC_capture: 17175 case OMPC_compare: 17176 case OMPC_seq_cst: 17177 case OMPC_acq_rel: 17178 case OMPC_acquire: 17179 case OMPC_release: 17180 case OMPC_relaxed: 17181 case OMPC_device: 17182 case OMPC_threads: 17183 case OMPC_simd: 17184 case OMPC_num_teams: 17185 case OMPC_thread_limit: 17186 case OMPC_priority: 17187 case OMPC_grainsize: 17188 case OMPC_nogroup: 17189 case OMPC_num_tasks: 17190 case OMPC_hint: 17191 case OMPC_dist_schedule: 17192 case OMPC_defaultmap: 17193 case OMPC_unknown: 17194 case OMPC_uniform: 17195 case OMPC_unified_address: 17196 case OMPC_unified_shared_memory: 17197 case OMPC_reverse_offload: 17198 case OMPC_dynamic_allocators: 17199 case OMPC_atomic_default_mem_order: 17200 case OMPC_device_type: 17201 case OMPC_match: 17202 case OMPC_order: 17203 case OMPC_destroy: 17204 case OMPC_novariants: 17205 case OMPC_nocontext: 17206 case OMPC_detach: 17207 case OMPC_uses_allocators: 17208 case OMPC_when: 17209 case OMPC_bind: 17210 default: 17211 llvm_unreachable("Clause is not allowed."); 17212 } 17213 return Res; 17214 } 17215 17216 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 17217 ExprObjectKind OK, SourceLocation Loc) { 17218 ExprResult Res = BuildDeclRefExpr( 17219 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 17220 if (!Res.isUsable()) 17221 return ExprError(); 17222 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 17223 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 17224 if (!Res.isUsable()) 17225 return ExprError(); 17226 } 17227 if (VK != VK_LValue && Res.get()->isGLValue()) { 17228 Res = DefaultLvalueConversion(Res.get()); 17229 if (!Res.isUsable()) 17230 return ExprError(); 17231 } 17232 return Res; 17233 } 17234 17235 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 17236 SourceLocation StartLoc, 17237 SourceLocation LParenLoc, 17238 SourceLocation EndLoc) { 17239 SmallVector<Expr *, 8> Vars; 17240 SmallVector<Expr *, 8> PrivateCopies; 17241 for (Expr *RefExpr : VarList) { 17242 assert(RefExpr && "NULL expr in OpenMP private clause."); 17243 SourceLocation ELoc; 17244 SourceRange ERange; 17245 Expr *SimpleRefExpr = RefExpr; 17246 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 17247 if (Res.second) { 17248 // It will be analyzed later. 17249 Vars.push_back(RefExpr); 17250 PrivateCopies.push_back(nullptr); 17251 } 17252 ValueDecl *D = Res.first; 17253 if (!D) 17254 continue; 17255 17256 QualType Type = D->getType(); 17257 auto *VD = dyn_cast<VarDecl>(D); 17258 17259 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 17260 // A variable that appears in a private clause must not have an incomplete 17261 // type or a reference type. 17262 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 17263 continue; 17264 Type = Type.getNonReferenceType(); 17265 17266 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 17267 // A variable that is privatized must not have a const-qualified type 17268 // unless it is of class type with a mutable member. This restriction does 17269 // not apply to the firstprivate clause. 17270 // 17271 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions] 17272 // A variable that appears in a private clause must not have a 17273 // const-qualified type unless it is of class type with a mutable member. 17274 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc)) 17275 continue; 17276 17277 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 17278 // in a Construct] 17279 // Variables with the predetermined data-sharing attributes may not be 17280 // listed in data-sharing attributes clauses, except for the cases 17281 // listed below. For these exceptions only, listing a predetermined 17282 // variable in a data-sharing attribute clause is allowed and overrides 17283 // the variable's predetermined data-sharing attributes. 17284 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 17285 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 17286 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 17287 << getOpenMPClauseName(OMPC_private); 17288 reportOriginalDsa(*this, DSAStack, D, DVar); 17289 continue; 17290 } 17291 17292 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 17293 // Variably modified types are not supported for tasks. 17294 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 17295 isOpenMPTaskingDirective(CurrDir)) { 17296 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 17297 << getOpenMPClauseName(OMPC_private) << Type 17298 << getOpenMPDirectiveName(CurrDir); 17299 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 17300 VarDecl::DeclarationOnly; 17301 Diag(D->getLocation(), 17302 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17303 << D; 17304 continue; 17305 } 17306 17307 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 17308 // A list item cannot appear in both a map clause and a data-sharing 17309 // attribute clause on the same construct 17310 // 17311 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 17312 // A list item cannot appear in both a map clause and a data-sharing 17313 // attribute clause on the same construct unless the construct is a 17314 // combined construct. 17315 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) || 17316 CurrDir == OMPD_target) { 17317 OpenMPClauseKind ConflictKind; 17318 if (DSAStack->checkMappableExprComponentListsForDecl( 17319 VD, /*CurrentRegionOnly=*/true, 17320 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 17321 OpenMPClauseKind WhereFoundClauseKind) -> bool { 17322 ConflictKind = WhereFoundClauseKind; 17323 return true; 17324 })) { 17325 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 17326 << getOpenMPClauseName(OMPC_private) 17327 << getOpenMPClauseName(ConflictKind) 17328 << getOpenMPDirectiveName(CurrDir); 17329 reportOriginalDsa(*this, DSAStack, D, DVar); 17330 continue; 17331 } 17332 } 17333 17334 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 17335 // A variable of class type (or array thereof) that appears in a private 17336 // clause requires an accessible, unambiguous default constructor for the 17337 // class type. 17338 // Generate helper private variable and initialize it with the default 17339 // value. The address of the original variable is replaced by the address of 17340 // the new private variable in CodeGen. This new variable is not added to 17341 // IdResolver, so the code in the OpenMP region uses original variable for 17342 // proper diagnostics. 17343 Type = Type.getUnqualifiedType(); 17344 VarDecl *VDPrivate = 17345 buildVarDecl(*this, ELoc, Type, D->getName(), 17346 D->hasAttrs() ? &D->getAttrs() : nullptr, 17347 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 17348 ActOnUninitializedDecl(VDPrivate); 17349 if (VDPrivate->isInvalidDecl()) 17350 continue; 17351 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 17352 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 17353 17354 DeclRefExpr *Ref = nullptr; 17355 if (!VD && !CurContext->isDependentContext()) 17356 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 17357 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 17358 Vars.push_back((VD || CurContext->isDependentContext()) 17359 ? RefExpr->IgnoreParens() 17360 : Ref); 17361 PrivateCopies.push_back(VDPrivateRefExpr); 17362 } 17363 17364 if (Vars.empty()) 17365 return nullptr; 17366 17367 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 17368 PrivateCopies); 17369 } 17370 17371 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 17372 SourceLocation StartLoc, 17373 SourceLocation LParenLoc, 17374 SourceLocation EndLoc) { 17375 SmallVector<Expr *, 8> Vars; 17376 SmallVector<Expr *, 8> PrivateCopies; 17377 SmallVector<Expr *, 8> Inits; 17378 SmallVector<Decl *, 4> ExprCaptures; 17379 bool IsImplicitClause = 17380 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 17381 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc(); 17382 17383 for (Expr *RefExpr : VarList) { 17384 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 17385 SourceLocation ELoc; 17386 SourceRange ERange; 17387 Expr *SimpleRefExpr = RefExpr; 17388 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 17389 if (Res.second) { 17390 // It will be analyzed later. 17391 Vars.push_back(RefExpr); 17392 PrivateCopies.push_back(nullptr); 17393 Inits.push_back(nullptr); 17394 } 17395 ValueDecl *D = Res.first; 17396 if (!D) 17397 continue; 17398 17399 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 17400 QualType Type = D->getType(); 17401 auto *VD = dyn_cast<VarDecl>(D); 17402 17403 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 17404 // A variable that appears in a private clause must not have an incomplete 17405 // type or a reference type. 17406 if (RequireCompleteType(ELoc, Type, 17407 diag::err_omp_firstprivate_incomplete_type)) 17408 continue; 17409 Type = Type.getNonReferenceType(); 17410 17411 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 17412 // A variable of class type (or array thereof) that appears in a private 17413 // clause requires an accessible, unambiguous copy constructor for the 17414 // class type. 17415 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 17416 17417 // If an implicit firstprivate variable found it was checked already. 17418 DSAStackTy::DSAVarData TopDVar; 17419 if (!IsImplicitClause) { 17420 DSAStackTy::DSAVarData DVar = 17421 DSAStack->getTopDSA(D, /*FromParent=*/false); 17422 TopDVar = DVar; 17423 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 17424 bool IsConstant = ElemType.isConstant(Context); 17425 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 17426 // A list item that specifies a given variable may not appear in more 17427 // than one clause on the same directive, except that a variable may be 17428 // specified in both firstprivate and lastprivate clauses. 17429 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 17430 // A list item may appear in a firstprivate or lastprivate clause but not 17431 // both. 17432 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 17433 (isOpenMPDistributeDirective(CurrDir) || 17434 DVar.CKind != OMPC_lastprivate) && 17435 DVar.RefExpr) { 17436 Diag(ELoc, diag::err_omp_wrong_dsa) 17437 << getOpenMPClauseName(DVar.CKind) 17438 << getOpenMPClauseName(OMPC_firstprivate); 17439 reportOriginalDsa(*this, DSAStack, D, DVar); 17440 continue; 17441 } 17442 17443 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 17444 // in a Construct] 17445 // Variables with the predetermined data-sharing attributes may not be 17446 // listed in data-sharing attributes clauses, except for the cases 17447 // listed below. For these exceptions only, listing a predetermined 17448 // variable in a data-sharing attribute clause is allowed and overrides 17449 // the variable's predetermined data-sharing attributes. 17450 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 17451 // in a Construct, C/C++, p.2] 17452 // Variables with const-qualified type having no mutable member may be 17453 // listed in a firstprivate clause, even if they are static data members. 17454 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 17455 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 17456 Diag(ELoc, diag::err_omp_wrong_dsa) 17457 << getOpenMPClauseName(DVar.CKind) 17458 << getOpenMPClauseName(OMPC_firstprivate); 17459 reportOriginalDsa(*this, DSAStack, D, DVar); 17460 continue; 17461 } 17462 17463 // OpenMP [2.9.3.4, Restrictions, p.2] 17464 // A list item that is private within a parallel region must not appear 17465 // in a firstprivate clause on a worksharing construct if any of the 17466 // worksharing regions arising from the worksharing construct ever bind 17467 // to any of the parallel regions arising from the parallel construct. 17468 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 17469 // A list item that is private within a teams region must not appear in a 17470 // firstprivate clause on a distribute construct if any of the distribute 17471 // regions arising from the distribute construct ever bind to any of the 17472 // teams regions arising from the teams construct. 17473 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 17474 // A list item that appears in a reduction clause of a teams construct 17475 // must not appear in a firstprivate clause on a distribute construct if 17476 // any of the distribute regions arising from the distribute construct 17477 // ever bind to any of the teams regions arising from the teams construct. 17478 if ((isOpenMPWorksharingDirective(CurrDir) || 17479 isOpenMPDistributeDirective(CurrDir)) && 17480 !isOpenMPParallelDirective(CurrDir) && 17481 !isOpenMPTeamsDirective(CurrDir)) { 17482 DVar = DSAStack->getImplicitDSA(D, true); 17483 if (DVar.CKind != OMPC_shared && 17484 (isOpenMPParallelDirective(DVar.DKind) || 17485 isOpenMPTeamsDirective(DVar.DKind) || 17486 DVar.DKind == OMPD_unknown)) { 17487 Diag(ELoc, diag::err_omp_required_access) 17488 << getOpenMPClauseName(OMPC_firstprivate) 17489 << getOpenMPClauseName(OMPC_shared); 17490 reportOriginalDsa(*this, DSAStack, D, DVar); 17491 continue; 17492 } 17493 } 17494 // OpenMP [2.9.3.4, Restrictions, p.3] 17495 // A list item that appears in a reduction clause of a parallel construct 17496 // must not appear in a firstprivate clause on a worksharing or task 17497 // construct if any of the worksharing or task regions arising from the 17498 // worksharing or task construct ever bind to any of the parallel regions 17499 // arising from the parallel construct. 17500 // OpenMP [2.9.3.4, Restrictions, p.4] 17501 // A list item that appears in a reduction clause in worksharing 17502 // construct must not appear in a firstprivate clause in a task construct 17503 // encountered during execution of any of the worksharing regions arising 17504 // from the worksharing construct. 17505 if (isOpenMPTaskingDirective(CurrDir)) { 17506 DVar = DSAStack->hasInnermostDSA( 17507 D, 17508 [](OpenMPClauseKind C, bool AppliedToPointee) { 17509 return C == OMPC_reduction && !AppliedToPointee; 17510 }, 17511 [](OpenMPDirectiveKind K) { 17512 return isOpenMPParallelDirective(K) || 17513 isOpenMPWorksharingDirective(K) || 17514 isOpenMPTeamsDirective(K); 17515 }, 17516 /*FromParent=*/true); 17517 if (DVar.CKind == OMPC_reduction && 17518 (isOpenMPParallelDirective(DVar.DKind) || 17519 isOpenMPWorksharingDirective(DVar.DKind) || 17520 isOpenMPTeamsDirective(DVar.DKind))) { 17521 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 17522 << getOpenMPDirectiveName(DVar.DKind); 17523 reportOriginalDsa(*this, DSAStack, D, DVar); 17524 continue; 17525 } 17526 } 17527 17528 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 17529 // A list item cannot appear in both a map clause and a data-sharing 17530 // attribute clause on the same construct 17531 // 17532 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 17533 // A list item cannot appear in both a map clause and a data-sharing 17534 // attribute clause on the same construct unless the construct is a 17535 // combined construct. 17536 if ((LangOpts.OpenMP <= 45 && 17537 isOpenMPTargetExecutionDirective(CurrDir)) || 17538 CurrDir == OMPD_target) { 17539 OpenMPClauseKind ConflictKind; 17540 if (DSAStack->checkMappableExprComponentListsForDecl( 17541 VD, /*CurrentRegionOnly=*/true, 17542 [&ConflictKind]( 17543 OMPClauseMappableExprCommon::MappableExprComponentListRef, 17544 OpenMPClauseKind WhereFoundClauseKind) { 17545 ConflictKind = WhereFoundClauseKind; 17546 return true; 17547 })) { 17548 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 17549 << getOpenMPClauseName(OMPC_firstprivate) 17550 << getOpenMPClauseName(ConflictKind) 17551 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 17552 reportOriginalDsa(*this, DSAStack, D, DVar); 17553 continue; 17554 } 17555 } 17556 } 17557 17558 // Variably modified types are not supported for tasks. 17559 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 17560 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 17561 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 17562 << getOpenMPClauseName(OMPC_firstprivate) << Type 17563 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 17564 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 17565 VarDecl::DeclarationOnly; 17566 Diag(D->getLocation(), 17567 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17568 << D; 17569 continue; 17570 } 17571 17572 Type = Type.getUnqualifiedType(); 17573 VarDecl *VDPrivate = 17574 buildVarDecl(*this, ELoc, Type, D->getName(), 17575 D->hasAttrs() ? &D->getAttrs() : nullptr, 17576 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 17577 // Generate helper private variable and initialize it with the value of the 17578 // original variable. The address of the original variable is replaced by 17579 // the address of the new private variable in the CodeGen. This new variable 17580 // is not added to IdResolver, so the code in the OpenMP region uses 17581 // original variable for proper diagnostics and variable capturing. 17582 Expr *VDInitRefExpr = nullptr; 17583 // For arrays generate initializer for single element and replace it by the 17584 // original array element in CodeGen. 17585 if (Type->isArrayType()) { 17586 VarDecl *VDInit = 17587 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 17588 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 17589 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get(); 17590 ElemType = ElemType.getUnqualifiedType(); 17591 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 17592 ".firstprivate.temp"); 17593 InitializedEntity Entity = 17594 InitializedEntity::InitializeVariable(VDInitTemp); 17595 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 17596 17597 InitializationSequence InitSeq(*this, Entity, Kind, Init); 17598 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 17599 if (Result.isInvalid()) 17600 VDPrivate->setInvalidDecl(); 17601 else 17602 VDPrivate->setInit(Result.getAs<Expr>()); 17603 // Remove temp variable declaration. 17604 Context.Deallocate(VDInitTemp); 17605 } else { 17606 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 17607 ".firstprivate.temp"); 17608 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 17609 RefExpr->getExprLoc()); 17610 AddInitializerToDecl(VDPrivate, 17611 DefaultLvalueConversion(VDInitRefExpr).get(), 17612 /*DirectInit=*/false); 17613 } 17614 if (VDPrivate->isInvalidDecl()) { 17615 if (IsImplicitClause) { 17616 Diag(RefExpr->getExprLoc(), 17617 diag::note_omp_task_predetermined_firstprivate_here); 17618 } 17619 continue; 17620 } 17621 CurContext->addDecl(VDPrivate); 17622 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 17623 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 17624 RefExpr->getExprLoc()); 17625 DeclRefExpr *Ref = nullptr; 17626 if (!VD && !CurContext->isDependentContext()) { 17627 if (TopDVar.CKind == OMPC_lastprivate) { 17628 Ref = TopDVar.PrivateCopy; 17629 } else { 17630 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 17631 if (!isOpenMPCapturedDecl(D)) 17632 ExprCaptures.push_back(Ref->getDecl()); 17633 } 17634 } 17635 if (!IsImplicitClause) 17636 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 17637 Vars.push_back((VD || CurContext->isDependentContext()) 17638 ? RefExpr->IgnoreParens() 17639 : Ref); 17640 PrivateCopies.push_back(VDPrivateRefExpr); 17641 Inits.push_back(VDInitRefExpr); 17642 } 17643 17644 if (Vars.empty()) 17645 return nullptr; 17646 17647 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 17648 Vars, PrivateCopies, Inits, 17649 buildPreInits(Context, ExprCaptures)); 17650 } 17651 17652 OMPClause *Sema::ActOnOpenMPLastprivateClause( 17653 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, 17654 SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc, 17655 SourceLocation LParenLoc, SourceLocation EndLoc) { 17656 if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) { 17657 assert(ColonLoc.isValid() && "Colon location must be valid."); 17658 Diag(LPKindLoc, diag::err_omp_unexpected_clause_value) 17659 << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0, 17660 /*Last=*/OMPC_LASTPRIVATE_unknown) 17661 << getOpenMPClauseName(OMPC_lastprivate); 17662 return nullptr; 17663 } 17664 17665 SmallVector<Expr *, 8> Vars; 17666 SmallVector<Expr *, 8> SrcExprs; 17667 SmallVector<Expr *, 8> DstExprs; 17668 SmallVector<Expr *, 8> AssignmentOps; 17669 SmallVector<Decl *, 4> ExprCaptures; 17670 SmallVector<Expr *, 4> ExprPostUpdates; 17671 for (Expr *RefExpr : VarList) { 17672 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 17673 SourceLocation ELoc; 17674 SourceRange ERange; 17675 Expr *SimpleRefExpr = RefExpr; 17676 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 17677 if (Res.second) { 17678 // It will be analyzed later. 17679 Vars.push_back(RefExpr); 17680 SrcExprs.push_back(nullptr); 17681 DstExprs.push_back(nullptr); 17682 AssignmentOps.push_back(nullptr); 17683 } 17684 ValueDecl *D = Res.first; 17685 if (!D) 17686 continue; 17687 17688 QualType Type = D->getType(); 17689 auto *VD = dyn_cast<VarDecl>(D); 17690 17691 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 17692 // A variable that appears in a lastprivate clause must not have an 17693 // incomplete type or a reference type. 17694 if (RequireCompleteType(ELoc, Type, 17695 diag::err_omp_lastprivate_incomplete_type)) 17696 continue; 17697 Type = Type.getNonReferenceType(); 17698 17699 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 17700 // A variable that is privatized must not have a const-qualified type 17701 // unless it is of class type with a mutable member. This restriction does 17702 // not apply to the firstprivate clause. 17703 // 17704 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions] 17705 // A variable that appears in a lastprivate clause must not have a 17706 // const-qualified type unless it is of class type with a mutable member. 17707 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc)) 17708 continue; 17709 17710 // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions] 17711 // A list item that appears in a lastprivate clause with the conditional 17712 // modifier must be a scalar variable. 17713 if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) { 17714 Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar); 17715 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 17716 VarDecl::DeclarationOnly; 17717 Diag(D->getLocation(), 17718 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17719 << D; 17720 continue; 17721 } 17722 17723 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 17724 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 17725 // in a Construct] 17726 // Variables with the predetermined data-sharing attributes may not be 17727 // listed in data-sharing attributes clauses, except for the cases 17728 // listed below. 17729 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 17730 // A list item may appear in a firstprivate or lastprivate clause but not 17731 // both. 17732 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 17733 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 17734 (isOpenMPDistributeDirective(CurrDir) || 17735 DVar.CKind != OMPC_firstprivate) && 17736 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 17737 Diag(ELoc, diag::err_omp_wrong_dsa) 17738 << getOpenMPClauseName(DVar.CKind) 17739 << getOpenMPClauseName(OMPC_lastprivate); 17740 reportOriginalDsa(*this, DSAStack, D, DVar); 17741 continue; 17742 } 17743 17744 // OpenMP [2.14.3.5, Restrictions, p.2] 17745 // A list item that is private within a parallel region, or that appears in 17746 // the reduction clause of a parallel construct, must not appear in a 17747 // lastprivate clause on a worksharing construct if any of the corresponding 17748 // worksharing regions ever binds to any of the corresponding parallel 17749 // regions. 17750 DSAStackTy::DSAVarData TopDVar = DVar; 17751 if (isOpenMPWorksharingDirective(CurrDir) && 17752 !isOpenMPParallelDirective(CurrDir) && 17753 !isOpenMPTeamsDirective(CurrDir)) { 17754 DVar = DSAStack->getImplicitDSA(D, true); 17755 if (DVar.CKind != OMPC_shared) { 17756 Diag(ELoc, diag::err_omp_required_access) 17757 << getOpenMPClauseName(OMPC_lastprivate) 17758 << getOpenMPClauseName(OMPC_shared); 17759 reportOriginalDsa(*this, DSAStack, D, DVar); 17760 continue; 17761 } 17762 } 17763 17764 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 17765 // A variable of class type (or array thereof) that appears in a 17766 // lastprivate clause requires an accessible, unambiguous default 17767 // constructor for the class type, unless the list item is also specified 17768 // in a firstprivate clause. 17769 // A variable of class type (or array thereof) that appears in a 17770 // lastprivate clause requires an accessible, unambiguous copy assignment 17771 // operator for the class type. 17772 Type = Context.getBaseElementType(Type).getNonReferenceType(); 17773 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(), 17774 Type.getUnqualifiedType(), ".lastprivate.src", 17775 D->hasAttrs() ? &D->getAttrs() : nullptr); 17776 DeclRefExpr *PseudoSrcExpr = 17777 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 17778 VarDecl *DstVD = 17779 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 17780 D->hasAttrs() ? &D->getAttrs() : nullptr); 17781 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 17782 // For arrays generate assignment operation for single element and replace 17783 // it by the original array element in CodeGen. 17784 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 17785 PseudoDstExpr, PseudoSrcExpr); 17786 if (AssignmentOp.isInvalid()) 17787 continue; 17788 AssignmentOp = 17789 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 17790 if (AssignmentOp.isInvalid()) 17791 continue; 17792 17793 DeclRefExpr *Ref = nullptr; 17794 if (!VD && !CurContext->isDependentContext()) { 17795 if (TopDVar.CKind == OMPC_firstprivate) { 17796 Ref = TopDVar.PrivateCopy; 17797 } else { 17798 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 17799 if (!isOpenMPCapturedDecl(D)) 17800 ExprCaptures.push_back(Ref->getDecl()); 17801 } 17802 if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) || 17803 (!isOpenMPCapturedDecl(D) && 17804 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 17805 ExprResult RefRes = DefaultLvalueConversion(Ref); 17806 if (!RefRes.isUsable()) 17807 continue; 17808 ExprResult PostUpdateRes = 17809 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 17810 RefRes.get()); 17811 if (!PostUpdateRes.isUsable()) 17812 continue; 17813 ExprPostUpdates.push_back( 17814 IgnoredValueConversions(PostUpdateRes.get()).get()); 17815 } 17816 } 17817 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 17818 Vars.push_back((VD || CurContext->isDependentContext()) 17819 ? RefExpr->IgnoreParens() 17820 : Ref); 17821 SrcExprs.push_back(PseudoSrcExpr); 17822 DstExprs.push_back(PseudoDstExpr); 17823 AssignmentOps.push_back(AssignmentOp.get()); 17824 } 17825 17826 if (Vars.empty()) 17827 return nullptr; 17828 17829 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 17830 Vars, SrcExprs, DstExprs, AssignmentOps, 17831 LPKind, LPKindLoc, ColonLoc, 17832 buildPreInits(Context, ExprCaptures), 17833 buildPostUpdate(*this, ExprPostUpdates)); 17834 } 17835 17836 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 17837 SourceLocation StartLoc, 17838 SourceLocation LParenLoc, 17839 SourceLocation EndLoc) { 17840 SmallVector<Expr *, 8> Vars; 17841 for (Expr *RefExpr : VarList) { 17842 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 17843 SourceLocation ELoc; 17844 SourceRange ERange; 17845 Expr *SimpleRefExpr = RefExpr; 17846 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 17847 if (Res.second) { 17848 // It will be analyzed later. 17849 Vars.push_back(RefExpr); 17850 } 17851 ValueDecl *D = Res.first; 17852 if (!D) 17853 continue; 17854 17855 auto *VD = dyn_cast<VarDecl>(D); 17856 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 17857 // in a Construct] 17858 // Variables with the predetermined data-sharing attributes may not be 17859 // listed in data-sharing attributes clauses, except for the cases 17860 // listed below. For these exceptions only, listing a predetermined 17861 // variable in a data-sharing attribute clause is allowed and overrides 17862 // the variable's predetermined data-sharing attributes. 17863 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 17864 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 17865 DVar.RefExpr) { 17866 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 17867 << getOpenMPClauseName(OMPC_shared); 17868 reportOriginalDsa(*this, DSAStack, D, DVar); 17869 continue; 17870 } 17871 17872 DeclRefExpr *Ref = nullptr; 17873 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 17874 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 17875 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 17876 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 17877 ? RefExpr->IgnoreParens() 17878 : Ref); 17879 } 17880 17881 if (Vars.empty()) 17882 return nullptr; 17883 17884 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 17885 } 17886 17887 namespace { 17888 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 17889 DSAStackTy *Stack; 17890 17891 public: 17892 bool VisitDeclRefExpr(DeclRefExpr *E) { 17893 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 17894 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 17895 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 17896 return false; 17897 if (DVar.CKind != OMPC_unknown) 17898 return true; 17899 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 17900 VD, 17901 [](OpenMPClauseKind C, bool AppliedToPointee) { 17902 return isOpenMPPrivate(C) && !AppliedToPointee; 17903 }, 17904 [](OpenMPDirectiveKind) { return true; }, 17905 /*FromParent=*/true); 17906 return DVarPrivate.CKind != OMPC_unknown; 17907 } 17908 return false; 17909 } 17910 bool VisitStmt(Stmt *S) { 17911 for (Stmt *Child : S->children()) { 17912 if (Child && Visit(Child)) 17913 return true; 17914 } 17915 return false; 17916 } 17917 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 17918 }; 17919 } // namespace 17920 17921 namespace { 17922 // Transform MemberExpression for specified FieldDecl of current class to 17923 // DeclRefExpr to specified OMPCapturedExprDecl. 17924 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 17925 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 17926 ValueDecl *Field = nullptr; 17927 DeclRefExpr *CapturedExpr = nullptr; 17928 17929 public: 17930 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 17931 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 17932 17933 ExprResult TransformMemberExpr(MemberExpr *E) { 17934 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 17935 E->getMemberDecl() == Field) { 17936 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 17937 return CapturedExpr; 17938 } 17939 return BaseTransform::TransformMemberExpr(E); 17940 } 17941 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 17942 }; 17943 } // namespace 17944 17945 template <typename T, typename U> 17946 static T filterLookupForUDReductionAndMapper( 17947 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) { 17948 for (U &Set : Lookups) { 17949 for (auto *D : Set) { 17950 if (T Res = Gen(cast<ValueDecl>(D))) 17951 return Res; 17952 } 17953 } 17954 return T(); 17955 } 17956 17957 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) { 17958 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case"); 17959 17960 for (auto RD : D->redecls()) { 17961 // Don't bother with extra checks if we already know this one isn't visible. 17962 if (RD == D) 17963 continue; 17964 17965 auto ND = cast<NamedDecl>(RD); 17966 if (LookupResult::isVisible(SemaRef, ND)) 17967 return ND; 17968 } 17969 17970 return nullptr; 17971 } 17972 17973 static void 17974 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id, 17975 SourceLocation Loc, QualType Ty, 17976 SmallVectorImpl<UnresolvedSet<8>> &Lookups) { 17977 // Find all of the associated namespaces and classes based on the 17978 // arguments we have. 17979 Sema::AssociatedNamespaceSet AssociatedNamespaces; 17980 Sema::AssociatedClassSet AssociatedClasses; 17981 OpaqueValueExpr OVE(Loc, Ty, VK_LValue); 17982 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces, 17983 AssociatedClasses); 17984 17985 // C++ [basic.lookup.argdep]p3: 17986 // Let X be the lookup set produced by unqualified lookup (3.4.1) 17987 // and let Y be the lookup set produced by argument dependent 17988 // lookup (defined as follows). If X contains [...] then Y is 17989 // empty. Otherwise Y is the set of declarations found in the 17990 // namespaces associated with the argument types as described 17991 // below. The set of declarations found by the lookup of the name 17992 // is the union of X and Y. 17993 // 17994 // Here, we compute Y and add its members to the overloaded 17995 // candidate set. 17996 for (auto *NS : AssociatedNamespaces) { 17997 // When considering an associated namespace, the lookup is the 17998 // same as the lookup performed when the associated namespace is 17999 // used as a qualifier (3.4.3.2) except that: 18000 // 18001 // -- Any using-directives in the associated namespace are 18002 // ignored. 18003 // 18004 // -- Any namespace-scope friend functions declared in 18005 // associated classes are visible within their respective 18006 // namespaces even if they are not visible during an ordinary 18007 // lookup (11.4). 18008 DeclContext::lookup_result R = NS->lookup(Id.getName()); 18009 for (auto *D : R) { 18010 auto *Underlying = D; 18011 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 18012 Underlying = USD->getTargetDecl(); 18013 18014 if (!isa<OMPDeclareReductionDecl>(Underlying) && 18015 !isa<OMPDeclareMapperDecl>(Underlying)) 18016 continue; 18017 18018 if (!SemaRef.isVisible(D)) { 18019 D = findAcceptableDecl(SemaRef, D); 18020 if (!D) 18021 continue; 18022 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 18023 Underlying = USD->getTargetDecl(); 18024 } 18025 Lookups.emplace_back(); 18026 Lookups.back().addDecl(Underlying); 18027 } 18028 } 18029 } 18030 18031 static ExprResult 18032 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 18033 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 18034 const DeclarationNameInfo &ReductionId, QualType Ty, 18035 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 18036 if (ReductionIdScopeSpec.isInvalid()) 18037 return ExprError(); 18038 SmallVector<UnresolvedSet<8>, 4> Lookups; 18039 if (S) { 18040 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 18041 Lookup.suppressDiagnostics(); 18042 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 18043 NamedDecl *D = Lookup.getRepresentativeDecl(); 18044 do { 18045 S = S->getParent(); 18046 } while (S && !S->isDeclScope(D)); 18047 if (S) 18048 S = S->getParent(); 18049 Lookups.emplace_back(); 18050 Lookups.back().append(Lookup.begin(), Lookup.end()); 18051 Lookup.clear(); 18052 } 18053 } else if (auto *ULE = 18054 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 18055 Lookups.push_back(UnresolvedSet<8>()); 18056 Decl *PrevD = nullptr; 18057 for (NamedDecl *D : ULE->decls()) { 18058 if (D == PrevD) 18059 Lookups.push_back(UnresolvedSet<8>()); 18060 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D)) 18061 Lookups.back().addDecl(DRD); 18062 PrevD = D; 18063 } 18064 } 18065 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || 18066 Ty->isInstantiationDependentType() || 18067 Ty->containsUnexpandedParameterPack() || 18068 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 18069 return !D->isInvalidDecl() && 18070 (D->getType()->isDependentType() || 18071 D->getType()->isInstantiationDependentType() || 18072 D->getType()->containsUnexpandedParameterPack()); 18073 })) { 18074 UnresolvedSet<8> ResSet; 18075 for (const UnresolvedSet<8> &Set : Lookups) { 18076 if (Set.empty()) 18077 continue; 18078 ResSet.append(Set.begin(), Set.end()); 18079 // The last item marks the end of all declarations at the specified scope. 18080 ResSet.addDecl(Set[Set.size() - 1]); 18081 } 18082 return UnresolvedLookupExpr::Create( 18083 SemaRef.Context, /*NamingClass=*/nullptr, 18084 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 18085 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 18086 } 18087 // Lookup inside the classes. 18088 // C++ [over.match.oper]p3: 18089 // For a unary operator @ with an operand of a type whose 18090 // cv-unqualified version is T1, and for a binary operator @ with 18091 // a left operand of a type whose cv-unqualified version is T1 and 18092 // a right operand of a type whose cv-unqualified version is T2, 18093 // three sets of candidate functions, designated member 18094 // candidates, non-member candidates and built-in candidates, are 18095 // constructed as follows: 18096 // -- If T1 is a complete class type or a class currently being 18097 // defined, the set of member candidates is the result of the 18098 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 18099 // the set of member candidates is empty. 18100 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 18101 Lookup.suppressDiagnostics(); 18102 if (const auto *TyRec = Ty->getAs<RecordType>()) { 18103 // Complete the type if it can be completed. 18104 // If the type is neither complete nor being defined, bail out now. 18105 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() || 18106 TyRec->getDecl()->getDefinition()) { 18107 Lookup.clear(); 18108 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl()); 18109 if (Lookup.empty()) { 18110 Lookups.emplace_back(); 18111 Lookups.back().append(Lookup.begin(), Lookup.end()); 18112 } 18113 } 18114 } 18115 // Perform ADL. 18116 if (SemaRef.getLangOpts().CPlusPlus) 18117 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups); 18118 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 18119 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 18120 if (!D->isInvalidDecl() && 18121 SemaRef.Context.hasSameType(D->getType(), Ty)) 18122 return D; 18123 return nullptr; 18124 })) 18125 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), 18126 VK_LValue, Loc); 18127 if (SemaRef.getLangOpts().CPlusPlus) { 18128 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 18129 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 18130 if (!D->isInvalidDecl() && 18131 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 18132 !Ty.isMoreQualifiedThan(D->getType())) 18133 return D; 18134 return nullptr; 18135 })) { 18136 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 18137 /*DetectVirtual=*/false); 18138 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 18139 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 18140 VD->getType().getUnqualifiedType()))) { 18141 if (SemaRef.CheckBaseClassAccess( 18142 Loc, VD->getType(), Ty, Paths.front(), 18143 /*DiagID=*/0) != Sema::AR_inaccessible) { 18144 SemaRef.BuildBasePathArray(Paths, BasePath); 18145 return SemaRef.BuildDeclRefExpr( 18146 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc); 18147 } 18148 } 18149 } 18150 } 18151 } 18152 if (ReductionIdScopeSpec.isSet()) { 18153 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) 18154 << Ty << Range; 18155 return ExprError(); 18156 } 18157 return ExprEmpty(); 18158 } 18159 18160 namespace { 18161 /// Data for the reduction-based clauses. 18162 struct ReductionData { 18163 /// List of original reduction items. 18164 SmallVector<Expr *, 8> Vars; 18165 /// List of private copies of the reduction items. 18166 SmallVector<Expr *, 8> Privates; 18167 /// LHS expressions for the reduction_op expressions. 18168 SmallVector<Expr *, 8> LHSs; 18169 /// RHS expressions for the reduction_op expressions. 18170 SmallVector<Expr *, 8> RHSs; 18171 /// Reduction operation expression. 18172 SmallVector<Expr *, 8> ReductionOps; 18173 /// inscan copy operation expressions. 18174 SmallVector<Expr *, 8> InscanCopyOps; 18175 /// inscan copy temp array expressions for prefix sums. 18176 SmallVector<Expr *, 8> InscanCopyArrayTemps; 18177 /// inscan copy temp array element expressions for prefix sums. 18178 SmallVector<Expr *, 8> InscanCopyArrayElems; 18179 /// Taskgroup descriptors for the corresponding reduction items in 18180 /// in_reduction clauses. 18181 SmallVector<Expr *, 8> TaskgroupDescriptors; 18182 /// List of captures for clause. 18183 SmallVector<Decl *, 4> ExprCaptures; 18184 /// List of postupdate expressions. 18185 SmallVector<Expr *, 4> ExprPostUpdates; 18186 /// Reduction modifier. 18187 unsigned RedModifier = 0; 18188 ReductionData() = delete; 18189 /// Reserves required memory for the reduction data. 18190 ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) { 18191 Vars.reserve(Size); 18192 Privates.reserve(Size); 18193 LHSs.reserve(Size); 18194 RHSs.reserve(Size); 18195 ReductionOps.reserve(Size); 18196 if (RedModifier == OMPC_REDUCTION_inscan) { 18197 InscanCopyOps.reserve(Size); 18198 InscanCopyArrayTemps.reserve(Size); 18199 InscanCopyArrayElems.reserve(Size); 18200 } 18201 TaskgroupDescriptors.reserve(Size); 18202 ExprCaptures.reserve(Size); 18203 ExprPostUpdates.reserve(Size); 18204 } 18205 /// Stores reduction item and reduction operation only (required for dependent 18206 /// reduction item). 18207 void push(Expr *Item, Expr *ReductionOp) { 18208 Vars.emplace_back(Item); 18209 Privates.emplace_back(nullptr); 18210 LHSs.emplace_back(nullptr); 18211 RHSs.emplace_back(nullptr); 18212 ReductionOps.emplace_back(ReductionOp); 18213 TaskgroupDescriptors.emplace_back(nullptr); 18214 if (RedModifier == OMPC_REDUCTION_inscan) { 18215 InscanCopyOps.push_back(nullptr); 18216 InscanCopyArrayTemps.push_back(nullptr); 18217 InscanCopyArrayElems.push_back(nullptr); 18218 } 18219 } 18220 /// Stores reduction data. 18221 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp, 18222 Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp, 18223 Expr *CopyArrayElem) { 18224 Vars.emplace_back(Item); 18225 Privates.emplace_back(Private); 18226 LHSs.emplace_back(LHS); 18227 RHSs.emplace_back(RHS); 18228 ReductionOps.emplace_back(ReductionOp); 18229 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor); 18230 if (RedModifier == OMPC_REDUCTION_inscan) { 18231 InscanCopyOps.push_back(CopyOp); 18232 InscanCopyArrayTemps.push_back(CopyArrayTemp); 18233 InscanCopyArrayElems.push_back(CopyArrayElem); 18234 } else { 18235 assert(CopyOp == nullptr && CopyArrayTemp == nullptr && 18236 CopyArrayElem == nullptr && 18237 "Copy operation must be used for inscan reductions only."); 18238 } 18239 } 18240 }; 18241 } // namespace 18242 18243 static bool checkOMPArraySectionConstantForReduction( 18244 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement, 18245 SmallVectorImpl<llvm::APSInt> &ArraySizes) { 18246 const Expr *Length = OASE->getLength(); 18247 if (Length == nullptr) { 18248 // For array sections of the form [1:] or [:], we would need to analyze 18249 // the lower bound... 18250 if (OASE->getColonLocFirst().isValid()) 18251 return false; 18252 18253 // This is an array subscript which has implicit length 1! 18254 SingleElement = true; 18255 ArraySizes.push_back(llvm::APSInt::get(1)); 18256 } else { 18257 Expr::EvalResult Result; 18258 if (!Length->EvaluateAsInt(Result, Context)) 18259 return false; 18260 18261 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 18262 SingleElement = (ConstantLengthValue.getSExtValue() == 1); 18263 ArraySizes.push_back(ConstantLengthValue); 18264 } 18265 18266 // Get the base of this array section and walk up from there. 18267 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 18268 18269 // We require length = 1 for all array sections except the right-most to 18270 // guarantee that the memory region is contiguous and has no holes in it. 18271 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) { 18272 Length = TempOASE->getLength(); 18273 if (Length == nullptr) { 18274 // For array sections of the form [1:] or [:], we would need to analyze 18275 // the lower bound... 18276 if (OASE->getColonLocFirst().isValid()) 18277 return false; 18278 18279 // This is an array subscript which has implicit length 1! 18280 ArraySizes.push_back(llvm::APSInt::get(1)); 18281 } else { 18282 Expr::EvalResult Result; 18283 if (!Length->EvaluateAsInt(Result, Context)) 18284 return false; 18285 18286 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 18287 if (ConstantLengthValue.getSExtValue() != 1) 18288 return false; 18289 18290 ArraySizes.push_back(ConstantLengthValue); 18291 } 18292 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 18293 } 18294 18295 // If we have a single element, we don't need to add the implicit lengths. 18296 if (!SingleElement) { 18297 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) { 18298 // Has implicit length 1! 18299 ArraySizes.push_back(llvm::APSInt::get(1)); 18300 Base = TempASE->getBase()->IgnoreParenImpCasts(); 18301 } 18302 } 18303 18304 // This array section can be privatized as a single value or as a constant 18305 // sized array. 18306 return true; 18307 } 18308 18309 static BinaryOperatorKind 18310 getRelatedCompoundReductionOp(BinaryOperatorKind BOK) { 18311 if (BOK == BO_Add) 18312 return BO_AddAssign; 18313 if (BOK == BO_Mul) 18314 return BO_MulAssign; 18315 if (BOK == BO_And) 18316 return BO_AndAssign; 18317 if (BOK == BO_Or) 18318 return BO_OrAssign; 18319 if (BOK == BO_Xor) 18320 return BO_XorAssign; 18321 return BOK; 18322 } 18323 18324 static bool actOnOMPReductionKindClause( 18325 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, 18326 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 18327 SourceLocation ColonLoc, SourceLocation EndLoc, 18328 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 18329 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { 18330 DeclarationName DN = ReductionId.getName(); 18331 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator(); 18332 BinaryOperatorKind BOK = BO_Comma; 18333 18334 ASTContext &Context = S.Context; 18335 // OpenMP [2.14.3.6, reduction clause] 18336 // C 18337 // reduction-identifier is either an identifier or one of the following 18338 // operators: +, -, *, &, |, ^, && and || 18339 // C++ 18340 // reduction-identifier is either an id-expression or one of the following 18341 // operators: +, -, *, &, |, ^, && and || 18342 switch (OOK) { 18343 case OO_Plus: 18344 case OO_Minus: 18345 BOK = BO_Add; 18346 break; 18347 case OO_Star: 18348 BOK = BO_Mul; 18349 break; 18350 case OO_Amp: 18351 BOK = BO_And; 18352 break; 18353 case OO_Pipe: 18354 BOK = BO_Or; 18355 break; 18356 case OO_Caret: 18357 BOK = BO_Xor; 18358 break; 18359 case OO_AmpAmp: 18360 BOK = BO_LAnd; 18361 break; 18362 case OO_PipePipe: 18363 BOK = BO_LOr; 18364 break; 18365 case OO_New: 18366 case OO_Delete: 18367 case OO_Array_New: 18368 case OO_Array_Delete: 18369 case OO_Slash: 18370 case OO_Percent: 18371 case OO_Tilde: 18372 case OO_Exclaim: 18373 case OO_Equal: 18374 case OO_Less: 18375 case OO_Greater: 18376 case OO_LessEqual: 18377 case OO_GreaterEqual: 18378 case OO_PlusEqual: 18379 case OO_MinusEqual: 18380 case OO_StarEqual: 18381 case OO_SlashEqual: 18382 case OO_PercentEqual: 18383 case OO_CaretEqual: 18384 case OO_AmpEqual: 18385 case OO_PipeEqual: 18386 case OO_LessLess: 18387 case OO_GreaterGreater: 18388 case OO_LessLessEqual: 18389 case OO_GreaterGreaterEqual: 18390 case OO_EqualEqual: 18391 case OO_ExclaimEqual: 18392 case OO_Spaceship: 18393 case OO_PlusPlus: 18394 case OO_MinusMinus: 18395 case OO_Comma: 18396 case OO_ArrowStar: 18397 case OO_Arrow: 18398 case OO_Call: 18399 case OO_Subscript: 18400 case OO_Conditional: 18401 case OO_Coawait: 18402 case NUM_OVERLOADED_OPERATORS: 18403 llvm_unreachable("Unexpected reduction identifier"); 18404 case OO_None: 18405 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) { 18406 if (II->isStr("max")) 18407 BOK = BO_GT; 18408 else if (II->isStr("min")) 18409 BOK = BO_LT; 18410 } 18411 break; 18412 } 18413 SourceRange ReductionIdRange; 18414 if (ReductionIdScopeSpec.isValid()) 18415 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 18416 else 18417 ReductionIdRange.setBegin(ReductionId.getBeginLoc()); 18418 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 18419 18420 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 18421 bool FirstIter = true; 18422 for (Expr *RefExpr : VarList) { 18423 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 18424 // OpenMP [2.1, C/C++] 18425 // A list item is a variable or array section, subject to the restrictions 18426 // specified in Section 2.4 on page 42 and in each of the sections 18427 // describing clauses and directives for which a list appears. 18428 // OpenMP [2.14.3.3, Restrictions, p.1] 18429 // A variable that is part of another variable (as an array or 18430 // structure element) cannot appear in a private clause. 18431 if (!FirstIter && IR != ER) 18432 ++IR; 18433 FirstIter = false; 18434 SourceLocation ELoc; 18435 SourceRange ERange; 18436 Expr *SimpleRefExpr = RefExpr; 18437 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 18438 /*AllowArraySection=*/true); 18439 if (Res.second) { 18440 // Try to find 'declare reduction' corresponding construct before using 18441 // builtin/overloaded operators. 18442 QualType Type = Context.DependentTy; 18443 CXXCastPath BasePath; 18444 ExprResult DeclareReductionRef = buildDeclareReductionRef( 18445 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 18446 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 18447 Expr *ReductionOp = nullptr; 18448 if (S.CurContext->isDependentContext() && 18449 (DeclareReductionRef.isUnset() || 18450 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 18451 ReductionOp = DeclareReductionRef.get(); 18452 // It will be analyzed later. 18453 RD.push(RefExpr, ReductionOp); 18454 } 18455 ValueDecl *D = Res.first; 18456 if (!D) 18457 continue; 18458 18459 Expr *TaskgroupDescriptor = nullptr; 18460 QualType Type; 18461 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 18462 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 18463 if (ASE) { 18464 Type = ASE->getType().getNonReferenceType(); 18465 } else if (OASE) { 18466 QualType BaseType = 18467 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 18468 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 18469 Type = ATy->getElementType(); 18470 else 18471 Type = BaseType->getPointeeType(); 18472 Type = Type.getNonReferenceType(); 18473 } else { 18474 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 18475 } 18476 auto *VD = dyn_cast<VarDecl>(D); 18477 18478 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 18479 // A variable that appears in a private clause must not have an incomplete 18480 // type or a reference type. 18481 if (S.RequireCompleteType(ELoc, D->getType(), 18482 diag::err_omp_reduction_incomplete_type)) 18483 continue; 18484 // OpenMP [2.14.3.6, reduction clause, Restrictions] 18485 // A list item that appears in a reduction clause must not be 18486 // const-qualified. 18487 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc, 18488 /*AcceptIfMutable*/ false, ASE || OASE)) 18489 continue; 18490 18491 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); 18492 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 18493 // If a list-item is a reference type then it must bind to the same object 18494 // for all threads of the team. 18495 if (!ASE && !OASE) { 18496 if (VD) { 18497 VarDecl *VDDef = VD->getDefinition(); 18498 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 18499 DSARefChecker Check(Stack); 18500 if (Check.Visit(VDDef->getInit())) { 18501 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) 18502 << getOpenMPClauseName(ClauseKind) << ERange; 18503 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 18504 continue; 18505 } 18506 } 18507 } 18508 18509 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 18510 // in a Construct] 18511 // Variables with the predetermined data-sharing attributes may not be 18512 // listed in data-sharing attributes clauses, except for the cases 18513 // listed below. For these exceptions only, listing a predetermined 18514 // variable in a data-sharing attribute clause is allowed and overrides 18515 // the variable's predetermined data-sharing attributes. 18516 // OpenMP [2.14.3.6, Restrictions, p.3] 18517 // Any number of reduction clauses can be specified on the directive, 18518 // but a list item can appear only once in the reduction clauses for that 18519 // directive. 18520 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 18521 if (DVar.CKind == OMPC_reduction) { 18522 S.Diag(ELoc, diag::err_omp_once_referenced) 18523 << getOpenMPClauseName(ClauseKind); 18524 if (DVar.RefExpr) 18525 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 18526 continue; 18527 } 18528 if (DVar.CKind != OMPC_unknown) { 18529 S.Diag(ELoc, diag::err_omp_wrong_dsa) 18530 << getOpenMPClauseName(DVar.CKind) 18531 << getOpenMPClauseName(OMPC_reduction); 18532 reportOriginalDsa(S, Stack, D, DVar); 18533 continue; 18534 } 18535 18536 // OpenMP [2.14.3.6, Restrictions, p.1] 18537 // A list item that appears in a reduction clause of a worksharing 18538 // construct must be shared in the parallel regions to which any of the 18539 // worksharing regions arising from the worksharing construct bind. 18540 if (isOpenMPWorksharingDirective(CurrDir) && 18541 !isOpenMPParallelDirective(CurrDir) && 18542 !isOpenMPTeamsDirective(CurrDir)) { 18543 DVar = Stack->getImplicitDSA(D, true); 18544 if (DVar.CKind != OMPC_shared) { 18545 S.Diag(ELoc, diag::err_omp_required_access) 18546 << getOpenMPClauseName(OMPC_reduction) 18547 << getOpenMPClauseName(OMPC_shared); 18548 reportOriginalDsa(S, Stack, D, DVar); 18549 continue; 18550 } 18551 } 18552 } else { 18553 // Threadprivates cannot be shared between threads, so dignose if the base 18554 // is a threadprivate variable. 18555 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 18556 if (DVar.CKind == OMPC_threadprivate) { 18557 S.Diag(ELoc, diag::err_omp_wrong_dsa) 18558 << getOpenMPClauseName(DVar.CKind) 18559 << getOpenMPClauseName(OMPC_reduction); 18560 reportOriginalDsa(S, Stack, D, DVar); 18561 continue; 18562 } 18563 } 18564 18565 // Try to find 'declare reduction' corresponding construct before using 18566 // builtin/overloaded operators. 18567 CXXCastPath BasePath; 18568 ExprResult DeclareReductionRef = buildDeclareReductionRef( 18569 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 18570 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 18571 if (DeclareReductionRef.isInvalid()) 18572 continue; 18573 if (S.CurContext->isDependentContext() && 18574 (DeclareReductionRef.isUnset() || 18575 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 18576 RD.push(RefExpr, DeclareReductionRef.get()); 18577 continue; 18578 } 18579 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 18580 // Not allowed reduction identifier is found. 18581 S.Diag(ReductionId.getBeginLoc(), 18582 diag::err_omp_unknown_reduction_identifier) 18583 << Type << ReductionIdRange; 18584 continue; 18585 } 18586 18587 // OpenMP [2.14.3.6, reduction clause, Restrictions] 18588 // The type of a list item that appears in a reduction clause must be valid 18589 // for the reduction-identifier. For a max or min reduction in C, the type 18590 // of the list item must be an allowed arithmetic data type: char, int, 18591 // float, double, or _Bool, possibly modified with long, short, signed, or 18592 // unsigned. For a max or min reduction in C++, the type of the list item 18593 // must be an allowed arithmetic data type: char, wchar_t, int, float, 18594 // double, or bool, possibly modified with long, short, signed, or unsigned. 18595 if (DeclareReductionRef.isUnset()) { 18596 if ((BOK == BO_GT || BOK == BO_LT) && 18597 !(Type->isScalarType() || 18598 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 18599 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 18600 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; 18601 if (!ASE && !OASE) { 18602 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 18603 VarDecl::DeclarationOnly; 18604 S.Diag(D->getLocation(), 18605 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 18606 << D; 18607 } 18608 continue; 18609 } 18610 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 18611 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { 18612 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) 18613 << getOpenMPClauseName(ClauseKind); 18614 if (!ASE && !OASE) { 18615 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 18616 VarDecl::DeclarationOnly; 18617 S.Diag(D->getLocation(), 18618 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 18619 << D; 18620 } 18621 continue; 18622 } 18623 } 18624 18625 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 18626 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", 18627 D->hasAttrs() ? &D->getAttrs() : nullptr); 18628 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), 18629 D->hasAttrs() ? &D->getAttrs() : nullptr); 18630 QualType PrivateTy = Type; 18631 18632 // Try if we can determine constant lengths for all array sections and avoid 18633 // the VLA. 18634 bool ConstantLengthOASE = false; 18635 if (OASE) { 18636 bool SingleElement; 18637 llvm::SmallVector<llvm::APSInt, 4> ArraySizes; 18638 ConstantLengthOASE = checkOMPArraySectionConstantForReduction( 18639 Context, OASE, SingleElement, ArraySizes); 18640 18641 // If we don't have a single element, we must emit a constant array type. 18642 if (ConstantLengthOASE && !SingleElement) { 18643 for (llvm::APSInt &Size : ArraySizes) 18644 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr, 18645 ArrayType::Normal, 18646 /*IndexTypeQuals=*/0); 18647 } 18648 } 18649 18650 if ((OASE && !ConstantLengthOASE) || 18651 (!OASE && !ASE && 18652 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 18653 if (!Context.getTargetInfo().isVLASupported()) { 18654 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) { 18655 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 18656 S.Diag(ELoc, diag::note_vla_unsupported); 18657 continue; 18658 } else { 18659 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 18660 S.targetDiag(ELoc, diag::note_vla_unsupported); 18661 } 18662 } 18663 // For arrays/array sections only: 18664 // Create pseudo array type for private copy. The size for this array will 18665 // be generated during codegen. 18666 // For array subscripts or single variables Private Ty is the same as Type 18667 // (type of the variable or single array element). 18668 PrivateTy = Context.getVariableArrayType( 18669 Type, 18670 new (Context) 18671 OpaqueValueExpr(ELoc, Context.getSizeType(), VK_PRValue), 18672 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 18673 } else if (!ASE && !OASE && 18674 Context.getAsArrayType(D->getType().getNonReferenceType())) { 18675 PrivateTy = D->getType().getNonReferenceType(); 18676 } 18677 // Private copy. 18678 VarDecl *PrivateVD = 18679 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 18680 D->hasAttrs() ? &D->getAttrs() : nullptr, 18681 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 18682 // Add initializer for private variable. 18683 Expr *Init = nullptr; 18684 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); 18685 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); 18686 if (DeclareReductionRef.isUsable()) { 18687 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 18688 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 18689 if (DRD->getInitializer()) { 18690 Init = DRDRef; 18691 RHSVD->setInit(DRDRef); 18692 RHSVD->setInitStyle(VarDecl::CallInit); 18693 } 18694 } else { 18695 switch (BOK) { 18696 case BO_Add: 18697 case BO_Xor: 18698 case BO_Or: 18699 case BO_LOr: 18700 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 18701 if (Type->isScalarType() || Type->isAnyComplexType()) 18702 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 18703 break; 18704 case BO_Mul: 18705 case BO_LAnd: 18706 if (Type->isScalarType() || Type->isAnyComplexType()) { 18707 // '*' and '&&' reduction ops - initializer is '1'. 18708 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 18709 } 18710 break; 18711 case BO_And: { 18712 // '&' reduction op - initializer is '~0'. 18713 QualType OrigType = Type; 18714 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 18715 Type = ComplexTy->getElementType(); 18716 if (Type->isRealFloatingType()) { 18717 llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue( 18718 Context.getFloatTypeSemantics(Type)); 18719 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 18720 Type, ELoc); 18721 } else if (Type->isScalarType()) { 18722 uint64_t Size = Context.getTypeSize(Type); 18723 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 18724 llvm::APInt InitValue = llvm::APInt::getAllOnes(Size); 18725 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 18726 } 18727 if (Init && OrigType->isAnyComplexType()) { 18728 // Init = 0xFFFF + 0xFFFFi; 18729 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 18730 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 18731 } 18732 Type = OrigType; 18733 break; 18734 } 18735 case BO_LT: 18736 case BO_GT: { 18737 // 'min' reduction op - initializer is 'Largest representable number in 18738 // the reduction list item type'. 18739 // 'max' reduction op - initializer is 'Least representable number in 18740 // the reduction list item type'. 18741 if (Type->isIntegerType() || Type->isPointerType()) { 18742 bool IsSigned = Type->hasSignedIntegerRepresentation(); 18743 uint64_t Size = Context.getTypeSize(Type); 18744 QualType IntTy = 18745 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 18746 llvm::APInt InitValue = 18747 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 18748 : llvm::APInt::getMinValue(Size) 18749 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 18750 : llvm::APInt::getMaxValue(Size); 18751 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 18752 if (Type->isPointerType()) { 18753 // Cast to pointer type. 18754 ExprResult CastExpr = S.BuildCStyleCastExpr( 18755 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init); 18756 if (CastExpr.isInvalid()) 18757 continue; 18758 Init = CastExpr.get(); 18759 } 18760 } else if (Type->isRealFloatingType()) { 18761 llvm::APFloat InitValue = llvm::APFloat::getLargest( 18762 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 18763 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 18764 Type, ELoc); 18765 } 18766 break; 18767 } 18768 case BO_PtrMemD: 18769 case BO_PtrMemI: 18770 case BO_MulAssign: 18771 case BO_Div: 18772 case BO_Rem: 18773 case BO_Sub: 18774 case BO_Shl: 18775 case BO_Shr: 18776 case BO_LE: 18777 case BO_GE: 18778 case BO_EQ: 18779 case BO_NE: 18780 case BO_Cmp: 18781 case BO_AndAssign: 18782 case BO_XorAssign: 18783 case BO_OrAssign: 18784 case BO_Assign: 18785 case BO_AddAssign: 18786 case BO_SubAssign: 18787 case BO_DivAssign: 18788 case BO_RemAssign: 18789 case BO_ShlAssign: 18790 case BO_ShrAssign: 18791 case BO_Comma: 18792 llvm_unreachable("Unexpected reduction operation"); 18793 } 18794 } 18795 if (Init && DeclareReductionRef.isUnset()) { 18796 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 18797 // Store initializer for single element in private copy. Will be used 18798 // during codegen. 18799 PrivateVD->setInit(RHSVD->getInit()); 18800 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 18801 } else if (!Init) { 18802 S.ActOnUninitializedDecl(RHSVD); 18803 // Store initializer for single element in private copy. Will be used 18804 // during codegen. 18805 PrivateVD->setInit(RHSVD->getInit()); 18806 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 18807 } 18808 if (RHSVD->isInvalidDecl()) 18809 continue; 18810 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 18811 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) 18812 << Type << ReductionIdRange; 18813 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 18814 VarDecl::DeclarationOnly; 18815 S.Diag(D->getLocation(), 18816 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 18817 << D; 18818 continue; 18819 } 18820 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); 18821 ExprResult ReductionOp; 18822 if (DeclareReductionRef.isUsable()) { 18823 QualType RedTy = DeclareReductionRef.get()->getType(); 18824 QualType PtrRedTy = Context.getPointerType(RedTy); 18825 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 18826 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 18827 if (!BasePath.empty()) { 18828 LHS = S.DefaultLvalueConversion(LHS.get()); 18829 RHS = S.DefaultLvalueConversion(RHS.get()); 18830 LHS = ImplicitCastExpr::Create( 18831 Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath, 18832 LHS.get()->getValueKind(), FPOptionsOverride()); 18833 RHS = ImplicitCastExpr::Create( 18834 Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath, 18835 RHS.get()->getValueKind(), FPOptionsOverride()); 18836 } 18837 FunctionProtoType::ExtProtoInfo EPI; 18838 QualType Params[] = {PtrRedTy, PtrRedTy}; 18839 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 18840 auto *OVE = new (Context) OpaqueValueExpr( 18841 ELoc, Context.getPointerType(FnTy), VK_PRValue, OK_Ordinary, 18842 S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); 18843 Expr *Args[] = {LHS.get(), RHS.get()}; 18844 ReductionOp = 18845 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_PRValue, ELoc, 18846 S.CurFPFeatureOverrides()); 18847 } else { 18848 BinaryOperatorKind CombBOK = getRelatedCompoundReductionOp(BOK); 18849 if (Type->isRecordType() && CombBOK != BOK) { 18850 Sema::TentativeAnalysisScope Trap(S); 18851 ReductionOp = 18852 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 18853 CombBOK, LHSDRE, RHSDRE); 18854 } 18855 if (!ReductionOp.isUsable()) { 18856 ReductionOp = 18857 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, 18858 LHSDRE, RHSDRE); 18859 if (ReductionOp.isUsable()) { 18860 if (BOK != BO_LT && BOK != BO_GT) { 18861 ReductionOp = 18862 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 18863 BO_Assign, LHSDRE, ReductionOp.get()); 18864 } else { 18865 auto *ConditionalOp = new (Context) 18866 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, 18867 RHSDRE, Type, VK_LValue, OK_Ordinary); 18868 ReductionOp = 18869 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 18870 BO_Assign, LHSDRE, ConditionalOp); 18871 } 18872 } 18873 } 18874 if (ReductionOp.isUsable()) 18875 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(), 18876 /*DiscardedValue*/ false); 18877 if (!ReductionOp.isUsable()) 18878 continue; 18879 } 18880 18881 // Add copy operations for inscan reductions. 18882 // LHS = RHS; 18883 ExprResult CopyOpRes, TempArrayRes, TempArrayElem; 18884 if (ClauseKind == OMPC_reduction && 18885 RD.RedModifier == OMPC_REDUCTION_inscan) { 18886 ExprResult RHS = S.DefaultLvalueConversion(RHSDRE); 18887 CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE, 18888 RHS.get()); 18889 if (!CopyOpRes.isUsable()) 18890 continue; 18891 CopyOpRes = 18892 S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true); 18893 if (!CopyOpRes.isUsable()) 18894 continue; 18895 // For simd directive and simd-based directives in simd mode no need to 18896 // construct temp array, need just a single temp element. 18897 if (Stack->getCurrentDirective() == OMPD_simd || 18898 (S.getLangOpts().OpenMPSimd && 18899 isOpenMPSimdDirective(Stack->getCurrentDirective()))) { 18900 VarDecl *TempArrayVD = 18901 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 18902 D->hasAttrs() ? &D->getAttrs() : nullptr); 18903 // Add a constructor to the temp decl. 18904 S.ActOnUninitializedDecl(TempArrayVD); 18905 TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc); 18906 } else { 18907 // Build temp array for prefix sum. 18908 auto *Dim = new (S.Context) 18909 OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue); 18910 QualType ArrayTy = 18911 S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal, 18912 /*IndexTypeQuals=*/0, {ELoc, ELoc}); 18913 VarDecl *TempArrayVD = 18914 buildVarDecl(S, ELoc, ArrayTy, D->getName(), 18915 D->hasAttrs() ? &D->getAttrs() : nullptr); 18916 // Add a constructor to the temp decl. 18917 S.ActOnUninitializedDecl(TempArrayVD); 18918 TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc); 18919 TempArrayElem = 18920 S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get()); 18921 auto *Idx = new (S.Context) 18922 OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue); 18923 TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(), 18924 ELoc, Idx, ELoc); 18925 } 18926 } 18927 18928 // OpenMP [2.15.4.6, Restrictions, p.2] 18929 // A list item that appears in an in_reduction clause of a task construct 18930 // must appear in a task_reduction clause of a construct associated with a 18931 // taskgroup region that includes the participating task in its taskgroup 18932 // set. The construct associated with the innermost region that meets this 18933 // condition must specify the same reduction-identifier as the in_reduction 18934 // clause. 18935 if (ClauseKind == OMPC_in_reduction) { 18936 SourceRange ParentSR; 18937 BinaryOperatorKind ParentBOK; 18938 const Expr *ParentReductionOp = nullptr; 18939 Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr; 18940 DSAStackTy::DSAVarData ParentBOKDSA = 18941 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK, 18942 ParentBOKTD); 18943 DSAStackTy::DSAVarData ParentReductionOpDSA = 18944 Stack->getTopMostTaskgroupReductionData( 18945 D, ParentSR, ParentReductionOp, ParentReductionOpTD); 18946 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown; 18947 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown; 18948 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) || 18949 (DeclareReductionRef.isUsable() && IsParentBOK) || 18950 (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) { 18951 bool EmitError = true; 18952 if (IsParentReductionOp && DeclareReductionRef.isUsable()) { 18953 llvm::FoldingSetNodeID RedId, ParentRedId; 18954 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true); 18955 DeclareReductionRef.get()->Profile(RedId, Context, 18956 /*Canonical=*/true); 18957 EmitError = RedId != ParentRedId; 18958 } 18959 if (EmitError) { 18960 S.Diag(ReductionId.getBeginLoc(), 18961 diag::err_omp_reduction_identifier_mismatch) 18962 << ReductionIdRange << RefExpr->getSourceRange(); 18963 S.Diag(ParentSR.getBegin(), 18964 diag::note_omp_previous_reduction_identifier) 18965 << ParentSR 18966 << (IsParentBOK ? ParentBOKDSA.RefExpr 18967 : ParentReductionOpDSA.RefExpr) 18968 ->getSourceRange(); 18969 continue; 18970 } 18971 } 18972 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD; 18973 } 18974 18975 DeclRefExpr *Ref = nullptr; 18976 Expr *VarsExpr = RefExpr->IgnoreParens(); 18977 if (!VD && !S.CurContext->isDependentContext()) { 18978 if (ASE || OASE) { 18979 TransformExprToCaptures RebuildToCapture(S, D); 18980 VarsExpr = 18981 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 18982 Ref = RebuildToCapture.getCapturedExpr(); 18983 } else { 18984 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); 18985 } 18986 if (!S.isOpenMPCapturedDecl(D)) { 18987 RD.ExprCaptures.emplace_back(Ref->getDecl()); 18988 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 18989 ExprResult RefRes = S.DefaultLvalueConversion(Ref); 18990 if (!RefRes.isUsable()) 18991 continue; 18992 ExprResult PostUpdateRes = 18993 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 18994 RefRes.get()); 18995 if (!PostUpdateRes.isUsable()) 18996 continue; 18997 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 18998 Stack->getCurrentDirective() == OMPD_taskgroup) { 18999 S.Diag(RefExpr->getExprLoc(), 19000 diag::err_omp_reduction_non_addressable_expression) 19001 << RefExpr->getSourceRange(); 19002 continue; 19003 } 19004 RD.ExprPostUpdates.emplace_back( 19005 S.IgnoredValueConversions(PostUpdateRes.get()).get()); 19006 } 19007 } 19008 } 19009 // All reduction items are still marked as reduction (to do not increase 19010 // code base size). 19011 unsigned Modifier = RD.RedModifier; 19012 // Consider task_reductions as reductions with task modifier. Required for 19013 // correct analysis of in_reduction clauses. 19014 if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction) 19015 Modifier = OMPC_REDUCTION_task; 19016 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier, 19017 ASE || OASE); 19018 if (Modifier == OMPC_REDUCTION_task && 19019 (CurrDir == OMPD_taskgroup || 19020 ((isOpenMPParallelDirective(CurrDir) || 19021 isOpenMPWorksharingDirective(CurrDir)) && 19022 !isOpenMPSimdDirective(CurrDir)))) { 19023 if (DeclareReductionRef.isUsable()) 19024 Stack->addTaskgroupReductionData(D, ReductionIdRange, 19025 DeclareReductionRef.get()); 19026 else 19027 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK); 19028 } 19029 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(), 19030 TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(), 19031 TempArrayElem.get()); 19032 } 19033 return RD.Vars.empty(); 19034 } 19035 19036 OMPClause *Sema::ActOnOpenMPReductionClause( 19037 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, 19038 SourceLocation StartLoc, SourceLocation LParenLoc, 19039 SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, 19040 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 19041 ArrayRef<Expr *> UnresolvedReductions) { 19042 if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) { 19043 Diag(LParenLoc, diag::err_omp_unexpected_clause_value) 19044 << getListOfPossibleValues(OMPC_reduction, /*First=*/0, 19045 /*Last=*/OMPC_REDUCTION_unknown) 19046 << getOpenMPClauseName(OMPC_reduction); 19047 return nullptr; 19048 } 19049 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions 19050 // A reduction clause with the inscan reduction-modifier may only appear on a 19051 // worksharing-loop construct, a worksharing-loop SIMD construct, a simd 19052 // construct, a parallel worksharing-loop construct or a parallel 19053 // worksharing-loop SIMD construct. 19054 if (Modifier == OMPC_REDUCTION_inscan && 19055 (DSAStack->getCurrentDirective() != OMPD_for && 19056 DSAStack->getCurrentDirective() != OMPD_for_simd && 19057 DSAStack->getCurrentDirective() != OMPD_simd && 19058 DSAStack->getCurrentDirective() != OMPD_parallel_for && 19059 DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) { 19060 Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction); 19061 return nullptr; 19062 } 19063 19064 ReductionData RD(VarList.size(), Modifier); 19065 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, 19066 StartLoc, LParenLoc, ColonLoc, EndLoc, 19067 ReductionIdScopeSpec, ReductionId, 19068 UnresolvedReductions, RD)) 19069 return nullptr; 19070 19071 return OMPReductionClause::Create( 19072 Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier, 19073 RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 19074 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps, 19075 RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems, 19076 buildPreInits(Context, RD.ExprCaptures), 19077 buildPostUpdate(*this, RD.ExprPostUpdates)); 19078 } 19079 19080 OMPClause *Sema::ActOnOpenMPTaskReductionClause( 19081 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 19082 SourceLocation ColonLoc, SourceLocation EndLoc, 19083 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 19084 ArrayRef<Expr *> UnresolvedReductions) { 19085 ReductionData RD(VarList.size()); 19086 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList, 19087 StartLoc, LParenLoc, ColonLoc, EndLoc, 19088 ReductionIdScopeSpec, ReductionId, 19089 UnresolvedReductions, RD)) 19090 return nullptr; 19091 19092 return OMPTaskReductionClause::Create( 19093 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 19094 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 19095 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 19096 buildPreInits(Context, RD.ExprCaptures), 19097 buildPostUpdate(*this, RD.ExprPostUpdates)); 19098 } 19099 19100 OMPClause *Sema::ActOnOpenMPInReductionClause( 19101 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 19102 SourceLocation ColonLoc, SourceLocation EndLoc, 19103 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 19104 ArrayRef<Expr *> UnresolvedReductions) { 19105 ReductionData RD(VarList.size()); 19106 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList, 19107 StartLoc, LParenLoc, ColonLoc, EndLoc, 19108 ReductionIdScopeSpec, ReductionId, 19109 UnresolvedReductions, RD)) 19110 return nullptr; 19111 19112 return OMPInReductionClause::Create( 19113 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 19114 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 19115 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors, 19116 buildPreInits(Context, RD.ExprCaptures), 19117 buildPostUpdate(*this, RD.ExprPostUpdates)); 19118 } 19119 19120 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 19121 SourceLocation LinLoc) { 19122 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 19123 LinKind == OMPC_LINEAR_unknown) { 19124 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 19125 return true; 19126 } 19127 return false; 19128 } 19129 19130 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, 19131 OpenMPLinearClauseKind LinKind, QualType Type, 19132 bool IsDeclareSimd) { 19133 const auto *VD = dyn_cast_or_null<VarDecl>(D); 19134 // A variable must not have an incomplete type or a reference type. 19135 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 19136 return true; 19137 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 19138 !Type->isReferenceType()) { 19139 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 19140 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 19141 return true; 19142 } 19143 Type = Type.getNonReferenceType(); 19144 19145 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 19146 // A variable that is privatized must not have a const-qualified type 19147 // unless it is of class type with a mutable member. This restriction does 19148 // not apply to the firstprivate clause, nor to the linear clause on 19149 // declarative directives (like declare simd). 19150 if (!IsDeclareSimd && 19151 rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc)) 19152 return true; 19153 19154 // A list item must be of integral or pointer type. 19155 Type = Type.getUnqualifiedType().getCanonicalType(); 19156 const auto *Ty = Type.getTypePtrOrNull(); 19157 if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() && 19158 !Ty->isIntegralType(Context) && !Ty->isPointerType())) { 19159 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 19160 if (D) { 19161 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 19162 VarDecl::DeclarationOnly; 19163 Diag(D->getLocation(), 19164 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 19165 << D; 19166 } 19167 return true; 19168 } 19169 return false; 19170 } 19171 19172 OMPClause *Sema::ActOnOpenMPLinearClause( 19173 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 19174 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 19175 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 19176 SmallVector<Expr *, 8> Vars; 19177 SmallVector<Expr *, 8> Privates; 19178 SmallVector<Expr *, 8> Inits; 19179 SmallVector<Decl *, 4> ExprCaptures; 19180 SmallVector<Expr *, 4> ExprPostUpdates; 19181 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 19182 LinKind = OMPC_LINEAR_val; 19183 for (Expr *RefExpr : VarList) { 19184 assert(RefExpr && "NULL expr in OpenMP linear clause."); 19185 SourceLocation ELoc; 19186 SourceRange ERange; 19187 Expr *SimpleRefExpr = RefExpr; 19188 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 19189 if (Res.second) { 19190 // It will be analyzed later. 19191 Vars.push_back(RefExpr); 19192 Privates.push_back(nullptr); 19193 Inits.push_back(nullptr); 19194 } 19195 ValueDecl *D = Res.first; 19196 if (!D) 19197 continue; 19198 19199 QualType Type = D->getType(); 19200 auto *VD = dyn_cast<VarDecl>(D); 19201 19202 // OpenMP [2.14.3.7, linear clause] 19203 // A list-item cannot appear in more than one linear clause. 19204 // A list-item that appears in a linear clause cannot appear in any 19205 // other data-sharing attribute clause. 19206 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 19207 if (DVar.RefExpr) { 19208 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 19209 << getOpenMPClauseName(OMPC_linear); 19210 reportOriginalDsa(*this, DSAStack, D, DVar); 19211 continue; 19212 } 19213 19214 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 19215 continue; 19216 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 19217 19218 // Build private copy of original var. 19219 VarDecl *Private = 19220 buildVarDecl(*this, ELoc, Type, D->getName(), 19221 D->hasAttrs() ? &D->getAttrs() : nullptr, 19222 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 19223 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 19224 // Build var to save initial value. 19225 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 19226 Expr *InitExpr; 19227 DeclRefExpr *Ref = nullptr; 19228 if (!VD && !CurContext->isDependentContext()) { 19229 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 19230 if (!isOpenMPCapturedDecl(D)) { 19231 ExprCaptures.push_back(Ref->getDecl()); 19232 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 19233 ExprResult RefRes = DefaultLvalueConversion(Ref); 19234 if (!RefRes.isUsable()) 19235 continue; 19236 ExprResult PostUpdateRes = 19237 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 19238 SimpleRefExpr, RefRes.get()); 19239 if (!PostUpdateRes.isUsable()) 19240 continue; 19241 ExprPostUpdates.push_back( 19242 IgnoredValueConversions(PostUpdateRes.get()).get()); 19243 } 19244 } 19245 } 19246 if (LinKind == OMPC_LINEAR_uval) 19247 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 19248 else 19249 InitExpr = VD ? SimpleRefExpr : Ref; 19250 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 19251 /*DirectInit=*/false); 19252 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 19253 19254 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 19255 Vars.push_back((VD || CurContext->isDependentContext()) 19256 ? RefExpr->IgnoreParens() 19257 : Ref); 19258 Privates.push_back(PrivateRef); 19259 Inits.push_back(InitRef); 19260 } 19261 19262 if (Vars.empty()) 19263 return nullptr; 19264 19265 Expr *StepExpr = Step; 19266 Expr *CalcStepExpr = nullptr; 19267 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 19268 !Step->isInstantiationDependent() && 19269 !Step->containsUnexpandedParameterPack()) { 19270 SourceLocation StepLoc = Step->getBeginLoc(); 19271 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 19272 if (Val.isInvalid()) 19273 return nullptr; 19274 StepExpr = Val.get(); 19275 19276 // Build var to save the step value. 19277 VarDecl *SaveVar = 19278 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 19279 ExprResult SaveRef = 19280 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 19281 ExprResult CalcStep = 19282 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 19283 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false); 19284 19285 // Warn about zero linear step (it would be probably better specified as 19286 // making corresponding variables 'const'). 19287 if (Optional<llvm::APSInt> Result = 19288 StepExpr->getIntegerConstantExpr(Context)) { 19289 if (!Result->isNegative() && !Result->isStrictlyPositive()) 19290 Diag(StepLoc, diag::warn_omp_linear_step_zero) 19291 << Vars[0] << (Vars.size() > 1); 19292 } else if (CalcStep.isUsable()) { 19293 // Calculate the step beforehand instead of doing this on each iteration. 19294 // (This is not used if the number of iterations may be kfold-ed). 19295 CalcStepExpr = CalcStep.get(); 19296 } 19297 } 19298 19299 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 19300 ColonLoc, EndLoc, Vars, Privates, Inits, 19301 StepExpr, CalcStepExpr, 19302 buildPreInits(Context, ExprCaptures), 19303 buildPostUpdate(*this, ExprPostUpdates)); 19304 } 19305 19306 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 19307 Expr *NumIterations, Sema &SemaRef, 19308 Scope *S, DSAStackTy *Stack) { 19309 // Walk the vars and build update/final expressions for the CodeGen. 19310 SmallVector<Expr *, 8> Updates; 19311 SmallVector<Expr *, 8> Finals; 19312 SmallVector<Expr *, 8> UsedExprs; 19313 Expr *Step = Clause.getStep(); 19314 Expr *CalcStep = Clause.getCalcStep(); 19315 // OpenMP [2.14.3.7, linear clause] 19316 // If linear-step is not specified it is assumed to be 1. 19317 if (!Step) 19318 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 19319 else if (CalcStep) 19320 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 19321 bool HasErrors = false; 19322 auto CurInit = Clause.inits().begin(); 19323 auto CurPrivate = Clause.privates().begin(); 19324 OpenMPLinearClauseKind LinKind = Clause.getModifier(); 19325 for (Expr *RefExpr : Clause.varlists()) { 19326 SourceLocation ELoc; 19327 SourceRange ERange; 19328 Expr *SimpleRefExpr = RefExpr; 19329 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange); 19330 ValueDecl *D = Res.first; 19331 if (Res.second || !D) { 19332 Updates.push_back(nullptr); 19333 Finals.push_back(nullptr); 19334 HasErrors = true; 19335 continue; 19336 } 19337 auto &&Info = Stack->isLoopControlVariable(D); 19338 // OpenMP [2.15.11, distribute simd Construct] 19339 // A list item may not appear in a linear clause, unless it is the loop 19340 // iteration variable. 19341 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) && 19342 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) { 19343 SemaRef.Diag(ELoc, 19344 diag::err_omp_linear_distribute_var_non_loop_iteration); 19345 Updates.push_back(nullptr); 19346 Finals.push_back(nullptr); 19347 HasErrors = true; 19348 continue; 19349 } 19350 Expr *InitExpr = *CurInit; 19351 19352 // Build privatized reference to the current linear var. 19353 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 19354 Expr *CapturedRef; 19355 if (LinKind == OMPC_LINEAR_uval) 19356 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 19357 else 19358 CapturedRef = 19359 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 19360 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 19361 /*RefersToCapture=*/true); 19362 19363 // Build update: Var = InitExpr + IV * Step 19364 ExprResult Update; 19365 if (!Info.first) 19366 Update = buildCounterUpdate( 19367 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step, 19368 /*Subtract=*/false, /*IsNonRectangularLB=*/false); 19369 else 19370 Update = *CurPrivate; 19371 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(), 19372 /*DiscardedValue*/ false); 19373 19374 // Build final: Var = PrivCopy; 19375 ExprResult Final; 19376 if (!Info.first) 19377 Final = SemaRef.BuildBinOp( 19378 S, RefExpr->getExprLoc(), BO_Assign, CapturedRef, 19379 SemaRef.DefaultLvalueConversion(*CurPrivate).get()); 19380 else 19381 Final = *CurPrivate; 19382 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(), 19383 /*DiscardedValue*/ false); 19384 19385 if (!Update.isUsable() || !Final.isUsable()) { 19386 Updates.push_back(nullptr); 19387 Finals.push_back(nullptr); 19388 UsedExprs.push_back(nullptr); 19389 HasErrors = true; 19390 } else { 19391 Updates.push_back(Update.get()); 19392 Finals.push_back(Final.get()); 19393 if (!Info.first) 19394 UsedExprs.push_back(SimpleRefExpr); 19395 } 19396 ++CurInit; 19397 ++CurPrivate; 19398 } 19399 if (Expr *S = Clause.getStep()) 19400 UsedExprs.push_back(S); 19401 // Fill the remaining part with the nullptr. 19402 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr); 19403 Clause.setUpdates(Updates); 19404 Clause.setFinals(Finals); 19405 Clause.setUsedExprs(UsedExprs); 19406 return HasErrors; 19407 } 19408 19409 OMPClause *Sema::ActOnOpenMPAlignedClause( 19410 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 19411 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 19412 SmallVector<Expr *, 8> Vars; 19413 for (Expr *RefExpr : VarList) { 19414 assert(RefExpr && "NULL expr in OpenMP linear clause."); 19415 SourceLocation ELoc; 19416 SourceRange ERange; 19417 Expr *SimpleRefExpr = RefExpr; 19418 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 19419 if (Res.second) { 19420 // It will be analyzed later. 19421 Vars.push_back(RefExpr); 19422 } 19423 ValueDecl *D = Res.first; 19424 if (!D) 19425 continue; 19426 19427 QualType QType = D->getType(); 19428 auto *VD = dyn_cast<VarDecl>(D); 19429 19430 // OpenMP [2.8.1, simd construct, Restrictions] 19431 // The type of list items appearing in the aligned clause must be 19432 // array, pointer, reference to array, or reference to pointer. 19433 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 19434 const Type *Ty = QType.getTypePtrOrNull(); 19435 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 19436 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 19437 << QType << getLangOpts().CPlusPlus << ERange; 19438 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 19439 VarDecl::DeclarationOnly; 19440 Diag(D->getLocation(), 19441 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 19442 << D; 19443 continue; 19444 } 19445 19446 // OpenMP [2.8.1, simd construct, Restrictions] 19447 // A list-item cannot appear in more than one aligned clause. 19448 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 19449 Diag(ELoc, diag::err_omp_used_in_clause_twice) 19450 << 0 << getOpenMPClauseName(OMPC_aligned) << ERange; 19451 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 19452 << getOpenMPClauseName(OMPC_aligned); 19453 continue; 19454 } 19455 19456 DeclRefExpr *Ref = nullptr; 19457 if (!VD && isOpenMPCapturedDecl(D)) 19458 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 19459 Vars.push_back(DefaultFunctionArrayConversion( 19460 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 19461 .get()); 19462 } 19463 19464 // OpenMP [2.8.1, simd construct, Description] 19465 // The parameter of the aligned clause, alignment, must be a constant 19466 // positive integer expression. 19467 // If no optional parameter is specified, implementation-defined default 19468 // alignments for SIMD instructions on the target platforms are assumed. 19469 if (Alignment != nullptr) { 19470 ExprResult AlignResult = 19471 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 19472 if (AlignResult.isInvalid()) 19473 return nullptr; 19474 Alignment = AlignResult.get(); 19475 } 19476 if (Vars.empty()) 19477 return nullptr; 19478 19479 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 19480 EndLoc, Vars, Alignment); 19481 } 19482 19483 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 19484 SourceLocation StartLoc, 19485 SourceLocation LParenLoc, 19486 SourceLocation EndLoc) { 19487 SmallVector<Expr *, 8> Vars; 19488 SmallVector<Expr *, 8> SrcExprs; 19489 SmallVector<Expr *, 8> DstExprs; 19490 SmallVector<Expr *, 8> AssignmentOps; 19491 for (Expr *RefExpr : VarList) { 19492 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 19493 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 19494 // It will be analyzed later. 19495 Vars.push_back(RefExpr); 19496 SrcExprs.push_back(nullptr); 19497 DstExprs.push_back(nullptr); 19498 AssignmentOps.push_back(nullptr); 19499 continue; 19500 } 19501 19502 SourceLocation ELoc = RefExpr->getExprLoc(); 19503 // OpenMP [2.1, C/C++] 19504 // A list item is a variable name. 19505 // OpenMP [2.14.4.1, Restrictions, p.1] 19506 // A list item that appears in a copyin clause must be threadprivate. 19507 auto *DE = dyn_cast<DeclRefExpr>(RefExpr); 19508 if (!DE || !isa<VarDecl>(DE->getDecl())) { 19509 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 19510 << 0 << RefExpr->getSourceRange(); 19511 continue; 19512 } 19513 19514 Decl *D = DE->getDecl(); 19515 auto *VD = cast<VarDecl>(D); 19516 19517 QualType Type = VD->getType(); 19518 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 19519 // It will be analyzed later. 19520 Vars.push_back(DE); 19521 SrcExprs.push_back(nullptr); 19522 DstExprs.push_back(nullptr); 19523 AssignmentOps.push_back(nullptr); 19524 continue; 19525 } 19526 19527 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 19528 // A list item that appears in a copyin clause must be threadprivate. 19529 if (!DSAStack->isThreadPrivate(VD)) { 19530 Diag(ELoc, diag::err_omp_required_access) 19531 << getOpenMPClauseName(OMPC_copyin) 19532 << getOpenMPDirectiveName(OMPD_threadprivate); 19533 continue; 19534 } 19535 19536 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 19537 // A variable of class type (or array thereof) that appears in a 19538 // copyin clause requires an accessible, unambiguous copy assignment 19539 // operator for the class type. 19540 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 19541 VarDecl *SrcVD = 19542 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(), 19543 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 19544 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr( 19545 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 19546 VarDecl *DstVD = 19547 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst", 19548 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 19549 DeclRefExpr *PseudoDstExpr = 19550 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 19551 // For arrays generate assignment operation for single element and replace 19552 // it by the original array element in CodeGen. 19553 ExprResult AssignmentOp = 19554 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr, 19555 PseudoSrcExpr); 19556 if (AssignmentOp.isInvalid()) 19557 continue; 19558 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 19559 /*DiscardedValue*/ false); 19560 if (AssignmentOp.isInvalid()) 19561 continue; 19562 19563 DSAStack->addDSA(VD, DE, OMPC_copyin); 19564 Vars.push_back(DE); 19565 SrcExprs.push_back(PseudoSrcExpr); 19566 DstExprs.push_back(PseudoDstExpr); 19567 AssignmentOps.push_back(AssignmentOp.get()); 19568 } 19569 19570 if (Vars.empty()) 19571 return nullptr; 19572 19573 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 19574 SrcExprs, DstExprs, AssignmentOps); 19575 } 19576 19577 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 19578 SourceLocation StartLoc, 19579 SourceLocation LParenLoc, 19580 SourceLocation EndLoc) { 19581 SmallVector<Expr *, 8> Vars; 19582 SmallVector<Expr *, 8> SrcExprs; 19583 SmallVector<Expr *, 8> DstExprs; 19584 SmallVector<Expr *, 8> AssignmentOps; 19585 for (Expr *RefExpr : VarList) { 19586 assert(RefExpr && "NULL expr in OpenMP linear clause."); 19587 SourceLocation ELoc; 19588 SourceRange ERange; 19589 Expr *SimpleRefExpr = RefExpr; 19590 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 19591 if (Res.second) { 19592 // It will be analyzed later. 19593 Vars.push_back(RefExpr); 19594 SrcExprs.push_back(nullptr); 19595 DstExprs.push_back(nullptr); 19596 AssignmentOps.push_back(nullptr); 19597 } 19598 ValueDecl *D = Res.first; 19599 if (!D) 19600 continue; 19601 19602 QualType Type = D->getType(); 19603 auto *VD = dyn_cast<VarDecl>(D); 19604 19605 // OpenMP [2.14.4.2, Restrictions, p.2] 19606 // A list item that appears in a copyprivate clause may not appear in a 19607 // private or firstprivate clause on the single construct. 19608 if (!VD || !DSAStack->isThreadPrivate(VD)) { 19609 DSAStackTy::DSAVarData DVar = 19610 DSAStack->getTopDSA(D, /*FromParent=*/false); 19611 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 19612 DVar.RefExpr) { 19613 Diag(ELoc, diag::err_omp_wrong_dsa) 19614 << getOpenMPClauseName(DVar.CKind) 19615 << getOpenMPClauseName(OMPC_copyprivate); 19616 reportOriginalDsa(*this, DSAStack, D, DVar); 19617 continue; 19618 } 19619 19620 // OpenMP [2.11.4.2, Restrictions, p.1] 19621 // All list items that appear in a copyprivate clause must be either 19622 // threadprivate or private in the enclosing context. 19623 if (DVar.CKind == OMPC_unknown) { 19624 DVar = DSAStack->getImplicitDSA(D, false); 19625 if (DVar.CKind == OMPC_shared) { 19626 Diag(ELoc, diag::err_omp_required_access) 19627 << getOpenMPClauseName(OMPC_copyprivate) 19628 << "threadprivate or private in the enclosing context"; 19629 reportOriginalDsa(*this, DSAStack, D, DVar); 19630 continue; 19631 } 19632 } 19633 } 19634 19635 // Variably modified types are not supported. 19636 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 19637 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 19638 << getOpenMPClauseName(OMPC_copyprivate) << Type 19639 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 19640 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 19641 VarDecl::DeclarationOnly; 19642 Diag(D->getLocation(), 19643 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 19644 << D; 19645 continue; 19646 } 19647 19648 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 19649 // A variable of class type (or array thereof) that appears in a 19650 // copyin clause requires an accessible, unambiguous copy assignment 19651 // operator for the class type. 19652 Type = Context.getBaseElementType(Type.getNonReferenceType()) 19653 .getUnqualifiedType(); 19654 VarDecl *SrcVD = 19655 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src", 19656 D->hasAttrs() ? &D->getAttrs() : nullptr); 19657 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 19658 VarDecl *DstVD = 19659 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst", 19660 D->hasAttrs() ? &D->getAttrs() : nullptr); 19661 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 19662 ExprResult AssignmentOp = BuildBinOp( 19663 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr); 19664 if (AssignmentOp.isInvalid()) 19665 continue; 19666 AssignmentOp = 19667 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 19668 if (AssignmentOp.isInvalid()) 19669 continue; 19670 19671 // No need to mark vars as copyprivate, they are already threadprivate or 19672 // implicitly private. 19673 assert(VD || isOpenMPCapturedDecl(D)); 19674 Vars.push_back( 19675 VD ? RefExpr->IgnoreParens() 19676 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 19677 SrcExprs.push_back(PseudoSrcExpr); 19678 DstExprs.push_back(PseudoDstExpr); 19679 AssignmentOps.push_back(AssignmentOp.get()); 19680 } 19681 19682 if (Vars.empty()) 19683 return nullptr; 19684 19685 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 19686 Vars, SrcExprs, DstExprs, AssignmentOps); 19687 } 19688 19689 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 19690 SourceLocation StartLoc, 19691 SourceLocation LParenLoc, 19692 SourceLocation EndLoc) { 19693 if (VarList.empty()) 19694 return nullptr; 19695 19696 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 19697 } 19698 19699 /// Tries to find omp_depend_t. type. 19700 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack, 19701 bool Diagnose = true) { 19702 QualType OMPDependT = Stack->getOMPDependT(); 19703 if (!OMPDependT.isNull()) 19704 return true; 19705 IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t"); 19706 ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope()); 19707 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 19708 if (Diagnose) 19709 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t"; 19710 return false; 19711 } 19712 Stack->setOMPDependT(PT.get()); 19713 return true; 19714 } 19715 19716 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, 19717 SourceLocation LParenLoc, 19718 SourceLocation EndLoc) { 19719 if (!Depobj) 19720 return nullptr; 19721 19722 bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack); 19723 19724 // OpenMP 5.0, 2.17.10.1 depobj Construct 19725 // depobj is an lvalue expression of type omp_depend_t. 19726 if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() && 19727 !Depobj->isInstantiationDependent() && 19728 !Depobj->containsUnexpandedParameterPack() && 19729 (OMPDependTFound && 19730 !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(), 19731 /*CompareUnqualified=*/true))) { 19732 Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue) 19733 << 0 << Depobj->getType() << Depobj->getSourceRange(); 19734 } 19735 19736 if (!Depobj->isLValue()) { 19737 Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue) 19738 << 1 << Depobj->getSourceRange(); 19739 } 19740 19741 return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj); 19742 } 19743 19744 OMPClause * 19745 Sema::ActOnOpenMPDependClause(const OMPDependClause::DependDataTy &Data, 19746 Expr *DepModifier, ArrayRef<Expr *> VarList, 19747 SourceLocation StartLoc, SourceLocation LParenLoc, 19748 SourceLocation EndLoc) { 19749 OpenMPDependClauseKind DepKind = Data.DepKind; 19750 SourceLocation DepLoc = Data.DepLoc; 19751 if (DSAStack->getCurrentDirective() == OMPD_ordered && 19752 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 19753 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 19754 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 19755 return nullptr; 19756 } 19757 if (DSAStack->getCurrentDirective() == OMPD_taskwait && 19758 DepKind == OMPC_DEPEND_mutexinoutset) { 19759 Diag(DepLoc, diag::err_omp_taskwait_depend_mutexinoutset_not_allowed); 19760 return nullptr; 19761 } 19762 if ((DSAStack->getCurrentDirective() != OMPD_ordered || 19763 DSAStack->getCurrentDirective() == OMPD_depobj) && 19764 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 19765 DepKind == OMPC_DEPEND_sink || 19766 ((LangOpts.OpenMP < 50 || 19767 DSAStack->getCurrentDirective() == OMPD_depobj) && 19768 DepKind == OMPC_DEPEND_depobj))) { 19769 SmallVector<unsigned, 6> Except = {OMPC_DEPEND_source, OMPC_DEPEND_sink, 19770 OMPC_DEPEND_outallmemory, 19771 OMPC_DEPEND_inoutallmemory}; 19772 if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj) 19773 Except.push_back(OMPC_DEPEND_depobj); 19774 if (LangOpts.OpenMP < 51) 19775 Except.push_back(OMPC_DEPEND_inoutset); 19776 std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier) 19777 ? "depend modifier(iterator) or " 19778 : ""; 19779 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 19780 << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0, 19781 /*Last=*/OMPC_DEPEND_unknown, 19782 Except) 19783 << getOpenMPClauseName(OMPC_depend); 19784 return nullptr; 19785 } 19786 if (DepModifier && 19787 (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) { 19788 Diag(DepModifier->getExprLoc(), 19789 diag::err_omp_depend_sink_source_with_modifier); 19790 return nullptr; 19791 } 19792 if (DepModifier && 19793 !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator)) 19794 Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator); 19795 19796 SmallVector<Expr *, 8> Vars; 19797 DSAStackTy::OperatorOffsetTy OpsOffs; 19798 llvm::APSInt DepCounter(/*BitWidth=*/32); 19799 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 19800 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) { 19801 if (const Expr *OrderedCountExpr = 19802 DSAStack->getParentOrderedRegionParam().first) { 19803 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 19804 TotalDepCount.setIsUnsigned(/*Val=*/true); 19805 } 19806 } 19807 for (Expr *RefExpr : VarList) { 19808 assert(RefExpr && "NULL expr in OpenMP shared clause."); 19809 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 19810 // It will be analyzed later. 19811 Vars.push_back(RefExpr); 19812 continue; 19813 } 19814 19815 SourceLocation ELoc = RefExpr->getExprLoc(); 19816 Expr *SimpleExpr = RefExpr->IgnoreParenCasts(); 19817 if (DepKind == OMPC_DEPEND_sink) { 19818 if (DSAStack->getParentOrderedRegionParam().first && 19819 DepCounter >= TotalDepCount) { 19820 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 19821 continue; 19822 } 19823 ++DepCounter; 19824 // OpenMP [2.13.9, Summary] 19825 // depend(dependence-type : vec), where dependence-type is: 19826 // 'sink' and where vec is the iteration vector, which has the form: 19827 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 19828 // where n is the value specified by the ordered clause in the loop 19829 // directive, xi denotes the loop iteration variable of the i-th nested 19830 // loop associated with the loop directive, and di is a constant 19831 // non-negative integer. 19832 if (CurContext->isDependentContext()) { 19833 // It will be analyzed later. 19834 Vars.push_back(RefExpr); 19835 continue; 19836 } 19837 SimpleExpr = SimpleExpr->IgnoreImplicit(); 19838 OverloadedOperatorKind OOK = OO_None; 19839 SourceLocation OOLoc; 19840 Expr *LHS = SimpleExpr; 19841 Expr *RHS = nullptr; 19842 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 19843 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 19844 OOLoc = BO->getOperatorLoc(); 19845 LHS = BO->getLHS()->IgnoreParenImpCasts(); 19846 RHS = BO->getRHS()->IgnoreParenImpCasts(); 19847 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 19848 OOK = OCE->getOperator(); 19849 OOLoc = OCE->getOperatorLoc(); 19850 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 19851 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 19852 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 19853 OOK = MCE->getMethodDecl() 19854 ->getNameInfo() 19855 .getName() 19856 .getCXXOverloadedOperator(); 19857 OOLoc = MCE->getCallee()->getExprLoc(); 19858 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 19859 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 19860 } 19861 SourceLocation ELoc; 19862 SourceRange ERange; 19863 auto Res = getPrivateItem(*this, LHS, ELoc, ERange); 19864 if (Res.second) { 19865 // It will be analyzed later. 19866 Vars.push_back(RefExpr); 19867 } 19868 ValueDecl *D = Res.first; 19869 if (!D) 19870 continue; 19871 19872 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 19873 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 19874 continue; 19875 } 19876 if (RHS) { 19877 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 19878 RHS, OMPC_depend, /*StrictlyPositive=*/false); 19879 if (RHSRes.isInvalid()) 19880 continue; 19881 } 19882 if (!CurContext->isDependentContext() && 19883 DSAStack->getParentOrderedRegionParam().first && 19884 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 19885 const ValueDecl *VD = 19886 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue()); 19887 if (VD) 19888 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 19889 << 1 << VD; 19890 else 19891 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; 19892 continue; 19893 } 19894 OpsOffs.emplace_back(RHS, OOK); 19895 } else { 19896 bool OMPDependTFound = LangOpts.OpenMP >= 50; 19897 if (OMPDependTFound) 19898 OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack, 19899 DepKind == OMPC_DEPEND_depobj); 19900 if (DepKind == OMPC_DEPEND_depobj) { 19901 // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++ 19902 // List items used in depend clauses with the depobj dependence type 19903 // must be expressions of the omp_depend_t type. 19904 if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() && 19905 !RefExpr->isInstantiationDependent() && 19906 !RefExpr->containsUnexpandedParameterPack() && 19907 (OMPDependTFound && 19908 !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(), 19909 RefExpr->getType()))) { 19910 Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue) 19911 << 0 << RefExpr->getType() << RefExpr->getSourceRange(); 19912 continue; 19913 } 19914 if (!RefExpr->isLValue()) { 19915 Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue) 19916 << 1 << RefExpr->getType() << RefExpr->getSourceRange(); 19917 continue; 19918 } 19919 } else { 19920 // OpenMP 5.0 [2.17.11, Restrictions] 19921 // List items used in depend clauses cannot be zero-length array 19922 // sections. 19923 QualType ExprTy = RefExpr->getType().getNonReferenceType(); 19924 const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr); 19925 if (OASE) { 19926 QualType BaseType = 19927 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 19928 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 19929 ExprTy = ATy->getElementType(); 19930 else 19931 ExprTy = BaseType->getPointeeType(); 19932 ExprTy = ExprTy.getNonReferenceType(); 19933 const Expr *Length = OASE->getLength(); 19934 Expr::EvalResult Result; 19935 if (Length && !Length->isValueDependent() && 19936 Length->EvaluateAsInt(Result, Context) && 19937 Result.Val.getInt().isZero()) { 19938 Diag(ELoc, 19939 diag::err_omp_depend_zero_length_array_section_not_allowed) 19940 << SimpleExpr->getSourceRange(); 19941 continue; 19942 } 19943 } 19944 19945 // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++ 19946 // List items used in depend clauses with the in, out, inout, 19947 // inoutset, or mutexinoutset dependence types cannot be 19948 // expressions of the omp_depend_t type. 19949 if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() && 19950 !RefExpr->isInstantiationDependent() && 19951 !RefExpr->containsUnexpandedParameterPack() && 19952 (!RefExpr->IgnoreParenImpCasts()->isLValue() || 19953 (OMPDependTFound && 19954 DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr()))) { 19955 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 19956 << (LangOpts.OpenMP >= 50 ? 1 : 0) 19957 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 19958 continue; 19959 } 19960 19961 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 19962 if (ASE && !ASE->getBase()->isTypeDependent() && 19963 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() && 19964 !ASE->getBase()->getType().getNonReferenceType()->isArrayType()) { 19965 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 19966 << (LangOpts.OpenMP >= 50 ? 1 : 0) 19967 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 19968 continue; 19969 } 19970 19971 ExprResult Res; 19972 { 19973 Sema::TentativeAnalysisScope Trap(*this); 19974 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, 19975 RefExpr->IgnoreParenImpCasts()); 19976 } 19977 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) && 19978 !isa<OMPArrayShapingExpr>(SimpleExpr)) { 19979 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 19980 << (LangOpts.OpenMP >= 50 ? 1 : 0) 19981 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 19982 continue; 19983 } 19984 } 19985 } 19986 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 19987 } 19988 19989 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 19990 TotalDepCount > VarList.size() && 19991 DSAStack->getParentOrderedRegionParam().first && 19992 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { 19993 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 19994 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 19995 } 19996 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 19997 DepKind != OMPC_DEPEND_outallmemory && 19998 DepKind != OMPC_DEPEND_inoutallmemory && Vars.empty()) 19999 return nullptr; 20000 20001 auto *C = OMPDependClause::Create( 20002 Context, StartLoc, LParenLoc, EndLoc, 20003 {DepKind, DepLoc, Data.ColonLoc, Data.OmpAllMemoryLoc}, DepModifier, Vars, 20004 TotalDepCount.getZExtValue()); 20005 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) && 20006 DSAStack->isParentOrderedRegion()) 20007 DSAStack->addDoacrossDependClause(C, OpsOffs); 20008 return C; 20009 } 20010 20011 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, 20012 Expr *Device, SourceLocation StartLoc, 20013 SourceLocation LParenLoc, 20014 SourceLocation ModifierLoc, 20015 SourceLocation EndLoc) { 20016 assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) && 20017 "Unexpected device modifier in OpenMP < 50."); 20018 20019 bool ErrorFound = false; 20020 if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) { 20021 std::string Values = 20022 getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown); 20023 Diag(ModifierLoc, diag::err_omp_unexpected_clause_value) 20024 << Values << getOpenMPClauseName(OMPC_device); 20025 ErrorFound = true; 20026 } 20027 20028 Expr *ValExpr = Device; 20029 Stmt *HelperValStmt = nullptr; 20030 20031 // OpenMP [2.9.1, Restrictions] 20032 // The device expression must evaluate to a non-negative integer value. 20033 ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 20034 /*StrictlyPositive=*/false) || 20035 ErrorFound; 20036 if (ErrorFound) 20037 return nullptr; 20038 20039 // OpenMP 5.0 [2.12.5, Restrictions] 20040 // In case of ancestor device-modifier, a requires directive with 20041 // the reverse_offload clause must be specified. 20042 if (Modifier == OMPC_DEVICE_ancestor) { 20043 if (!DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>()) { 20044 targetDiag( 20045 StartLoc, 20046 diag::err_omp_device_ancestor_without_requires_reverse_offload); 20047 ErrorFound = true; 20048 } 20049 } 20050 20051 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 20052 OpenMPDirectiveKind CaptureRegion = 20053 getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP); 20054 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 20055 ValExpr = MakeFullExpr(ValExpr).get(); 20056 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 20057 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 20058 HelperValStmt = buildPreInits(Context, Captures); 20059 } 20060 20061 return new (Context) 20062 OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 20063 LParenLoc, ModifierLoc, EndLoc); 20064 } 20065 20066 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 20067 DSAStackTy *Stack, QualType QTy, 20068 bool FullCheck = true) { 20069 if (SemaRef.RequireCompleteType(SL, QTy, diag::err_incomplete_type)) 20070 return false; 20071 if (FullCheck && !SemaRef.CurContext->isDependentContext() && 20072 !QTy.isTriviallyCopyableType(SemaRef.Context)) 20073 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR; 20074 return true; 20075 } 20076 20077 /// Return true if it can be proven that the provided array expression 20078 /// (array section or array subscript) does NOT specify the whole size of the 20079 /// array whose base type is \a BaseQTy. 20080 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 20081 const Expr *E, 20082 QualType BaseQTy) { 20083 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 20084 20085 // If this is an array subscript, it refers to the whole size if the size of 20086 // the dimension is constant and equals 1. Also, an array section assumes the 20087 // format of an array subscript if no colon is used. 20088 if (isa<ArraySubscriptExpr>(E) || 20089 (OASE && OASE->getColonLocFirst().isInvalid())) { 20090 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 20091 return ATy->getSize().getSExtValue() != 1; 20092 // Size can't be evaluated statically. 20093 return false; 20094 } 20095 20096 assert(OASE && "Expecting array section if not an array subscript."); 20097 const Expr *LowerBound = OASE->getLowerBound(); 20098 const Expr *Length = OASE->getLength(); 20099 20100 // If there is a lower bound that does not evaluates to zero, we are not 20101 // covering the whole dimension. 20102 if (LowerBound) { 20103 Expr::EvalResult Result; 20104 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext())) 20105 return false; // Can't get the integer value as a constant. 20106 20107 llvm::APSInt ConstLowerBound = Result.Val.getInt(); 20108 if (ConstLowerBound.getSExtValue()) 20109 return true; 20110 } 20111 20112 // If we don't have a length we covering the whole dimension. 20113 if (!Length) 20114 return false; 20115 20116 // If the base is a pointer, we don't have a way to get the size of the 20117 // pointee. 20118 if (BaseQTy->isPointerType()) 20119 return false; 20120 20121 // We can only check if the length is the same as the size of the dimension 20122 // if we have a constant array. 20123 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 20124 if (!CATy) 20125 return false; 20126 20127 Expr::EvalResult Result; 20128 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 20129 return false; // Can't get the integer value as a constant. 20130 20131 llvm::APSInt ConstLength = Result.Val.getInt(); 20132 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 20133 } 20134 20135 // Return true if it can be proven that the provided array expression (array 20136 // section or array subscript) does NOT specify a single element of the array 20137 // whose base type is \a BaseQTy. 20138 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 20139 const Expr *E, 20140 QualType BaseQTy) { 20141 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 20142 20143 // An array subscript always refer to a single element. Also, an array section 20144 // assumes the format of an array subscript if no colon is used. 20145 if (isa<ArraySubscriptExpr>(E) || 20146 (OASE && OASE->getColonLocFirst().isInvalid())) 20147 return false; 20148 20149 assert(OASE && "Expecting array section if not an array subscript."); 20150 const Expr *Length = OASE->getLength(); 20151 20152 // If we don't have a length we have to check if the array has unitary size 20153 // for this dimension. Also, we should always expect a length if the base type 20154 // is pointer. 20155 if (!Length) { 20156 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 20157 return ATy->getSize().getSExtValue() != 1; 20158 // We cannot assume anything. 20159 return false; 20160 } 20161 20162 // Check if the length evaluates to 1. 20163 Expr::EvalResult Result; 20164 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 20165 return false; // Can't get the integer value as a constant. 20166 20167 llvm::APSInt ConstLength = Result.Val.getInt(); 20168 return ConstLength.getSExtValue() != 1; 20169 } 20170 20171 // The base of elements of list in a map clause have to be either: 20172 // - a reference to variable or field. 20173 // - a member expression. 20174 // - an array expression. 20175 // 20176 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 20177 // reference to 'r'. 20178 // 20179 // If we have: 20180 // 20181 // struct SS { 20182 // Bla S; 20183 // foo() { 20184 // #pragma omp target map (S.Arr[:12]); 20185 // } 20186 // } 20187 // 20188 // We want to retrieve the member expression 'this->S'; 20189 20190 // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2] 20191 // If a list item is an array section, it must specify contiguous storage. 20192 // 20193 // For this restriction it is sufficient that we make sure only references 20194 // to variables or fields and array expressions, and that no array sections 20195 // exist except in the rightmost expression (unless they cover the whole 20196 // dimension of the array). E.g. these would be invalid: 20197 // 20198 // r.ArrS[3:5].Arr[6:7] 20199 // 20200 // r.ArrS[3:5].x 20201 // 20202 // but these would be valid: 20203 // r.ArrS[3].Arr[6:7] 20204 // 20205 // r.ArrS[3].x 20206 namespace { 20207 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> { 20208 Sema &SemaRef; 20209 OpenMPClauseKind CKind = OMPC_unknown; 20210 OpenMPDirectiveKind DKind = OMPD_unknown; 20211 OMPClauseMappableExprCommon::MappableExprComponentList &Components; 20212 bool IsNonContiguous = false; 20213 bool NoDiagnose = false; 20214 const Expr *RelevantExpr = nullptr; 20215 bool AllowUnitySizeArraySection = true; 20216 bool AllowWholeSizeArraySection = true; 20217 bool AllowAnotherPtr = true; 20218 SourceLocation ELoc; 20219 SourceRange ERange; 20220 20221 void emitErrorMsg() { 20222 // If nothing else worked, this is not a valid map clause expression. 20223 if (SemaRef.getLangOpts().OpenMP < 50) { 20224 SemaRef.Diag(ELoc, 20225 diag::err_omp_expected_named_var_member_or_array_expression) 20226 << ERange; 20227 } else { 20228 SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses) 20229 << getOpenMPClauseName(CKind) << ERange; 20230 } 20231 } 20232 20233 public: 20234 bool VisitDeclRefExpr(DeclRefExpr *DRE) { 20235 if (!isa<VarDecl>(DRE->getDecl())) { 20236 emitErrorMsg(); 20237 return false; 20238 } 20239 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 20240 RelevantExpr = DRE; 20241 // Record the component. 20242 Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous); 20243 return true; 20244 } 20245 20246 bool VisitMemberExpr(MemberExpr *ME) { 20247 Expr *E = ME; 20248 Expr *BaseE = ME->getBase()->IgnoreParenCasts(); 20249 20250 if (isa<CXXThisExpr>(BaseE)) { 20251 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 20252 // We found a base expression: this->Val. 20253 RelevantExpr = ME; 20254 } else { 20255 E = BaseE; 20256 } 20257 20258 if (!isa<FieldDecl>(ME->getMemberDecl())) { 20259 if (!NoDiagnose) { 20260 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 20261 << ME->getSourceRange(); 20262 return false; 20263 } 20264 if (RelevantExpr) 20265 return false; 20266 return Visit(E); 20267 } 20268 20269 auto *FD = cast<FieldDecl>(ME->getMemberDecl()); 20270 20271 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 20272 // A bit-field cannot appear in a map clause. 20273 // 20274 if (FD->isBitField()) { 20275 if (!NoDiagnose) { 20276 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 20277 << ME->getSourceRange() << getOpenMPClauseName(CKind); 20278 return false; 20279 } 20280 if (RelevantExpr) 20281 return false; 20282 return Visit(E); 20283 } 20284 20285 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 20286 // If the type of a list item is a reference to a type T then the type 20287 // will be considered to be T for all purposes of this clause. 20288 QualType CurType = BaseE->getType().getNonReferenceType(); 20289 20290 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 20291 // A list item cannot be a variable that is a member of a structure with 20292 // a union type. 20293 // 20294 if (CurType->isUnionType()) { 20295 if (!NoDiagnose) { 20296 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 20297 << ME->getSourceRange(); 20298 return false; 20299 } 20300 return RelevantExpr || Visit(E); 20301 } 20302 20303 // If we got a member expression, we should not expect any array section 20304 // before that: 20305 // 20306 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 20307 // If a list item is an element of a structure, only the rightmost symbol 20308 // of the variable reference can be an array section. 20309 // 20310 AllowUnitySizeArraySection = false; 20311 AllowWholeSizeArraySection = false; 20312 20313 // Record the component. 20314 Components.emplace_back(ME, FD, IsNonContiguous); 20315 return RelevantExpr || Visit(E); 20316 } 20317 20318 bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) { 20319 Expr *E = AE->getBase()->IgnoreParenImpCasts(); 20320 20321 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 20322 if (!NoDiagnose) { 20323 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 20324 << 0 << AE->getSourceRange(); 20325 return false; 20326 } 20327 return RelevantExpr || Visit(E); 20328 } 20329 20330 // If we got an array subscript that express the whole dimension we 20331 // can have any array expressions before. If it only expressing part of 20332 // the dimension, we can only have unitary-size array expressions. 20333 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE, E->getType())) 20334 AllowWholeSizeArraySection = false; 20335 20336 if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) { 20337 Expr::EvalResult Result; 20338 if (!AE->getIdx()->isValueDependent() && 20339 AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) && 20340 !Result.Val.getInt().isZero()) { 20341 SemaRef.Diag(AE->getIdx()->getExprLoc(), 20342 diag::err_omp_invalid_map_this_expr); 20343 SemaRef.Diag(AE->getIdx()->getExprLoc(), 20344 diag::note_omp_invalid_subscript_on_this_ptr_map); 20345 } 20346 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 20347 RelevantExpr = TE; 20348 } 20349 20350 // Record the component - we don't have any declaration associated. 20351 Components.emplace_back(AE, nullptr, IsNonContiguous); 20352 20353 return RelevantExpr || Visit(E); 20354 } 20355 20356 bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) { 20357 // After OMP 5.0 Array section in reduction clause will be implicitly 20358 // mapped 20359 assert(!(SemaRef.getLangOpts().OpenMP < 50 && NoDiagnose) && 20360 "Array sections cannot be implicitly mapped."); 20361 Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 20362 QualType CurType = 20363 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 20364 20365 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 20366 // If the type of a list item is a reference to a type T then the type 20367 // will be considered to be T for all purposes of this clause. 20368 if (CurType->isReferenceType()) 20369 CurType = CurType->getPointeeType(); 20370 20371 bool IsPointer = CurType->isAnyPointerType(); 20372 20373 if (!IsPointer && !CurType->isArrayType()) { 20374 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 20375 << 0 << OASE->getSourceRange(); 20376 return false; 20377 } 20378 20379 bool NotWhole = 20380 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType); 20381 bool NotUnity = 20382 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType); 20383 20384 if (AllowWholeSizeArraySection) { 20385 // Any array section is currently allowed. Allowing a whole size array 20386 // section implies allowing a unity array section as well. 20387 // 20388 // If this array section refers to the whole dimension we can still 20389 // accept other array sections before this one, except if the base is a 20390 // pointer. Otherwise, only unitary sections are accepted. 20391 if (NotWhole || IsPointer) 20392 AllowWholeSizeArraySection = false; 20393 } else if (DKind == OMPD_target_update && 20394 SemaRef.getLangOpts().OpenMP >= 50) { 20395 if (IsPointer && !AllowAnotherPtr) 20396 SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined) 20397 << /*array of unknown bound */ 1; 20398 else 20399 IsNonContiguous = true; 20400 } else if (AllowUnitySizeArraySection && NotUnity) { 20401 // A unity or whole array section is not allowed and that is not 20402 // compatible with the properties of the current array section. 20403 if (NoDiagnose) 20404 return false; 20405 SemaRef.Diag(ELoc, 20406 diag::err_array_section_does_not_specify_contiguous_storage) 20407 << OASE->getSourceRange(); 20408 return false; 20409 } 20410 20411 if (IsPointer) 20412 AllowAnotherPtr = false; 20413 20414 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) { 20415 Expr::EvalResult ResultR; 20416 Expr::EvalResult ResultL; 20417 if (!OASE->getLength()->isValueDependent() && 20418 OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) && 20419 !ResultR.Val.getInt().isOne()) { 20420 SemaRef.Diag(OASE->getLength()->getExprLoc(), 20421 diag::err_omp_invalid_map_this_expr); 20422 SemaRef.Diag(OASE->getLength()->getExprLoc(), 20423 diag::note_omp_invalid_length_on_this_ptr_mapping); 20424 } 20425 if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() && 20426 OASE->getLowerBound()->EvaluateAsInt(ResultL, 20427 SemaRef.getASTContext()) && 20428 !ResultL.Val.getInt().isZero()) { 20429 SemaRef.Diag(OASE->getLowerBound()->getExprLoc(), 20430 diag::err_omp_invalid_map_this_expr); 20431 SemaRef.Diag(OASE->getLowerBound()->getExprLoc(), 20432 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping); 20433 } 20434 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 20435 RelevantExpr = TE; 20436 } 20437 20438 // Record the component - we don't have any declaration associated. 20439 Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false); 20440 return RelevantExpr || Visit(E); 20441 } 20442 bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) { 20443 Expr *Base = E->getBase(); 20444 20445 // Record the component - we don't have any declaration associated. 20446 Components.emplace_back(E, nullptr, IsNonContiguous); 20447 20448 return Visit(Base->IgnoreParenImpCasts()); 20449 } 20450 20451 bool VisitUnaryOperator(UnaryOperator *UO) { 20452 if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() || 20453 UO->getOpcode() != UO_Deref) { 20454 emitErrorMsg(); 20455 return false; 20456 } 20457 if (!RelevantExpr) { 20458 // Record the component if haven't found base decl. 20459 Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false); 20460 } 20461 return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts()); 20462 } 20463 bool VisitBinaryOperator(BinaryOperator *BO) { 20464 if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) { 20465 emitErrorMsg(); 20466 return false; 20467 } 20468 20469 // Pointer arithmetic is the only thing we expect to happen here so after we 20470 // make sure the binary operator is a pointer type, the we only thing need 20471 // to to is to visit the subtree that has the same type as root (so that we 20472 // know the other subtree is just an offset) 20473 Expr *LE = BO->getLHS()->IgnoreParenImpCasts(); 20474 Expr *RE = BO->getRHS()->IgnoreParenImpCasts(); 20475 Components.emplace_back(BO, nullptr, false); 20476 assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() || 20477 RE->getType().getTypePtr() == BO->getType().getTypePtr()) && 20478 "Either LHS or RHS have base decl inside"); 20479 if (BO->getType().getTypePtr() == LE->getType().getTypePtr()) 20480 return RelevantExpr || Visit(LE); 20481 return RelevantExpr || Visit(RE); 20482 } 20483 bool VisitCXXThisExpr(CXXThisExpr *CTE) { 20484 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 20485 RelevantExpr = CTE; 20486 Components.emplace_back(CTE, nullptr, IsNonContiguous); 20487 return true; 20488 } 20489 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) { 20490 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 20491 Components.emplace_back(COCE, nullptr, IsNonContiguous); 20492 return true; 20493 } 20494 bool VisitOpaqueValueExpr(OpaqueValueExpr *E) { 20495 Expr *Source = E->getSourceExpr(); 20496 if (!Source) { 20497 emitErrorMsg(); 20498 return false; 20499 } 20500 return Visit(Source); 20501 } 20502 bool VisitStmt(Stmt *) { 20503 emitErrorMsg(); 20504 return false; 20505 } 20506 const Expr *getFoundBase() const { return RelevantExpr; } 20507 explicit MapBaseChecker( 20508 Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, 20509 OMPClauseMappableExprCommon::MappableExprComponentList &Components, 20510 bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange) 20511 : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components), 20512 NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {} 20513 }; 20514 } // namespace 20515 20516 /// Return the expression of the base of the mappable expression or null if it 20517 /// cannot be determined and do all the necessary checks to see if the 20518 /// expression is valid as a standalone mappable expression. In the process, 20519 /// record all the components of the expression. 20520 static const Expr *checkMapClauseExpressionBase( 20521 Sema &SemaRef, Expr *E, 20522 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 20523 OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) { 20524 SourceLocation ELoc = E->getExprLoc(); 20525 SourceRange ERange = E->getSourceRange(); 20526 MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc, 20527 ERange); 20528 if (Checker.Visit(E->IgnoreParens())) { 20529 // Check if the highest dimension array section has length specified 20530 if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() && 20531 (CKind == OMPC_to || CKind == OMPC_from)) { 20532 auto CI = CurComponents.rbegin(); 20533 auto CE = CurComponents.rend(); 20534 for (; CI != CE; ++CI) { 20535 const auto *OASE = 20536 dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression()); 20537 if (!OASE) 20538 continue; 20539 if (OASE && OASE->getLength()) 20540 break; 20541 SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length) 20542 << ERange; 20543 } 20544 } 20545 return Checker.getFoundBase(); 20546 } 20547 return nullptr; 20548 } 20549 20550 // Return true if expression E associated with value VD has conflicts with other 20551 // map information. 20552 static bool checkMapConflicts( 20553 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E, 20554 bool CurrentRegionOnly, 20555 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 20556 OpenMPClauseKind CKind) { 20557 assert(VD && E); 20558 SourceLocation ELoc = E->getExprLoc(); 20559 SourceRange ERange = E->getSourceRange(); 20560 20561 // In order to easily check the conflicts we need to match each component of 20562 // the expression under test with the components of the expressions that are 20563 // already in the stack. 20564 20565 assert(!CurComponents.empty() && "Map clause expression with no components!"); 20566 assert(CurComponents.back().getAssociatedDeclaration() == VD && 20567 "Map clause expression with unexpected base!"); 20568 20569 // Variables to help detecting enclosing problems in data environment nests. 20570 bool IsEnclosedByDataEnvironmentExpr = false; 20571 const Expr *EnclosingExpr = nullptr; 20572 20573 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 20574 VD, CurrentRegionOnly, 20575 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc, 20576 ERange, CKind, &EnclosingExpr, 20577 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef 20578 StackComponents, 20579 OpenMPClauseKind Kind) { 20580 if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50) 20581 return false; 20582 assert(!StackComponents.empty() && 20583 "Map clause expression with no components!"); 20584 assert(StackComponents.back().getAssociatedDeclaration() == VD && 20585 "Map clause expression with unexpected base!"); 20586 (void)VD; 20587 20588 // The whole expression in the stack. 20589 const Expr *RE = StackComponents.front().getAssociatedExpression(); 20590 20591 // Expressions must start from the same base. Here we detect at which 20592 // point both expressions diverge from each other and see if we can 20593 // detect if the memory referred to both expressions is contiguous and 20594 // do not overlap. 20595 auto CI = CurComponents.rbegin(); 20596 auto CE = CurComponents.rend(); 20597 auto SI = StackComponents.rbegin(); 20598 auto SE = StackComponents.rend(); 20599 for (; CI != CE && SI != SE; ++CI, ++SI) { 20600 20601 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 20602 // At most one list item can be an array item derived from a given 20603 // variable in map clauses of the same construct. 20604 if (CurrentRegionOnly && 20605 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 20606 isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) || 20607 isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) && 20608 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 20609 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) || 20610 isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) { 20611 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 20612 diag::err_omp_multiple_array_items_in_map_clause) 20613 << CI->getAssociatedExpression()->getSourceRange(); 20614 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 20615 diag::note_used_here) 20616 << SI->getAssociatedExpression()->getSourceRange(); 20617 return true; 20618 } 20619 20620 // Do both expressions have the same kind? 20621 if (CI->getAssociatedExpression()->getStmtClass() != 20622 SI->getAssociatedExpression()->getStmtClass()) 20623 break; 20624 20625 // Are we dealing with different variables/fields? 20626 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 20627 break; 20628 } 20629 // Check if the extra components of the expressions in the enclosing 20630 // data environment are redundant for the current base declaration. 20631 // If they are, the maps completely overlap, which is legal. 20632 for (; SI != SE; ++SI) { 20633 QualType Type; 20634 if (const auto *ASE = 20635 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 20636 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 20637 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>( 20638 SI->getAssociatedExpression())) { 20639 const Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 20640 Type = 20641 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 20642 } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>( 20643 SI->getAssociatedExpression())) { 20644 Type = OASE->getBase()->getType()->getPointeeType(); 20645 } 20646 if (Type.isNull() || Type->isAnyPointerType() || 20647 checkArrayExpressionDoesNotReferToWholeSize( 20648 SemaRef, SI->getAssociatedExpression(), Type)) 20649 break; 20650 } 20651 20652 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 20653 // List items of map clauses in the same construct must not share 20654 // original storage. 20655 // 20656 // If the expressions are exactly the same or one is a subset of the 20657 // other, it means they are sharing storage. 20658 if (CI == CE && SI == SE) { 20659 if (CurrentRegionOnly) { 20660 if (CKind == OMPC_map) { 20661 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 20662 } else { 20663 assert(CKind == OMPC_to || CKind == OMPC_from); 20664 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 20665 << ERange; 20666 } 20667 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 20668 << RE->getSourceRange(); 20669 return true; 20670 } 20671 // If we find the same expression in the enclosing data environment, 20672 // that is legal. 20673 IsEnclosedByDataEnvironmentExpr = true; 20674 return false; 20675 } 20676 20677 QualType DerivedType = 20678 std::prev(CI)->getAssociatedDeclaration()->getType(); 20679 SourceLocation DerivedLoc = 20680 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 20681 20682 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 20683 // If the type of a list item is a reference to a type T then the type 20684 // will be considered to be T for all purposes of this clause. 20685 DerivedType = DerivedType.getNonReferenceType(); 20686 20687 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 20688 // A variable for which the type is pointer and an array section 20689 // derived from that variable must not appear as list items of map 20690 // clauses of the same construct. 20691 // 20692 // Also, cover one of the cases in: 20693 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 20694 // If any part of the original storage of a list item has corresponding 20695 // storage in the device data environment, all of the original storage 20696 // must have corresponding storage in the device data environment. 20697 // 20698 if (DerivedType->isAnyPointerType()) { 20699 if (CI == CE || SI == SE) { 20700 SemaRef.Diag( 20701 DerivedLoc, 20702 diag::err_omp_pointer_mapped_along_with_derived_section) 20703 << DerivedLoc; 20704 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 20705 << RE->getSourceRange(); 20706 return true; 20707 } 20708 if (CI->getAssociatedExpression()->getStmtClass() != 20709 SI->getAssociatedExpression()->getStmtClass() || 20710 CI->getAssociatedDeclaration()->getCanonicalDecl() == 20711 SI->getAssociatedDeclaration()->getCanonicalDecl()) { 20712 assert(CI != CE && SI != SE); 20713 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced) 20714 << DerivedLoc; 20715 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 20716 << RE->getSourceRange(); 20717 return true; 20718 } 20719 } 20720 20721 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 20722 // List items of map clauses in the same construct must not share 20723 // original storage. 20724 // 20725 // An expression is a subset of the other. 20726 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 20727 if (CKind == OMPC_map) { 20728 if (CI != CE || SI != SE) { 20729 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is 20730 // a pointer. 20731 auto Begin = 20732 CI != CE ? CurComponents.begin() : StackComponents.begin(); 20733 auto End = CI != CE ? CurComponents.end() : StackComponents.end(); 20734 auto It = Begin; 20735 while (It != End && !It->getAssociatedDeclaration()) 20736 std::advance(It, 1); 20737 assert(It != End && 20738 "Expected at least one component with the declaration."); 20739 if (It != Begin && It->getAssociatedDeclaration() 20740 ->getType() 20741 .getCanonicalType() 20742 ->isAnyPointerType()) { 20743 IsEnclosedByDataEnvironmentExpr = false; 20744 EnclosingExpr = nullptr; 20745 return false; 20746 } 20747 } 20748 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 20749 } else { 20750 assert(CKind == OMPC_to || CKind == OMPC_from); 20751 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 20752 << ERange; 20753 } 20754 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 20755 << RE->getSourceRange(); 20756 return true; 20757 } 20758 20759 // The current expression uses the same base as other expression in the 20760 // data environment but does not contain it completely. 20761 if (!CurrentRegionOnly && SI != SE) 20762 EnclosingExpr = RE; 20763 20764 // The current expression is a subset of the expression in the data 20765 // environment. 20766 IsEnclosedByDataEnvironmentExpr |= 20767 (!CurrentRegionOnly && CI != CE && SI == SE); 20768 20769 return false; 20770 }); 20771 20772 if (CurrentRegionOnly) 20773 return FoundError; 20774 20775 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 20776 // If any part of the original storage of a list item has corresponding 20777 // storage in the device data environment, all of the original storage must 20778 // have corresponding storage in the device data environment. 20779 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 20780 // If a list item is an element of a structure, and a different element of 20781 // the structure has a corresponding list item in the device data environment 20782 // prior to a task encountering the construct associated with the map clause, 20783 // then the list item must also have a corresponding list item in the device 20784 // data environment prior to the task encountering the construct. 20785 // 20786 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 20787 SemaRef.Diag(ELoc, 20788 diag::err_omp_original_storage_is_shared_and_does_not_contain) 20789 << ERange; 20790 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 20791 << EnclosingExpr->getSourceRange(); 20792 return true; 20793 } 20794 20795 return FoundError; 20796 } 20797 20798 // Look up the user-defined mapper given the mapper name and mapped type, and 20799 // build a reference to it. 20800 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S, 20801 CXXScopeSpec &MapperIdScopeSpec, 20802 const DeclarationNameInfo &MapperId, 20803 QualType Type, 20804 Expr *UnresolvedMapper) { 20805 if (MapperIdScopeSpec.isInvalid()) 20806 return ExprError(); 20807 // Get the actual type for the array type. 20808 if (Type->isArrayType()) { 20809 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type"); 20810 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType(); 20811 } 20812 // Find all user-defined mappers with the given MapperId. 20813 SmallVector<UnresolvedSet<8>, 4> Lookups; 20814 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName); 20815 Lookup.suppressDiagnostics(); 20816 if (S) { 20817 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) { 20818 NamedDecl *D = Lookup.getRepresentativeDecl(); 20819 while (S && !S->isDeclScope(D)) 20820 S = S->getParent(); 20821 if (S) 20822 S = S->getParent(); 20823 Lookups.emplace_back(); 20824 Lookups.back().append(Lookup.begin(), Lookup.end()); 20825 Lookup.clear(); 20826 } 20827 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) { 20828 // Extract the user-defined mappers with the given MapperId. 20829 Lookups.push_back(UnresolvedSet<8>()); 20830 for (NamedDecl *D : ULE->decls()) { 20831 auto *DMD = cast<OMPDeclareMapperDecl>(D); 20832 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation."); 20833 Lookups.back().addDecl(DMD); 20834 } 20835 } 20836 // Defer the lookup for dependent types. The results will be passed through 20837 // UnresolvedMapper on instantiation. 20838 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() || 20839 Type->isInstantiationDependentType() || 20840 Type->containsUnexpandedParameterPack() || 20841 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 20842 return !D->isInvalidDecl() && 20843 (D->getType()->isDependentType() || 20844 D->getType()->isInstantiationDependentType() || 20845 D->getType()->containsUnexpandedParameterPack()); 20846 })) { 20847 UnresolvedSet<8> URS; 20848 for (const UnresolvedSet<8> &Set : Lookups) { 20849 if (Set.empty()) 20850 continue; 20851 URS.append(Set.begin(), Set.end()); 20852 } 20853 return UnresolvedLookupExpr::Create( 20854 SemaRef.Context, /*NamingClass=*/nullptr, 20855 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId, 20856 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end()); 20857 } 20858 SourceLocation Loc = MapperId.getLoc(); 20859 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 20860 // The type must be of struct, union or class type in C and C++ 20861 if (!Type->isStructureOrClassType() && !Type->isUnionType() && 20862 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) { 20863 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type); 20864 return ExprError(); 20865 } 20866 // Perform argument dependent lookup. 20867 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet()) 20868 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups); 20869 // Return the first user-defined mapper with the desired type. 20870 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 20871 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * { 20872 if (!D->isInvalidDecl() && 20873 SemaRef.Context.hasSameType(D->getType(), Type)) 20874 return D; 20875 return nullptr; 20876 })) 20877 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 20878 // Find the first user-defined mapper with a type derived from the desired 20879 // type. 20880 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 20881 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * { 20882 if (!D->isInvalidDecl() && 20883 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) && 20884 !Type.isMoreQualifiedThan(D->getType())) 20885 return D; 20886 return nullptr; 20887 })) { 20888 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 20889 /*DetectVirtual=*/false); 20890 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) { 20891 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 20892 VD->getType().getUnqualifiedType()))) { 20893 if (SemaRef.CheckBaseClassAccess( 20894 Loc, VD->getType(), Type, Paths.front(), 20895 /*DiagID=*/0) != Sema::AR_inaccessible) { 20896 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 20897 } 20898 } 20899 } 20900 } 20901 // Report error if a mapper is specified, but cannot be found. 20902 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") { 20903 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper) 20904 << Type << MapperId.getName(); 20905 return ExprError(); 20906 } 20907 return ExprEmpty(); 20908 } 20909 20910 namespace { 20911 // Utility struct that gathers all the related lists associated with a mappable 20912 // expression. 20913 struct MappableVarListInfo { 20914 // The list of expressions. 20915 ArrayRef<Expr *> VarList; 20916 // The list of processed expressions. 20917 SmallVector<Expr *, 16> ProcessedVarList; 20918 // The mappble components for each expression. 20919 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 20920 // The base declaration of the variable. 20921 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 20922 // The reference to the user-defined mapper associated with every expression. 20923 SmallVector<Expr *, 16> UDMapperList; 20924 20925 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 20926 // We have a list of components and base declarations for each entry in the 20927 // variable list. 20928 VarComponents.reserve(VarList.size()); 20929 VarBaseDeclarations.reserve(VarList.size()); 20930 } 20931 }; 20932 } // namespace 20933 20934 // Check the validity of the provided variable list for the provided clause kind 20935 // \a CKind. In the check process the valid expressions, mappable expression 20936 // components, variables, and user-defined mappers are extracted and used to 20937 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a 20938 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec, 20939 // and \a MapperId are expected to be valid if the clause kind is 'map'. 20940 static void checkMappableExpressionList( 20941 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind, 20942 MappableVarListInfo &MVLI, SourceLocation StartLoc, 20943 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId, 20944 ArrayRef<Expr *> UnresolvedMappers, 20945 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 20946 ArrayRef<OpenMPMapModifierKind> Modifiers = None, 20947 bool IsMapTypeImplicit = false, bool NoDiagnose = false) { 20948 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 20949 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 20950 "Unexpected clause kind with mappable expressions!"); 20951 20952 // If the identifier of user-defined mapper is not specified, it is "default". 20953 // We do not change the actual name in this clause to distinguish whether a 20954 // mapper is specified explicitly, i.e., it is not explicitly specified when 20955 // MapperId.getName() is empty. 20956 if (!MapperId.getName() || MapperId.getName().isEmpty()) { 20957 auto &DeclNames = SemaRef.getASTContext().DeclarationNames; 20958 MapperId.setName(DeclNames.getIdentifier( 20959 &SemaRef.getASTContext().Idents.get("default"))); 20960 MapperId.setLoc(StartLoc); 20961 } 20962 20963 // Iterators to find the current unresolved mapper expression. 20964 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end(); 20965 bool UpdateUMIt = false; 20966 Expr *UnresolvedMapper = nullptr; 20967 20968 bool HasHoldModifier = 20969 llvm::is_contained(Modifiers, OMPC_MAP_MODIFIER_ompx_hold); 20970 20971 // Keep track of the mappable components and base declarations in this clause. 20972 // Each entry in the list is going to have a list of components associated. We 20973 // record each set of the components so that we can build the clause later on. 20974 // In the end we should have the same amount of declarations and component 20975 // lists. 20976 20977 for (Expr *RE : MVLI.VarList) { 20978 assert(RE && "Null expr in omp to/from/map clause"); 20979 SourceLocation ELoc = RE->getExprLoc(); 20980 20981 // Find the current unresolved mapper expression. 20982 if (UpdateUMIt && UMIt != UMEnd) { 20983 UMIt++; 20984 assert( 20985 UMIt != UMEnd && 20986 "Expect the size of UnresolvedMappers to match with that of VarList"); 20987 } 20988 UpdateUMIt = true; 20989 if (UMIt != UMEnd) 20990 UnresolvedMapper = *UMIt; 20991 20992 const Expr *VE = RE->IgnoreParenLValueCasts(); 20993 20994 if (VE->isValueDependent() || VE->isTypeDependent() || 20995 VE->isInstantiationDependent() || 20996 VE->containsUnexpandedParameterPack()) { 20997 // Try to find the associated user-defined mapper. 20998 ExprResult ER = buildUserDefinedMapperRef( 20999 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 21000 VE->getType().getCanonicalType(), UnresolvedMapper); 21001 if (ER.isInvalid()) 21002 continue; 21003 MVLI.UDMapperList.push_back(ER.get()); 21004 // We can only analyze this information once the missing information is 21005 // resolved. 21006 MVLI.ProcessedVarList.push_back(RE); 21007 continue; 21008 } 21009 21010 Expr *SimpleExpr = RE->IgnoreParenCasts(); 21011 21012 if (!RE->isLValue()) { 21013 if (SemaRef.getLangOpts().OpenMP < 50) { 21014 SemaRef.Diag( 21015 ELoc, diag::err_omp_expected_named_var_member_or_array_expression) 21016 << RE->getSourceRange(); 21017 } else { 21018 SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses) 21019 << getOpenMPClauseName(CKind) << RE->getSourceRange(); 21020 } 21021 continue; 21022 } 21023 21024 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 21025 ValueDecl *CurDeclaration = nullptr; 21026 21027 // Obtain the array or member expression bases if required. Also, fill the 21028 // components array with all the components identified in the process. 21029 const Expr *BE = 21030 checkMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind, 21031 DSAS->getCurrentDirective(), NoDiagnose); 21032 if (!BE) 21033 continue; 21034 21035 assert(!CurComponents.empty() && 21036 "Invalid mappable expression information."); 21037 21038 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) { 21039 // Add store "this" pointer to class in DSAStackTy for future checking 21040 DSAS->addMappedClassesQualTypes(TE->getType()); 21041 // Try to find the associated user-defined mapper. 21042 ExprResult ER = buildUserDefinedMapperRef( 21043 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 21044 VE->getType().getCanonicalType(), UnresolvedMapper); 21045 if (ER.isInvalid()) 21046 continue; 21047 MVLI.UDMapperList.push_back(ER.get()); 21048 // Skip restriction checking for variable or field declarations 21049 MVLI.ProcessedVarList.push_back(RE); 21050 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 21051 MVLI.VarComponents.back().append(CurComponents.begin(), 21052 CurComponents.end()); 21053 MVLI.VarBaseDeclarations.push_back(nullptr); 21054 continue; 21055 } 21056 21057 // For the following checks, we rely on the base declaration which is 21058 // expected to be associated with the last component. The declaration is 21059 // expected to be a variable or a field (if 'this' is being mapped). 21060 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 21061 assert(CurDeclaration && "Null decl on map clause."); 21062 assert( 21063 CurDeclaration->isCanonicalDecl() && 21064 "Expecting components to have associated only canonical declarations."); 21065 21066 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 21067 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 21068 21069 assert((VD || FD) && "Only variables or fields are expected here!"); 21070 (void)FD; 21071 21072 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 21073 // threadprivate variables cannot appear in a map clause. 21074 // OpenMP 4.5 [2.10.5, target update Construct] 21075 // threadprivate variables cannot appear in a from clause. 21076 if (VD && DSAS->isThreadPrivate(VD)) { 21077 if (NoDiagnose) 21078 continue; 21079 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 21080 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 21081 << getOpenMPClauseName(CKind); 21082 reportOriginalDsa(SemaRef, DSAS, VD, DVar); 21083 continue; 21084 } 21085 21086 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 21087 // A list item cannot appear in both a map clause and a data-sharing 21088 // attribute clause on the same construct. 21089 21090 // Check conflicts with other map clause expressions. We check the conflicts 21091 // with the current construct separately from the enclosing data 21092 // environment, because the restrictions are different. We only have to 21093 // check conflicts across regions for the map clauses. 21094 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 21095 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 21096 break; 21097 if (CKind == OMPC_map && 21098 (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) && 21099 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 21100 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 21101 break; 21102 21103 // OpenMP 4.5 [2.10.5, target update Construct] 21104 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 21105 // If the type of a list item is a reference to a type T then the type will 21106 // be considered to be T for all purposes of this clause. 21107 auto I = llvm::find_if( 21108 CurComponents, 21109 [](const OMPClauseMappableExprCommon::MappableComponent &MC) { 21110 return MC.getAssociatedDeclaration(); 21111 }); 21112 assert(I != CurComponents.end() && "Null decl on map clause."); 21113 (void)I; 21114 QualType Type; 21115 auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens()); 21116 auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens()); 21117 auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens()); 21118 if (ASE) { 21119 Type = ASE->getType().getNonReferenceType(); 21120 } else if (OASE) { 21121 QualType BaseType = 21122 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 21123 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 21124 Type = ATy->getElementType(); 21125 else 21126 Type = BaseType->getPointeeType(); 21127 Type = Type.getNonReferenceType(); 21128 } else if (OAShE) { 21129 Type = OAShE->getBase()->getType()->getPointeeType(); 21130 } else { 21131 Type = VE->getType(); 21132 } 21133 21134 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 21135 // A list item in a to or from clause must have a mappable type. 21136 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 21137 // A list item must have a mappable type. 21138 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 21139 DSAS, Type, /*FullCheck=*/true)) 21140 continue; 21141 21142 if (CKind == OMPC_map) { 21143 // target enter data 21144 // OpenMP [2.10.2, Restrictions, p. 99] 21145 // A map-type must be specified in all map clauses and must be either 21146 // to or alloc. 21147 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 21148 if (DKind == OMPD_target_enter_data && 21149 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 21150 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 21151 << (IsMapTypeImplicit ? 1 : 0) 21152 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 21153 << getOpenMPDirectiveName(DKind); 21154 continue; 21155 } 21156 21157 // target exit_data 21158 // OpenMP [2.10.3, Restrictions, p. 102] 21159 // A map-type must be specified in all map clauses and must be either 21160 // from, release, or delete. 21161 if (DKind == OMPD_target_exit_data && 21162 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 21163 MapType == OMPC_MAP_delete)) { 21164 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 21165 << (IsMapTypeImplicit ? 1 : 0) 21166 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 21167 << getOpenMPDirectiveName(DKind); 21168 continue; 21169 } 21170 21171 // The 'ompx_hold' modifier is specifically intended to be used on a 21172 // 'target' or 'target data' directive to prevent data from being unmapped 21173 // during the associated statement. It is not permitted on a 'target 21174 // enter data' or 'target exit data' directive, which have no associated 21175 // statement. 21176 if ((DKind == OMPD_target_enter_data || DKind == OMPD_target_exit_data) && 21177 HasHoldModifier) { 21178 SemaRef.Diag(StartLoc, 21179 diag::err_omp_invalid_map_type_modifier_for_directive) 21180 << getOpenMPSimpleClauseTypeName(OMPC_map, 21181 OMPC_MAP_MODIFIER_ompx_hold) 21182 << getOpenMPDirectiveName(DKind); 21183 continue; 21184 } 21185 21186 // target, target data 21187 // OpenMP 5.0 [2.12.2, Restrictions, p. 163] 21188 // OpenMP 5.0 [2.12.5, Restrictions, p. 174] 21189 // A map-type in a map clause must be to, from, tofrom or alloc 21190 if ((DKind == OMPD_target_data || 21191 isOpenMPTargetExecutionDirective(DKind)) && 21192 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from || 21193 MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) { 21194 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 21195 << (IsMapTypeImplicit ? 1 : 0) 21196 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 21197 << getOpenMPDirectiveName(DKind); 21198 continue; 21199 } 21200 21201 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 21202 // A list item cannot appear in both a map clause and a data-sharing 21203 // attribute clause on the same construct 21204 // 21205 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 21206 // A list item cannot appear in both a map clause and a data-sharing 21207 // attribute clause on the same construct unless the construct is a 21208 // combined construct. 21209 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 && 21210 isOpenMPTargetExecutionDirective(DKind)) || 21211 DKind == OMPD_target)) { 21212 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 21213 if (isOpenMPPrivate(DVar.CKind)) { 21214 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 21215 << getOpenMPClauseName(DVar.CKind) 21216 << getOpenMPClauseName(OMPC_map) 21217 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 21218 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar); 21219 continue; 21220 } 21221 } 21222 } 21223 21224 // Try to find the associated user-defined mapper. 21225 ExprResult ER = buildUserDefinedMapperRef( 21226 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 21227 Type.getCanonicalType(), UnresolvedMapper); 21228 if (ER.isInvalid()) 21229 continue; 21230 MVLI.UDMapperList.push_back(ER.get()); 21231 21232 // Save the current expression. 21233 MVLI.ProcessedVarList.push_back(RE); 21234 21235 // Store the components in the stack so that they can be used to check 21236 // against other clauses later on. 21237 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 21238 /*WhereFoundClauseKind=*/OMPC_map); 21239 21240 // Save the components and declaration to create the clause. For purposes of 21241 // the clause creation, any component list that has has base 'this' uses 21242 // null as base declaration. 21243 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 21244 MVLI.VarComponents.back().append(CurComponents.begin(), 21245 CurComponents.end()); 21246 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 21247 : CurDeclaration); 21248 } 21249 } 21250 21251 OMPClause *Sema::ActOnOpenMPMapClause( 21252 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 21253 ArrayRef<SourceLocation> MapTypeModifiersLoc, 21254 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 21255 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, 21256 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 21257 const OMPVarListLocTy &Locs, bool NoDiagnose, 21258 ArrayRef<Expr *> UnresolvedMappers) { 21259 OpenMPMapModifierKind Modifiers[] = { 21260 OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown, 21261 OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown, 21262 OMPC_MAP_MODIFIER_unknown}; 21263 SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers]; 21264 21265 // Process map-type-modifiers, flag errors for duplicate modifiers. 21266 unsigned Count = 0; 21267 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) { 21268 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown && 21269 llvm::is_contained(Modifiers, MapTypeModifiers[I])) { 21270 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier); 21271 continue; 21272 } 21273 assert(Count < NumberOfOMPMapClauseModifiers && 21274 "Modifiers exceed the allowed number of map type modifiers"); 21275 Modifiers[Count] = MapTypeModifiers[I]; 21276 ModifiersLoc[Count] = MapTypeModifiersLoc[I]; 21277 ++Count; 21278 } 21279 21280 MappableVarListInfo MVLI(VarList); 21281 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc, 21282 MapperIdScopeSpec, MapperId, UnresolvedMappers, 21283 MapType, Modifiers, IsMapTypeImplicit, 21284 NoDiagnose); 21285 21286 // We need to produce a map clause even if we don't have variables so that 21287 // other diagnostics related with non-existing map clauses are accurate. 21288 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList, 21289 MVLI.VarBaseDeclarations, MVLI.VarComponents, 21290 MVLI.UDMapperList, Modifiers, ModifiersLoc, 21291 MapperIdScopeSpec.getWithLocInContext(Context), 21292 MapperId, MapType, IsMapTypeImplicit, MapLoc); 21293 } 21294 21295 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 21296 TypeResult ParsedType) { 21297 assert(ParsedType.isUsable()); 21298 21299 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 21300 if (ReductionType.isNull()) 21301 return QualType(); 21302 21303 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 21304 // A type name in a declare reduction directive cannot be a function type, an 21305 // array type, a reference type, or a type qualified with const, volatile or 21306 // restrict. 21307 if (ReductionType.hasQualifiers()) { 21308 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 21309 return QualType(); 21310 } 21311 21312 if (ReductionType->isFunctionType()) { 21313 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 21314 return QualType(); 21315 } 21316 if (ReductionType->isReferenceType()) { 21317 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 21318 return QualType(); 21319 } 21320 if (ReductionType->isArrayType()) { 21321 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 21322 return QualType(); 21323 } 21324 return ReductionType; 21325 } 21326 21327 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 21328 Scope *S, DeclContext *DC, DeclarationName Name, 21329 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 21330 AccessSpecifier AS, Decl *PrevDeclInScope) { 21331 SmallVector<Decl *, 8> Decls; 21332 Decls.reserve(ReductionTypes.size()); 21333 21334 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 21335 forRedeclarationInCurContext()); 21336 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 21337 // A reduction-identifier may not be re-declared in the current scope for the 21338 // same type or for a type that is compatible according to the base language 21339 // rules. 21340 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 21341 OMPDeclareReductionDecl *PrevDRD = nullptr; 21342 bool InCompoundScope = true; 21343 if (S != nullptr) { 21344 // Find previous declaration with the same name not referenced in other 21345 // declarations. 21346 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 21347 InCompoundScope = 21348 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 21349 LookupName(Lookup, S); 21350 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 21351 /*AllowInlineNamespace=*/false); 21352 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 21353 LookupResult::Filter Filter = Lookup.makeFilter(); 21354 while (Filter.hasNext()) { 21355 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 21356 if (InCompoundScope) { 21357 auto I = UsedAsPrevious.find(PrevDecl); 21358 if (I == UsedAsPrevious.end()) 21359 UsedAsPrevious[PrevDecl] = false; 21360 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope()) 21361 UsedAsPrevious[D] = true; 21362 } 21363 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 21364 PrevDecl->getLocation(); 21365 } 21366 Filter.done(); 21367 if (InCompoundScope) { 21368 for (const auto &PrevData : UsedAsPrevious) { 21369 if (!PrevData.second) { 21370 PrevDRD = PrevData.first; 21371 break; 21372 } 21373 } 21374 } 21375 } else if (PrevDeclInScope != nullptr) { 21376 auto *PrevDRDInScope = PrevDRD = 21377 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 21378 do { 21379 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 21380 PrevDRDInScope->getLocation(); 21381 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 21382 } while (PrevDRDInScope != nullptr); 21383 } 21384 for (const auto &TyData : ReductionTypes) { 21385 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 21386 bool Invalid = false; 21387 if (I != PreviousRedeclTypes.end()) { 21388 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 21389 << TyData.first; 21390 Diag(I->second, diag::note_previous_definition); 21391 Invalid = true; 21392 } 21393 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 21394 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 21395 Name, TyData.first, PrevDRD); 21396 DC->addDecl(DRD); 21397 DRD->setAccess(AS); 21398 Decls.push_back(DRD); 21399 if (Invalid) 21400 DRD->setInvalidDecl(); 21401 else 21402 PrevDRD = DRD; 21403 } 21404 21405 return DeclGroupPtrTy::make( 21406 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 21407 } 21408 21409 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 21410 auto *DRD = cast<OMPDeclareReductionDecl>(D); 21411 21412 // Enter new function scope. 21413 PushFunctionScope(); 21414 setFunctionHasBranchProtectedScope(); 21415 getCurFunction()->setHasOMPDeclareReductionCombiner(); 21416 21417 if (S != nullptr) 21418 PushDeclContext(S, DRD); 21419 else 21420 CurContext = DRD; 21421 21422 PushExpressionEvaluationContext( 21423 ExpressionEvaluationContext::PotentiallyEvaluated); 21424 21425 QualType ReductionType = DRD->getType(); 21426 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 21427 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 21428 // uses semantics of argument handles by value, but it should be passed by 21429 // reference. C lang does not support references, so pass all parameters as 21430 // pointers. 21431 // Create 'T omp_in;' variable. 21432 VarDecl *OmpInParm = 21433 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 21434 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 21435 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 21436 // uses semantics of argument handles by value, but it should be passed by 21437 // reference. C lang does not support references, so pass all parameters as 21438 // pointers. 21439 // Create 'T omp_out;' variable. 21440 VarDecl *OmpOutParm = 21441 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 21442 if (S != nullptr) { 21443 PushOnScopeChains(OmpInParm, S); 21444 PushOnScopeChains(OmpOutParm, S); 21445 } else { 21446 DRD->addDecl(OmpInParm); 21447 DRD->addDecl(OmpOutParm); 21448 } 21449 Expr *InE = 21450 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation()); 21451 Expr *OutE = 21452 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation()); 21453 DRD->setCombinerData(InE, OutE); 21454 } 21455 21456 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 21457 auto *DRD = cast<OMPDeclareReductionDecl>(D); 21458 DiscardCleanupsInEvaluationContext(); 21459 PopExpressionEvaluationContext(); 21460 21461 PopDeclContext(); 21462 PopFunctionScopeInfo(); 21463 21464 if (Combiner != nullptr) 21465 DRD->setCombiner(Combiner); 21466 else 21467 DRD->setInvalidDecl(); 21468 } 21469 21470 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 21471 auto *DRD = cast<OMPDeclareReductionDecl>(D); 21472 21473 // Enter new function scope. 21474 PushFunctionScope(); 21475 setFunctionHasBranchProtectedScope(); 21476 21477 if (S != nullptr) 21478 PushDeclContext(S, DRD); 21479 else 21480 CurContext = DRD; 21481 21482 PushExpressionEvaluationContext( 21483 ExpressionEvaluationContext::PotentiallyEvaluated); 21484 21485 QualType ReductionType = DRD->getType(); 21486 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 21487 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 21488 // uses semantics of argument handles by value, but it should be passed by 21489 // reference. C lang does not support references, so pass all parameters as 21490 // pointers. 21491 // Create 'T omp_priv;' variable. 21492 VarDecl *OmpPrivParm = 21493 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 21494 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 21495 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 21496 // uses semantics of argument handles by value, but it should be passed by 21497 // reference. C lang does not support references, so pass all parameters as 21498 // pointers. 21499 // Create 'T omp_orig;' variable. 21500 VarDecl *OmpOrigParm = 21501 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 21502 if (S != nullptr) { 21503 PushOnScopeChains(OmpPrivParm, S); 21504 PushOnScopeChains(OmpOrigParm, S); 21505 } else { 21506 DRD->addDecl(OmpPrivParm); 21507 DRD->addDecl(OmpOrigParm); 21508 } 21509 Expr *OrigE = 21510 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation()); 21511 Expr *PrivE = 21512 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation()); 21513 DRD->setInitializerData(OrigE, PrivE); 21514 return OmpPrivParm; 21515 } 21516 21517 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 21518 VarDecl *OmpPrivParm) { 21519 auto *DRD = cast<OMPDeclareReductionDecl>(D); 21520 DiscardCleanupsInEvaluationContext(); 21521 PopExpressionEvaluationContext(); 21522 21523 PopDeclContext(); 21524 PopFunctionScopeInfo(); 21525 21526 if (Initializer != nullptr) { 21527 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit); 21528 } else if (OmpPrivParm->hasInit()) { 21529 DRD->setInitializer(OmpPrivParm->getInit(), 21530 OmpPrivParm->isDirectInit() 21531 ? OMPDeclareReductionDecl::DirectInit 21532 : OMPDeclareReductionDecl::CopyInit); 21533 } else { 21534 DRD->setInvalidDecl(); 21535 } 21536 } 21537 21538 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 21539 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 21540 for (Decl *D : DeclReductions.get()) { 21541 if (IsValid) { 21542 if (S) 21543 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S, 21544 /*AddToContext=*/false); 21545 } else { 21546 D->setInvalidDecl(); 21547 } 21548 } 21549 return DeclReductions; 21550 } 21551 21552 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) { 21553 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 21554 QualType T = TInfo->getType(); 21555 if (D.isInvalidType()) 21556 return true; 21557 21558 if (getLangOpts().CPlusPlus) { 21559 // Check that there are no default arguments (C++ only). 21560 CheckExtraCXXDefaultArguments(D); 21561 } 21562 21563 return CreateParsedType(T, TInfo); 21564 } 21565 21566 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, 21567 TypeResult ParsedType) { 21568 assert(ParsedType.isUsable() && "Expect usable parsed mapper type"); 21569 21570 QualType MapperType = GetTypeFromParser(ParsedType.get()); 21571 assert(!MapperType.isNull() && "Expect valid mapper type"); 21572 21573 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 21574 // The type must be of struct, union or class type in C and C++ 21575 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) { 21576 Diag(TyLoc, diag::err_omp_mapper_wrong_type); 21577 return QualType(); 21578 } 21579 return MapperType; 21580 } 21581 21582 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective( 21583 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, 21584 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, 21585 Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) { 21586 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName, 21587 forRedeclarationInCurContext()); 21588 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 21589 // A mapper-identifier may not be redeclared in the current scope for the 21590 // same type or for a type that is compatible according to the base language 21591 // rules. 21592 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 21593 OMPDeclareMapperDecl *PrevDMD = nullptr; 21594 bool InCompoundScope = true; 21595 if (S != nullptr) { 21596 // Find previous declaration with the same name not referenced in other 21597 // declarations. 21598 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 21599 InCompoundScope = 21600 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 21601 LookupName(Lookup, S); 21602 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 21603 /*AllowInlineNamespace=*/false); 21604 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious; 21605 LookupResult::Filter Filter = Lookup.makeFilter(); 21606 while (Filter.hasNext()) { 21607 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next()); 21608 if (InCompoundScope) { 21609 auto I = UsedAsPrevious.find(PrevDecl); 21610 if (I == UsedAsPrevious.end()) 21611 UsedAsPrevious[PrevDecl] = false; 21612 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope()) 21613 UsedAsPrevious[D] = true; 21614 } 21615 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 21616 PrevDecl->getLocation(); 21617 } 21618 Filter.done(); 21619 if (InCompoundScope) { 21620 for (const auto &PrevData : UsedAsPrevious) { 21621 if (!PrevData.second) { 21622 PrevDMD = PrevData.first; 21623 break; 21624 } 21625 } 21626 } 21627 } else if (PrevDeclInScope) { 21628 auto *PrevDMDInScope = PrevDMD = 21629 cast<OMPDeclareMapperDecl>(PrevDeclInScope); 21630 do { 21631 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] = 21632 PrevDMDInScope->getLocation(); 21633 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope(); 21634 } while (PrevDMDInScope != nullptr); 21635 } 21636 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType()); 21637 bool Invalid = false; 21638 if (I != PreviousRedeclTypes.end()) { 21639 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition) 21640 << MapperType << Name; 21641 Diag(I->second, diag::note_previous_definition); 21642 Invalid = true; 21643 } 21644 // Build expressions for implicit maps of data members with 'default' 21645 // mappers. 21646 SmallVector<OMPClause *, 4> ClausesWithImplicit(Clauses.begin(), 21647 Clauses.end()); 21648 if (LangOpts.OpenMP >= 50) 21649 processImplicitMapsWithDefaultMappers(*this, DSAStack, ClausesWithImplicit); 21650 auto *DMD = 21651 OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, MapperType, VN, 21652 ClausesWithImplicit, PrevDMD); 21653 if (S) 21654 PushOnScopeChains(DMD, S); 21655 else 21656 DC->addDecl(DMD); 21657 DMD->setAccess(AS); 21658 if (Invalid) 21659 DMD->setInvalidDecl(); 21660 21661 auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl(); 21662 VD->setDeclContext(DMD); 21663 VD->setLexicalDeclContext(DMD); 21664 DMD->addDecl(VD); 21665 DMD->setMapperVarRef(MapperVarRef); 21666 21667 return DeclGroupPtrTy::make(DeclGroupRef(DMD)); 21668 } 21669 21670 ExprResult 21671 Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType, 21672 SourceLocation StartLoc, 21673 DeclarationName VN) { 21674 TypeSourceInfo *TInfo = 21675 Context.getTrivialTypeSourceInfo(MapperType, StartLoc); 21676 auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(), 21677 StartLoc, StartLoc, VN.getAsIdentifierInfo(), 21678 MapperType, TInfo, SC_None); 21679 if (S) 21680 PushOnScopeChains(VD, S, /*AddToContext=*/false); 21681 Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc); 21682 DSAStack->addDeclareMapperVarRef(E); 21683 return E; 21684 } 21685 21686 bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const { 21687 assert(LangOpts.OpenMP && "Expected OpenMP mode."); 21688 const Expr *Ref = DSAStack->getDeclareMapperVarRef(); 21689 if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref)) { 21690 if (VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl()) 21691 return true; 21692 if (VD->isUsableInConstantExpressions(Context)) 21693 return true; 21694 return false; 21695 } 21696 return true; 21697 } 21698 21699 const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const { 21700 assert(LangOpts.OpenMP && "Expected OpenMP mode."); 21701 return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl(); 21702 } 21703 21704 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 21705 SourceLocation StartLoc, 21706 SourceLocation LParenLoc, 21707 SourceLocation EndLoc) { 21708 Expr *ValExpr = NumTeams; 21709 Stmt *HelperValStmt = nullptr; 21710 21711 // OpenMP [teams Constrcut, Restrictions] 21712 // The num_teams expression must evaluate to a positive integer value. 21713 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 21714 /*StrictlyPositive=*/true)) 21715 return nullptr; 21716 21717 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 21718 OpenMPDirectiveKind CaptureRegion = 21719 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP); 21720 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 21721 ValExpr = MakeFullExpr(ValExpr).get(); 21722 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 21723 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 21724 HelperValStmt = buildPreInits(Context, Captures); 21725 } 21726 21727 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 21728 StartLoc, LParenLoc, EndLoc); 21729 } 21730 21731 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 21732 SourceLocation StartLoc, 21733 SourceLocation LParenLoc, 21734 SourceLocation EndLoc) { 21735 Expr *ValExpr = ThreadLimit; 21736 Stmt *HelperValStmt = nullptr; 21737 21738 // OpenMP [teams Constrcut, Restrictions] 21739 // The thread_limit expression must evaluate to a positive integer value. 21740 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 21741 /*StrictlyPositive=*/true)) 21742 return nullptr; 21743 21744 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 21745 OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause( 21746 DKind, OMPC_thread_limit, LangOpts.OpenMP); 21747 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 21748 ValExpr = MakeFullExpr(ValExpr).get(); 21749 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 21750 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 21751 HelperValStmt = buildPreInits(Context, Captures); 21752 } 21753 21754 return new (Context) OMPThreadLimitClause( 21755 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 21756 } 21757 21758 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 21759 SourceLocation StartLoc, 21760 SourceLocation LParenLoc, 21761 SourceLocation EndLoc) { 21762 Expr *ValExpr = Priority; 21763 Stmt *HelperValStmt = nullptr; 21764 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 21765 21766 // OpenMP [2.9.1, task Constrcut] 21767 // The priority-value is a non-negative numerical scalar expression. 21768 if (!isNonNegativeIntegerValue( 21769 ValExpr, *this, OMPC_priority, 21770 /*StrictlyPositive=*/false, /*BuildCapture=*/true, 21771 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 21772 return nullptr; 21773 21774 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion, 21775 StartLoc, LParenLoc, EndLoc); 21776 } 21777 21778 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 21779 SourceLocation StartLoc, 21780 SourceLocation LParenLoc, 21781 SourceLocation EndLoc) { 21782 Expr *ValExpr = Grainsize; 21783 Stmt *HelperValStmt = nullptr; 21784 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 21785 21786 // OpenMP [2.9.2, taskloop Constrcut] 21787 // The parameter of the grainsize clause must be a positive integer 21788 // expression. 21789 if (!isNonNegativeIntegerValue( 21790 ValExpr, *this, OMPC_grainsize, 21791 /*StrictlyPositive=*/true, /*BuildCapture=*/true, 21792 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 21793 return nullptr; 21794 21795 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion, 21796 StartLoc, LParenLoc, EndLoc); 21797 } 21798 21799 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 21800 SourceLocation StartLoc, 21801 SourceLocation LParenLoc, 21802 SourceLocation EndLoc) { 21803 Expr *ValExpr = NumTasks; 21804 Stmt *HelperValStmt = nullptr; 21805 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 21806 21807 // OpenMP [2.9.2, taskloop Constrcut] 21808 // The parameter of the num_tasks clause must be a positive integer 21809 // expression. 21810 if (!isNonNegativeIntegerValue( 21811 ValExpr, *this, OMPC_num_tasks, 21812 /*StrictlyPositive=*/true, /*BuildCapture=*/true, 21813 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 21814 return nullptr; 21815 21816 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion, 21817 StartLoc, LParenLoc, EndLoc); 21818 } 21819 21820 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 21821 SourceLocation LParenLoc, 21822 SourceLocation EndLoc) { 21823 // OpenMP [2.13.2, critical construct, Description] 21824 // ... where hint-expression is an integer constant expression that evaluates 21825 // to a valid lock hint. 21826 ExprResult HintExpr = 21827 VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint, false); 21828 if (HintExpr.isInvalid()) 21829 return nullptr; 21830 return new (Context) 21831 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 21832 } 21833 21834 /// Tries to find omp_event_handle_t type. 21835 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc, 21836 DSAStackTy *Stack) { 21837 QualType OMPEventHandleT = Stack->getOMPEventHandleT(); 21838 if (!OMPEventHandleT.isNull()) 21839 return true; 21840 IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t"); 21841 ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope()); 21842 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 21843 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t"; 21844 return false; 21845 } 21846 Stack->setOMPEventHandleT(PT.get()); 21847 return true; 21848 } 21849 21850 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, 21851 SourceLocation LParenLoc, 21852 SourceLocation EndLoc) { 21853 if (!Evt->isValueDependent() && !Evt->isTypeDependent() && 21854 !Evt->isInstantiationDependent() && 21855 !Evt->containsUnexpandedParameterPack()) { 21856 if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack)) 21857 return nullptr; 21858 // OpenMP 5.0, 2.10.1 task Construct. 21859 // event-handle is a variable of the omp_event_handle_t type. 21860 auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts()); 21861 if (!Ref) { 21862 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 21863 << "omp_event_handle_t" << 0 << Evt->getSourceRange(); 21864 return nullptr; 21865 } 21866 auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl()); 21867 if (!VD) { 21868 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 21869 << "omp_event_handle_t" << 0 << Evt->getSourceRange(); 21870 return nullptr; 21871 } 21872 if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(), 21873 VD->getType()) || 21874 VD->getType().isConstant(Context)) { 21875 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 21876 << "omp_event_handle_t" << 1 << VD->getType() 21877 << Evt->getSourceRange(); 21878 return nullptr; 21879 } 21880 // OpenMP 5.0, 2.10.1 task Construct 21881 // [detach clause]... The event-handle will be considered as if it was 21882 // specified on a firstprivate clause. 21883 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false); 21884 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 21885 DVar.RefExpr) { 21886 Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa) 21887 << getOpenMPClauseName(DVar.CKind) 21888 << getOpenMPClauseName(OMPC_firstprivate); 21889 reportOriginalDsa(*this, DSAStack, VD, DVar); 21890 return nullptr; 21891 } 21892 } 21893 21894 return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc); 21895 } 21896 21897 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 21898 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 21899 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 21900 SourceLocation EndLoc) { 21901 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 21902 std::string Values; 21903 Values += "'"; 21904 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 21905 Values += "'"; 21906 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 21907 << Values << getOpenMPClauseName(OMPC_dist_schedule); 21908 return nullptr; 21909 } 21910 Expr *ValExpr = ChunkSize; 21911 Stmt *HelperValStmt = nullptr; 21912 if (ChunkSize) { 21913 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 21914 !ChunkSize->isInstantiationDependent() && 21915 !ChunkSize->containsUnexpandedParameterPack()) { 21916 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 21917 ExprResult Val = 21918 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 21919 if (Val.isInvalid()) 21920 return nullptr; 21921 21922 ValExpr = Val.get(); 21923 21924 // OpenMP [2.7.1, Restrictions] 21925 // chunk_size must be a loop invariant integer expression with a positive 21926 // value. 21927 if (Optional<llvm::APSInt> Result = 21928 ValExpr->getIntegerConstantExpr(Context)) { 21929 if (Result->isSigned() && !Result->isStrictlyPositive()) { 21930 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 21931 << "dist_schedule" << ChunkSize->getSourceRange(); 21932 return nullptr; 21933 } 21934 } else if (getOpenMPCaptureRegionForClause( 21935 DSAStack->getCurrentDirective(), OMPC_dist_schedule, 21936 LangOpts.OpenMP) != OMPD_unknown && 21937 !CurContext->isDependentContext()) { 21938 ValExpr = MakeFullExpr(ValExpr).get(); 21939 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 21940 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 21941 HelperValStmt = buildPreInits(Context, Captures); 21942 } 21943 } 21944 } 21945 21946 return new (Context) 21947 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 21948 Kind, ValExpr, HelperValStmt); 21949 } 21950 21951 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 21952 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 21953 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 21954 SourceLocation KindLoc, SourceLocation EndLoc) { 21955 if (getLangOpts().OpenMP < 50) { 21956 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || 21957 Kind != OMPC_DEFAULTMAP_scalar) { 21958 std::string Value; 21959 SourceLocation Loc; 21960 Value += "'"; 21961 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 21962 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 21963 OMPC_DEFAULTMAP_MODIFIER_tofrom); 21964 Loc = MLoc; 21965 } else { 21966 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 21967 OMPC_DEFAULTMAP_scalar); 21968 Loc = KindLoc; 21969 } 21970 Value += "'"; 21971 Diag(Loc, diag::err_omp_unexpected_clause_value) 21972 << Value << getOpenMPClauseName(OMPC_defaultmap); 21973 return nullptr; 21974 } 21975 } else { 21976 bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown); 21977 bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) || 21978 (LangOpts.OpenMP >= 50 && KindLoc.isInvalid()); 21979 if (!isDefaultmapKind || !isDefaultmapModifier) { 21980 StringRef KindValue = "'scalar', 'aggregate', 'pointer'"; 21981 if (LangOpts.OpenMP == 50) { 21982 StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', " 21983 "'firstprivate', 'none', 'default'"; 21984 if (!isDefaultmapKind && isDefaultmapModifier) { 21985 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 21986 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 21987 } else if (isDefaultmapKind && !isDefaultmapModifier) { 21988 Diag(MLoc, diag::err_omp_unexpected_clause_value) 21989 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 21990 } else { 21991 Diag(MLoc, diag::err_omp_unexpected_clause_value) 21992 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 21993 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 21994 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 21995 } 21996 } else { 21997 StringRef ModifierValue = 21998 "'alloc', 'from', 'to', 'tofrom', " 21999 "'firstprivate', 'none', 'default', 'present'"; 22000 if (!isDefaultmapKind && isDefaultmapModifier) { 22001 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 22002 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 22003 } else if (isDefaultmapKind && !isDefaultmapModifier) { 22004 Diag(MLoc, diag::err_omp_unexpected_clause_value) 22005 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 22006 } else { 22007 Diag(MLoc, diag::err_omp_unexpected_clause_value) 22008 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 22009 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 22010 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 22011 } 22012 } 22013 return nullptr; 22014 } 22015 22016 // OpenMP [5.0, 2.12.5, Restrictions, p. 174] 22017 // At most one defaultmap clause for each category can appear on the 22018 // directive. 22019 if (DSAStack->checkDefaultmapCategory(Kind)) { 22020 Diag(StartLoc, diag::err_omp_one_defaultmap_each_category); 22021 return nullptr; 22022 } 22023 } 22024 if (Kind == OMPC_DEFAULTMAP_unknown) { 22025 // Variable category is not specified - mark all categories. 22026 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc); 22027 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc); 22028 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc); 22029 } else { 22030 DSAStack->setDefaultDMAAttr(M, Kind, StartLoc); 22031 } 22032 22033 return new (Context) 22034 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 22035 } 22036 22037 bool Sema::ActOnStartOpenMPDeclareTargetContext( 22038 DeclareTargetContextInfo &DTCI) { 22039 DeclContext *CurLexicalContext = getCurLexicalContext(); 22040 if (!CurLexicalContext->isFileContext() && 22041 !CurLexicalContext->isExternCContext() && 22042 !CurLexicalContext->isExternCXXContext() && 22043 !isa<CXXRecordDecl>(CurLexicalContext) && 22044 !isa<ClassTemplateDecl>(CurLexicalContext) && 22045 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) && 22046 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) { 22047 Diag(DTCI.Loc, diag::err_omp_region_not_file_context); 22048 return false; 22049 } 22050 DeclareTargetNesting.push_back(DTCI); 22051 return true; 22052 } 22053 22054 const Sema::DeclareTargetContextInfo 22055 Sema::ActOnOpenMPEndDeclareTargetDirective() { 22056 assert(!DeclareTargetNesting.empty() && 22057 "check isInOpenMPDeclareTargetContext() first!"); 22058 return DeclareTargetNesting.pop_back_val(); 22059 } 22060 22061 void Sema::ActOnFinishedOpenMPDeclareTargetContext( 22062 DeclareTargetContextInfo &DTCI) { 22063 for (auto &It : DTCI.ExplicitlyMapped) 22064 ActOnOpenMPDeclareTargetName(It.first, It.second.Loc, It.second.MT, DTCI); 22065 } 22066 22067 void Sema::DiagnoseUnterminatedOpenMPDeclareTarget() { 22068 if (DeclareTargetNesting.empty()) 22069 return; 22070 DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back(); 22071 Diag(DTCI.Loc, diag::warn_omp_unterminated_declare_target) 22072 << getOpenMPDirectiveName(DTCI.Kind); 22073 } 22074 22075 NamedDecl *Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, 22076 CXXScopeSpec &ScopeSpec, 22077 const DeclarationNameInfo &Id) { 22078 LookupResult Lookup(*this, Id, LookupOrdinaryName); 22079 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 22080 22081 if (Lookup.isAmbiguous()) 22082 return nullptr; 22083 Lookup.suppressDiagnostics(); 22084 22085 if (!Lookup.isSingleResult()) { 22086 VarOrFuncDeclFilterCCC CCC(*this); 22087 if (TypoCorrection Corrected = 22088 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC, 22089 CTK_ErrorRecovery)) { 22090 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 22091 << Id.getName()); 22092 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 22093 return nullptr; 22094 } 22095 22096 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 22097 return nullptr; 22098 } 22099 22100 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 22101 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) && 22102 !isa<FunctionTemplateDecl>(ND)) { 22103 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 22104 return nullptr; 22105 } 22106 return ND; 22107 } 22108 22109 void Sema::ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, 22110 OMPDeclareTargetDeclAttr::MapTypeTy MT, 22111 DeclareTargetContextInfo &DTCI) { 22112 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) || 22113 isa<FunctionTemplateDecl>(ND)) && 22114 "Expected variable, function or function template."); 22115 22116 // Diagnose marking after use as it may lead to incorrect diagnosis and 22117 // codegen. 22118 if (LangOpts.OpenMP >= 50 && 22119 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced())) 22120 Diag(Loc, diag::warn_omp_declare_target_after_first_use); 22121 22122 // Explicit declare target lists have precedence. 22123 const unsigned Level = -1; 22124 22125 auto *VD = cast<ValueDecl>(ND); 22126 llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 22127 OMPDeclareTargetDeclAttr::getActiveAttr(VD); 22128 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getDevType() != DTCI.DT && 22129 ActiveAttr.getValue()->getLevel() == Level) { 22130 Diag(Loc, diag::err_omp_device_type_mismatch) 22131 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DTCI.DT) 22132 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr( 22133 ActiveAttr.getValue()->getDevType()); 22134 return; 22135 } 22136 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getMapType() != MT && 22137 ActiveAttr.getValue()->getLevel() == Level) { 22138 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND; 22139 return; 22140 } 22141 22142 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() == Level) 22143 return; 22144 22145 Expr *IndirectE = nullptr; 22146 bool IsIndirect = false; 22147 if (DTCI.Indirect.hasValue()) { 22148 IndirectE = DTCI.Indirect.getValue(); 22149 if (!IndirectE) 22150 IsIndirect = true; 22151 } 22152 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit( 22153 Context, MT, DTCI.DT, IndirectE, IsIndirect, Level, 22154 SourceRange(Loc, Loc)); 22155 ND->addAttr(A); 22156 if (ASTMutationListener *ML = Context.getASTMutationListener()) 22157 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 22158 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc); 22159 } 22160 22161 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 22162 Sema &SemaRef, Decl *D) { 22163 if (!D || !isa<VarDecl>(D)) 22164 return; 22165 auto *VD = cast<VarDecl>(D); 22166 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy = 22167 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 22168 if (SemaRef.LangOpts.OpenMP >= 50 && 22169 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) || 22170 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) && 22171 VD->hasGlobalStorage()) { 22172 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) { 22173 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions 22174 // If a lambda declaration and definition appears between a 22175 // declare target directive and the matching end declare target 22176 // directive, all variables that are captured by the lambda 22177 // expression must also appear in a to clause. 22178 SemaRef.Diag(VD->getLocation(), 22179 diag::err_omp_lambda_capture_in_declare_target_not_to); 22180 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here) 22181 << VD << 0 << SR; 22182 return; 22183 } 22184 } 22185 if (MapTy) 22186 return; 22187 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context); 22188 SemaRef.Diag(SL, diag::note_used_here) << SR; 22189 } 22190 22191 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 22192 Sema &SemaRef, DSAStackTy *Stack, 22193 ValueDecl *VD) { 22194 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) || 22195 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(), 22196 /*FullCheck=*/false); 22197 } 22198 22199 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 22200 SourceLocation IdLoc) { 22201 if (!D || D->isInvalidDecl()) 22202 return; 22203 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 22204 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation(); 22205 if (auto *VD = dyn_cast<VarDecl>(D)) { 22206 // Only global variables can be marked as declare target. 22207 if (!VD->isFileVarDecl() && !VD->isStaticLocal() && 22208 !VD->isStaticDataMember()) 22209 return; 22210 // 2.10.6: threadprivate variable cannot appear in a declare target 22211 // directive. 22212 if (DSAStack->isThreadPrivate(VD)) { 22213 Diag(SL, diag::err_omp_threadprivate_in_target); 22214 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 22215 return; 22216 } 22217 } 22218 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) 22219 D = FTD->getTemplatedDecl(); 22220 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 22221 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 22222 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD); 22223 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) { 22224 Diag(IdLoc, diag::err_omp_function_in_link_clause); 22225 Diag(FD->getLocation(), diag::note_defined_here) << FD; 22226 return; 22227 } 22228 } 22229 if (auto *VD = dyn_cast<ValueDecl>(D)) { 22230 // Problem if any with var declared with incomplete type will be reported 22231 // as normal, so no need to check it here. 22232 if ((E || !VD->getType()->isIncompleteType()) && 22233 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) 22234 return; 22235 if (!E && isInOpenMPDeclareTargetContext()) { 22236 // Checking declaration inside declare target region. 22237 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) || 22238 isa<FunctionTemplateDecl>(D)) { 22239 llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 22240 OMPDeclareTargetDeclAttr::getActiveAttr(VD); 22241 unsigned Level = DeclareTargetNesting.size(); 22242 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() >= Level) 22243 return; 22244 DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back(); 22245 Expr *IndirectE = nullptr; 22246 bool IsIndirect = false; 22247 if (DTCI.Indirect.hasValue()) { 22248 IndirectE = DTCI.Indirect.getValue(); 22249 if (!IndirectE) 22250 IsIndirect = true; 22251 } 22252 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit( 22253 Context, OMPDeclareTargetDeclAttr::MT_To, DTCI.DT, IndirectE, 22254 IsIndirect, Level, SourceRange(DTCI.Loc, DTCI.Loc)); 22255 D->addAttr(A); 22256 if (ASTMutationListener *ML = Context.getASTMutationListener()) 22257 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 22258 } 22259 return; 22260 } 22261 } 22262 if (!E) 22263 return; 22264 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 22265 } 22266 22267 OMPClause *Sema::ActOnOpenMPToClause( 22268 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 22269 ArrayRef<SourceLocation> MotionModifiersLoc, 22270 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 22271 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 22272 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) { 22273 OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown, 22274 OMPC_MOTION_MODIFIER_unknown}; 22275 SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers]; 22276 22277 // Process motion-modifiers, flag errors for duplicate modifiers. 22278 unsigned Count = 0; 22279 for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) { 22280 if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown && 22281 llvm::is_contained(Modifiers, MotionModifiers[I])) { 22282 Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier); 22283 continue; 22284 } 22285 assert(Count < NumberOfOMPMotionModifiers && 22286 "Modifiers exceed the allowed number of motion modifiers"); 22287 Modifiers[Count] = MotionModifiers[I]; 22288 ModifiersLoc[Count] = MotionModifiersLoc[I]; 22289 ++Count; 22290 } 22291 22292 MappableVarListInfo MVLI(VarList); 22293 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc, 22294 MapperIdScopeSpec, MapperId, UnresolvedMappers); 22295 if (MVLI.ProcessedVarList.empty()) 22296 return nullptr; 22297 22298 return OMPToClause::Create( 22299 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 22300 MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc, 22301 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 22302 } 22303 22304 OMPClause *Sema::ActOnOpenMPFromClause( 22305 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 22306 ArrayRef<SourceLocation> MotionModifiersLoc, 22307 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 22308 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 22309 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) { 22310 OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown, 22311 OMPC_MOTION_MODIFIER_unknown}; 22312 SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers]; 22313 22314 // Process motion-modifiers, flag errors for duplicate modifiers. 22315 unsigned Count = 0; 22316 for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) { 22317 if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown && 22318 llvm::is_contained(Modifiers, MotionModifiers[I])) { 22319 Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier); 22320 continue; 22321 } 22322 assert(Count < NumberOfOMPMotionModifiers && 22323 "Modifiers exceed the allowed number of motion modifiers"); 22324 Modifiers[Count] = MotionModifiers[I]; 22325 ModifiersLoc[Count] = MotionModifiersLoc[I]; 22326 ++Count; 22327 } 22328 22329 MappableVarListInfo MVLI(VarList); 22330 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc, 22331 MapperIdScopeSpec, MapperId, UnresolvedMappers); 22332 if (MVLI.ProcessedVarList.empty()) 22333 return nullptr; 22334 22335 return OMPFromClause::Create( 22336 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 22337 MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc, 22338 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 22339 } 22340 22341 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 22342 const OMPVarListLocTy &Locs) { 22343 MappableVarListInfo MVLI(VarList); 22344 SmallVector<Expr *, 8> PrivateCopies; 22345 SmallVector<Expr *, 8> Inits; 22346 22347 for (Expr *RefExpr : VarList) { 22348 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 22349 SourceLocation ELoc; 22350 SourceRange ERange; 22351 Expr *SimpleRefExpr = RefExpr; 22352 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 22353 if (Res.second) { 22354 // It will be analyzed later. 22355 MVLI.ProcessedVarList.push_back(RefExpr); 22356 PrivateCopies.push_back(nullptr); 22357 Inits.push_back(nullptr); 22358 } 22359 ValueDecl *D = Res.first; 22360 if (!D) 22361 continue; 22362 22363 QualType Type = D->getType(); 22364 Type = Type.getNonReferenceType().getUnqualifiedType(); 22365 22366 auto *VD = dyn_cast<VarDecl>(D); 22367 22368 // Item should be a pointer or reference to pointer. 22369 if (!Type->isPointerType()) { 22370 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 22371 << 0 << RefExpr->getSourceRange(); 22372 continue; 22373 } 22374 22375 // Build the private variable and the expression that refers to it. 22376 auto VDPrivate = 22377 buildVarDecl(*this, ELoc, Type, D->getName(), 22378 D->hasAttrs() ? &D->getAttrs() : nullptr, 22379 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 22380 if (VDPrivate->isInvalidDecl()) 22381 continue; 22382 22383 CurContext->addDecl(VDPrivate); 22384 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 22385 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 22386 22387 // Add temporary variable to initialize the private copy of the pointer. 22388 VarDecl *VDInit = 22389 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 22390 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr( 22391 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc()); 22392 AddInitializerToDecl(VDPrivate, 22393 DefaultLvalueConversion(VDInitRefExpr).get(), 22394 /*DirectInit=*/false); 22395 22396 // If required, build a capture to implement the privatization initialized 22397 // with the current list item value. 22398 DeclRefExpr *Ref = nullptr; 22399 if (!VD) 22400 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 22401 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 22402 PrivateCopies.push_back(VDPrivateRefExpr); 22403 Inits.push_back(VDInitRefExpr); 22404 22405 // We need to add a data sharing attribute for this variable to make sure it 22406 // is correctly captured. A variable that shows up in a use_device_ptr has 22407 // similar properties of a first private variable. 22408 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 22409 22410 // Create a mappable component for the list item. List items in this clause 22411 // only need a component. 22412 MVLI.VarBaseDeclarations.push_back(D); 22413 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 22414 MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D, 22415 /*IsNonContiguous=*/false); 22416 } 22417 22418 if (MVLI.ProcessedVarList.empty()) 22419 return nullptr; 22420 22421 return OMPUseDevicePtrClause::Create( 22422 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits, 22423 MVLI.VarBaseDeclarations, MVLI.VarComponents); 22424 } 22425 22426 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, 22427 const OMPVarListLocTy &Locs) { 22428 MappableVarListInfo MVLI(VarList); 22429 22430 for (Expr *RefExpr : VarList) { 22431 assert(RefExpr && "NULL expr in OpenMP use_device_addr clause."); 22432 SourceLocation ELoc; 22433 SourceRange ERange; 22434 Expr *SimpleRefExpr = RefExpr; 22435 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 22436 /*AllowArraySection=*/true); 22437 if (Res.second) { 22438 // It will be analyzed later. 22439 MVLI.ProcessedVarList.push_back(RefExpr); 22440 } 22441 ValueDecl *D = Res.first; 22442 if (!D) 22443 continue; 22444 auto *VD = dyn_cast<VarDecl>(D); 22445 22446 // If required, build a capture to implement the privatization initialized 22447 // with the current list item value. 22448 DeclRefExpr *Ref = nullptr; 22449 if (!VD) 22450 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 22451 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 22452 22453 // We need to add a data sharing attribute for this variable to make sure it 22454 // is correctly captured. A variable that shows up in a use_device_addr has 22455 // similar properties of a first private variable. 22456 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 22457 22458 // Create a mappable component for the list item. List items in this clause 22459 // only need a component. 22460 MVLI.VarBaseDeclarations.push_back(D); 22461 MVLI.VarComponents.emplace_back(); 22462 Expr *Component = SimpleRefExpr; 22463 if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) || 22464 isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts()))) 22465 Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get(); 22466 MVLI.VarComponents.back().emplace_back(Component, D, 22467 /*IsNonContiguous=*/false); 22468 } 22469 22470 if (MVLI.ProcessedVarList.empty()) 22471 return nullptr; 22472 22473 return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList, 22474 MVLI.VarBaseDeclarations, 22475 MVLI.VarComponents); 22476 } 22477 22478 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 22479 const OMPVarListLocTy &Locs) { 22480 MappableVarListInfo MVLI(VarList); 22481 for (Expr *RefExpr : VarList) { 22482 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 22483 SourceLocation ELoc; 22484 SourceRange ERange; 22485 Expr *SimpleRefExpr = RefExpr; 22486 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 22487 if (Res.second) { 22488 // It will be analyzed later. 22489 MVLI.ProcessedVarList.push_back(RefExpr); 22490 } 22491 ValueDecl *D = Res.first; 22492 if (!D) 22493 continue; 22494 22495 QualType Type = D->getType(); 22496 // item should be a pointer or array or reference to pointer or array 22497 if (!Type.getNonReferenceType()->isPointerType() && 22498 !Type.getNonReferenceType()->isArrayType()) { 22499 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 22500 << 0 << RefExpr->getSourceRange(); 22501 continue; 22502 } 22503 22504 // Check if the declaration in the clause does not show up in any data 22505 // sharing attribute. 22506 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 22507 if (isOpenMPPrivate(DVar.CKind)) { 22508 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 22509 << getOpenMPClauseName(DVar.CKind) 22510 << getOpenMPClauseName(OMPC_is_device_ptr) 22511 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 22512 reportOriginalDsa(*this, DSAStack, D, DVar); 22513 continue; 22514 } 22515 22516 const Expr *ConflictExpr; 22517 if (DSAStack->checkMappableExprComponentListsForDecl( 22518 D, /*CurrentRegionOnly=*/true, 22519 [&ConflictExpr]( 22520 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 22521 OpenMPClauseKind) -> bool { 22522 ConflictExpr = R.front().getAssociatedExpression(); 22523 return true; 22524 })) { 22525 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 22526 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 22527 << ConflictExpr->getSourceRange(); 22528 continue; 22529 } 22530 22531 // Store the components in the stack so that they can be used to check 22532 // against other clauses later on. 22533 OMPClauseMappableExprCommon::MappableComponent MC( 22534 SimpleRefExpr, D, /*IsNonContiguous=*/false); 22535 DSAStack->addMappableExpressionComponents( 22536 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 22537 22538 // Record the expression we've just processed. 22539 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 22540 22541 // Create a mappable component for the list item. List items in this clause 22542 // only need a component. We use a null declaration to signal fields in 22543 // 'this'. 22544 assert((isa<DeclRefExpr>(SimpleRefExpr) || 22545 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 22546 "Unexpected device pointer expression!"); 22547 MVLI.VarBaseDeclarations.push_back( 22548 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 22549 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 22550 MVLI.VarComponents.back().push_back(MC); 22551 } 22552 22553 if (MVLI.ProcessedVarList.empty()) 22554 return nullptr; 22555 22556 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList, 22557 MVLI.VarBaseDeclarations, 22558 MVLI.VarComponents); 22559 } 22560 22561 OMPClause *Sema::ActOnOpenMPHasDeviceAddrClause(ArrayRef<Expr *> VarList, 22562 const OMPVarListLocTy &Locs) { 22563 MappableVarListInfo MVLI(VarList); 22564 for (Expr *RefExpr : VarList) { 22565 assert(RefExpr && "NULL expr in OpenMP has_device_addr clause."); 22566 SourceLocation ELoc; 22567 SourceRange ERange; 22568 Expr *SimpleRefExpr = RefExpr; 22569 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 22570 /*AllowArraySection=*/true); 22571 if (Res.second) { 22572 // It will be analyzed later. 22573 MVLI.ProcessedVarList.push_back(RefExpr); 22574 } 22575 ValueDecl *D = Res.first; 22576 if (!D) 22577 continue; 22578 22579 // Check if the declaration in the clause does not show up in any data 22580 // sharing attribute. 22581 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 22582 if (isOpenMPPrivate(DVar.CKind)) { 22583 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 22584 << getOpenMPClauseName(DVar.CKind) 22585 << getOpenMPClauseName(OMPC_has_device_addr) 22586 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 22587 reportOriginalDsa(*this, DSAStack, D, DVar); 22588 continue; 22589 } 22590 22591 const Expr *ConflictExpr; 22592 if (DSAStack->checkMappableExprComponentListsForDecl( 22593 D, /*CurrentRegionOnly=*/true, 22594 [&ConflictExpr]( 22595 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 22596 OpenMPClauseKind) -> bool { 22597 ConflictExpr = R.front().getAssociatedExpression(); 22598 return true; 22599 })) { 22600 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 22601 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 22602 << ConflictExpr->getSourceRange(); 22603 continue; 22604 } 22605 22606 // Store the components in the stack so that they can be used to check 22607 // against other clauses later on. 22608 OMPClauseMappableExprCommon::MappableComponent MC( 22609 SimpleRefExpr, D, /*IsNonContiguous=*/false); 22610 DSAStack->addMappableExpressionComponents( 22611 D, MC, /*WhereFoundClauseKind=*/OMPC_has_device_addr); 22612 22613 // Record the expression we've just processed. 22614 auto *VD = dyn_cast<VarDecl>(D); 22615 if (!VD && !CurContext->isDependentContext()) { 22616 DeclRefExpr *Ref = 22617 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 22618 assert(Ref && "has_device_addr capture failed"); 22619 MVLI.ProcessedVarList.push_back(Ref); 22620 } else 22621 MVLI.ProcessedVarList.push_back(RefExpr->IgnoreParens()); 22622 22623 // Create a mappable component for the list item. List items in this clause 22624 // only need a component. We use a null declaration to signal fields in 22625 // 'this'. 22626 assert((isa<DeclRefExpr>(SimpleRefExpr) || 22627 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 22628 "Unexpected device pointer expression!"); 22629 MVLI.VarBaseDeclarations.push_back( 22630 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 22631 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 22632 MVLI.VarComponents.back().push_back(MC); 22633 } 22634 22635 if (MVLI.ProcessedVarList.empty()) 22636 return nullptr; 22637 22638 return OMPHasDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList, 22639 MVLI.VarBaseDeclarations, 22640 MVLI.VarComponents); 22641 } 22642 22643 OMPClause *Sema::ActOnOpenMPAllocateClause( 22644 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, 22645 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 22646 if (Allocator) { 22647 // OpenMP [2.11.4 allocate Clause, Description] 22648 // allocator is an expression of omp_allocator_handle_t type. 22649 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack)) 22650 return nullptr; 22651 22652 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator); 22653 if (AllocatorRes.isInvalid()) 22654 return nullptr; 22655 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(), 22656 DSAStack->getOMPAllocatorHandleT(), 22657 Sema::AA_Initializing, 22658 /*AllowExplicit=*/true); 22659 if (AllocatorRes.isInvalid()) 22660 return nullptr; 22661 Allocator = AllocatorRes.get(); 22662 } else { 22663 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions. 22664 // allocate clauses that appear on a target construct or on constructs in a 22665 // target region must specify an allocator expression unless a requires 22666 // directive with the dynamic_allocators clause is present in the same 22667 // compilation unit. 22668 if (LangOpts.OpenMPIsDevice && 22669 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>()) 22670 targetDiag(StartLoc, diag::err_expected_allocator_expression); 22671 } 22672 // Analyze and build list of variables. 22673 SmallVector<Expr *, 8> Vars; 22674 for (Expr *RefExpr : VarList) { 22675 assert(RefExpr && "NULL expr in OpenMP private clause."); 22676 SourceLocation ELoc; 22677 SourceRange ERange; 22678 Expr *SimpleRefExpr = RefExpr; 22679 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 22680 if (Res.second) { 22681 // It will be analyzed later. 22682 Vars.push_back(RefExpr); 22683 } 22684 ValueDecl *D = Res.first; 22685 if (!D) 22686 continue; 22687 22688 auto *VD = dyn_cast<VarDecl>(D); 22689 DeclRefExpr *Ref = nullptr; 22690 if (!VD && !CurContext->isDependentContext()) 22691 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 22692 Vars.push_back((VD || CurContext->isDependentContext()) 22693 ? RefExpr->IgnoreParens() 22694 : Ref); 22695 } 22696 22697 if (Vars.empty()) 22698 return nullptr; 22699 22700 if (Allocator) 22701 DSAStack->addInnerAllocatorExpr(Allocator); 22702 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator, 22703 ColonLoc, EndLoc, Vars); 22704 } 22705 22706 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, 22707 SourceLocation StartLoc, 22708 SourceLocation LParenLoc, 22709 SourceLocation EndLoc) { 22710 SmallVector<Expr *, 8> Vars; 22711 for (Expr *RefExpr : VarList) { 22712 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 22713 SourceLocation ELoc; 22714 SourceRange ERange; 22715 Expr *SimpleRefExpr = RefExpr; 22716 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 22717 if (Res.second) 22718 // It will be analyzed later. 22719 Vars.push_back(RefExpr); 22720 ValueDecl *D = Res.first; 22721 if (!D) 22722 continue; 22723 22724 // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions. 22725 // A list-item cannot appear in more than one nontemporal clause. 22726 if (const Expr *PrevRef = 22727 DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) { 22728 Diag(ELoc, diag::err_omp_used_in_clause_twice) 22729 << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange; 22730 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 22731 << getOpenMPClauseName(OMPC_nontemporal); 22732 continue; 22733 } 22734 22735 Vars.push_back(RefExpr); 22736 } 22737 22738 if (Vars.empty()) 22739 return nullptr; 22740 22741 return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc, 22742 Vars); 22743 } 22744 22745 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, 22746 SourceLocation StartLoc, 22747 SourceLocation LParenLoc, 22748 SourceLocation EndLoc) { 22749 SmallVector<Expr *, 8> Vars; 22750 for (Expr *RefExpr : VarList) { 22751 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 22752 SourceLocation ELoc; 22753 SourceRange ERange; 22754 Expr *SimpleRefExpr = RefExpr; 22755 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 22756 /*AllowArraySection=*/true); 22757 if (Res.second) 22758 // It will be analyzed later. 22759 Vars.push_back(RefExpr); 22760 ValueDecl *D = Res.first; 22761 if (!D) 22762 continue; 22763 22764 const DSAStackTy::DSAVarData DVar = 22765 DSAStack->getTopDSA(D, /*FromParent=*/true); 22766 // OpenMP 5.0, 2.9.6, scan Directive, Restrictions. 22767 // A list item that appears in the inclusive or exclusive clause must appear 22768 // in a reduction clause with the inscan modifier on the enclosing 22769 // worksharing-loop, worksharing-loop SIMD, or simd construct. 22770 if (DVar.CKind != OMPC_reduction || DVar.Modifier != OMPC_REDUCTION_inscan) 22771 Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction) 22772 << RefExpr->getSourceRange(); 22773 22774 if (DSAStack->getParentDirective() != OMPD_unknown) 22775 DSAStack->markDeclAsUsedInScanDirective(D); 22776 Vars.push_back(RefExpr); 22777 } 22778 22779 if (Vars.empty()) 22780 return nullptr; 22781 22782 return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 22783 } 22784 22785 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, 22786 SourceLocation StartLoc, 22787 SourceLocation LParenLoc, 22788 SourceLocation EndLoc) { 22789 SmallVector<Expr *, 8> Vars; 22790 for (Expr *RefExpr : VarList) { 22791 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 22792 SourceLocation ELoc; 22793 SourceRange ERange; 22794 Expr *SimpleRefExpr = RefExpr; 22795 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 22796 /*AllowArraySection=*/true); 22797 if (Res.second) 22798 // It will be analyzed later. 22799 Vars.push_back(RefExpr); 22800 ValueDecl *D = Res.first; 22801 if (!D) 22802 continue; 22803 22804 OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective(); 22805 DSAStackTy::DSAVarData DVar; 22806 if (ParentDirective != OMPD_unknown) 22807 DVar = DSAStack->getTopDSA(D, /*FromParent=*/true); 22808 // OpenMP 5.0, 2.9.6, scan Directive, Restrictions. 22809 // A list item that appears in the inclusive or exclusive clause must appear 22810 // in a reduction clause with the inscan modifier on the enclosing 22811 // worksharing-loop, worksharing-loop SIMD, or simd construct. 22812 if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction || 22813 DVar.Modifier != OMPC_REDUCTION_inscan) { 22814 Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction) 22815 << RefExpr->getSourceRange(); 22816 } else { 22817 DSAStack->markDeclAsUsedInScanDirective(D); 22818 } 22819 Vars.push_back(RefExpr); 22820 } 22821 22822 if (Vars.empty()) 22823 return nullptr; 22824 22825 return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 22826 } 22827 22828 /// Tries to find omp_alloctrait_t type. 22829 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) { 22830 QualType OMPAlloctraitT = Stack->getOMPAlloctraitT(); 22831 if (!OMPAlloctraitT.isNull()) 22832 return true; 22833 IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t"); 22834 ParsedType PT = S.getTypeName(II, Loc, S.getCurScope()); 22835 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 22836 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t"; 22837 return false; 22838 } 22839 Stack->setOMPAlloctraitT(PT.get()); 22840 return true; 22841 } 22842 22843 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause( 22844 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, 22845 ArrayRef<UsesAllocatorsData> Data) { 22846 // OpenMP [2.12.5, target Construct] 22847 // allocator is an identifier of omp_allocator_handle_t type. 22848 if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack)) 22849 return nullptr; 22850 // OpenMP [2.12.5, target Construct] 22851 // allocator-traits-array is an identifier of const omp_alloctrait_t * type. 22852 if (llvm::any_of( 22853 Data, 22854 [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) && 22855 !findOMPAlloctraitT(*this, StartLoc, DSAStack)) 22856 return nullptr; 22857 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators; 22858 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 22859 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 22860 StringRef Allocator = 22861 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind); 22862 DeclarationName AllocatorName = &Context.Idents.get(Allocator); 22863 PredefinedAllocators.insert(LookupSingleName( 22864 TUScope, AllocatorName, StartLoc, Sema::LookupAnyName)); 22865 } 22866 22867 SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData; 22868 for (const UsesAllocatorsData &D : Data) { 22869 Expr *AllocatorExpr = nullptr; 22870 // Check allocator expression. 22871 if (D.Allocator->isTypeDependent()) { 22872 AllocatorExpr = D.Allocator; 22873 } else { 22874 // Traits were specified - need to assign new allocator to the specified 22875 // allocator, so it must be an lvalue. 22876 AllocatorExpr = D.Allocator->IgnoreParenImpCasts(); 22877 auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr); 22878 bool IsPredefinedAllocator = false; 22879 if (DRE) 22880 IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl()); 22881 if (!DRE || 22882 !(Context.hasSameUnqualifiedType( 22883 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) || 22884 Context.typesAreCompatible(AllocatorExpr->getType(), 22885 DSAStack->getOMPAllocatorHandleT(), 22886 /*CompareUnqualified=*/true)) || 22887 (!IsPredefinedAllocator && 22888 (AllocatorExpr->getType().isConstant(Context) || 22889 !AllocatorExpr->isLValue()))) { 22890 Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected) 22891 << "omp_allocator_handle_t" << (DRE ? 1 : 0) 22892 << AllocatorExpr->getType() << D.Allocator->getSourceRange(); 22893 continue; 22894 } 22895 // OpenMP [2.12.5, target Construct] 22896 // Predefined allocators appearing in a uses_allocators clause cannot have 22897 // traits specified. 22898 if (IsPredefinedAllocator && D.AllocatorTraits) { 22899 Diag(D.AllocatorTraits->getExprLoc(), 22900 diag::err_omp_predefined_allocator_with_traits) 22901 << D.AllocatorTraits->getSourceRange(); 22902 Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator) 22903 << cast<NamedDecl>(DRE->getDecl())->getName() 22904 << D.Allocator->getSourceRange(); 22905 continue; 22906 } 22907 // OpenMP [2.12.5, target Construct] 22908 // Non-predefined allocators appearing in a uses_allocators clause must 22909 // have traits specified. 22910 if (!IsPredefinedAllocator && !D.AllocatorTraits) { 22911 Diag(D.Allocator->getExprLoc(), 22912 diag::err_omp_nonpredefined_allocator_without_traits); 22913 continue; 22914 } 22915 // No allocator traits - just convert it to rvalue. 22916 if (!D.AllocatorTraits) 22917 AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get(); 22918 DSAStack->addUsesAllocatorsDecl( 22919 DRE->getDecl(), 22920 IsPredefinedAllocator 22921 ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator 22922 : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator); 22923 } 22924 Expr *AllocatorTraitsExpr = nullptr; 22925 if (D.AllocatorTraits) { 22926 if (D.AllocatorTraits->isTypeDependent()) { 22927 AllocatorTraitsExpr = D.AllocatorTraits; 22928 } else { 22929 // OpenMP [2.12.5, target Construct] 22930 // Arrays that contain allocator traits that appear in a uses_allocators 22931 // clause must be constant arrays, have constant values and be defined 22932 // in the same scope as the construct in which the clause appears. 22933 AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts(); 22934 // Check that traits expr is a constant array. 22935 QualType TraitTy; 22936 if (const ArrayType *Ty = 22937 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe()) 22938 if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty)) 22939 TraitTy = ConstArrayTy->getElementType(); 22940 if (TraitTy.isNull() || 22941 !(Context.hasSameUnqualifiedType(TraitTy, 22942 DSAStack->getOMPAlloctraitT()) || 22943 Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(), 22944 /*CompareUnqualified=*/true))) { 22945 Diag(D.AllocatorTraits->getExprLoc(), 22946 diag::err_omp_expected_array_alloctraits) 22947 << AllocatorTraitsExpr->getType(); 22948 continue; 22949 } 22950 // Do not map by default allocator traits if it is a standalone 22951 // variable. 22952 if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr)) 22953 DSAStack->addUsesAllocatorsDecl( 22954 DRE->getDecl(), 22955 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait); 22956 } 22957 } 22958 OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back(); 22959 NewD.Allocator = AllocatorExpr; 22960 NewD.AllocatorTraits = AllocatorTraitsExpr; 22961 NewD.LParenLoc = D.LParenLoc; 22962 NewD.RParenLoc = D.RParenLoc; 22963 } 22964 return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc, 22965 NewData); 22966 } 22967 22968 OMPClause *Sema::ActOnOpenMPAffinityClause( 22969 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 22970 SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) { 22971 SmallVector<Expr *, 8> Vars; 22972 for (Expr *RefExpr : Locators) { 22973 assert(RefExpr && "NULL expr in OpenMP shared clause."); 22974 if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) { 22975 // It will be analyzed later. 22976 Vars.push_back(RefExpr); 22977 continue; 22978 } 22979 22980 SourceLocation ELoc = RefExpr->getExprLoc(); 22981 Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts(); 22982 22983 if (!SimpleExpr->isLValue()) { 22984 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 22985 << 1 << 0 << RefExpr->getSourceRange(); 22986 continue; 22987 } 22988 22989 ExprResult Res; 22990 { 22991 Sema::TentativeAnalysisScope Trap(*this); 22992 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr); 22993 } 22994 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) && 22995 !isa<OMPArrayShapingExpr>(SimpleExpr)) { 22996 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 22997 << 1 << 0 << RefExpr->getSourceRange(); 22998 continue; 22999 } 23000 Vars.push_back(SimpleExpr); 23001 } 23002 23003 return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 23004 EndLoc, Modifier, Vars); 23005 } 23006 23007 OMPClause *Sema::ActOnOpenMPBindClause(OpenMPBindClauseKind Kind, 23008 SourceLocation KindLoc, 23009 SourceLocation StartLoc, 23010 SourceLocation LParenLoc, 23011 SourceLocation EndLoc) { 23012 if (Kind == OMPC_BIND_unknown) { 23013 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 23014 << getListOfPossibleValues(OMPC_bind, /*First=*/0, 23015 /*Last=*/unsigned(OMPC_BIND_unknown)) 23016 << getOpenMPClauseName(OMPC_bind); 23017 return nullptr; 23018 } 23019 23020 return OMPBindClause::Create(Context, Kind, KindLoc, StartLoc, LParenLoc, 23021 EndLoc); 23022 } 23023