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/StringExtras.h" 39 #include "llvm/Frontend/OpenMP/OMPConstants.h" 40 #include <set> 41 42 using namespace clang; 43 using namespace llvm::omp; 44 45 //===----------------------------------------------------------------------===// 46 // Stack of data-sharing attributes for variables 47 //===----------------------------------------------------------------------===// 48 49 static const Expr *checkMapClauseExpressionBase( 50 Sema &SemaRef, Expr *E, 51 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 52 OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose); 53 54 namespace { 55 /// Default data sharing attributes, which can be applied to directive. 56 enum DefaultDataSharingAttributes { 57 DSA_unspecified = 0, /// Data sharing attribute not specified. 58 DSA_none = 1 << 0, /// Default data sharing attribute 'none'. 59 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'. 60 DSA_firstprivate = 1 << 2, /// Default data sharing attribute 'firstprivate'. 61 }; 62 63 /// Stack for tracking declarations used in OpenMP directives and 64 /// clauses and their data-sharing attributes. 65 class DSAStackTy { 66 public: 67 struct DSAVarData { 68 OpenMPDirectiveKind DKind = OMPD_unknown; 69 OpenMPClauseKind CKind = OMPC_unknown; 70 unsigned Modifier = 0; 71 const Expr *RefExpr = nullptr; 72 DeclRefExpr *PrivateCopy = nullptr; 73 SourceLocation ImplicitDSALoc; 74 bool AppliedToPointee = false; 75 DSAVarData() = default; 76 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 77 const Expr *RefExpr, DeclRefExpr *PrivateCopy, 78 SourceLocation ImplicitDSALoc, unsigned Modifier, 79 bool AppliedToPointee) 80 : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr), 81 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc), 82 AppliedToPointee(AppliedToPointee) {} 83 }; 84 using OperatorOffsetTy = 85 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>; 86 using DoacrossDependMapTy = 87 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>; 88 /// Kind of the declaration used in the uses_allocators clauses. 89 enum class UsesAllocatorsDeclKind { 90 /// Predefined allocator 91 PredefinedAllocator, 92 /// User-defined allocator 93 UserDefinedAllocator, 94 /// The declaration that represent allocator trait 95 AllocatorTrait, 96 }; 97 98 private: 99 struct DSAInfo { 100 OpenMPClauseKind Attributes = OMPC_unknown; 101 unsigned Modifier = 0; 102 /// Pointer to a reference expression and a flag which shows that the 103 /// variable is marked as lastprivate(true) or not (false). 104 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr; 105 DeclRefExpr *PrivateCopy = nullptr; 106 /// true if the attribute is applied to the pointee, not the variable 107 /// itself. 108 bool AppliedToPointee = false; 109 }; 110 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>; 111 using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>; 112 using LCDeclInfo = std::pair<unsigned, VarDecl *>; 113 using LoopControlVariablesMapTy = 114 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>; 115 /// Struct that associates a component with the clause kind where they are 116 /// found. 117 struct MappedExprComponentTy { 118 OMPClauseMappableExprCommon::MappableExprComponentLists Components; 119 OpenMPClauseKind Kind = OMPC_unknown; 120 }; 121 using MappedExprComponentsTy = 122 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>; 123 using CriticalsWithHintsTy = 124 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>; 125 struct ReductionData { 126 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>; 127 SourceRange ReductionRange; 128 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp; 129 ReductionData() = default; 130 void set(BinaryOperatorKind BO, SourceRange RR) { 131 ReductionRange = RR; 132 ReductionOp = BO; 133 } 134 void set(const Expr *RefExpr, SourceRange RR) { 135 ReductionRange = RR; 136 ReductionOp = RefExpr; 137 } 138 }; 139 using DeclReductionMapTy = 140 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>; 141 struct DefaultmapInfo { 142 OpenMPDefaultmapClauseModifier ImplicitBehavior = 143 OMPC_DEFAULTMAP_MODIFIER_unknown; 144 SourceLocation SLoc; 145 DefaultmapInfo() = default; 146 DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc) 147 : ImplicitBehavior(M), SLoc(Loc) {} 148 }; 149 150 struct SharingMapTy { 151 DeclSAMapTy SharingMap; 152 DeclReductionMapTy ReductionMap; 153 UsedRefMapTy AlignedMap; 154 UsedRefMapTy NontemporalMap; 155 MappedExprComponentsTy MappedExprComponents; 156 LoopControlVariablesMapTy LCVMap; 157 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 158 SourceLocation DefaultAttrLoc; 159 DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown]; 160 OpenMPDirectiveKind Directive = OMPD_unknown; 161 DeclarationNameInfo DirectiveName; 162 Scope *CurScope = nullptr; 163 DeclContext *Context = nullptr; 164 SourceLocation ConstructLoc; 165 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 166 /// get the data (loop counters etc.) about enclosing loop-based construct. 167 /// This data is required during codegen. 168 DoacrossDependMapTy DoacrossDepends; 169 /// First argument (Expr *) contains optional argument of the 170 /// 'ordered' clause, the second one is true if the regions has 'ordered' 171 /// clause, false otherwise. 172 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion; 173 unsigned AssociatedLoops = 1; 174 bool HasMutipleLoops = false; 175 const Decl *PossiblyLoopCounter = nullptr; 176 bool NowaitRegion = false; 177 bool CancelRegion = false; 178 bool LoopStart = false; 179 bool BodyComplete = false; 180 SourceLocation PrevScanLocation; 181 SourceLocation PrevOrderedLocation; 182 SourceLocation InnerTeamsRegionLoc; 183 /// Reference to the taskgroup task_reduction reference expression. 184 Expr *TaskgroupReductionRef = nullptr; 185 llvm::DenseSet<QualType> MappedClassesQualTypes; 186 SmallVector<Expr *, 4> InnerUsedAllocators; 187 llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates; 188 /// List of globals marked as declare target link in this target region 189 /// (isOpenMPTargetExecutionDirective(Directive) == true). 190 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls; 191 /// List of decls used in inclusive/exclusive clauses of the scan directive. 192 llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective; 193 llvm::DenseMap<CanonicalDeclPtr<const Decl>, UsesAllocatorsDeclKind> 194 UsesAllocatorsDecls; 195 Expr *DeclareMapperVar = nullptr; 196 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 197 Scope *CurScope, SourceLocation Loc) 198 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 199 ConstructLoc(Loc) {} 200 SharingMapTy() = default; 201 }; 202 203 using StackTy = SmallVector<SharingMapTy, 4>; 204 205 /// Stack of used declaration and their data-sharing attributes. 206 DeclSAMapTy Threadprivates; 207 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr; 208 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack; 209 /// true, if check for DSA must be from parent directive, false, if 210 /// from current directive. 211 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 212 Sema &SemaRef; 213 bool ForceCapturing = false; 214 /// true if all the variables in the target executable directives must be 215 /// captured by reference. 216 bool ForceCaptureByReferenceInTargetExecutable = false; 217 CriticalsWithHintsTy Criticals; 218 unsigned IgnoredStackElements = 0; 219 220 /// Iterators over the stack iterate in order from innermost to outermost 221 /// directive. 222 using const_iterator = StackTy::const_reverse_iterator; 223 const_iterator begin() const { 224 return Stack.empty() ? const_iterator() 225 : Stack.back().first.rbegin() + IgnoredStackElements; 226 } 227 const_iterator end() const { 228 return Stack.empty() ? const_iterator() : Stack.back().first.rend(); 229 } 230 using iterator = StackTy::reverse_iterator; 231 iterator begin() { 232 return Stack.empty() ? iterator() 233 : Stack.back().first.rbegin() + IgnoredStackElements; 234 } 235 iterator end() { 236 return Stack.empty() ? iterator() : Stack.back().first.rend(); 237 } 238 239 // Convenience operations to get at the elements of the stack. 240 241 bool isStackEmpty() const { 242 return Stack.empty() || 243 Stack.back().second != CurrentNonCapturingFunctionScope || 244 Stack.back().first.size() <= IgnoredStackElements; 245 } 246 size_t getStackSize() const { 247 return isStackEmpty() ? 0 248 : Stack.back().first.size() - IgnoredStackElements; 249 } 250 251 SharingMapTy *getTopOfStackOrNull() { 252 size_t Size = getStackSize(); 253 if (Size == 0) 254 return nullptr; 255 return &Stack.back().first[Size - 1]; 256 } 257 const SharingMapTy *getTopOfStackOrNull() const { 258 return const_cast<DSAStackTy &>(*this).getTopOfStackOrNull(); 259 } 260 SharingMapTy &getTopOfStack() { 261 assert(!isStackEmpty() && "no current directive"); 262 return *getTopOfStackOrNull(); 263 } 264 const SharingMapTy &getTopOfStack() const { 265 return const_cast<DSAStackTy &>(*this).getTopOfStack(); 266 } 267 268 SharingMapTy *getSecondOnStackOrNull() { 269 size_t Size = getStackSize(); 270 if (Size <= 1) 271 return nullptr; 272 return &Stack.back().first[Size - 2]; 273 } 274 const SharingMapTy *getSecondOnStackOrNull() const { 275 return const_cast<DSAStackTy &>(*this).getSecondOnStackOrNull(); 276 } 277 278 /// Get the stack element at a certain level (previously returned by 279 /// \c getNestingLevel). 280 /// 281 /// Note that nesting levels count from outermost to innermost, and this is 282 /// the reverse of our iteration order where new inner levels are pushed at 283 /// the front of the stack. 284 SharingMapTy &getStackElemAtLevel(unsigned Level) { 285 assert(Level < getStackSize() && "no such stack element"); 286 return Stack.back().first[Level]; 287 } 288 const SharingMapTy &getStackElemAtLevel(unsigned Level) const { 289 return const_cast<DSAStackTy &>(*this).getStackElemAtLevel(Level); 290 } 291 292 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const; 293 294 /// Checks if the variable is a local for OpenMP region. 295 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const; 296 297 /// Vector of previously declared requires directives 298 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls; 299 /// omp_allocator_handle_t type. 300 QualType OMPAllocatorHandleT; 301 /// omp_depend_t type. 302 QualType OMPDependT; 303 /// omp_event_handle_t type. 304 QualType OMPEventHandleT; 305 /// omp_alloctrait_t type. 306 QualType OMPAlloctraitT; 307 /// Expression for the predefined allocators. 308 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = { 309 nullptr}; 310 /// Vector of previously encountered target directives 311 SmallVector<SourceLocation, 2> TargetLocations; 312 SourceLocation AtomicLocation; 313 /// Vector of declare variant construct traits. 314 SmallVector<llvm::omp::TraitProperty, 8> ConstructTraits; 315 316 public: 317 explicit DSAStackTy(Sema &S) : SemaRef(S) {} 318 319 /// Sets omp_allocator_handle_t type. 320 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; } 321 /// Gets omp_allocator_handle_t type. 322 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; } 323 /// Sets omp_alloctrait_t type. 324 void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; } 325 /// Gets omp_alloctrait_t type. 326 QualType getOMPAlloctraitT() const { return OMPAlloctraitT; } 327 /// Sets the given default allocator. 328 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, 329 Expr *Allocator) { 330 OMPPredefinedAllocators[AllocatorKind] = Allocator; 331 } 332 /// Returns the specified default allocator. 333 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const { 334 return OMPPredefinedAllocators[AllocatorKind]; 335 } 336 /// Sets omp_depend_t type. 337 void setOMPDependT(QualType Ty) { OMPDependT = Ty; } 338 /// Gets omp_depend_t type. 339 QualType getOMPDependT() const { return OMPDependT; } 340 341 /// Sets omp_event_handle_t type. 342 void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; } 343 /// Gets omp_event_handle_t type. 344 QualType getOMPEventHandleT() const { return OMPEventHandleT; } 345 346 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 347 OpenMPClauseKind getClauseParsingMode() const { 348 assert(isClauseParsingMode() && "Must be in clause parsing mode."); 349 return ClauseKindMode; 350 } 351 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 352 353 bool isBodyComplete() const { 354 const SharingMapTy *Top = getTopOfStackOrNull(); 355 return Top && Top->BodyComplete; 356 } 357 void setBodyComplete() { getTopOfStack().BodyComplete = true; } 358 359 bool isForceVarCapturing() const { return ForceCapturing; } 360 void setForceVarCapturing(bool V) { ForceCapturing = V; } 361 362 void setForceCaptureByReferenceInTargetExecutable(bool V) { 363 ForceCaptureByReferenceInTargetExecutable = V; 364 } 365 bool isForceCaptureByReferenceInTargetExecutable() const { 366 return ForceCaptureByReferenceInTargetExecutable; 367 } 368 369 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 370 Scope *CurScope, SourceLocation Loc) { 371 assert(!IgnoredStackElements && 372 "cannot change stack while ignoring elements"); 373 if (Stack.empty() || 374 Stack.back().second != CurrentNonCapturingFunctionScope) 375 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope); 376 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc); 377 Stack.back().first.back().DefaultAttrLoc = Loc; 378 } 379 380 void pop() { 381 assert(!IgnoredStackElements && 382 "cannot change stack while ignoring elements"); 383 assert(!Stack.back().first.empty() && 384 "Data-sharing attributes stack is empty!"); 385 Stack.back().first.pop_back(); 386 } 387 388 /// RAII object to temporarily leave the scope of a directive when we want to 389 /// logically operate in its parent. 390 class ParentDirectiveScope { 391 DSAStackTy &Self; 392 bool Active; 393 394 public: 395 ParentDirectiveScope(DSAStackTy &Self, bool Activate) 396 : Self(Self), Active(false) { 397 if (Activate) 398 enable(); 399 } 400 ~ParentDirectiveScope() { disable(); } 401 void disable() { 402 if (Active) { 403 --Self.IgnoredStackElements; 404 Active = false; 405 } 406 } 407 void enable() { 408 if (!Active) { 409 ++Self.IgnoredStackElements; 410 Active = true; 411 } 412 } 413 }; 414 415 /// Marks that we're started loop parsing. 416 void loopInit() { 417 assert(isOpenMPLoopDirective(getCurrentDirective()) && 418 "Expected loop-based directive."); 419 getTopOfStack().LoopStart = true; 420 } 421 /// Start capturing of the variables in the loop context. 422 void loopStart() { 423 assert(isOpenMPLoopDirective(getCurrentDirective()) && 424 "Expected loop-based directive."); 425 getTopOfStack().LoopStart = false; 426 } 427 /// true, if variables are captured, false otherwise. 428 bool isLoopStarted() const { 429 assert(isOpenMPLoopDirective(getCurrentDirective()) && 430 "Expected loop-based directive."); 431 return !getTopOfStack().LoopStart; 432 } 433 /// Marks (or clears) declaration as possibly loop counter. 434 void resetPossibleLoopCounter(const Decl *D = nullptr) { 435 getTopOfStack().PossiblyLoopCounter = D ? D->getCanonicalDecl() : D; 436 } 437 /// Gets the possible loop counter decl. 438 const Decl *getPossiblyLoopCunter() const { 439 return getTopOfStack().PossiblyLoopCounter; 440 } 441 /// Start new OpenMP region stack in new non-capturing function. 442 void pushFunction() { 443 assert(!IgnoredStackElements && 444 "cannot change stack while ignoring elements"); 445 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction(); 446 assert(!isa<CapturingScopeInfo>(CurFnScope)); 447 CurrentNonCapturingFunctionScope = CurFnScope; 448 } 449 /// Pop region stack for non-capturing function. 450 void popFunction(const FunctionScopeInfo *OldFSI) { 451 assert(!IgnoredStackElements && 452 "cannot change stack while ignoring elements"); 453 if (!Stack.empty() && Stack.back().second == OldFSI) { 454 assert(Stack.back().first.empty()); 455 Stack.pop_back(); 456 } 457 CurrentNonCapturingFunctionScope = nullptr; 458 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) { 459 if (!isa<CapturingScopeInfo>(FSI)) { 460 CurrentNonCapturingFunctionScope = FSI; 461 break; 462 } 463 } 464 } 465 466 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) { 467 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint); 468 } 469 const std::pair<const OMPCriticalDirective *, llvm::APSInt> 470 getCriticalWithHint(const DeclarationNameInfo &Name) const { 471 auto I = Criticals.find(Name.getAsString()); 472 if (I != Criticals.end()) 473 return I->second; 474 return std::make_pair(nullptr, llvm::APSInt()); 475 } 476 /// If 'aligned' declaration for given variable \a D was not seen yet, 477 /// add it and return NULL; otherwise return previous occurrence's expression 478 /// for diagnostics. 479 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE); 480 /// If 'nontemporal' 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 *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE); 484 485 /// Register specified variable as loop control variable. 486 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture); 487 /// Check if the specified variable is a loop control variable for 488 /// current region. 489 /// \return The index of the loop control variable in the list of associated 490 /// for-loops (from outer to inner). 491 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const; 492 /// Check if the specified variable is a loop control variable for 493 /// parent region. 494 /// \return The index of the loop control variable in the list of associated 495 /// for-loops (from outer to inner). 496 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const; 497 /// Check if the specified variable is a loop control variable for 498 /// current region. 499 /// \return The index of the loop control variable in the list of associated 500 /// for-loops (from outer to inner). 501 const LCDeclInfo isLoopControlVariable(const ValueDecl *D, 502 unsigned Level) const; 503 /// Get the loop control variable for the I-th loop (or nullptr) in 504 /// parent directive. 505 const ValueDecl *getParentLoopControlVariable(unsigned I) const; 506 507 /// Marks the specified decl \p D as used in scan directive. 508 void markDeclAsUsedInScanDirective(ValueDecl *D) { 509 if (SharingMapTy *Stack = getSecondOnStackOrNull()) 510 Stack->UsedInScanDirective.insert(D); 511 } 512 513 /// Checks if the specified declaration was used in the inner scan directive. 514 bool isUsedInScanDirective(ValueDecl *D) const { 515 if (const SharingMapTy *Stack = getTopOfStackOrNull()) 516 return Stack->UsedInScanDirective.contains(D); 517 return false; 518 } 519 520 /// Adds explicit data sharing attribute to the specified declaration. 521 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 522 DeclRefExpr *PrivateCopy = nullptr, unsigned Modifier = 0, 523 bool AppliedToPointee = false); 524 525 /// Adds additional information for the reduction items with the reduction id 526 /// represented as an operator. 527 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 528 BinaryOperatorKind BOK); 529 /// Adds additional information for the reduction items with the reduction id 530 /// represented as reduction identifier. 531 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 532 const Expr *ReductionRef); 533 /// Returns the location and reduction operation from the innermost parent 534 /// region for the given \p D. 535 const DSAVarData 536 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 537 BinaryOperatorKind &BOK, 538 Expr *&TaskgroupDescriptor) const; 539 /// Returns the location and reduction operation from the innermost parent 540 /// region for the given \p D. 541 const DSAVarData 542 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 543 const Expr *&ReductionRef, 544 Expr *&TaskgroupDescriptor) const; 545 /// Return reduction reference expression for the current taskgroup or 546 /// parallel/worksharing directives with task reductions. 547 Expr *getTaskgroupReductionRef() const { 548 assert((getTopOfStack().Directive == OMPD_taskgroup || 549 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 550 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 551 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 552 "taskgroup reference expression requested for non taskgroup or " 553 "parallel/worksharing directive."); 554 return getTopOfStack().TaskgroupReductionRef; 555 } 556 /// Checks if the given \p VD declaration is actually a taskgroup reduction 557 /// descriptor variable at the \p Level of OpenMP regions. 558 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const { 559 return getStackElemAtLevel(Level).TaskgroupReductionRef && 560 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef) 561 ->getDecl() == VD; 562 } 563 564 /// Returns data sharing attributes from top of the stack for the 565 /// specified declaration. 566 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 567 /// Returns data-sharing attributes for the specified declaration. 568 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const; 569 /// Returns data-sharing attributes for the specified declaration. 570 const DSAVarData getImplicitDSA(ValueDecl *D, unsigned Level) const; 571 /// Checks if the specified variables has data-sharing attributes which 572 /// match specified \a CPred predicate in any directive which matches \a DPred 573 /// predicate. 574 const DSAVarData 575 hasDSA(ValueDecl *D, 576 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 577 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 578 bool FromParent) const; 579 /// Checks if the specified variables has data-sharing attributes which 580 /// match specified \a CPred predicate in any innermost directive which 581 /// matches \a DPred predicate. 582 const DSAVarData 583 hasInnermostDSA(ValueDecl *D, 584 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 585 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 586 bool FromParent) const; 587 /// Checks if the specified variables has explicit data-sharing 588 /// attributes which match specified \a CPred predicate at the specified 589 /// OpenMP region. 590 bool 591 hasExplicitDSA(const ValueDecl *D, 592 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 593 unsigned Level, bool NotLastprivate = false) const; 594 595 /// Returns true if the directive at level \Level matches in the 596 /// specified \a DPred predicate. 597 bool hasExplicitDirective( 598 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 599 unsigned Level) const; 600 601 /// Finds a directive which matches specified \a DPred predicate. 602 bool hasDirective( 603 const llvm::function_ref<bool( 604 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)> 605 DPred, 606 bool FromParent) const; 607 608 /// Returns currently analyzed directive. 609 OpenMPDirectiveKind getCurrentDirective() const { 610 const SharingMapTy *Top = getTopOfStackOrNull(); 611 return Top ? Top->Directive : OMPD_unknown; 612 } 613 /// Returns directive kind at specified level. 614 OpenMPDirectiveKind getDirective(unsigned Level) const { 615 assert(!isStackEmpty() && "No directive at specified level."); 616 return getStackElemAtLevel(Level).Directive; 617 } 618 /// Returns the capture region at the specified level. 619 OpenMPDirectiveKind getCaptureRegion(unsigned Level, 620 unsigned OpenMPCaptureLevel) const { 621 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 622 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level)); 623 return CaptureRegions[OpenMPCaptureLevel]; 624 } 625 /// Returns parent directive. 626 OpenMPDirectiveKind getParentDirective() const { 627 const SharingMapTy *Parent = getSecondOnStackOrNull(); 628 return Parent ? Parent->Directive : OMPD_unknown; 629 } 630 631 /// Add requires decl to internal vector 632 void addRequiresDecl(OMPRequiresDecl *RD) { RequiresDecls.push_back(RD); } 633 634 /// Checks if the defined 'requires' directive has specified type of clause. 635 template <typename ClauseType> bool hasRequiresDeclWithClause() const { 636 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) { 637 return llvm::any_of(D->clauselists(), [](const OMPClause *C) { 638 return isa<ClauseType>(C); 639 }); 640 }); 641 } 642 643 /// Checks for a duplicate clause amongst previously declared requires 644 /// directives 645 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const { 646 bool IsDuplicate = false; 647 for (OMPClause *CNew : ClauseList) { 648 for (const OMPRequiresDecl *D : RequiresDecls) { 649 for (const OMPClause *CPrev : D->clauselists()) { 650 if (CNew->getClauseKind() == CPrev->getClauseKind()) { 651 SemaRef.Diag(CNew->getBeginLoc(), 652 diag::err_omp_requires_clause_redeclaration) 653 << getOpenMPClauseName(CNew->getClauseKind()); 654 SemaRef.Diag(CPrev->getBeginLoc(), 655 diag::note_omp_requires_previous_clause) 656 << getOpenMPClauseName(CPrev->getClauseKind()); 657 IsDuplicate = true; 658 } 659 } 660 } 661 } 662 return IsDuplicate; 663 } 664 665 /// Add location of previously encountered target to internal vector 666 void addTargetDirLocation(SourceLocation LocStart) { 667 TargetLocations.push_back(LocStart); 668 } 669 670 /// Add location for the first encountered atomicc directive. 671 void addAtomicDirectiveLoc(SourceLocation Loc) { 672 if (AtomicLocation.isInvalid()) 673 AtomicLocation = Loc; 674 } 675 676 /// Returns the location of the first encountered atomic directive in the 677 /// module. 678 SourceLocation getAtomicDirectiveLoc() const { return AtomicLocation; } 679 680 // Return previously encountered target region locations. 681 ArrayRef<SourceLocation> getEncounteredTargetLocs() const { 682 return TargetLocations; 683 } 684 685 /// Set default data sharing attribute to none. 686 void setDefaultDSANone(SourceLocation Loc) { 687 getTopOfStack().DefaultAttr = DSA_none; 688 getTopOfStack().DefaultAttrLoc = Loc; 689 } 690 /// Set default data sharing attribute to shared. 691 void setDefaultDSAShared(SourceLocation Loc) { 692 getTopOfStack().DefaultAttr = DSA_shared; 693 getTopOfStack().DefaultAttrLoc = Loc; 694 } 695 /// Set default data sharing attribute to firstprivate. 696 void setDefaultDSAFirstPrivate(SourceLocation Loc) { 697 getTopOfStack().DefaultAttr = DSA_firstprivate; 698 getTopOfStack().DefaultAttrLoc = Loc; 699 } 700 /// Set default data mapping attribute to Modifier:Kind 701 void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M, 702 OpenMPDefaultmapClauseKind Kind, SourceLocation Loc) { 703 DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind]; 704 DMI.ImplicitBehavior = M; 705 DMI.SLoc = Loc; 706 } 707 /// Check whether the implicit-behavior has been set in defaultmap 708 bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) { 709 if (VariableCategory == OMPC_DEFAULTMAP_unknown) 710 return getTopOfStack() 711 .DefaultmapMap[OMPC_DEFAULTMAP_aggregate] 712 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown || 713 getTopOfStack() 714 .DefaultmapMap[OMPC_DEFAULTMAP_scalar] 715 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown || 716 getTopOfStack() 717 .DefaultmapMap[OMPC_DEFAULTMAP_pointer] 718 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown; 719 return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior != 720 OMPC_DEFAULTMAP_MODIFIER_unknown; 721 } 722 723 ArrayRef<llvm::omp::TraitProperty> getConstructTraits() { 724 return ConstructTraits; 725 } 726 void handleConstructTrait(ArrayRef<llvm::omp::TraitProperty> Traits, 727 bool ScopeEntry) { 728 if (ScopeEntry) 729 ConstructTraits.append(Traits.begin(), Traits.end()); 730 else 731 for (llvm::omp::TraitProperty Trait : llvm::reverse(Traits)) { 732 llvm::omp::TraitProperty Top = ConstructTraits.pop_back_val(); 733 assert(Top == Trait && "Something left a trait on the stack!"); 734 (void)Trait; 735 (void)Top; 736 } 737 } 738 739 DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const { 740 return getStackSize() <= Level ? DSA_unspecified 741 : getStackElemAtLevel(Level).DefaultAttr; 742 } 743 DefaultDataSharingAttributes getDefaultDSA() const { 744 return isStackEmpty() ? DSA_unspecified : getTopOfStack().DefaultAttr; 745 } 746 SourceLocation getDefaultDSALocation() const { 747 return isStackEmpty() ? SourceLocation() : getTopOfStack().DefaultAttrLoc; 748 } 749 OpenMPDefaultmapClauseModifier 750 getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const { 751 return isStackEmpty() 752 ? OMPC_DEFAULTMAP_MODIFIER_unknown 753 : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior; 754 } 755 OpenMPDefaultmapClauseModifier 756 getDefaultmapModifierAtLevel(unsigned Level, 757 OpenMPDefaultmapClauseKind Kind) const { 758 return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior; 759 } 760 bool isDefaultmapCapturedByRef(unsigned Level, 761 OpenMPDefaultmapClauseKind Kind) const { 762 OpenMPDefaultmapClauseModifier M = 763 getDefaultmapModifierAtLevel(Level, Kind); 764 if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) { 765 return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) || 766 (M == OMPC_DEFAULTMAP_MODIFIER_to) || 767 (M == OMPC_DEFAULTMAP_MODIFIER_from) || 768 (M == OMPC_DEFAULTMAP_MODIFIER_tofrom); 769 } 770 return true; 771 } 772 static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M, 773 OpenMPDefaultmapClauseKind Kind) { 774 switch (Kind) { 775 case OMPC_DEFAULTMAP_scalar: 776 case OMPC_DEFAULTMAP_pointer: 777 return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) || 778 (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) || 779 (M == OMPC_DEFAULTMAP_MODIFIER_default); 780 case OMPC_DEFAULTMAP_aggregate: 781 return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate; 782 default: 783 break; 784 } 785 llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum"); 786 } 787 bool mustBeFirstprivateAtLevel(unsigned Level, 788 OpenMPDefaultmapClauseKind Kind) const { 789 OpenMPDefaultmapClauseModifier M = 790 getDefaultmapModifierAtLevel(Level, Kind); 791 return mustBeFirstprivateBase(M, Kind); 792 } 793 bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const { 794 OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind); 795 return mustBeFirstprivateBase(M, Kind); 796 } 797 798 /// Checks if the specified variable is a threadprivate. 799 bool isThreadPrivate(VarDecl *D) { 800 const DSAVarData DVar = getTopDSA(D, false); 801 return isOpenMPThreadPrivate(DVar.CKind); 802 } 803 804 /// Marks current region as ordered (it has an 'ordered' clause). 805 void setOrderedRegion(bool IsOrdered, const Expr *Param, 806 OMPOrderedClause *Clause) { 807 if (IsOrdered) 808 getTopOfStack().OrderedRegion.emplace(Param, Clause); 809 else 810 getTopOfStack().OrderedRegion.reset(); 811 } 812 /// Returns true, if region is ordered (has associated 'ordered' clause), 813 /// false - otherwise. 814 bool isOrderedRegion() const { 815 if (const SharingMapTy *Top = getTopOfStackOrNull()) 816 return Top->OrderedRegion.hasValue(); 817 return false; 818 } 819 /// Returns optional parameter for the ordered region. 820 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const { 821 if (const SharingMapTy *Top = getTopOfStackOrNull()) 822 if (Top->OrderedRegion.hasValue()) 823 return Top->OrderedRegion.getValue(); 824 return std::make_pair(nullptr, nullptr); 825 } 826 /// Returns true, if parent region is ordered (has associated 827 /// 'ordered' clause), false - otherwise. 828 bool isParentOrderedRegion() const { 829 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 830 return Parent->OrderedRegion.hasValue(); 831 return false; 832 } 833 /// Returns optional parameter for the ordered region. 834 std::pair<const Expr *, OMPOrderedClause *> 835 getParentOrderedRegionParam() const { 836 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 837 if (Parent->OrderedRegion.hasValue()) 838 return Parent->OrderedRegion.getValue(); 839 return std::make_pair(nullptr, nullptr); 840 } 841 /// Marks current region as nowait (it has a 'nowait' clause). 842 void setNowaitRegion(bool IsNowait = true) { 843 getTopOfStack().NowaitRegion = IsNowait; 844 } 845 /// Returns true, if parent region is nowait (has associated 846 /// 'nowait' clause), false - otherwise. 847 bool isParentNowaitRegion() const { 848 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 849 return Parent->NowaitRegion; 850 return false; 851 } 852 /// Marks parent region as cancel region. 853 void setParentCancelRegion(bool Cancel = true) { 854 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 855 Parent->CancelRegion |= Cancel; 856 } 857 /// Return true if current region has inner cancel construct. 858 bool isCancelRegion() const { 859 const SharingMapTy *Top = getTopOfStackOrNull(); 860 return Top ? Top->CancelRegion : false; 861 } 862 863 /// Mark that parent region already has scan directive. 864 void setParentHasScanDirective(SourceLocation Loc) { 865 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 866 Parent->PrevScanLocation = Loc; 867 } 868 /// Return true if current region has inner cancel construct. 869 bool doesParentHasScanDirective() const { 870 const SharingMapTy *Top = getSecondOnStackOrNull(); 871 return Top ? Top->PrevScanLocation.isValid() : false; 872 } 873 /// Return true if current region has inner cancel construct. 874 SourceLocation getParentScanDirectiveLoc() const { 875 const SharingMapTy *Top = getSecondOnStackOrNull(); 876 return Top ? Top->PrevScanLocation : SourceLocation(); 877 } 878 /// Mark that parent region already has ordered directive. 879 void setParentHasOrderedDirective(SourceLocation Loc) { 880 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 881 Parent->PrevOrderedLocation = Loc; 882 } 883 /// Return true if current region has inner ordered construct. 884 bool doesParentHasOrderedDirective() const { 885 const SharingMapTy *Top = getSecondOnStackOrNull(); 886 return Top ? Top->PrevOrderedLocation.isValid() : false; 887 } 888 /// Returns the location of the previously specified ordered directive. 889 SourceLocation getParentOrderedDirectiveLoc() const { 890 const SharingMapTy *Top = getSecondOnStackOrNull(); 891 return Top ? Top->PrevOrderedLocation : SourceLocation(); 892 } 893 894 /// Set collapse value for the region. 895 void setAssociatedLoops(unsigned Val) { 896 getTopOfStack().AssociatedLoops = Val; 897 if (Val > 1) 898 getTopOfStack().HasMutipleLoops = true; 899 } 900 /// Return collapse value for region. 901 unsigned getAssociatedLoops() const { 902 const SharingMapTy *Top = getTopOfStackOrNull(); 903 return Top ? Top->AssociatedLoops : 0; 904 } 905 /// Returns true if the construct is associated with multiple loops. 906 bool hasMutipleLoops() const { 907 const SharingMapTy *Top = getTopOfStackOrNull(); 908 return Top ? Top->HasMutipleLoops : false; 909 } 910 911 /// Marks current target region as one with closely nested teams 912 /// region. 913 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 914 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 915 Parent->InnerTeamsRegionLoc = TeamsRegionLoc; 916 } 917 /// Returns true, if current region has closely nested teams region. 918 bool hasInnerTeamsRegion() const { 919 return getInnerTeamsRegionLoc().isValid(); 920 } 921 /// Returns location of the nested teams region (if any). 922 SourceLocation getInnerTeamsRegionLoc() const { 923 const SharingMapTy *Top = getTopOfStackOrNull(); 924 return Top ? Top->InnerTeamsRegionLoc : SourceLocation(); 925 } 926 927 Scope *getCurScope() const { 928 const SharingMapTy *Top = getTopOfStackOrNull(); 929 return Top ? Top->CurScope : nullptr; 930 } 931 void setContext(DeclContext *DC) { getTopOfStack().Context = DC; } 932 SourceLocation getConstructLoc() const { 933 const SharingMapTy *Top = getTopOfStackOrNull(); 934 return Top ? Top->ConstructLoc : SourceLocation(); 935 } 936 937 /// Do the check specified in \a Check to all component lists and return true 938 /// if any issue is found. 939 bool checkMappableExprComponentListsForDecl( 940 const ValueDecl *VD, bool CurrentRegionOnly, 941 const llvm::function_ref< 942 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 943 OpenMPClauseKind)> 944 Check) const { 945 if (isStackEmpty()) 946 return false; 947 auto SI = begin(); 948 auto SE = end(); 949 950 if (SI == SE) 951 return false; 952 953 if (CurrentRegionOnly) 954 SE = std::next(SI); 955 else 956 std::advance(SI, 1); 957 958 for (; SI != SE; ++SI) { 959 auto MI = SI->MappedExprComponents.find(VD); 960 if (MI != SI->MappedExprComponents.end()) 961 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 962 MI->second.Components) 963 if (Check(L, MI->second.Kind)) 964 return true; 965 } 966 return false; 967 } 968 969 /// Do the check specified in \a Check to all component lists at a given level 970 /// and return true if any issue is found. 971 bool checkMappableExprComponentListsForDeclAtLevel( 972 const ValueDecl *VD, unsigned Level, 973 const llvm::function_ref< 974 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 975 OpenMPClauseKind)> 976 Check) const { 977 if (getStackSize() <= Level) 978 return false; 979 980 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 981 auto MI = StackElem.MappedExprComponents.find(VD); 982 if (MI != StackElem.MappedExprComponents.end()) 983 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 984 MI->second.Components) 985 if (Check(L, MI->second.Kind)) 986 return true; 987 return false; 988 } 989 990 /// Create a new mappable expression component list associated with a given 991 /// declaration and initialize it with the provided list of components. 992 void addMappableExpressionComponents( 993 const ValueDecl *VD, 994 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 995 OpenMPClauseKind WhereFoundClauseKind) { 996 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD]; 997 // Create new entry and append the new components there. 998 MEC.Components.resize(MEC.Components.size() + 1); 999 MEC.Components.back().append(Components.begin(), Components.end()); 1000 MEC.Kind = WhereFoundClauseKind; 1001 } 1002 1003 unsigned getNestingLevel() const { 1004 assert(!isStackEmpty()); 1005 return getStackSize() - 1; 1006 } 1007 void addDoacrossDependClause(OMPDependClause *C, 1008 const OperatorOffsetTy &OpsOffs) { 1009 SharingMapTy *Parent = getSecondOnStackOrNull(); 1010 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive)); 1011 Parent->DoacrossDepends.try_emplace(C, OpsOffs); 1012 } 1013 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 1014 getDoacrossDependClauses() const { 1015 const SharingMapTy &StackElem = getTopOfStack(); 1016 if (isOpenMPWorksharingDirective(StackElem.Directive)) { 1017 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends; 1018 return llvm::make_range(Ref.begin(), Ref.end()); 1019 } 1020 return llvm::make_range(StackElem.DoacrossDepends.end(), 1021 StackElem.DoacrossDepends.end()); 1022 } 1023 1024 // Store types of classes which have been explicitly mapped 1025 void addMappedClassesQualTypes(QualType QT) { 1026 SharingMapTy &StackElem = getTopOfStack(); 1027 StackElem.MappedClassesQualTypes.insert(QT); 1028 } 1029 1030 // Return set of mapped classes types 1031 bool isClassPreviouslyMapped(QualType QT) const { 1032 const SharingMapTy &StackElem = getTopOfStack(); 1033 return StackElem.MappedClassesQualTypes.contains(QT); 1034 } 1035 1036 /// Adds global declare target to the parent target region. 1037 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) { 1038 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 1039 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && 1040 "Expected declare target link global."); 1041 for (auto &Elem : *this) { 1042 if (isOpenMPTargetExecutionDirective(Elem.Directive)) { 1043 Elem.DeclareTargetLinkVarDecls.push_back(E); 1044 return; 1045 } 1046 } 1047 } 1048 1049 /// Returns the list of globals with declare target link if current directive 1050 /// is target. 1051 ArrayRef<DeclRefExpr *> getLinkGlobals() const { 1052 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) && 1053 "Expected target executable directive."); 1054 return getTopOfStack().DeclareTargetLinkVarDecls; 1055 } 1056 1057 /// Adds list of allocators expressions. 1058 void addInnerAllocatorExpr(Expr *E) { 1059 getTopOfStack().InnerUsedAllocators.push_back(E); 1060 } 1061 /// Return list of used allocators. 1062 ArrayRef<Expr *> getInnerAllocators() const { 1063 return getTopOfStack().InnerUsedAllocators; 1064 } 1065 /// Marks the declaration as implicitly firstprivate nin the task-based 1066 /// regions. 1067 void addImplicitTaskFirstprivate(unsigned Level, Decl *D) { 1068 getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D); 1069 } 1070 /// Checks if the decl is implicitly firstprivate in the task-based region. 1071 bool isImplicitTaskFirstprivate(Decl *D) const { 1072 return getTopOfStack().ImplicitTaskFirstprivates.contains(D); 1073 } 1074 1075 /// Marks decl as used in uses_allocators clause as the allocator. 1076 void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) { 1077 getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind); 1078 } 1079 /// Checks if specified decl is used in uses allocator clause as the 1080 /// allocator. 1081 Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level, 1082 const Decl *D) const { 1083 const SharingMapTy &StackElem = getTopOfStack(); 1084 auto I = StackElem.UsesAllocatorsDecls.find(D); 1085 if (I == StackElem.UsesAllocatorsDecls.end()) 1086 return None; 1087 return I->getSecond(); 1088 } 1089 Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const { 1090 const SharingMapTy &StackElem = getTopOfStack(); 1091 auto I = StackElem.UsesAllocatorsDecls.find(D); 1092 if (I == StackElem.UsesAllocatorsDecls.end()) 1093 return None; 1094 return I->getSecond(); 1095 } 1096 1097 void addDeclareMapperVarRef(Expr *Ref) { 1098 SharingMapTy &StackElem = getTopOfStack(); 1099 StackElem.DeclareMapperVar = Ref; 1100 } 1101 const Expr *getDeclareMapperVarRef() const { 1102 const SharingMapTy *Top = getTopOfStackOrNull(); 1103 return Top ? Top->DeclareMapperVar : nullptr; 1104 } 1105 }; 1106 1107 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) { 1108 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind); 1109 } 1110 1111 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) { 1112 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || 1113 DKind == OMPD_unknown; 1114 } 1115 1116 } // namespace 1117 1118 static const Expr *getExprAsWritten(const Expr *E) { 1119 if (const auto *FE = dyn_cast<FullExpr>(E)) 1120 E = FE->getSubExpr(); 1121 1122 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 1123 E = MTE->getSubExpr(); 1124 1125 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 1126 E = Binder->getSubExpr(); 1127 1128 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 1129 E = ICE->getSubExprAsWritten(); 1130 return E->IgnoreParens(); 1131 } 1132 1133 static Expr *getExprAsWritten(Expr *E) { 1134 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E))); 1135 } 1136 1137 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) { 1138 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) 1139 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 1140 D = ME->getMemberDecl(); 1141 const auto *VD = dyn_cast<VarDecl>(D); 1142 const auto *FD = dyn_cast<FieldDecl>(D); 1143 if (VD != nullptr) { 1144 VD = VD->getCanonicalDecl(); 1145 D = VD; 1146 } else { 1147 assert(FD); 1148 FD = FD->getCanonicalDecl(); 1149 D = FD; 1150 } 1151 return D; 1152 } 1153 1154 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 1155 return const_cast<ValueDecl *>( 1156 getCanonicalDecl(const_cast<const ValueDecl *>(D))); 1157 } 1158 1159 DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter, 1160 ValueDecl *D) const { 1161 D = getCanonicalDecl(D); 1162 auto *VD = dyn_cast<VarDecl>(D); 1163 const auto *FD = dyn_cast<FieldDecl>(D); 1164 DSAVarData DVar; 1165 if (Iter == end()) { 1166 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1167 // in a region but not in construct] 1168 // File-scope or namespace-scope variables referenced in called routines 1169 // in the region are shared unless they appear in a threadprivate 1170 // directive. 1171 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD)) 1172 DVar.CKind = OMPC_shared; 1173 1174 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 1175 // in a region but not in construct] 1176 // Variables with static storage duration that are declared in called 1177 // routines in the region are shared. 1178 if (VD && VD->hasGlobalStorage()) 1179 DVar.CKind = OMPC_shared; 1180 1181 // Non-static data members are shared by default. 1182 if (FD) 1183 DVar.CKind = OMPC_shared; 1184 1185 return DVar; 1186 } 1187 1188 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1189 // in a Construct, C/C++, predetermined, p.1] 1190 // Variables with automatic storage duration that are declared in a scope 1191 // inside the construct are private. 1192 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 1193 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 1194 DVar.CKind = OMPC_private; 1195 return DVar; 1196 } 1197 1198 DVar.DKind = Iter->Directive; 1199 // Explicitly specified attributes and local variables with predetermined 1200 // attributes. 1201 if (Iter->SharingMap.count(D)) { 1202 const DSAInfo &Data = Iter->SharingMap.lookup(D); 1203 DVar.RefExpr = Data.RefExpr.getPointer(); 1204 DVar.PrivateCopy = Data.PrivateCopy; 1205 DVar.CKind = Data.Attributes; 1206 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1207 DVar.Modifier = Data.Modifier; 1208 DVar.AppliedToPointee = Data.AppliedToPointee; 1209 return DVar; 1210 } 1211 1212 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1213 // in a Construct, C/C++, implicitly determined, p.1] 1214 // In a parallel or task construct, the data-sharing attributes of these 1215 // variables are determined by the default clause, if present. 1216 switch (Iter->DefaultAttr) { 1217 case DSA_shared: 1218 DVar.CKind = OMPC_shared; 1219 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1220 return DVar; 1221 case DSA_none: 1222 return DVar; 1223 case DSA_firstprivate: 1224 if (VD->getStorageDuration() == SD_Static && 1225 VD->getDeclContext()->isFileContext()) { 1226 DVar.CKind = OMPC_unknown; 1227 } else { 1228 DVar.CKind = OMPC_firstprivate; 1229 } 1230 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1231 return DVar; 1232 case DSA_unspecified: 1233 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1234 // in a Construct, implicitly determined, p.2] 1235 // In a parallel construct, if no default clause is present, these 1236 // variables are shared. 1237 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1238 if ((isOpenMPParallelDirective(DVar.DKind) && 1239 !isOpenMPTaskLoopDirective(DVar.DKind)) || 1240 isOpenMPTeamsDirective(DVar.DKind)) { 1241 DVar.CKind = OMPC_shared; 1242 return DVar; 1243 } 1244 1245 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1246 // in a Construct, implicitly determined, p.4] 1247 // In a task construct, if no default clause is present, a variable that in 1248 // the enclosing context is determined to be shared by all implicit tasks 1249 // bound to the current team is shared. 1250 if (isOpenMPTaskingDirective(DVar.DKind)) { 1251 DSAVarData DVarTemp; 1252 const_iterator I = Iter, E = end(); 1253 do { 1254 ++I; 1255 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 1256 // Referenced in a Construct, implicitly determined, p.6] 1257 // In a task construct, if no default clause is present, a variable 1258 // whose data-sharing attribute is not determined by the rules above is 1259 // firstprivate. 1260 DVarTemp = getDSA(I, D); 1261 if (DVarTemp.CKind != OMPC_shared) { 1262 DVar.RefExpr = nullptr; 1263 DVar.CKind = OMPC_firstprivate; 1264 return DVar; 1265 } 1266 } while (I != E && !isImplicitTaskingRegion(I->Directive)); 1267 DVar.CKind = 1268 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 1269 return DVar; 1270 } 1271 } 1272 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1273 // in a Construct, implicitly determined, p.3] 1274 // For constructs other than task, if no default clause is present, these 1275 // variables inherit their data-sharing attributes from the enclosing 1276 // context. 1277 return getDSA(++Iter, D); 1278 } 1279 1280 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D, 1281 const Expr *NewDE) { 1282 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 1283 D = getCanonicalDecl(D); 1284 SharingMapTy &StackElem = getTopOfStack(); 1285 auto It = StackElem.AlignedMap.find(D); 1286 if (It == StackElem.AlignedMap.end()) { 1287 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 1288 StackElem.AlignedMap[D] = NewDE; 1289 return nullptr; 1290 } 1291 assert(It->second && "Unexpected nullptr expr in the aligned map"); 1292 return It->second; 1293 } 1294 1295 const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D, 1296 const Expr *NewDE) { 1297 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 1298 D = getCanonicalDecl(D); 1299 SharingMapTy &StackElem = getTopOfStack(); 1300 auto It = StackElem.NontemporalMap.find(D); 1301 if (It == StackElem.NontemporalMap.end()) { 1302 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 1303 StackElem.NontemporalMap[D] = NewDE; 1304 return nullptr; 1305 } 1306 assert(It->second && "Unexpected nullptr expr in the aligned map"); 1307 return It->second; 1308 } 1309 1310 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) { 1311 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1312 D = getCanonicalDecl(D); 1313 SharingMapTy &StackElem = getTopOfStack(); 1314 StackElem.LCVMap.try_emplace( 1315 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)); 1316 } 1317 1318 const DSAStackTy::LCDeclInfo 1319 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const { 1320 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1321 D = getCanonicalDecl(D); 1322 const SharingMapTy &StackElem = getTopOfStack(); 1323 auto It = StackElem.LCVMap.find(D); 1324 if (It != StackElem.LCVMap.end()) 1325 return It->second; 1326 return {0, nullptr}; 1327 } 1328 1329 const DSAStackTy::LCDeclInfo 1330 DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const { 1331 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1332 D = getCanonicalDecl(D); 1333 for (unsigned I = Level + 1; I > 0; --I) { 1334 const SharingMapTy &StackElem = getStackElemAtLevel(I - 1); 1335 auto It = StackElem.LCVMap.find(D); 1336 if (It != StackElem.LCVMap.end()) 1337 return It->second; 1338 } 1339 return {0, nullptr}; 1340 } 1341 1342 const DSAStackTy::LCDeclInfo 1343 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const { 1344 const SharingMapTy *Parent = getSecondOnStackOrNull(); 1345 assert(Parent && "Data-sharing attributes stack is empty"); 1346 D = getCanonicalDecl(D); 1347 auto It = Parent->LCVMap.find(D); 1348 if (It != Parent->LCVMap.end()) 1349 return It->second; 1350 return {0, nullptr}; 1351 } 1352 1353 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const { 1354 const SharingMapTy *Parent = getSecondOnStackOrNull(); 1355 assert(Parent && "Data-sharing attributes stack is empty"); 1356 if (Parent->LCVMap.size() < I) 1357 return nullptr; 1358 for (const auto &Pair : Parent->LCVMap) 1359 if (Pair.second.first == I) 1360 return Pair.first; 1361 return nullptr; 1362 } 1363 1364 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 1365 DeclRefExpr *PrivateCopy, unsigned Modifier, 1366 bool AppliedToPointee) { 1367 D = getCanonicalDecl(D); 1368 if (A == OMPC_threadprivate) { 1369 DSAInfo &Data = Threadprivates[D]; 1370 Data.Attributes = A; 1371 Data.RefExpr.setPointer(E); 1372 Data.PrivateCopy = nullptr; 1373 Data.Modifier = Modifier; 1374 } else { 1375 DSAInfo &Data = getTopOfStack().SharingMap[D]; 1376 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 1377 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 1378 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 1379 (isLoopControlVariable(D).first && A == OMPC_private)); 1380 Data.Modifier = Modifier; 1381 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 1382 Data.RefExpr.setInt(/*IntVal=*/true); 1383 return; 1384 } 1385 const bool IsLastprivate = 1386 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 1387 Data.Attributes = A; 1388 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 1389 Data.PrivateCopy = PrivateCopy; 1390 Data.AppliedToPointee = AppliedToPointee; 1391 if (PrivateCopy) { 1392 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()]; 1393 Data.Modifier = Modifier; 1394 Data.Attributes = A; 1395 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 1396 Data.PrivateCopy = nullptr; 1397 Data.AppliedToPointee = AppliedToPointee; 1398 } 1399 } 1400 } 1401 1402 /// Build a variable declaration for OpenMP loop iteration variable. 1403 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 1404 StringRef Name, const AttrVec *Attrs = nullptr, 1405 DeclRefExpr *OrigRef = nullptr) { 1406 DeclContext *DC = SemaRef.CurContext; 1407 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 1408 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 1409 auto *Decl = 1410 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 1411 if (Attrs) { 1412 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 1413 I != E; ++I) 1414 Decl->addAttr(*I); 1415 } 1416 Decl->setImplicit(); 1417 if (OrigRef) { 1418 Decl->addAttr( 1419 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef)); 1420 } 1421 return Decl; 1422 } 1423 1424 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 1425 SourceLocation Loc, 1426 bool RefersToCapture = false) { 1427 D->setReferenced(); 1428 D->markUsed(S.Context); 1429 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 1430 SourceLocation(), D, RefersToCapture, Loc, Ty, 1431 VK_LValue); 1432 } 1433 1434 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 1435 BinaryOperatorKind BOK) { 1436 D = getCanonicalDecl(D); 1437 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1438 assert( 1439 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && 1440 "Additional reduction info may be specified only for reduction items."); 1441 ReductionData &ReductionData = getTopOfStack().ReductionMap[D]; 1442 assert(ReductionData.ReductionRange.isInvalid() && 1443 (getTopOfStack().Directive == OMPD_taskgroup || 1444 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 1445 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 1446 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 1447 "Additional reduction info may be specified only once for reduction " 1448 "items."); 1449 ReductionData.set(BOK, SR); 1450 Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef; 1451 if (!TaskgroupReductionRef) { 1452 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1453 SemaRef.Context.VoidPtrTy, ".task_red."); 1454 TaskgroupReductionRef = 1455 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1456 } 1457 } 1458 1459 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 1460 const Expr *ReductionRef) { 1461 D = getCanonicalDecl(D); 1462 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1463 assert( 1464 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && 1465 "Additional reduction info may be specified only for reduction items."); 1466 ReductionData &ReductionData = getTopOfStack().ReductionMap[D]; 1467 assert(ReductionData.ReductionRange.isInvalid() && 1468 (getTopOfStack().Directive == OMPD_taskgroup || 1469 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 1470 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 1471 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 1472 "Additional reduction info may be specified only once for reduction " 1473 "items."); 1474 ReductionData.set(ReductionRef, SR); 1475 Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef; 1476 if (!TaskgroupReductionRef) { 1477 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1478 SemaRef.Context.VoidPtrTy, ".task_red."); 1479 TaskgroupReductionRef = 1480 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1481 } 1482 } 1483 1484 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1485 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK, 1486 Expr *&TaskgroupDescriptor) const { 1487 D = getCanonicalDecl(D); 1488 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1489 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) { 1490 const DSAInfo &Data = I->SharingMap.lookup(D); 1491 if (Data.Attributes != OMPC_reduction || 1492 Data.Modifier != OMPC_REDUCTION_task) 1493 continue; 1494 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1495 if (!ReductionData.ReductionOp || 1496 ReductionData.ReductionOp.is<const Expr *>()) 1497 return DSAVarData(); 1498 SR = ReductionData.ReductionRange; 1499 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>(); 1500 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1501 "expression for the descriptor is not " 1502 "set."); 1503 TaskgroupDescriptor = I->TaskgroupReductionRef; 1504 return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(), 1505 Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task, 1506 /*AppliedToPointee=*/false); 1507 } 1508 return DSAVarData(); 1509 } 1510 1511 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1512 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef, 1513 Expr *&TaskgroupDescriptor) const { 1514 D = getCanonicalDecl(D); 1515 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1516 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) { 1517 const DSAInfo &Data = I->SharingMap.lookup(D); 1518 if (Data.Attributes != OMPC_reduction || 1519 Data.Modifier != OMPC_REDUCTION_task) 1520 continue; 1521 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1522 if (!ReductionData.ReductionOp || 1523 !ReductionData.ReductionOp.is<const Expr *>()) 1524 return DSAVarData(); 1525 SR = ReductionData.ReductionRange; 1526 ReductionRef = ReductionData.ReductionOp.get<const Expr *>(); 1527 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1528 "expression for the descriptor is not " 1529 "set."); 1530 TaskgroupDescriptor = I->TaskgroupReductionRef; 1531 return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(), 1532 Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task, 1533 /*AppliedToPointee=*/false); 1534 } 1535 return DSAVarData(); 1536 } 1537 1538 bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const { 1539 D = D->getCanonicalDecl(); 1540 for (const_iterator E = end(); I != E; ++I) { 1541 if (isImplicitOrExplicitTaskingRegion(I->Directive) || 1542 isOpenMPTargetExecutionDirective(I->Directive)) { 1543 if (I->CurScope) { 1544 Scope *TopScope = I->CurScope->getParent(); 1545 Scope *CurScope = getCurScope(); 1546 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D)) 1547 CurScope = CurScope->getParent(); 1548 return CurScope != TopScope; 1549 } 1550 for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent()) 1551 if (I->Context == DC) 1552 return true; 1553 return false; 1554 } 1555 } 1556 return false; 1557 } 1558 1559 static bool isConstNotMutableType(Sema &SemaRef, QualType Type, 1560 bool AcceptIfMutable = true, 1561 bool *IsClassType = nullptr) { 1562 ASTContext &Context = SemaRef.getASTContext(); 1563 Type = Type.getNonReferenceType().getCanonicalType(); 1564 bool IsConstant = Type.isConstant(Context); 1565 Type = Context.getBaseElementType(Type); 1566 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus 1567 ? Type->getAsCXXRecordDecl() 1568 : nullptr; 1569 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 1570 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate()) 1571 RD = CTD->getTemplatedDecl(); 1572 if (IsClassType) 1573 *IsClassType = RD; 1574 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD && 1575 RD->hasDefinition() && RD->hasMutableFields()); 1576 } 1577 1578 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D, 1579 QualType Type, OpenMPClauseKind CKind, 1580 SourceLocation ELoc, 1581 bool AcceptIfMutable = true, 1582 bool ListItemNotVar = false) { 1583 ASTContext &Context = SemaRef.getASTContext(); 1584 bool IsClassType; 1585 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) { 1586 unsigned Diag = ListItemNotVar ? diag::err_omp_const_list_item 1587 : IsClassType ? diag::err_omp_const_not_mutable_variable 1588 : diag::err_omp_const_variable; 1589 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind); 1590 if (!ListItemNotVar && D) { 1591 const VarDecl *VD = dyn_cast<VarDecl>(D); 1592 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 1593 VarDecl::DeclarationOnly; 1594 SemaRef.Diag(D->getLocation(), 1595 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1596 << D; 1597 } 1598 return true; 1599 } 1600 return false; 1601 } 1602 1603 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, 1604 bool FromParent) { 1605 D = getCanonicalDecl(D); 1606 DSAVarData DVar; 1607 1608 auto *VD = dyn_cast<VarDecl>(D); 1609 auto TI = Threadprivates.find(D); 1610 if (TI != Threadprivates.end()) { 1611 DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); 1612 DVar.CKind = OMPC_threadprivate; 1613 DVar.Modifier = TI->getSecond().Modifier; 1614 return DVar; 1615 } 1616 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 1617 DVar.RefExpr = buildDeclRefExpr( 1618 SemaRef, VD, D->getType().getNonReferenceType(), 1619 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation()); 1620 DVar.CKind = OMPC_threadprivate; 1621 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1622 return DVar; 1623 } 1624 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1625 // in a Construct, C/C++, predetermined, p.1] 1626 // Variables appearing in threadprivate directives are threadprivate. 1627 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 1628 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1629 SemaRef.getLangOpts().OpenMPUseTLS && 1630 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 1631 (VD && VD->getStorageClass() == SC_Register && 1632 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 1633 DVar.RefExpr = buildDeclRefExpr( 1634 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation()); 1635 DVar.CKind = OMPC_threadprivate; 1636 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1637 return DVar; 1638 } 1639 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD && 1640 VD->isLocalVarDeclOrParm() && !isStackEmpty() && 1641 !isLoopControlVariable(D).first) { 1642 const_iterator IterTarget = 1643 std::find_if(begin(), end(), [](const SharingMapTy &Data) { 1644 return isOpenMPTargetExecutionDirective(Data.Directive); 1645 }); 1646 if (IterTarget != end()) { 1647 const_iterator ParentIterTarget = IterTarget + 1; 1648 for (const_iterator Iter = begin(); Iter != ParentIterTarget; ++Iter) { 1649 if (isOpenMPLocal(VD, Iter)) { 1650 DVar.RefExpr = 1651 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1652 D->getLocation()); 1653 DVar.CKind = OMPC_threadprivate; 1654 return DVar; 1655 } 1656 } 1657 if (!isClauseParsingMode() || IterTarget != begin()) { 1658 auto DSAIter = IterTarget->SharingMap.find(D); 1659 if (DSAIter != IterTarget->SharingMap.end() && 1660 isOpenMPPrivate(DSAIter->getSecond().Attributes)) { 1661 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer(); 1662 DVar.CKind = OMPC_threadprivate; 1663 return DVar; 1664 } 1665 const_iterator End = end(); 1666 if (!SemaRef.isOpenMPCapturedByRef(D, 1667 std::distance(ParentIterTarget, End), 1668 /*OpenMPCaptureLevel=*/0)) { 1669 DVar.RefExpr = 1670 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1671 IterTarget->ConstructLoc); 1672 DVar.CKind = OMPC_threadprivate; 1673 return DVar; 1674 } 1675 } 1676 } 1677 } 1678 1679 if (isStackEmpty()) 1680 // Not in OpenMP execution region and top scope was already checked. 1681 return DVar; 1682 1683 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1684 // in a Construct, C/C++, predetermined, p.4] 1685 // Static data members are shared. 1686 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1687 // in a Construct, C/C++, predetermined, p.7] 1688 // Variables with static storage duration that are declared in a scope 1689 // inside the construct are shared. 1690 if (VD && VD->isStaticDataMember()) { 1691 // Check for explicitly specified attributes. 1692 const_iterator I = begin(); 1693 const_iterator EndI = end(); 1694 if (FromParent && I != EndI) 1695 ++I; 1696 if (I != EndI) { 1697 auto It = I->SharingMap.find(D); 1698 if (It != I->SharingMap.end()) { 1699 const DSAInfo &Data = It->getSecond(); 1700 DVar.RefExpr = Data.RefExpr.getPointer(); 1701 DVar.PrivateCopy = Data.PrivateCopy; 1702 DVar.CKind = Data.Attributes; 1703 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1704 DVar.DKind = I->Directive; 1705 DVar.Modifier = Data.Modifier; 1706 DVar.AppliedToPointee = Data.AppliedToPointee; 1707 return DVar; 1708 } 1709 } 1710 1711 DVar.CKind = OMPC_shared; 1712 return DVar; 1713 } 1714 1715 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; }; 1716 // The predetermined shared attribute for const-qualified types having no 1717 // mutable members was removed after OpenMP 3.1. 1718 if (SemaRef.LangOpts.OpenMP <= 31) { 1719 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1720 // in a Construct, C/C++, predetermined, p.6] 1721 // Variables with const qualified type having no mutable member are 1722 // shared. 1723 if (isConstNotMutableType(SemaRef, D->getType())) { 1724 // Variables with const-qualified type having no mutable member may be 1725 // listed in a firstprivate clause, even if they are static data members. 1726 DSAVarData DVarTemp = hasInnermostDSA( 1727 D, 1728 [](OpenMPClauseKind C, bool) { 1729 return C == OMPC_firstprivate || C == OMPC_shared; 1730 }, 1731 MatchesAlways, FromParent); 1732 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 1733 return DVarTemp; 1734 1735 DVar.CKind = OMPC_shared; 1736 return DVar; 1737 } 1738 } 1739 1740 // Explicitly specified attributes and local variables with predetermined 1741 // attributes. 1742 const_iterator I = begin(); 1743 const_iterator EndI = end(); 1744 if (FromParent && I != EndI) 1745 ++I; 1746 if (I == EndI) 1747 return DVar; 1748 auto It = I->SharingMap.find(D); 1749 if (It != I->SharingMap.end()) { 1750 const DSAInfo &Data = It->getSecond(); 1751 DVar.RefExpr = Data.RefExpr.getPointer(); 1752 DVar.PrivateCopy = Data.PrivateCopy; 1753 DVar.CKind = Data.Attributes; 1754 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1755 DVar.DKind = I->Directive; 1756 DVar.Modifier = Data.Modifier; 1757 DVar.AppliedToPointee = Data.AppliedToPointee; 1758 } 1759 1760 return DVar; 1761 } 1762 1763 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1764 bool FromParent) const { 1765 if (isStackEmpty()) { 1766 const_iterator I; 1767 return getDSA(I, D); 1768 } 1769 D = getCanonicalDecl(D); 1770 const_iterator StartI = begin(); 1771 const_iterator EndI = end(); 1772 if (FromParent && StartI != EndI) 1773 ++StartI; 1774 return getDSA(StartI, D); 1775 } 1776 1777 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1778 unsigned Level) const { 1779 if (getStackSize() <= Level) 1780 return DSAVarData(); 1781 D = getCanonicalDecl(D); 1782 const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level); 1783 return getDSA(StartI, D); 1784 } 1785 1786 const DSAStackTy::DSAVarData 1787 DSAStackTy::hasDSA(ValueDecl *D, 1788 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1789 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1790 bool FromParent) const { 1791 if (isStackEmpty()) 1792 return {}; 1793 D = getCanonicalDecl(D); 1794 const_iterator I = begin(); 1795 const_iterator EndI = end(); 1796 if (FromParent && I != EndI) 1797 ++I; 1798 for (; I != EndI; ++I) { 1799 if (!DPred(I->Directive) && 1800 !isImplicitOrExplicitTaskingRegion(I->Directive)) 1801 continue; 1802 const_iterator NewI = I; 1803 DSAVarData DVar = getDSA(NewI, D); 1804 if (I == NewI && CPred(DVar.CKind, DVar.AppliedToPointee)) 1805 return DVar; 1806 } 1807 return {}; 1808 } 1809 1810 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 1811 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1812 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1813 bool FromParent) const { 1814 if (isStackEmpty()) 1815 return {}; 1816 D = getCanonicalDecl(D); 1817 const_iterator StartI = begin(); 1818 const_iterator EndI = end(); 1819 if (FromParent && StartI != EndI) 1820 ++StartI; 1821 if (StartI == EndI || !DPred(StartI->Directive)) 1822 return {}; 1823 const_iterator NewI = StartI; 1824 DSAVarData DVar = getDSA(NewI, D); 1825 return (NewI == StartI && CPred(DVar.CKind, DVar.AppliedToPointee)) 1826 ? DVar 1827 : DSAVarData(); 1828 } 1829 1830 bool DSAStackTy::hasExplicitDSA( 1831 const ValueDecl *D, 1832 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1833 unsigned Level, bool NotLastprivate) const { 1834 if (getStackSize() <= Level) 1835 return false; 1836 D = getCanonicalDecl(D); 1837 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 1838 auto I = StackElem.SharingMap.find(D); 1839 if (I != StackElem.SharingMap.end() && I->getSecond().RefExpr.getPointer() && 1840 CPred(I->getSecond().Attributes, I->getSecond().AppliedToPointee) && 1841 (!NotLastprivate || !I->getSecond().RefExpr.getInt())) 1842 return true; 1843 // Check predetermined rules for the loop control variables. 1844 auto LI = StackElem.LCVMap.find(D); 1845 if (LI != StackElem.LCVMap.end()) 1846 return CPred(OMPC_private, /*AppliedToPointee=*/false); 1847 return false; 1848 } 1849 1850 bool DSAStackTy::hasExplicitDirective( 1851 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1852 unsigned Level) const { 1853 if (getStackSize() <= Level) 1854 return false; 1855 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 1856 return DPred(StackElem.Directive); 1857 } 1858 1859 bool DSAStackTy::hasDirective( 1860 const llvm::function_ref<bool(OpenMPDirectiveKind, 1861 const DeclarationNameInfo &, SourceLocation)> 1862 DPred, 1863 bool FromParent) const { 1864 // We look only in the enclosing region. 1865 size_t Skip = FromParent ? 2 : 1; 1866 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end(); 1867 I != E; ++I) { 1868 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 1869 return true; 1870 } 1871 return false; 1872 } 1873 1874 void Sema::InitDataSharingAttributesStack() { 1875 VarDataSharingAttributesStack = new DSAStackTy(*this); 1876 } 1877 1878 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 1879 1880 void Sema::pushOpenMPFunctionRegion() { DSAStack->pushFunction(); } 1881 1882 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 1883 DSAStack->popFunction(OldFSI); 1884 } 1885 1886 static bool isOpenMPDeviceDelayedContext(Sema &S) { 1887 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && 1888 "Expected OpenMP device compilation."); 1889 return !S.isInOpenMPTargetExecutionDirective(); 1890 } 1891 1892 namespace { 1893 /// Status of the function emission on the host/device. 1894 enum class FunctionEmissionStatus { 1895 Emitted, 1896 Discarded, 1897 Unknown, 1898 }; 1899 } // anonymous namespace 1900 1901 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc, 1902 unsigned DiagID, 1903 FunctionDecl *FD) { 1904 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 1905 "Expected OpenMP device compilation."); 1906 1907 SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop; 1908 if (FD) { 1909 FunctionEmissionStatus FES = getEmissionStatus(FD); 1910 switch (FES) { 1911 case FunctionEmissionStatus::Emitted: 1912 Kind = SemaDiagnosticBuilder::K_Immediate; 1913 break; 1914 case FunctionEmissionStatus::Unknown: 1915 // TODO: We should always delay diagnostics here in case a target 1916 // region is in a function we do not emit. However, as the 1917 // current diagnostics are associated with the function containing 1918 // the target region and we do not emit that one, we would miss out 1919 // on diagnostics for the target region itself. We need to anchor 1920 // the diagnostics with the new generated function *or* ensure we 1921 // emit diagnostics associated with the surrounding function. 1922 Kind = isOpenMPDeviceDelayedContext(*this) 1923 ? SemaDiagnosticBuilder::K_Deferred 1924 : SemaDiagnosticBuilder::K_Immediate; 1925 break; 1926 case FunctionEmissionStatus::TemplateDiscarded: 1927 case FunctionEmissionStatus::OMPDiscarded: 1928 Kind = SemaDiagnosticBuilder::K_Nop; 1929 break; 1930 case FunctionEmissionStatus::CUDADiscarded: 1931 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation"); 1932 break; 1933 } 1934 } 1935 1936 return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this); 1937 } 1938 1939 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc, 1940 unsigned DiagID, 1941 FunctionDecl *FD) { 1942 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice && 1943 "Expected OpenMP host compilation."); 1944 1945 SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop; 1946 if (FD) { 1947 FunctionEmissionStatus FES = getEmissionStatus(FD); 1948 switch (FES) { 1949 case FunctionEmissionStatus::Emitted: 1950 Kind = SemaDiagnosticBuilder::K_Immediate; 1951 break; 1952 case FunctionEmissionStatus::Unknown: 1953 Kind = SemaDiagnosticBuilder::K_Deferred; 1954 break; 1955 case FunctionEmissionStatus::TemplateDiscarded: 1956 case FunctionEmissionStatus::OMPDiscarded: 1957 case FunctionEmissionStatus::CUDADiscarded: 1958 Kind = SemaDiagnosticBuilder::K_Nop; 1959 break; 1960 } 1961 } 1962 1963 return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this); 1964 } 1965 1966 static OpenMPDefaultmapClauseKind 1967 getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) { 1968 if (LO.OpenMP <= 45) { 1969 if (VD->getType().getNonReferenceType()->isScalarType()) 1970 return OMPC_DEFAULTMAP_scalar; 1971 return OMPC_DEFAULTMAP_aggregate; 1972 } 1973 if (VD->getType().getNonReferenceType()->isAnyPointerType()) 1974 return OMPC_DEFAULTMAP_pointer; 1975 if (VD->getType().getNonReferenceType()->isScalarType()) 1976 return OMPC_DEFAULTMAP_scalar; 1977 return OMPC_DEFAULTMAP_aggregate; 1978 } 1979 1980 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, 1981 unsigned OpenMPCaptureLevel) const { 1982 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1983 1984 ASTContext &Ctx = getASTContext(); 1985 bool IsByRef = true; 1986 1987 // Find the directive that is associated with the provided scope. 1988 D = cast<ValueDecl>(D->getCanonicalDecl()); 1989 QualType Ty = D->getType(); 1990 1991 bool IsVariableUsedInMapClause = false; 1992 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 1993 // This table summarizes how a given variable should be passed to the device 1994 // given its type and the clauses where it appears. This table is based on 1995 // the description in OpenMP 4.5 [2.10.4, target Construct] and 1996 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 1997 // 1998 // ========================================================================= 1999 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 2000 // | |(tofrom:scalar)| | pvt | | | | 2001 // ========================================================================= 2002 // | scl | | | | - | | bycopy| 2003 // | scl | | - | x | - | - | bycopy| 2004 // | scl | | x | - | - | - | null | 2005 // | scl | x | | | - | | byref | 2006 // | scl | x | - | x | - | - | bycopy| 2007 // | scl | x | x | - | - | - | null | 2008 // | scl | | - | - | - | x | byref | 2009 // | scl | x | - | - | - | x | byref | 2010 // 2011 // | agg | n.a. | | | - | | byref | 2012 // | agg | n.a. | - | x | - | - | byref | 2013 // | agg | n.a. | x | - | - | - | null | 2014 // | agg | n.a. | - | - | - | x | byref | 2015 // | agg | n.a. | - | - | - | x[] | byref | 2016 // 2017 // | ptr | n.a. | | | - | | bycopy| 2018 // | ptr | n.a. | - | x | - | - | bycopy| 2019 // | ptr | n.a. | x | - | - | - | null | 2020 // | ptr | n.a. | - | - | - | x | byref | 2021 // | ptr | n.a. | - | - | - | x[] | bycopy| 2022 // | ptr | n.a. | - | - | x | | bycopy| 2023 // | ptr | n.a. | - | - | x | x | bycopy| 2024 // | ptr | n.a. | - | - | x | x[] | bycopy| 2025 // ========================================================================= 2026 // Legend: 2027 // scl - scalar 2028 // ptr - pointer 2029 // agg - aggregate 2030 // x - applies 2031 // - - invalid in this combination 2032 // [] - mapped with an array section 2033 // byref - should be mapped by reference 2034 // byval - should be mapped by value 2035 // null - initialize a local variable to null on the device 2036 // 2037 // Observations: 2038 // - All scalar declarations that show up in a map clause have to be passed 2039 // by reference, because they may have been mapped in the enclosing data 2040 // environment. 2041 // - If the scalar value does not fit the size of uintptr, it has to be 2042 // passed by reference, regardless the result in the table above. 2043 // - For pointers mapped by value that have either an implicit map or an 2044 // array section, the runtime library may pass the NULL value to the 2045 // device instead of the value passed to it by the compiler. 2046 2047 if (Ty->isReferenceType()) 2048 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 2049 2050 // Locate map clauses and see if the variable being captured is referred to 2051 // in any of those clauses. Here we only care about variables, not fields, 2052 // because fields are part of aggregates. 2053 bool IsVariableAssociatedWithSection = false; 2054 2055 DSAStack->checkMappableExprComponentListsForDeclAtLevel( 2056 D, Level, 2057 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, 2058 D](OMPClauseMappableExprCommon::MappableExprComponentListRef 2059 MapExprComponents, 2060 OpenMPClauseKind WhereFoundClauseKind) { 2061 // Only the map clause information influences how a variable is 2062 // captured. E.g. is_device_ptr does not require changing the default 2063 // behavior. 2064 if (WhereFoundClauseKind != OMPC_map) 2065 return false; 2066 2067 auto EI = MapExprComponents.rbegin(); 2068 auto EE = MapExprComponents.rend(); 2069 2070 assert(EI != EE && "Invalid map expression!"); 2071 2072 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 2073 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 2074 2075 ++EI; 2076 if (EI == EE) 2077 return false; 2078 2079 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 2080 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 2081 isa<MemberExpr>(EI->getAssociatedExpression()) || 2082 isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) { 2083 IsVariableAssociatedWithSection = true; 2084 // There is nothing more we need to know about this variable. 2085 return true; 2086 } 2087 2088 // Keep looking for more map info. 2089 return false; 2090 }); 2091 2092 if (IsVariableUsedInMapClause) { 2093 // If variable is identified in a map clause it is always captured by 2094 // reference except if it is a pointer that is dereferenced somehow. 2095 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 2096 } else { 2097 // By default, all the data that has a scalar type is mapped by copy 2098 // (except for reduction variables). 2099 // Defaultmap scalar is mutual exclusive to defaultmap pointer 2100 IsByRef = (DSAStack->isForceCaptureByReferenceInTargetExecutable() && 2101 !Ty->isAnyPointerType()) || 2102 !Ty->isScalarType() || 2103 DSAStack->isDefaultmapCapturedByRef( 2104 Level, getVariableCategoryFromDecl(LangOpts, D)) || 2105 DSAStack->hasExplicitDSA( 2106 D, 2107 [](OpenMPClauseKind K, bool AppliedToPointee) { 2108 return K == OMPC_reduction && !AppliedToPointee; 2109 }, 2110 Level); 2111 } 2112 } 2113 2114 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 2115 IsByRef = 2116 ((IsVariableUsedInMapClause && 2117 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) == 2118 OMPD_target) || 2119 !(DSAStack->hasExplicitDSA( 2120 D, 2121 [](OpenMPClauseKind K, bool AppliedToPointee) -> bool { 2122 return K == OMPC_firstprivate || 2123 (K == OMPC_reduction && AppliedToPointee); 2124 }, 2125 Level, /*NotLastprivate=*/true) || 2126 DSAStack->isUsesAllocatorsDecl(Level, D))) && 2127 // If the variable is artificial and must be captured by value - try to 2128 // capture by value. 2129 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() && 2130 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) && 2131 // If the variable is implicitly firstprivate and scalar - capture by 2132 // copy 2133 !(DSAStack->getDefaultDSA() == DSA_firstprivate && 2134 !DSAStack->hasExplicitDSA( 2135 D, [](OpenMPClauseKind K, bool) { return K != OMPC_unknown; }, 2136 Level) && 2137 !DSAStack->isLoopControlVariable(D, Level).first); 2138 } 2139 2140 // When passing data by copy, we need to make sure it fits the uintptr size 2141 // and alignment, because the runtime library only deals with uintptr types. 2142 // If it does not fit the uintptr size, we need to pass the data by reference 2143 // instead. 2144 if (!IsByRef && 2145 (Ctx.getTypeSizeInChars(Ty) > 2146 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 2147 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 2148 IsByRef = true; 2149 } 2150 2151 return IsByRef; 2152 } 2153 2154 unsigned Sema::getOpenMPNestingLevel() const { 2155 assert(getLangOpts().OpenMP); 2156 return DSAStack->getNestingLevel(); 2157 } 2158 2159 bool Sema::isInOpenMPTargetExecutionDirective() const { 2160 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) && 2161 !DSAStack->isClauseParsingMode()) || 2162 DSAStack->hasDirective( 2163 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 2164 SourceLocation) -> bool { 2165 return isOpenMPTargetExecutionDirective(K); 2166 }, 2167 false); 2168 } 2169 2170 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo, 2171 unsigned StopAt) { 2172 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2173 D = getCanonicalDecl(D); 2174 2175 auto *VD = dyn_cast<VarDecl>(D); 2176 // Do not capture constexpr variables. 2177 if (VD && VD->isConstexpr()) 2178 return nullptr; 2179 2180 // If we want to determine whether the variable should be captured from the 2181 // perspective of the current capturing scope, and we've already left all the 2182 // capturing scopes of the top directive on the stack, check from the 2183 // perspective of its parent directive (if any) instead. 2184 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII( 2185 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete()); 2186 2187 // If we are attempting to capture a global variable in a directive with 2188 // 'target' we return true so that this global is also mapped to the device. 2189 // 2190 if (VD && !VD->hasLocalStorage() && 2191 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) { 2192 if (isInOpenMPTargetExecutionDirective()) { 2193 DSAStackTy::DSAVarData DVarTop = 2194 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 2195 if (DVarTop.CKind != OMPC_unknown && DVarTop.RefExpr) 2196 return VD; 2197 // If the declaration is enclosed in a 'declare target' directive, 2198 // then it should not be captured. 2199 // 2200 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 2201 return nullptr; 2202 CapturedRegionScopeInfo *CSI = nullptr; 2203 for (FunctionScopeInfo *FSI : llvm::drop_begin( 2204 llvm::reverse(FunctionScopes), 2205 CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) { 2206 if (!isa<CapturingScopeInfo>(FSI)) 2207 return nullptr; 2208 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI)) 2209 if (RSI->CapRegionKind == CR_OpenMP) { 2210 CSI = RSI; 2211 break; 2212 } 2213 } 2214 assert(CSI && "Failed to find CapturedRegionScopeInfo"); 2215 SmallVector<OpenMPDirectiveKind, 4> Regions; 2216 getOpenMPCaptureRegions(Regions, 2217 DSAStack->getDirective(CSI->OpenMPLevel)); 2218 if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task) 2219 return VD; 2220 } 2221 if (isInOpenMPDeclareTargetContext()) { 2222 // Try to mark variable as declare target if it is used in capturing 2223 // regions. 2224 if (LangOpts.OpenMP <= 45 && 2225 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 2226 checkDeclIsAllowedInOpenMPTarget(nullptr, VD); 2227 return nullptr; 2228 } 2229 } 2230 2231 if (CheckScopeInfo) { 2232 bool OpenMPFound = false; 2233 for (unsigned I = StopAt + 1; I > 0; --I) { 2234 FunctionScopeInfo *FSI = FunctionScopes[I - 1]; 2235 if (!isa<CapturingScopeInfo>(FSI)) 2236 return nullptr; 2237 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI)) 2238 if (RSI->CapRegionKind == CR_OpenMP) { 2239 OpenMPFound = true; 2240 break; 2241 } 2242 } 2243 if (!OpenMPFound) 2244 return nullptr; 2245 } 2246 2247 if (DSAStack->getCurrentDirective() != OMPD_unknown && 2248 (!DSAStack->isClauseParsingMode() || 2249 DSAStack->getParentDirective() != OMPD_unknown)) { 2250 auto &&Info = DSAStack->isLoopControlVariable(D); 2251 if (Info.first || 2252 (VD && VD->hasLocalStorage() && 2253 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) || 2254 (VD && DSAStack->isForceVarCapturing())) 2255 return VD ? VD : Info.second; 2256 DSAStackTy::DSAVarData DVarTop = 2257 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 2258 if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) && 2259 (!VD || VD->hasLocalStorage() || !DVarTop.AppliedToPointee)) 2260 return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl()); 2261 // Threadprivate variables must not be captured. 2262 if (isOpenMPThreadPrivate(DVarTop.CKind)) 2263 return nullptr; 2264 // The variable is not private or it is the variable in the directive with 2265 // default(none) clause and not used in any clause. 2266 DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA( 2267 D, 2268 [](OpenMPClauseKind C, bool AppliedToPointee) { 2269 return isOpenMPPrivate(C) && !AppliedToPointee; 2270 }, 2271 [](OpenMPDirectiveKind) { return true; }, 2272 DSAStack->isClauseParsingMode()); 2273 // Global shared must not be captured. 2274 if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown && 2275 ((DSAStack->getDefaultDSA() != DSA_none && 2276 DSAStack->getDefaultDSA() != DSA_firstprivate) || 2277 DVarTop.CKind == OMPC_shared)) 2278 return nullptr; 2279 if (DVarPrivate.CKind != OMPC_unknown || 2280 (VD && (DSAStack->getDefaultDSA() == DSA_none || 2281 DSAStack->getDefaultDSA() == DSA_firstprivate))) 2282 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 2283 } 2284 return nullptr; 2285 } 2286 2287 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 2288 unsigned Level) const { 2289 FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 2290 } 2291 2292 void Sema::startOpenMPLoop() { 2293 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 2294 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) 2295 DSAStack->loopInit(); 2296 } 2297 2298 void Sema::startOpenMPCXXRangeFor() { 2299 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 2300 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 2301 DSAStack->resetPossibleLoopCounter(); 2302 DSAStack->loopStart(); 2303 } 2304 } 2305 2306 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, 2307 unsigned CapLevel) const { 2308 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2309 if (DSAStack->hasExplicitDirective(isOpenMPTaskingDirective, Level)) { 2310 bool IsTriviallyCopyable = 2311 D->getType().getNonReferenceType().isTriviallyCopyableType(Context) && 2312 !D->getType() 2313 .getNonReferenceType() 2314 .getCanonicalType() 2315 ->getAsCXXRecordDecl(); 2316 OpenMPDirectiveKind DKind = DSAStack->getDirective(Level); 2317 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2318 getOpenMPCaptureRegions(CaptureRegions, DKind); 2319 if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) && 2320 (IsTriviallyCopyable || 2321 !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) { 2322 if (DSAStack->hasExplicitDSA( 2323 D, 2324 [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; }, 2325 Level, /*NotLastprivate=*/true)) 2326 return OMPC_firstprivate; 2327 DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level); 2328 if (DVar.CKind != OMPC_shared && 2329 !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) { 2330 DSAStack->addImplicitTaskFirstprivate(Level, D); 2331 return OMPC_firstprivate; 2332 } 2333 } 2334 } 2335 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 2336 if (DSAStack->getAssociatedLoops() > 0 && !DSAStack->isLoopStarted()) { 2337 DSAStack->resetPossibleLoopCounter(D); 2338 DSAStack->loopStart(); 2339 return OMPC_private; 2340 } 2341 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() || 2342 DSAStack->isLoopControlVariable(D).first) && 2343 !DSAStack->hasExplicitDSA( 2344 D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; }, 2345 Level) && 2346 !isOpenMPSimdDirective(DSAStack->getCurrentDirective())) 2347 return OMPC_private; 2348 } 2349 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2350 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) && 2351 DSAStack->isForceVarCapturing() && 2352 !DSAStack->hasExplicitDSA( 2353 D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; }, 2354 Level)) 2355 return OMPC_private; 2356 } 2357 // User-defined allocators are private since they must be defined in the 2358 // context of target region. 2359 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) && 2360 DSAStack->isUsesAllocatorsDecl(Level, D).getValueOr( 2361 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) == 2362 DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator) 2363 return OMPC_private; 2364 return (DSAStack->hasExplicitDSA( 2365 D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; }, 2366 Level) || 2367 (DSAStack->isClauseParsingMode() && 2368 DSAStack->getClauseParsingMode() == OMPC_private) || 2369 // Consider taskgroup reduction descriptor variable a private 2370 // to avoid possible capture in the region. 2371 (DSAStack->hasExplicitDirective( 2372 [](OpenMPDirectiveKind K) { 2373 return K == OMPD_taskgroup || 2374 ((isOpenMPParallelDirective(K) || 2375 isOpenMPWorksharingDirective(K)) && 2376 !isOpenMPSimdDirective(K)); 2377 }, 2378 Level) && 2379 DSAStack->isTaskgroupReductionRef(D, Level))) 2380 ? OMPC_private 2381 : OMPC_unknown; 2382 } 2383 2384 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, 2385 unsigned Level) { 2386 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2387 D = getCanonicalDecl(D); 2388 OpenMPClauseKind OMPC = OMPC_unknown; 2389 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) { 2390 const unsigned NewLevel = I - 1; 2391 if (DSAStack->hasExplicitDSA( 2392 D, 2393 [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) { 2394 if (isOpenMPPrivate(K) && !AppliedToPointee) { 2395 OMPC = K; 2396 return true; 2397 } 2398 return false; 2399 }, 2400 NewLevel)) 2401 break; 2402 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel( 2403 D, NewLevel, 2404 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 2405 OpenMPClauseKind) { return true; })) { 2406 OMPC = OMPC_map; 2407 break; 2408 } 2409 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 2410 NewLevel)) { 2411 OMPC = OMPC_map; 2412 if (DSAStack->mustBeFirstprivateAtLevel( 2413 NewLevel, getVariableCategoryFromDecl(LangOpts, D))) 2414 OMPC = OMPC_firstprivate; 2415 break; 2416 } 2417 } 2418 if (OMPC != OMPC_unknown) 2419 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC))); 2420 } 2421 2422 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, 2423 unsigned CaptureLevel) const { 2424 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2425 // Return true if the current level is no longer enclosed in a target region. 2426 2427 SmallVector<OpenMPDirectiveKind, 4> Regions; 2428 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level)); 2429 const auto *VD = dyn_cast<VarDecl>(D); 2430 return VD && !VD->hasLocalStorage() && 2431 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 2432 Level) && 2433 Regions[CaptureLevel] != OMPD_task; 2434 } 2435 2436 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, 2437 unsigned CaptureLevel) const { 2438 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2439 // Return true if the current level is no longer enclosed in a target region. 2440 2441 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2442 if (!VD->hasLocalStorage()) { 2443 if (isInOpenMPTargetExecutionDirective()) 2444 return true; 2445 DSAStackTy::DSAVarData TopDVar = 2446 DSAStack->getTopDSA(D, /*FromParent=*/false); 2447 unsigned NumLevels = 2448 getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 2449 if (Level == 0) 2450 return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared; 2451 do { 2452 --Level; 2453 DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level); 2454 if (DVar.CKind != OMPC_shared) 2455 return true; 2456 } while (Level > 0); 2457 } 2458 } 2459 return true; 2460 } 2461 2462 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 2463 2464 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, 2465 OMPTraitInfo &TI) { 2466 OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI)); 2467 } 2468 2469 void Sema::ActOnOpenMPEndDeclareVariant() { 2470 assert(isInOpenMPDeclareVariantScope() && 2471 "Not in OpenMP declare variant scope!"); 2472 2473 OMPDeclareVariantScopes.pop_back(); 2474 } 2475 2476 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, 2477 const FunctionDecl *Callee, 2478 SourceLocation Loc) { 2479 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode."); 2480 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 2481 OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl()); 2482 // Ignore host functions during device analyzis. 2483 if (LangOpts.OpenMPIsDevice && 2484 (!DevTy || *DevTy == OMPDeclareTargetDeclAttr::DT_Host)) 2485 return; 2486 // Ignore nohost functions during host analyzis. 2487 if (!LangOpts.OpenMPIsDevice && DevTy && 2488 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 2489 return; 2490 const FunctionDecl *FD = Callee->getMostRecentDecl(); 2491 DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD); 2492 if (LangOpts.OpenMPIsDevice && DevTy && 2493 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) { 2494 // Diagnose host function called during device codegen. 2495 StringRef HostDevTy = 2496 getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host); 2497 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0; 2498 Diag(*OMPDeclareTargetDeclAttr::getLocation(FD), 2499 diag::note_omp_marked_device_type_here) 2500 << HostDevTy; 2501 return; 2502 } 2503 if (!LangOpts.OpenMPIsDevice && DevTy && 2504 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 2505 // Diagnose nohost function called during host codegen. 2506 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName( 2507 OMPC_device_type, OMPC_DEVICE_TYPE_nohost); 2508 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1; 2509 Diag(*OMPDeclareTargetDeclAttr::getLocation(FD), 2510 diag::note_omp_marked_device_type_here) 2511 << NoHostDevTy; 2512 } 2513 } 2514 2515 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 2516 const DeclarationNameInfo &DirName, 2517 Scope *CurScope, SourceLocation Loc) { 2518 DSAStack->push(DKind, DirName, CurScope, Loc); 2519 PushExpressionEvaluationContext( 2520 ExpressionEvaluationContext::PotentiallyEvaluated); 2521 } 2522 2523 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 2524 DSAStack->setClauseParsingMode(K); 2525 } 2526 2527 void Sema::EndOpenMPClause() { 2528 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 2529 CleanupVarDeclMarking(); 2530 } 2531 2532 static std::pair<ValueDecl *, bool> 2533 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 2534 SourceRange &ERange, bool AllowArraySection = false); 2535 2536 /// Check consistency of the reduction clauses. 2537 static void checkReductionClauses(Sema &S, DSAStackTy *Stack, 2538 ArrayRef<OMPClause *> Clauses) { 2539 bool InscanFound = false; 2540 SourceLocation InscanLoc; 2541 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions. 2542 // A reduction clause without the inscan reduction-modifier may not appear on 2543 // a construct on which a reduction clause with the inscan reduction-modifier 2544 // appears. 2545 for (OMPClause *C : Clauses) { 2546 if (C->getClauseKind() != OMPC_reduction) 2547 continue; 2548 auto *RC = cast<OMPReductionClause>(C); 2549 if (RC->getModifier() == OMPC_REDUCTION_inscan) { 2550 InscanFound = true; 2551 InscanLoc = RC->getModifierLoc(); 2552 continue; 2553 } 2554 if (RC->getModifier() == OMPC_REDUCTION_task) { 2555 // OpenMP 5.0, 2.19.5.4 reduction Clause. 2556 // A reduction clause with the task reduction-modifier may only appear on 2557 // a parallel construct, a worksharing construct or a combined or 2558 // composite construct for which any of the aforementioned constructs is a 2559 // constituent construct and simd or loop are not constituent constructs. 2560 OpenMPDirectiveKind CurDir = Stack->getCurrentDirective(); 2561 if (!(isOpenMPParallelDirective(CurDir) || 2562 isOpenMPWorksharingDirective(CurDir)) || 2563 isOpenMPSimdDirective(CurDir)) 2564 S.Diag(RC->getModifierLoc(), 2565 diag::err_omp_reduction_task_not_parallel_or_worksharing); 2566 continue; 2567 } 2568 } 2569 if (InscanFound) { 2570 for (OMPClause *C : Clauses) { 2571 if (C->getClauseKind() != OMPC_reduction) 2572 continue; 2573 auto *RC = cast<OMPReductionClause>(C); 2574 if (RC->getModifier() != OMPC_REDUCTION_inscan) { 2575 S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown 2576 ? RC->getBeginLoc() 2577 : RC->getModifierLoc(), 2578 diag::err_omp_inscan_reduction_expected); 2579 S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction); 2580 continue; 2581 } 2582 for (Expr *Ref : RC->varlists()) { 2583 assert(Ref && "NULL expr in OpenMP nontemporal clause."); 2584 SourceLocation ELoc; 2585 SourceRange ERange; 2586 Expr *SimpleRefExpr = Ref; 2587 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 2588 /*AllowArraySection=*/true); 2589 ValueDecl *D = Res.first; 2590 if (!D) 2591 continue; 2592 if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) { 2593 S.Diag(Ref->getExprLoc(), 2594 diag::err_omp_reduction_not_inclusive_exclusive) 2595 << Ref->getSourceRange(); 2596 } 2597 } 2598 } 2599 } 2600 } 2601 2602 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack, 2603 ArrayRef<OMPClause *> Clauses); 2604 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 2605 bool WithInit); 2606 2607 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 2608 const ValueDecl *D, 2609 const DSAStackTy::DSAVarData &DVar, 2610 bool IsLoopIterVar = false); 2611 2612 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 2613 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 2614 // A variable of class type (or array thereof) that appears in a lastprivate 2615 // clause requires an accessible, unambiguous default constructor for the 2616 // class type, unless the list item is also specified in a firstprivate 2617 // clause. 2618 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 2619 for (OMPClause *C : D->clauses()) { 2620 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 2621 SmallVector<Expr *, 8> PrivateCopies; 2622 for (Expr *DE : Clause->varlists()) { 2623 if (DE->isValueDependent() || DE->isTypeDependent()) { 2624 PrivateCopies.push_back(nullptr); 2625 continue; 2626 } 2627 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 2628 auto *VD = cast<VarDecl>(DRE->getDecl()); 2629 QualType Type = VD->getType().getNonReferenceType(); 2630 const DSAStackTy::DSAVarData DVar = 2631 DSAStack->getTopDSA(VD, /*FromParent=*/false); 2632 if (DVar.CKind == OMPC_lastprivate) { 2633 // Generate helper private variable and initialize it with the 2634 // default value. The address of the original variable is replaced 2635 // by the address of the new private variable in CodeGen. This new 2636 // variable is not added to IdResolver, so the code in the OpenMP 2637 // region uses original variable for proper diagnostics. 2638 VarDecl *VDPrivate = buildVarDecl( 2639 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 2640 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE); 2641 ActOnUninitializedDecl(VDPrivate); 2642 if (VDPrivate->isInvalidDecl()) { 2643 PrivateCopies.push_back(nullptr); 2644 continue; 2645 } 2646 PrivateCopies.push_back(buildDeclRefExpr( 2647 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 2648 } else { 2649 // The variable is also a firstprivate, so initialization sequence 2650 // for private copy is generated already. 2651 PrivateCopies.push_back(nullptr); 2652 } 2653 } 2654 Clause->setPrivateCopies(PrivateCopies); 2655 continue; 2656 } 2657 // Finalize nontemporal clause by handling private copies, if any. 2658 if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) { 2659 SmallVector<Expr *, 8> PrivateRefs; 2660 for (Expr *RefExpr : Clause->varlists()) { 2661 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 2662 SourceLocation ELoc; 2663 SourceRange ERange; 2664 Expr *SimpleRefExpr = RefExpr; 2665 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 2666 if (Res.second) 2667 // It will be analyzed later. 2668 PrivateRefs.push_back(RefExpr); 2669 ValueDecl *D = Res.first; 2670 if (!D) 2671 continue; 2672 2673 const DSAStackTy::DSAVarData DVar = 2674 DSAStack->getTopDSA(D, /*FromParent=*/false); 2675 PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy 2676 : SimpleRefExpr); 2677 } 2678 Clause->setPrivateRefs(PrivateRefs); 2679 continue; 2680 } 2681 if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) { 2682 for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) { 2683 OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I); 2684 auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts()); 2685 if (!DRE) 2686 continue; 2687 ValueDecl *VD = DRE->getDecl(); 2688 if (!VD || !isa<VarDecl>(VD)) 2689 continue; 2690 DSAStackTy::DSAVarData DVar = 2691 DSAStack->getTopDSA(VD, /*FromParent=*/false); 2692 // OpenMP [2.12.5, target Construct] 2693 // Memory allocators that appear in a uses_allocators clause cannot 2694 // appear in other data-sharing attribute clauses or data-mapping 2695 // attribute clauses in the same construct. 2696 Expr *MapExpr = nullptr; 2697 if (DVar.RefExpr || 2698 DSAStack->checkMappableExprComponentListsForDecl( 2699 VD, /*CurrentRegionOnly=*/true, 2700 [VD, &MapExpr]( 2701 OMPClauseMappableExprCommon::MappableExprComponentListRef 2702 MapExprComponents, 2703 OpenMPClauseKind C) { 2704 auto MI = MapExprComponents.rbegin(); 2705 auto ME = MapExprComponents.rend(); 2706 if (MI != ME && 2707 MI->getAssociatedDeclaration()->getCanonicalDecl() == 2708 VD->getCanonicalDecl()) { 2709 MapExpr = MI->getAssociatedExpression(); 2710 return true; 2711 } 2712 return false; 2713 })) { 2714 Diag(D.Allocator->getExprLoc(), 2715 diag::err_omp_allocator_used_in_clauses) 2716 << D.Allocator->getSourceRange(); 2717 if (DVar.RefExpr) 2718 reportOriginalDsa(*this, DSAStack, VD, DVar); 2719 else 2720 Diag(MapExpr->getExprLoc(), diag::note_used_here) 2721 << MapExpr->getSourceRange(); 2722 } 2723 } 2724 continue; 2725 } 2726 } 2727 // Check allocate clauses. 2728 if (!CurContext->isDependentContext()) 2729 checkAllocateClauses(*this, DSAStack, D->clauses()); 2730 checkReductionClauses(*this, DSAStack, D->clauses()); 2731 } 2732 2733 DSAStack->pop(); 2734 DiscardCleanupsInEvaluationContext(); 2735 PopExpressionEvaluationContext(); 2736 } 2737 2738 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 2739 Expr *NumIterations, Sema &SemaRef, 2740 Scope *S, DSAStackTy *Stack); 2741 2742 namespace { 2743 2744 class VarDeclFilterCCC final : public CorrectionCandidateCallback { 2745 private: 2746 Sema &SemaRef; 2747 2748 public: 2749 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 2750 bool ValidateCandidate(const TypoCorrection &Candidate) override { 2751 NamedDecl *ND = Candidate.getCorrectionDecl(); 2752 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 2753 return VD->hasGlobalStorage() && 2754 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 2755 SemaRef.getCurScope()); 2756 } 2757 return false; 2758 } 2759 2760 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2761 return std::make_unique<VarDeclFilterCCC>(*this); 2762 } 2763 }; 2764 2765 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback { 2766 private: 2767 Sema &SemaRef; 2768 2769 public: 2770 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 2771 bool ValidateCandidate(const TypoCorrection &Candidate) override { 2772 NamedDecl *ND = Candidate.getCorrectionDecl(); 2773 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) || 2774 isa<FunctionDecl>(ND))) { 2775 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 2776 SemaRef.getCurScope()); 2777 } 2778 return false; 2779 } 2780 2781 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2782 return std::make_unique<VarOrFuncDeclFilterCCC>(*this); 2783 } 2784 }; 2785 2786 } // namespace 2787 2788 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 2789 CXXScopeSpec &ScopeSpec, 2790 const DeclarationNameInfo &Id, 2791 OpenMPDirectiveKind Kind) { 2792 LookupResult Lookup(*this, Id, LookupOrdinaryName); 2793 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 2794 2795 if (Lookup.isAmbiguous()) 2796 return ExprError(); 2797 2798 VarDecl *VD; 2799 if (!Lookup.isSingleResult()) { 2800 VarDeclFilterCCC CCC(*this); 2801 if (TypoCorrection Corrected = 2802 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC, 2803 CTK_ErrorRecovery)) { 2804 diagnoseTypo(Corrected, 2805 PDiag(Lookup.empty() 2806 ? diag::err_undeclared_var_use_suggest 2807 : diag::err_omp_expected_var_arg_suggest) 2808 << Id.getName()); 2809 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 2810 } else { 2811 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 2812 : diag::err_omp_expected_var_arg) 2813 << Id.getName(); 2814 return ExprError(); 2815 } 2816 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) { 2817 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 2818 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 2819 return ExprError(); 2820 } 2821 Lookup.suppressDiagnostics(); 2822 2823 // OpenMP [2.9.2, Syntax, C/C++] 2824 // Variables must be file-scope, namespace-scope, or static block-scope. 2825 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) { 2826 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 2827 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal(); 2828 bool IsDecl = 2829 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2830 Diag(VD->getLocation(), 2831 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2832 << VD; 2833 return ExprError(); 2834 } 2835 2836 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 2837 NamedDecl *ND = CanonicalVD; 2838 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 2839 // A threadprivate directive for file-scope variables must appear outside 2840 // any definition or declaration. 2841 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 2842 !getCurLexicalContext()->isTranslationUnit()) { 2843 Diag(Id.getLoc(), diag::err_omp_var_scope) 2844 << getOpenMPDirectiveName(Kind) << VD; 2845 bool IsDecl = 2846 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2847 Diag(VD->getLocation(), 2848 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2849 << VD; 2850 return ExprError(); 2851 } 2852 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 2853 // A threadprivate directive for static class member variables must appear 2854 // in the class definition, in the same scope in which the member 2855 // variables are declared. 2856 if (CanonicalVD->isStaticDataMember() && 2857 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 2858 Diag(Id.getLoc(), diag::err_omp_var_scope) 2859 << getOpenMPDirectiveName(Kind) << VD; 2860 bool IsDecl = 2861 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2862 Diag(VD->getLocation(), 2863 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2864 << VD; 2865 return ExprError(); 2866 } 2867 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 2868 // A threadprivate directive for namespace-scope variables must appear 2869 // outside any definition or declaration other than the namespace 2870 // definition itself. 2871 if (CanonicalVD->getDeclContext()->isNamespace() && 2872 (!getCurLexicalContext()->isFileContext() || 2873 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 2874 Diag(Id.getLoc(), diag::err_omp_var_scope) 2875 << getOpenMPDirectiveName(Kind) << VD; 2876 bool IsDecl = 2877 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2878 Diag(VD->getLocation(), 2879 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2880 << VD; 2881 return ExprError(); 2882 } 2883 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 2884 // A threadprivate directive for static block-scope variables must appear 2885 // in the scope of the variable and not in a nested scope. 2886 if (CanonicalVD->isLocalVarDecl() && CurScope && 2887 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 2888 Diag(Id.getLoc(), diag::err_omp_var_scope) 2889 << getOpenMPDirectiveName(Kind) << VD; 2890 bool IsDecl = 2891 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2892 Diag(VD->getLocation(), 2893 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2894 << VD; 2895 return ExprError(); 2896 } 2897 2898 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 2899 // A threadprivate directive must lexically precede all references to any 2900 // of the variables in its list. 2901 if (Kind == OMPD_threadprivate && VD->isUsed() && 2902 !DSAStack->isThreadPrivate(VD)) { 2903 Diag(Id.getLoc(), diag::err_omp_var_used) 2904 << getOpenMPDirectiveName(Kind) << VD; 2905 return ExprError(); 2906 } 2907 2908 QualType ExprType = VD->getType().getNonReferenceType(); 2909 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 2910 SourceLocation(), VD, 2911 /*RefersToEnclosingVariableOrCapture=*/false, 2912 Id.getLoc(), ExprType, VK_LValue); 2913 } 2914 2915 Sema::DeclGroupPtrTy 2916 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 2917 ArrayRef<Expr *> VarList) { 2918 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 2919 CurContext->addDecl(D); 2920 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2921 } 2922 return nullptr; 2923 } 2924 2925 namespace { 2926 class LocalVarRefChecker final 2927 : public ConstStmtVisitor<LocalVarRefChecker, bool> { 2928 Sema &SemaRef; 2929 2930 public: 2931 bool VisitDeclRefExpr(const DeclRefExpr *E) { 2932 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 2933 if (VD->hasLocalStorage()) { 2934 SemaRef.Diag(E->getBeginLoc(), 2935 diag::err_omp_local_var_in_threadprivate_init) 2936 << E->getSourceRange(); 2937 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 2938 << VD << VD->getSourceRange(); 2939 return true; 2940 } 2941 } 2942 return false; 2943 } 2944 bool VisitStmt(const Stmt *S) { 2945 for (const Stmt *Child : S->children()) { 2946 if (Child && Visit(Child)) 2947 return true; 2948 } 2949 return false; 2950 } 2951 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 2952 }; 2953 } // namespace 2954 2955 OMPThreadPrivateDecl * 2956 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 2957 SmallVector<Expr *, 8> Vars; 2958 for (Expr *RefExpr : VarList) { 2959 auto *DE = cast<DeclRefExpr>(RefExpr); 2960 auto *VD = cast<VarDecl>(DE->getDecl()); 2961 SourceLocation ILoc = DE->getExprLoc(); 2962 2963 // Mark variable as used. 2964 VD->setReferenced(); 2965 VD->markUsed(Context); 2966 2967 QualType QType = VD->getType(); 2968 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 2969 // It will be analyzed later. 2970 Vars.push_back(DE); 2971 continue; 2972 } 2973 2974 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2975 // A threadprivate variable must not have an incomplete type. 2976 if (RequireCompleteType(ILoc, VD->getType(), 2977 diag::err_omp_threadprivate_incomplete_type)) { 2978 continue; 2979 } 2980 2981 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2982 // A threadprivate variable must not have a reference type. 2983 if (VD->getType()->isReferenceType()) { 2984 Diag(ILoc, diag::err_omp_ref_type_arg) 2985 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 2986 bool IsDecl = 2987 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2988 Diag(VD->getLocation(), 2989 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2990 << VD; 2991 continue; 2992 } 2993 2994 // Check if this is a TLS variable. If TLS is not being supported, produce 2995 // the corresponding diagnostic. 2996 if ((VD->getTLSKind() != VarDecl::TLS_None && 2997 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 2998 getLangOpts().OpenMPUseTLS && 2999 getASTContext().getTargetInfo().isTLSSupported())) || 3000 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 3001 !VD->isLocalVarDecl())) { 3002 Diag(ILoc, diag::err_omp_var_thread_local) 3003 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 3004 bool IsDecl = 3005 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 3006 Diag(VD->getLocation(), 3007 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 3008 << VD; 3009 continue; 3010 } 3011 3012 // Check if initial value of threadprivate variable reference variable with 3013 // local storage (it is not supported by runtime). 3014 if (const Expr *Init = VD->getAnyInitializer()) { 3015 LocalVarRefChecker Checker(*this); 3016 if (Checker.Visit(Init)) 3017 continue; 3018 } 3019 3020 Vars.push_back(RefExpr); 3021 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 3022 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 3023 Context, SourceRange(Loc, Loc))); 3024 if (ASTMutationListener *ML = Context.getASTMutationListener()) 3025 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 3026 } 3027 OMPThreadPrivateDecl *D = nullptr; 3028 if (!Vars.empty()) { 3029 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 3030 Vars); 3031 D->setAccess(AS_public); 3032 } 3033 return D; 3034 } 3035 3036 static OMPAllocateDeclAttr::AllocatorTypeTy 3037 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) { 3038 if (!Allocator) 3039 return OMPAllocateDeclAttr::OMPNullMemAlloc; 3040 if (Allocator->isTypeDependent() || Allocator->isValueDependent() || 3041 Allocator->isInstantiationDependent() || 3042 Allocator->containsUnexpandedParameterPack()) 3043 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; 3044 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; 3045 const Expr *AE = Allocator->IgnoreParenImpCasts(); 3046 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 3047 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 3048 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind); 3049 llvm::FoldingSetNodeID AEId, DAEId; 3050 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true); 3051 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true); 3052 if (AEId == DAEId) { 3053 AllocatorKindRes = AllocatorKind; 3054 break; 3055 } 3056 } 3057 return AllocatorKindRes; 3058 } 3059 3060 static bool checkPreviousOMPAllocateAttribute( 3061 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD, 3062 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) { 3063 if (!VD->hasAttr<OMPAllocateDeclAttr>()) 3064 return false; 3065 const auto *A = VD->getAttr<OMPAllocateDeclAttr>(); 3066 Expr *PrevAllocator = A->getAllocator(); 3067 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind = 3068 getAllocatorKind(S, Stack, PrevAllocator); 3069 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind; 3070 if (AllocatorsMatch && 3071 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc && 3072 Allocator && PrevAllocator) { 3073 const Expr *AE = Allocator->IgnoreParenImpCasts(); 3074 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts(); 3075 llvm::FoldingSetNodeID AEId, PAEId; 3076 AE->Profile(AEId, S.Context, /*Canonical=*/true); 3077 PAE->Profile(PAEId, S.Context, /*Canonical=*/true); 3078 AllocatorsMatch = AEId == PAEId; 3079 } 3080 if (!AllocatorsMatch) { 3081 SmallString<256> AllocatorBuffer; 3082 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer); 3083 if (Allocator) 3084 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy()); 3085 SmallString<256> PrevAllocatorBuffer; 3086 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer); 3087 if (PrevAllocator) 3088 PrevAllocator->printPretty(PrevAllocatorStream, nullptr, 3089 S.getPrintingPolicy()); 3090 3091 SourceLocation AllocatorLoc = 3092 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc(); 3093 SourceRange AllocatorRange = 3094 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange(); 3095 SourceLocation PrevAllocatorLoc = 3096 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation(); 3097 SourceRange PrevAllocatorRange = 3098 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange(); 3099 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator) 3100 << (Allocator ? 1 : 0) << AllocatorStream.str() 3101 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str() 3102 << AllocatorRange; 3103 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator) 3104 << PrevAllocatorRange; 3105 return true; 3106 } 3107 return false; 3108 } 3109 3110 static void 3111 applyOMPAllocateAttribute(Sema &S, VarDecl *VD, 3112 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, 3113 Expr *Allocator, Expr *Alignment, SourceRange SR) { 3114 if (VD->hasAttr<OMPAllocateDeclAttr>()) 3115 return; 3116 if (Alignment && 3117 (Alignment->isTypeDependent() || Alignment->isValueDependent() || 3118 Alignment->isInstantiationDependent() || 3119 Alignment->containsUnexpandedParameterPack())) 3120 // Apply later when we have a usable value. 3121 return; 3122 if (Allocator && 3123 (Allocator->isTypeDependent() || Allocator->isValueDependent() || 3124 Allocator->isInstantiationDependent() || 3125 Allocator->containsUnexpandedParameterPack())) 3126 return; 3127 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind, 3128 Allocator, Alignment, SR); 3129 VD->addAttr(A); 3130 if (ASTMutationListener *ML = S.Context.getASTMutationListener()) 3131 ML->DeclarationMarkedOpenMPAllocate(VD, A); 3132 } 3133 3134 Sema::DeclGroupPtrTy 3135 Sema::ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList, 3136 ArrayRef<OMPClause *> Clauses, 3137 DeclContext *Owner) { 3138 assert(Clauses.size() <= 2 && "Expected at most two clauses."); 3139 Expr *Alignment = nullptr; 3140 Expr *Allocator = nullptr; 3141 if (Clauses.empty()) { 3142 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions. 3143 // allocate directives that appear in a target region must specify an 3144 // allocator clause unless a requires directive with the dynamic_allocators 3145 // clause is present in the same compilation unit. 3146 if (LangOpts.OpenMPIsDevice && 3147 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>()) 3148 targetDiag(Loc, diag::err_expected_allocator_clause); 3149 } else { 3150 for (const OMPClause *C : Clauses) 3151 if (const auto *AC = dyn_cast<OMPAllocatorClause>(C)) 3152 Allocator = AC->getAllocator(); 3153 else if (const auto *AC = dyn_cast<OMPAlignClause>(C)) 3154 Alignment = AC->getAlignment(); 3155 else 3156 llvm_unreachable("Unexpected clause on allocate directive"); 3157 } 3158 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind = 3159 getAllocatorKind(*this, DSAStack, Allocator); 3160 SmallVector<Expr *, 8> Vars; 3161 for (Expr *RefExpr : VarList) { 3162 auto *DE = cast<DeclRefExpr>(RefExpr); 3163 auto *VD = cast<VarDecl>(DE->getDecl()); 3164 3165 // Check if this is a TLS variable or global register. 3166 if (VD->getTLSKind() != VarDecl::TLS_None || 3167 VD->hasAttr<OMPThreadPrivateDeclAttr>() || 3168 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 3169 !VD->isLocalVarDecl())) 3170 continue; 3171 3172 // If the used several times in the allocate directive, the same allocator 3173 // must be used. 3174 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD, 3175 AllocatorKind, Allocator)) 3176 continue; 3177 3178 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++ 3179 // If a list item has a static storage type, the allocator expression in the 3180 // allocator clause must be a constant expression that evaluates to one of 3181 // the predefined memory allocator values. 3182 if (Allocator && VD->hasGlobalStorage()) { 3183 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) { 3184 Diag(Allocator->getExprLoc(), 3185 diag::err_omp_expected_predefined_allocator) 3186 << Allocator->getSourceRange(); 3187 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 3188 VarDecl::DeclarationOnly; 3189 Diag(VD->getLocation(), 3190 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 3191 << VD; 3192 continue; 3193 } 3194 } 3195 3196 Vars.push_back(RefExpr); 3197 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator, Alignment, 3198 DE->getSourceRange()); 3199 } 3200 if (Vars.empty()) 3201 return nullptr; 3202 if (!Owner) 3203 Owner = getCurLexicalContext(); 3204 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses); 3205 D->setAccess(AS_public); 3206 Owner->addDecl(D); 3207 return DeclGroupPtrTy::make(DeclGroupRef(D)); 3208 } 3209 3210 Sema::DeclGroupPtrTy 3211 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc, 3212 ArrayRef<OMPClause *> ClauseList) { 3213 OMPRequiresDecl *D = nullptr; 3214 if (!CurContext->isFileContext()) { 3215 Diag(Loc, diag::err_omp_invalid_scope) << "requires"; 3216 } else { 3217 D = CheckOMPRequiresDecl(Loc, ClauseList); 3218 if (D) { 3219 CurContext->addDecl(D); 3220 DSAStack->addRequiresDecl(D); 3221 } 3222 } 3223 return DeclGroupPtrTy::make(DeclGroupRef(D)); 3224 } 3225 3226 void Sema::ActOnOpenMPAssumesDirective(SourceLocation Loc, 3227 OpenMPDirectiveKind DKind, 3228 ArrayRef<std::string> Assumptions, 3229 bool SkippedClauses) { 3230 if (!SkippedClauses && Assumptions.empty()) 3231 Diag(Loc, diag::err_omp_no_clause_for_directive) 3232 << llvm::omp::getAllAssumeClauseOptions() 3233 << llvm::omp::getOpenMPDirectiveName(DKind); 3234 3235 auto *AA = AssumptionAttr::Create(Context, llvm::join(Assumptions, ","), Loc); 3236 if (DKind == llvm::omp::Directive::OMPD_begin_assumes) { 3237 OMPAssumeScoped.push_back(AA); 3238 return; 3239 } 3240 3241 // Global assumes without assumption clauses are ignored. 3242 if (Assumptions.empty()) 3243 return; 3244 3245 assert(DKind == llvm::omp::Directive::OMPD_assumes && 3246 "Unexpected omp assumption directive!"); 3247 OMPAssumeGlobal.push_back(AA); 3248 3249 // The OMPAssumeGlobal scope above will take care of new declarations but 3250 // we also want to apply the assumption to existing ones, e.g., to 3251 // declarations in included headers. To this end, we traverse all existing 3252 // declaration contexts and annotate function declarations here. 3253 SmallVector<DeclContext *, 8> DeclContexts; 3254 auto *Ctx = CurContext; 3255 while (Ctx->getLexicalParent()) 3256 Ctx = Ctx->getLexicalParent(); 3257 DeclContexts.push_back(Ctx); 3258 while (!DeclContexts.empty()) { 3259 DeclContext *DC = DeclContexts.pop_back_val(); 3260 for (auto *SubDC : DC->decls()) { 3261 if (SubDC->isInvalidDecl()) 3262 continue; 3263 if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) { 3264 DeclContexts.push_back(CTD->getTemplatedDecl()); 3265 for (auto *S : CTD->specializations()) 3266 DeclContexts.push_back(S); 3267 continue; 3268 } 3269 if (auto *DC = dyn_cast<DeclContext>(SubDC)) 3270 DeclContexts.push_back(DC); 3271 if (auto *F = dyn_cast<FunctionDecl>(SubDC)) { 3272 F->addAttr(AA); 3273 continue; 3274 } 3275 } 3276 } 3277 } 3278 3279 void Sema::ActOnOpenMPEndAssumesDirective() { 3280 assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!"); 3281 OMPAssumeScoped.pop_back(); 3282 } 3283 3284 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc, 3285 ArrayRef<OMPClause *> ClauseList) { 3286 /// For target specific clauses, the requires directive cannot be 3287 /// specified after the handling of any of the target regions in the 3288 /// current compilation unit. 3289 ArrayRef<SourceLocation> TargetLocations = 3290 DSAStack->getEncounteredTargetLocs(); 3291 SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc(); 3292 if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) { 3293 for (const OMPClause *CNew : ClauseList) { 3294 // Check if any of the requires clauses affect target regions. 3295 if (isa<OMPUnifiedSharedMemoryClause>(CNew) || 3296 isa<OMPUnifiedAddressClause>(CNew) || 3297 isa<OMPReverseOffloadClause>(CNew) || 3298 isa<OMPDynamicAllocatorsClause>(CNew)) { 3299 Diag(Loc, diag::err_omp_directive_before_requires) 3300 << "target" << getOpenMPClauseName(CNew->getClauseKind()); 3301 for (SourceLocation TargetLoc : TargetLocations) { 3302 Diag(TargetLoc, diag::note_omp_requires_encountered_directive) 3303 << "target"; 3304 } 3305 } else if (!AtomicLoc.isInvalid() && 3306 isa<OMPAtomicDefaultMemOrderClause>(CNew)) { 3307 Diag(Loc, diag::err_omp_directive_before_requires) 3308 << "atomic" << getOpenMPClauseName(CNew->getClauseKind()); 3309 Diag(AtomicLoc, diag::note_omp_requires_encountered_directive) 3310 << "atomic"; 3311 } 3312 } 3313 } 3314 3315 if (!DSAStack->hasDuplicateRequiresClause(ClauseList)) 3316 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc, 3317 ClauseList); 3318 return nullptr; 3319 } 3320 3321 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 3322 const ValueDecl *D, 3323 const DSAStackTy::DSAVarData &DVar, 3324 bool IsLoopIterVar) { 3325 if (DVar.RefExpr) { 3326 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 3327 << getOpenMPClauseName(DVar.CKind); 3328 return; 3329 } 3330 enum { 3331 PDSA_StaticMemberShared, 3332 PDSA_StaticLocalVarShared, 3333 PDSA_LoopIterVarPrivate, 3334 PDSA_LoopIterVarLinear, 3335 PDSA_LoopIterVarLastprivate, 3336 PDSA_ConstVarShared, 3337 PDSA_GlobalVarShared, 3338 PDSA_TaskVarFirstprivate, 3339 PDSA_LocalVarPrivate, 3340 PDSA_Implicit 3341 } Reason = PDSA_Implicit; 3342 bool ReportHint = false; 3343 auto ReportLoc = D->getLocation(); 3344 auto *VD = dyn_cast<VarDecl>(D); 3345 if (IsLoopIterVar) { 3346 if (DVar.CKind == OMPC_private) 3347 Reason = PDSA_LoopIterVarPrivate; 3348 else if (DVar.CKind == OMPC_lastprivate) 3349 Reason = PDSA_LoopIterVarLastprivate; 3350 else 3351 Reason = PDSA_LoopIterVarLinear; 3352 } else if (isOpenMPTaskingDirective(DVar.DKind) && 3353 DVar.CKind == OMPC_firstprivate) { 3354 Reason = PDSA_TaskVarFirstprivate; 3355 ReportLoc = DVar.ImplicitDSALoc; 3356 } else if (VD && VD->isStaticLocal()) 3357 Reason = PDSA_StaticLocalVarShared; 3358 else if (VD && VD->isStaticDataMember()) 3359 Reason = PDSA_StaticMemberShared; 3360 else if (VD && VD->isFileVarDecl()) 3361 Reason = PDSA_GlobalVarShared; 3362 else if (D->getType().isConstant(SemaRef.getASTContext())) 3363 Reason = PDSA_ConstVarShared; 3364 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 3365 ReportHint = true; 3366 Reason = PDSA_LocalVarPrivate; 3367 } 3368 if (Reason != PDSA_Implicit) { 3369 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 3370 << Reason << ReportHint 3371 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 3372 } else if (DVar.ImplicitDSALoc.isValid()) { 3373 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 3374 << getOpenMPClauseName(DVar.CKind); 3375 } 3376 } 3377 3378 static OpenMPMapClauseKind 3379 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M, 3380 bool IsAggregateOrDeclareTarget) { 3381 OpenMPMapClauseKind Kind = OMPC_MAP_unknown; 3382 switch (M) { 3383 case OMPC_DEFAULTMAP_MODIFIER_alloc: 3384 Kind = OMPC_MAP_alloc; 3385 break; 3386 case OMPC_DEFAULTMAP_MODIFIER_to: 3387 Kind = OMPC_MAP_to; 3388 break; 3389 case OMPC_DEFAULTMAP_MODIFIER_from: 3390 Kind = OMPC_MAP_from; 3391 break; 3392 case OMPC_DEFAULTMAP_MODIFIER_tofrom: 3393 Kind = OMPC_MAP_tofrom; 3394 break; 3395 case OMPC_DEFAULTMAP_MODIFIER_present: 3396 // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description] 3397 // If implicit-behavior is present, each variable referenced in the 3398 // construct in the category specified by variable-category is treated as if 3399 // it had been listed in a map clause with the map-type of alloc and 3400 // map-type-modifier of present. 3401 Kind = OMPC_MAP_alloc; 3402 break; 3403 case OMPC_DEFAULTMAP_MODIFIER_firstprivate: 3404 case OMPC_DEFAULTMAP_MODIFIER_last: 3405 llvm_unreachable("Unexpected defaultmap implicit behavior"); 3406 case OMPC_DEFAULTMAP_MODIFIER_none: 3407 case OMPC_DEFAULTMAP_MODIFIER_default: 3408 case OMPC_DEFAULTMAP_MODIFIER_unknown: 3409 // IsAggregateOrDeclareTarget could be true if: 3410 // 1. the implicit behavior for aggregate is tofrom 3411 // 2. it's a declare target link 3412 if (IsAggregateOrDeclareTarget) { 3413 Kind = OMPC_MAP_tofrom; 3414 break; 3415 } 3416 llvm_unreachable("Unexpected defaultmap implicit behavior"); 3417 } 3418 assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known"); 3419 return Kind; 3420 } 3421 3422 namespace { 3423 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> { 3424 DSAStackTy *Stack; 3425 Sema &SemaRef; 3426 bool ErrorFound = false; 3427 bool TryCaptureCXXThisMembers = false; 3428 CapturedStmt *CS = nullptr; 3429 const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1; 3430 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate; 3431 llvm::SmallVector<Expr *, 4> ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete]; 3432 llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> 3433 ImplicitMapModifier[DefaultmapKindNum]; 3434 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA; 3435 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations; 3436 3437 void VisitSubCaptures(OMPExecutableDirective *S) { 3438 // Check implicitly captured variables. 3439 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt()) 3440 return; 3441 if (S->getDirectiveKind() == OMPD_atomic || 3442 S->getDirectiveKind() == OMPD_critical || 3443 S->getDirectiveKind() == OMPD_section || 3444 S->getDirectiveKind() == OMPD_master || 3445 S->getDirectiveKind() == OMPD_masked || 3446 isOpenMPLoopTransformationDirective(S->getDirectiveKind())) { 3447 Visit(S->getAssociatedStmt()); 3448 return; 3449 } 3450 visitSubCaptures(S->getInnermostCapturedStmt()); 3451 // Try to capture inner this->member references to generate correct mappings 3452 // and diagnostics. 3453 if (TryCaptureCXXThisMembers || 3454 (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 3455 llvm::any_of(S->getInnermostCapturedStmt()->captures(), 3456 [](const CapturedStmt::Capture &C) { 3457 return C.capturesThis(); 3458 }))) { 3459 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers; 3460 TryCaptureCXXThisMembers = true; 3461 Visit(S->getInnermostCapturedStmt()->getCapturedStmt()); 3462 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers; 3463 } 3464 // In tasks firstprivates are not captured anymore, need to analyze them 3465 // explicitly. 3466 if (isOpenMPTaskingDirective(S->getDirectiveKind()) && 3467 !isOpenMPTaskLoopDirective(S->getDirectiveKind())) { 3468 for (OMPClause *C : S->clauses()) 3469 if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) { 3470 for (Expr *Ref : FC->varlists()) 3471 Visit(Ref); 3472 } 3473 } 3474 } 3475 3476 public: 3477 void VisitDeclRefExpr(DeclRefExpr *E) { 3478 if (TryCaptureCXXThisMembers || E->isTypeDependent() || 3479 E->isValueDependent() || E->containsUnexpandedParameterPack() || 3480 E->isInstantiationDependent()) 3481 return; 3482 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 3483 // Check the datasharing rules for the expressions in the clauses. 3484 if (!CS || (isa<OMPCapturedExprDecl>(VD) && !CS->capturesVariable(VD) && 3485 !Stack->getTopDSA(VD, /*FromParent=*/false).RefExpr)) { 3486 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD)) 3487 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) { 3488 Visit(CED->getInit()); 3489 return; 3490 } 3491 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD)) 3492 // Do not analyze internal variables and do not enclose them into 3493 // implicit clauses. 3494 return; 3495 VD = VD->getCanonicalDecl(); 3496 // Skip internally declared variables. 3497 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) && 3498 !Stack->isImplicitTaskFirstprivate(VD)) 3499 return; 3500 // Skip allocators in uses_allocators clauses. 3501 if (Stack->isUsesAllocatorsDecl(VD).hasValue()) 3502 return; 3503 3504 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 3505 // Check if the variable has explicit DSA set and stop analysis if it so. 3506 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second) 3507 return; 3508 3509 // Skip internally declared static variables. 3510 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 3511 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 3512 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) && 3513 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || 3514 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) && 3515 !Stack->isImplicitTaskFirstprivate(VD)) 3516 return; 3517 3518 SourceLocation ELoc = E->getExprLoc(); 3519 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 3520 // The default(none) clause requires that each variable that is referenced 3521 // in the construct, and does not have a predetermined data-sharing 3522 // attribute, must have its data-sharing attribute explicitly determined 3523 // by being listed in a data-sharing attribute clause. 3524 if (DVar.CKind == OMPC_unknown && 3525 (Stack->getDefaultDSA() == DSA_none || 3526 Stack->getDefaultDSA() == DSA_firstprivate) && 3527 isImplicitOrExplicitTaskingRegion(DKind) && 3528 VarsWithInheritedDSA.count(VD) == 0) { 3529 bool InheritedDSA = Stack->getDefaultDSA() == DSA_none; 3530 if (!InheritedDSA && Stack->getDefaultDSA() == DSA_firstprivate) { 3531 DSAStackTy::DSAVarData DVar = 3532 Stack->getImplicitDSA(VD, /*FromParent=*/false); 3533 InheritedDSA = DVar.CKind == OMPC_unknown; 3534 } 3535 if (InheritedDSA) 3536 VarsWithInheritedDSA[VD] = E; 3537 return; 3538 } 3539 3540 // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description] 3541 // If implicit-behavior is none, each variable referenced in the 3542 // construct that does not have a predetermined data-sharing attribute 3543 // and does not appear in a to or link clause on a declare target 3544 // directive must be listed in a data-mapping attribute clause, a 3545 // data-haring attribute clause (including a data-sharing attribute 3546 // clause on a combined construct where target. is one of the 3547 // constituent constructs), or an is_device_ptr clause. 3548 OpenMPDefaultmapClauseKind ClauseKind = 3549 getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD); 3550 if (SemaRef.getLangOpts().OpenMP >= 50) { 3551 bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) == 3552 OMPC_DEFAULTMAP_MODIFIER_none; 3553 if (DVar.CKind == OMPC_unknown && IsModifierNone && 3554 VarsWithInheritedDSA.count(VD) == 0 && !Res) { 3555 // Only check for data-mapping attribute and is_device_ptr here 3556 // since we have already make sure that the declaration does not 3557 // have a data-sharing attribute above 3558 if (!Stack->checkMappableExprComponentListsForDecl( 3559 VD, /*CurrentRegionOnly=*/true, 3560 [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef 3561 MapExprComponents, 3562 OpenMPClauseKind) { 3563 auto MI = MapExprComponents.rbegin(); 3564 auto ME = MapExprComponents.rend(); 3565 return MI != ME && MI->getAssociatedDeclaration() == VD; 3566 })) { 3567 VarsWithInheritedDSA[VD] = E; 3568 return; 3569 } 3570 } 3571 } 3572 if (SemaRef.getLangOpts().OpenMP > 50) { 3573 bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) == 3574 OMPC_DEFAULTMAP_MODIFIER_present; 3575 if (IsModifierPresent) { 3576 if (llvm::find(ImplicitMapModifier[ClauseKind], 3577 OMPC_MAP_MODIFIER_present) == 3578 std::end(ImplicitMapModifier[ClauseKind])) { 3579 ImplicitMapModifier[ClauseKind].push_back( 3580 OMPC_MAP_MODIFIER_present); 3581 } 3582 } 3583 } 3584 3585 if (isOpenMPTargetExecutionDirective(DKind) && 3586 !Stack->isLoopControlVariable(VD).first) { 3587 if (!Stack->checkMappableExprComponentListsForDecl( 3588 VD, /*CurrentRegionOnly=*/true, 3589 [this](OMPClauseMappableExprCommon::MappableExprComponentListRef 3590 StackComponents, 3591 OpenMPClauseKind) { 3592 if (SemaRef.LangOpts.OpenMP >= 50) 3593 return !StackComponents.empty(); 3594 // Variable is used if it has been marked as an array, array 3595 // section, array shaping or the variable iself. 3596 return StackComponents.size() == 1 || 3597 std::all_of( 3598 std::next(StackComponents.rbegin()), 3599 StackComponents.rend(), 3600 [](const OMPClauseMappableExprCommon:: 3601 MappableComponent &MC) { 3602 return MC.getAssociatedDeclaration() == 3603 nullptr && 3604 (isa<OMPArraySectionExpr>( 3605 MC.getAssociatedExpression()) || 3606 isa<OMPArrayShapingExpr>( 3607 MC.getAssociatedExpression()) || 3608 isa<ArraySubscriptExpr>( 3609 MC.getAssociatedExpression())); 3610 }); 3611 })) { 3612 bool IsFirstprivate = false; 3613 // By default lambdas are captured as firstprivates. 3614 if (const auto *RD = 3615 VD->getType().getNonReferenceType()->getAsCXXRecordDecl()) 3616 IsFirstprivate = RD->isLambda(); 3617 IsFirstprivate = 3618 IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res); 3619 if (IsFirstprivate) { 3620 ImplicitFirstprivate.emplace_back(E); 3621 } else { 3622 OpenMPDefaultmapClauseModifier M = 3623 Stack->getDefaultmapModifier(ClauseKind); 3624 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier( 3625 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res); 3626 ImplicitMap[ClauseKind][Kind].emplace_back(E); 3627 } 3628 return; 3629 } 3630 } 3631 3632 // OpenMP [2.9.3.6, Restrictions, p.2] 3633 // A list item that appears in a reduction clause of the innermost 3634 // enclosing worksharing or parallel construct may not be accessed in an 3635 // explicit task. 3636 DVar = Stack->hasInnermostDSA( 3637 VD, 3638 [](OpenMPClauseKind C, bool AppliedToPointee) { 3639 return C == OMPC_reduction && !AppliedToPointee; 3640 }, 3641 [](OpenMPDirectiveKind K) { 3642 return isOpenMPParallelDirective(K) || 3643 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 3644 }, 3645 /*FromParent=*/true); 3646 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 3647 ErrorFound = true; 3648 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 3649 reportOriginalDsa(SemaRef, Stack, VD, DVar); 3650 return; 3651 } 3652 3653 // Define implicit data-sharing attributes for task. 3654 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false); 3655 if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) || 3656 (Stack->getDefaultDSA() == DSA_firstprivate && 3657 DVar.CKind == OMPC_firstprivate && !DVar.RefExpr)) && 3658 !Stack->isLoopControlVariable(VD).first) { 3659 ImplicitFirstprivate.push_back(E); 3660 return; 3661 } 3662 3663 // Store implicitly used globals with declare target link for parent 3664 // target. 3665 if (!isOpenMPTargetExecutionDirective(DKind) && Res && 3666 *Res == OMPDeclareTargetDeclAttr::MT_Link) { 3667 Stack->addToParentTargetRegionLinkGlobals(E); 3668 return; 3669 } 3670 } 3671 } 3672 void VisitMemberExpr(MemberExpr *E) { 3673 if (E->isTypeDependent() || E->isValueDependent() || 3674 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 3675 return; 3676 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 3677 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 3678 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) { 3679 if (!FD) 3680 return; 3681 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false); 3682 // Check if the variable has explicit DSA set and stop analysis if it 3683 // so. 3684 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second) 3685 return; 3686 3687 if (isOpenMPTargetExecutionDirective(DKind) && 3688 !Stack->isLoopControlVariable(FD).first && 3689 !Stack->checkMappableExprComponentListsForDecl( 3690 FD, /*CurrentRegionOnly=*/true, 3691 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 3692 StackComponents, 3693 OpenMPClauseKind) { 3694 return isa<CXXThisExpr>( 3695 cast<MemberExpr>( 3696 StackComponents.back().getAssociatedExpression()) 3697 ->getBase() 3698 ->IgnoreParens()); 3699 })) { 3700 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 3701 // A bit-field cannot appear in a map clause. 3702 // 3703 if (FD->isBitField()) 3704 return; 3705 3706 // Check to see if the member expression is referencing a class that 3707 // has already been explicitly mapped 3708 if (Stack->isClassPreviouslyMapped(TE->getType())) 3709 return; 3710 3711 OpenMPDefaultmapClauseModifier Modifier = 3712 Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate); 3713 OpenMPDefaultmapClauseKind ClauseKind = 3714 getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD); 3715 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier( 3716 Modifier, /*IsAggregateOrDeclareTarget*/ true); 3717 ImplicitMap[ClauseKind][Kind].emplace_back(E); 3718 return; 3719 } 3720 3721 SourceLocation ELoc = E->getExprLoc(); 3722 // OpenMP [2.9.3.6, Restrictions, p.2] 3723 // A list item that appears in a reduction clause of the innermost 3724 // enclosing worksharing or parallel construct may not be accessed in 3725 // an explicit task. 3726 DVar = Stack->hasInnermostDSA( 3727 FD, 3728 [](OpenMPClauseKind C, bool AppliedToPointee) { 3729 return C == OMPC_reduction && !AppliedToPointee; 3730 }, 3731 [](OpenMPDirectiveKind K) { 3732 return isOpenMPParallelDirective(K) || 3733 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 3734 }, 3735 /*FromParent=*/true); 3736 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 3737 ErrorFound = true; 3738 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 3739 reportOriginalDsa(SemaRef, Stack, FD, DVar); 3740 return; 3741 } 3742 3743 // Define implicit data-sharing attributes for task. 3744 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false); 3745 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 3746 !Stack->isLoopControlVariable(FD).first) { 3747 // Check if there is a captured expression for the current field in the 3748 // region. Do not mark it as firstprivate unless there is no captured 3749 // expression. 3750 // TODO: try to make it firstprivate. 3751 if (DVar.CKind != OMPC_unknown) 3752 ImplicitFirstprivate.push_back(E); 3753 } 3754 return; 3755 } 3756 if (isOpenMPTargetExecutionDirective(DKind)) { 3757 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 3758 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map, 3759 Stack->getCurrentDirective(), 3760 /*NoDiagnose=*/true)) 3761 return; 3762 const auto *VD = cast<ValueDecl>( 3763 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl()); 3764 if (!Stack->checkMappableExprComponentListsForDecl( 3765 VD, /*CurrentRegionOnly=*/true, 3766 [&CurComponents]( 3767 OMPClauseMappableExprCommon::MappableExprComponentListRef 3768 StackComponents, 3769 OpenMPClauseKind) { 3770 auto CCI = CurComponents.rbegin(); 3771 auto CCE = CurComponents.rend(); 3772 for (const auto &SC : llvm::reverse(StackComponents)) { 3773 // Do both expressions have the same kind? 3774 if (CCI->getAssociatedExpression()->getStmtClass() != 3775 SC.getAssociatedExpression()->getStmtClass()) 3776 if (!((isa<OMPArraySectionExpr>( 3777 SC.getAssociatedExpression()) || 3778 isa<OMPArrayShapingExpr>( 3779 SC.getAssociatedExpression())) && 3780 isa<ArraySubscriptExpr>( 3781 CCI->getAssociatedExpression()))) 3782 return false; 3783 3784 const Decl *CCD = CCI->getAssociatedDeclaration(); 3785 const Decl *SCD = SC.getAssociatedDeclaration(); 3786 CCD = CCD ? CCD->getCanonicalDecl() : nullptr; 3787 SCD = SCD ? SCD->getCanonicalDecl() : nullptr; 3788 if (SCD != CCD) 3789 return false; 3790 std::advance(CCI, 1); 3791 if (CCI == CCE) 3792 break; 3793 } 3794 return true; 3795 })) { 3796 Visit(E->getBase()); 3797 } 3798 } else if (!TryCaptureCXXThisMembers) { 3799 Visit(E->getBase()); 3800 } 3801 } 3802 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 3803 for (OMPClause *C : S->clauses()) { 3804 // Skip analysis of arguments of private clauses for task|target 3805 // directives. 3806 if (isa_and_nonnull<OMPPrivateClause>(C)) 3807 continue; 3808 // Skip analysis of arguments of implicitly defined firstprivate clause 3809 // for task|target directives. 3810 // Skip analysis of arguments of implicitly defined map clause for target 3811 // directives. 3812 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) && 3813 C->isImplicit() && 3814 !isOpenMPTaskingDirective(Stack->getCurrentDirective()))) { 3815 for (Stmt *CC : C->children()) { 3816 if (CC) 3817 Visit(CC); 3818 } 3819 } 3820 } 3821 // Check implicitly captured variables. 3822 VisitSubCaptures(S); 3823 } 3824 3825 void VisitOMPLoopTransformationDirective(OMPLoopTransformationDirective *S) { 3826 // Loop transformation directives do not introduce data sharing 3827 VisitStmt(S); 3828 } 3829 3830 void VisitCallExpr(CallExpr *S) { 3831 for (Stmt *C : S->arguments()) { 3832 if (C) { 3833 // Check implicitly captured variables in the task-based directives to 3834 // check if they must be firstprivatized. 3835 Visit(C); 3836 } 3837 } 3838 if (Expr *Callee = S->getCallee()) 3839 if (auto *CE = dyn_cast<MemberExpr>(Callee->IgnoreParenImpCasts())) 3840 Visit(CE->getBase()); 3841 } 3842 void VisitStmt(Stmt *S) { 3843 for (Stmt *C : S->children()) { 3844 if (C) { 3845 // Check implicitly captured variables in the task-based directives to 3846 // check if they must be firstprivatized. 3847 Visit(C); 3848 } 3849 } 3850 } 3851 3852 void visitSubCaptures(CapturedStmt *S) { 3853 for (const CapturedStmt::Capture &Cap : S->captures()) { 3854 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy()) 3855 continue; 3856 VarDecl *VD = Cap.getCapturedVar(); 3857 // Do not try to map the variable if it or its sub-component was mapped 3858 // already. 3859 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 3860 Stack->checkMappableExprComponentListsForDecl( 3861 VD, /*CurrentRegionOnly=*/true, 3862 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 3863 OpenMPClauseKind) { return true; })) 3864 continue; 3865 DeclRefExpr *DRE = buildDeclRefExpr( 3866 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context), 3867 Cap.getLocation(), /*RefersToCapture=*/true); 3868 Visit(DRE); 3869 } 3870 } 3871 bool isErrorFound() const { return ErrorFound; } 3872 ArrayRef<Expr *> getImplicitFirstprivate() const { 3873 return ImplicitFirstprivate; 3874 } 3875 ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind DK, 3876 OpenMPMapClauseKind MK) const { 3877 return ImplicitMap[DK][MK]; 3878 } 3879 ArrayRef<OpenMPMapModifierKind> 3880 getImplicitMapModifier(OpenMPDefaultmapClauseKind Kind) const { 3881 return ImplicitMapModifier[Kind]; 3882 } 3883 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const { 3884 return VarsWithInheritedDSA; 3885 } 3886 3887 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 3888 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) { 3889 // Process declare target link variables for the target directives. 3890 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) { 3891 for (DeclRefExpr *E : Stack->getLinkGlobals()) 3892 Visit(E); 3893 } 3894 } 3895 }; 3896 } // namespace 3897 3898 static void handleDeclareVariantConstructTrait(DSAStackTy *Stack, 3899 OpenMPDirectiveKind DKind, 3900 bool ScopeEntry) { 3901 SmallVector<llvm::omp::TraitProperty, 8> Traits; 3902 if (isOpenMPTargetExecutionDirective(DKind)) 3903 Traits.emplace_back(llvm::omp::TraitProperty::construct_target_target); 3904 if (isOpenMPTeamsDirective(DKind)) 3905 Traits.emplace_back(llvm::omp::TraitProperty::construct_teams_teams); 3906 if (isOpenMPParallelDirective(DKind)) 3907 Traits.emplace_back(llvm::omp::TraitProperty::construct_parallel_parallel); 3908 if (isOpenMPWorksharingDirective(DKind)) 3909 Traits.emplace_back(llvm::omp::TraitProperty::construct_for_for); 3910 if (isOpenMPSimdDirective(DKind)) 3911 Traits.emplace_back(llvm::omp::TraitProperty::construct_simd_simd); 3912 Stack->handleConstructTrait(Traits, ScopeEntry); 3913 } 3914 3915 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 3916 switch (DKind) { 3917 case OMPD_parallel: 3918 case OMPD_parallel_for: 3919 case OMPD_parallel_for_simd: 3920 case OMPD_parallel_sections: 3921 case OMPD_parallel_master: 3922 case OMPD_teams: 3923 case OMPD_teams_distribute: 3924 case OMPD_teams_distribute_simd: { 3925 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3926 QualType KmpInt32PtrTy = 3927 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3928 Sema::CapturedParamNameType Params[] = { 3929 std::make_pair(".global_tid.", KmpInt32PtrTy), 3930 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3931 std::make_pair(StringRef(), QualType()) // __context with shared vars 3932 }; 3933 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3934 Params); 3935 break; 3936 } 3937 case OMPD_target_teams: 3938 case OMPD_target_parallel: 3939 case OMPD_target_parallel_for: 3940 case OMPD_target_parallel_for_simd: 3941 case OMPD_target_teams_distribute: 3942 case OMPD_target_teams_distribute_simd: { 3943 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3944 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3945 QualType KmpInt32PtrTy = 3946 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3947 QualType Args[] = {VoidPtrTy}; 3948 FunctionProtoType::ExtProtoInfo EPI; 3949 EPI.Variadic = true; 3950 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3951 Sema::CapturedParamNameType Params[] = { 3952 std::make_pair(".global_tid.", KmpInt32Ty), 3953 std::make_pair(".part_id.", KmpInt32PtrTy), 3954 std::make_pair(".privates.", VoidPtrTy), 3955 std::make_pair( 3956 ".copy_fn.", 3957 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3958 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3959 std::make_pair(StringRef(), QualType()) // __context with shared vars 3960 }; 3961 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3962 Params, /*OpenMPCaptureLevel=*/0); 3963 // Mark this captured region as inlined, because we don't use outlined 3964 // function directly. 3965 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3966 AlwaysInlineAttr::CreateImplicit( 3967 Context, {}, AttributeCommonInfo::AS_Keyword, 3968 AlwaysInlineAttr::Keyword_forceinline)); 3969 Sema::CapturedParamNameType ParamsTarget[] = { 3970 std::make_pair(StringRef(), QualType()) // __context with shared vars 3971 }; 3972 // Start a captured region for 'target' with no implicit parameters. 3973 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3974 ParamsTarget, /*OpenMPCaptureLevel=*/1); 3975 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 3976 std::make_pair(".global_tid.", KmpInt32PtrTy), 3977 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3978 std::make_pair(StringRef(), QualType()) // __context with shared vars 3979 }; 3980 // Start a captured region for 'teams' or 'parallel'. Both regions have 3981 // the same implicit parameters. 3982 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3983 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2); 3984 break; 3985 } 3986 case OMPD_target: 3987 case OMPD_target_simd: { 3988 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3989 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3990 QualType KmpInt32PtrTy = 3991 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3992 QualType Args[] = {VoidPtrTy}; 3993 FunctionProtoType::ExtProtoInfo EPI; 3994 EPI.Variadic = true; 3995 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3996 Sema::CapturedParamNameType Params[] = { 3997 std::make_pair(".global_tid.", KmpInt32Ty), 3998 std::make_pair(".part_id.", KmpInt32PtrTy), 3999 std::make_pair(".privates.", VoidPtrTy), 4000 std::make_pair( 4001 ".copy_fn.", 4002 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4003 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4004 std::make_pair(StringRef(), QualType()) // __context with shared vars 4005 }; 4006 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4007 Params, /*OpenMPCaptureLevel=*/0); 4008 // Mark this captured region as inlined, because we don't use outlined 4009 // function directly. 4010 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4011 AlwaysInlineAttr::CreateImplicit( 4012 Context, {}, AttributeCommonInfo::AS_Keyword, 4013 AlwaysInlineAttr::Keyword_forceinline)); 4014 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4015 std::make_pair(StringRef(), QualType()), 4016 /*OpenMPCaptureLevel=*/1); 4017 break; 4018 } 4019 case OMPD_atomic: 4020 case OMPD_critical: 4021 case OMPD_section: 4022 case OMPD_master: 4023 case OMPD_masked: 4024 case OMPD_tile: 4025 case OMPD_unroll: 4026 break; 4027 case OMPD_loop: 4028 // TODO: 'loop' may require additional parameters depending on the binding. 4029 // Treat similar to OMPD_simd/OMPD_for for now. 4030 case OMPD_simd: 4031 case OMPD_for: 4032 case OMPD_for_simd: 4033 case OMPD_sections: 4034 case OMPD_single: 4035 case OMPD_taskgroup: 4036 case OMPD_distribute: 4037 case OMPD_distribute_simd: 4038 case OMPD_ordered: 4039 case OMPD_target_data: 4040 case OMPD_dispatch: { 4041 Sema::CapturedParamNameType Params[] = { 4042 std::make_pair(StringRef(), QualType()) // __context with shared vars 4043 }; 4044 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4045 Params); 4046 break; 4047 } 4048 case OMPD_task: { 4049 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4050 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4051 QualType KmpInt32PtrTy = 4052 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4053 QualType Args[] = {VoidPtrTy}; 4054 FunctionProtoType::ExtProtoInfo EPI; 4055 EPI.Variadic = true; 4056 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4057 Sema::CapturedParamNameType Params[] = { 4058 std::make_pair(".global_tid.", KmpInt32Ty), 4059 std::make_pair(".part_id.", KmpInt32PtrTy), 4060 std::make_pair(".privates.", VoidPtrTy), 4061 std::make_pair( 4062 ".copy_fn.", 4063 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4064 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4065 std::make_pair(StringRef(), QualType()) // __context with shared vars 4066 }; 4067 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4068 Params); 4069 // Mark this captured region as inlined, because we don't use outlined 4070 // function directly. 4071 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4072 AlwaysInlineAttr::CreateImplicit( 4073 Context, {}, AttributeCommonInfo::AS_Keyword, 4074 AlwaysInlineAttr::Keyword_forceinline)); 4075 break; 4076 } 4077 case OMPD_taskloop: 4078 case OMPD_taskloop_simd: 4079 case OMPD_master_taskloop: 4080 case OMPD_master_taskloop_simd: { 4081 QualType KmpInt32Ty = 4082 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 4083 .withConst(); 4084 QualType KmpUInt64Ty = 4085 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 4086 .withConst(); 4087 QualType KmpInt64Ty = 4088 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 4089 .withConst(); 4090 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4091 QualType KmpInt32PtrTy = 4092 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4093 QualType Args[] = {VoidPtrTy}; 4094 FunctionProtoType::ExtProtoInfo EPI; 4095 EPI.Variadic = true; 4096 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4097 Sema::CapturedParamNameType Params[] = { 4098 std::make_pair(".global_tid.", KmpInt32Ty), 4099 std::make_pair(".part_id.", KmpInt32PtrTy), 4100 std::make_pair(".privates.", VoidPtrTy), 4101 std::make_pair( 4102 ".copy_fn.", 4103 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4104 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4105 std::make_pair(".lb.", KmpUInt64Ty), 4106 std::make_pair(".ub.", KmpUInt64Ty), 4107 std::make_pair(".st.", KmpInt64Ty), 4108 std::make_pair(".liter.", KmpInt32Ty), 4109 std::make_pair(".reductions.", VoidPtrTy), 4110 std::make_pair(StringRef(), QualType()) // __context with shared vars 4111 }; 4112 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4113 Params); 4114 // Mark this captured region as inlined, because we don't use outlined 4115 // function directly. 4116 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4117 AlwaysInlineAttr::CreateImplicit( 4118 Context, {}, AttributeCommonInfo::AS_Keyword, 4119 AlwaysInlineAttr::Keyword_forceinline)); 4120 break; 4121 } 4122 case OMPD_parallel_master_taskloop: 4123 case OMPD_parallel_master_taskloop_simd: { 4124 QualType KmpInt32Ty = 4125 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 4126 .withConst(); 4127 QualType KmpUInt64Ty = 4128 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 4129 .withConst(); 4130 QualType KmpInt64Ty = 4131 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 4132 .withConst(); 4133 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4134 QualType KmpInt32PtrTy = 4135 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4136 Sema::CapturedParamNameType ParamsParallel[] = { 4137 std::make_pair(".global_tid.", KmpInt32PtrTy), 4138 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4139 std::make_pair(StringRef(), QualType()) // __context with shared vars 4140 }; 4141 // Start a captured region for 'parallel'. 4142 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4143 ParamsParallel, /*OpenMPCaptureLevel=*/0); 4144 QualType Args[] = {VoidPtrTy}; 4145 FunctionProtoType::ExtProtoInfo EPI; 4146 EPI.Variadic = true; 4147 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4148 Sema::CapturedParamNameType Params[] = { 4149 std::make_pair(".global_tid.", KmpInt32Ty), 4150 std::make_pair(".part_id.", KmpInt32PtrTy), 4151 std::make_pair(".privates.", VoidPtrTy), 4152 std::make_pair( 4153 ".copy_fn.", 4154 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4155 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4156 std::make_pair(".lb.", KmpUInt64Ty), 4157 std::make_pair(".ub.", KmpUInt64Ty), 4158 std::make_pair(".st.", KmpInt64Ty), 4159 std::make_pair(".liter.", KmpInt32Ty), 4160 std::make_pair(".reductions.", VoidPtrTy), 4161 std::make_pair(StringRef(), QualType()) // __context with shared vars 4162 }; 4163 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4164 Params, /*OpenMPCaptureLevel=*/1); 4165 // Mark this captured region as inlined, because we don't use outlined 4166 // function directly. 4167 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4168 AlwaysInlineAttr::CreateImplicit( 4169 Context, {}, AttributeCommonInfo::AS_Keyword, 4170 AlwaysInlineAttr::Keyword_forceinline)); 4171 break; 4172 } 4173 case OMPD_distribute_parallel_for_simd: 4174 case OMPD_distribute_parallel_for: { 4175 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4176 QualType KmpInt32PtrTy = 4177 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4178 Sema::CapturedParamNameType Params[] = { 4179 std::make_pair(".global_tid.", KmpInt32PtrTy), 4180 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4181 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 4182 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 4183 std::make_pair(StringRef(), QualType()) // __context with shared vars 4184 }; 4185 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4186 Params); 4187 break; 4188 } 4189 case OMPD_target_teams_distribute_parallel_for: 4190 case OMPD_target_teams_distribute_parallel_for_simd: { 4191 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4192 QualType KmpInt32PtrTy = 4193 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4194 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4195 4196 QualType Args[] = {VoidPtrTy}; 4197 FunctionProtoType::ExtProtoInfo EPI; 4198 EPI.Variadic = true; 4199 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4200 Sema::CapturedParamNameType Params[] = { 4201 std::make_pair(".global_tid.", KmpInt32Ty), 4202 std::make_pair(".part_id.", KmpInt32PtrTy), 4203 std::make_pair(".privates.", VoidPtrTy), 4204 std::make_pair( 4205 ".copy_fn.", 4206 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4207 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4208 std::make_pair(StringRef(), QualType()) // __context with shared vars 4209 }; 4210 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4211 Params, /*OpenMPCaptureLevel=*/0); 4212 // Mark this captured region as inlined, because we don't use outlined 4213 // function directly. 4214 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4215 AlwaysInlineAttr::CreateImplicit( 4216 Context, {}, AttributeCommonInfo::AS_Keyword, 4217 AlwaysInlineAttr::Keyword_forceinline)); 4218 Sema::CapturedParamNameType ParamsTarget[] = { 4219 std::make_pair(StringRef(), QualType()) // __context with shared vars 4220 }; 4221 // Start a captured region for 'target' with no implicit parameters. 4222 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4223 ParamsTarget, /*OpenMPCaptureLevel=*/1); 4224 4225 Sema::CapturedParamNameType ParamsTeams[] = { 4226 std::make_pair(".global_tid.", KmpInt32PtrTy), 4227 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4228 std::make_pair(StringRef(), QualType()) // __context with shared vars 4229 }; 4230 // Start a captured region for 'target' with no implicit parameters. 4231 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4232 ParamsTeams, /*OpenMPCaptureLevel=*/2); 4233 4234 Sema::CapturedParamNameType ParamsParallel[] = { 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 // Start a captured region for 'teams' or 'parallel'. Both regions have 4242 // the same implicit parameters. 4243 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4244 ParamsParallel, /*OpenMPCaptureLevel=*/3); 4245 break; 4246 } 4247 4248 case OMPD_teams_distribute_parallel_for: 4249 case OMPD_teams_distribute_parallel_for_simd: { 4250 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4251 QualType KmpInt32PtrTy = 4252 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4253 4254 Sema::CapturedParamNameType ParamsTeams[] = { 4255 std::make_pair(".global_tid.", KmpInt32PtrTy), 4256 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4257 std::make_pair(StringRef(), QualType()) // __context with shared vars 4258 }; 4259 // Start a captured region for 'target' with no implicit parameters. 4260 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4261 ParamsTeams, /*OpenMPCaptureLevel=*/0); 4262 4263 Sema::CapturedParamNameType ParamsParallel[] = { 4264 std::make_pair(".global_tid.", KmpInt32PtrTy), 4265 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4266 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 4267 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 4268 std::make_pair(StringRef(), QualType()) // __context with shared vars 4269 }; 4270 // Start a captured region for 'teams' or 'parallel'. Both regions have 4271 // the same implicit parameters. 4272 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4273 ParamsParallel, /*OpenMPCaptureLevel=*/1); 4274 break; 4275 } 4276 case OMPD_target_update: 4277 case OMPD_target_enter_data: 4278 case OMPD_target_exit_data: { 4279 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4280 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4281 QualType KmpInt32PtrTy = 4282 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4283 QualType Args[] = {VoidPtrTy}; 4284 FunctionProtoType::ExtProtoInfo EPI; 4285 EPI.Variadic = true; 4286 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4287 Sema::CapturedParamNameType Params[] = { 4288 std::make_pair(".global_tid.", KmpInt32Ty), 4289 std::make_pair(".part_id.", KmpInt32PtrTy), 4290 std::make_pair(".privates.", VoidPtrTy), 4291 std::make_pair( 4292 ".copy_fn.", 4293 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4294 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4295 std::make_pair(StringRef(), QualType()) // __context with shared vars 4296 }; 4297 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4298 Params); 4299 // Mark this captured region as inlined, because we don't use outlined 4300 // function directly. 4301 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4302 AlwaysInlineAttr::CreateImplicit( 4303 Context, {}, AttributeCommonInfo::AS_Keyword, 4304 AlwaysInlineAttr::Keyword_forceinline)); 4305 break; 4306 } 4307 case OMPD_threadprivate: 4308 case OMPD_allocate: 4309 case OMPD_taskyield: 4310 case OMPD_barrier: 4311 case OMPD_taskwait: 4312 case OMPD_cancellation_point: 4313 case OMPD_cancel: 4314 case OMPD_flush: 4315 case OMPD_depobj: 4316 case OMPD_scan: 4317 case OMPD_declare_reduction: 4318 case OMPD_declare_mapper: 4319 case OMPD_declare_simd: 4320 case OMPD_declare_target: 4321 case OMPD_end_declare_target: 4322 case OMPD_requires: 4323 case OMPD_declare_variant: 4324 case OMPD_begin_declare_variant: 4325 case OMPD_end_declare_variant: 4326 case OMPD_metadirective: 4327 llvm_unreachable("OpenMP Directive is not allowed"); 4328 case OMPD_unknown: 4329 default: 4330 llvm_unreachable("Unknown OpenMP directive"); 4331 } 4332 DSAStack->setContext(CurContext); 4333 handleDeclareVariantConstructTrait(DSAStack, DKind, /* ScopeEntry */ true); 4334 } 4335 4336 int Sema::getNumberOfConstructScopes(unsigned Level) const { 4337 return getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 4338 } 4339 4340 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 4341 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 4342 getOpenMPCaptureRegions(CaptureRegions, DKind); 4343 return CaptureRegions.size(); 4344 } 4345 4346 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 4347 Expr *CaptureExpr, bool WithInit, 4348 bool AsExpression) { 4349 assert(CaptureExpr); 4350 ASTContext &C = S.getASTContext(); 4351 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 4352 QualType Ty = Init->getType(); 4353 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 4354 if (S.getLangOpts().CPlusPlus) { 4355 Ty = C.getLValueReferenceType(Ty); 4356 } else { 4357 Ty = C.getPointerType(Ty); 4358 ExprResult Res = 4359 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 4360 if (!Res.isUsable()) 4361 return nullptr; 4362 Init = Res.get(); 4363 } 4364 WithInit = true; 4365 } 4366 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 4367 CaptureExpr->getBeginLoc()); 4368 if (!WithInit) 4369 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C)); 4370 S.CurContext->addHiddenDecl(CED); 4371 Sema::TentativeAnalysisScope Trap(S); 4372 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 4373 return CED; 4374 } 4375 4376 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 4377 bool WithInit) { 4378 OMPCapturedExprDecl *CD; 4379 if (VarDecl *VD = S.isOpenMPCapturedDecl(D)) 4380 CD = cast<OMPCapturedExprDecl>(VD); 4381 else 4382 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 4383 /*AsExpression=*/false); 4384 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 4385 CaptureExpr->getExprLoc()); 4386 } 4387 4388 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 4389 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get(); 4390 if (!Ref) { 4391 OMPCapturedExprDecl *CD = buildCaptureDecl( 4392 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr, 4393 /*WithInit=*/true, /*AsExpression=*/true); 4394 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 4395 CaptureExpr->getExprLoc()); 4396 } 4397 ExprResult Res = Ref; 4398 if (!S.getLangOpts().CPlusPlus && 4399 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 4400 Ref->getType()->isPointerType()) { 4401 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 4402 if (!Res.isUsable()) 4403 return ExprError(); 4404 } 4405 return S.DefaultLvalueConversion(Res.get()); 4406 } 4407 4408 namespace { 4409 // OpenMP directives parsed in this section are represented as a 4410 // CapturedStatement with an associated statement. If a syntax error 4411 // is detected during the parsing of the associated statement, the 4412 // compiler must abort processing and close the CapturedStatement. 4413 // 4414 // Combined directives such as 'target parallel' have more than one 4415 // nested CapturedStatements. This RAII ensures that we unwind out 4416 // of all the nested CapturedStatements when an error is found. 4417 class CaptureRegionUnwinderRAII { 4418 private: 4419 Sema &S; 4420 bool &ErrorFound; 4421 OpenMPDirectiveKind DKind = OMPD_unknown; 4422 4423 public: 4424 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 4425 OpenMPDirectiveKind DKind) 4426 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 4427 ~CaptureRegionUnwinderRAII() { 4428 if (ErrorFound) { 4429 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 4430 while (--ThisCaptureLevel >= 0) 4431 S.ActOnCapturedRegionError(); 4432 } 4433 } 4434 }; 4435 } // namespace 4436 4437 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) { 4438 // Capture variables captured by reference in lambdas for target-based 4439 // directives. 4440 if (!CurContext->isDependentContext() && 4441 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) || 4442 isOpenMPTargetDataManagementDirective( 4443 DSAStack->getCurrentDirective()))) { 4444 QualType Type = V->getType(); 4445 if (const auto *RD = Type.getCanonicalType() 4446 .getNonReferenceType() 4447 ->getAsCXXRecordDecl()) { 4448 bool SavedForceCaptureByReferenceInTargetExecutable = 4449 DSAStack->isForceCaptureByReferenceInTargetExecutable(); 4450 DSAStack->setForceCaptureByReferenceInTargetExecutable( 4451 /*V=*/true); 4452 if (RD->isLambda()) { 4453 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures; 4454 FieldDecl *ThisCapture; 4455 RD->getCaptureFields(Captures, ThisCapture); 4456 for (const LambdaCapture &LC : RD->captures()) { 4457 if (LC.getCaptureKind() == LCK_ByRef) { 4458 VarDecl *VD = LC.getCapturedVar(); 4459 DeclContext *VDC = VD->getDeclContext(); 4460 if (!VDC->Encloses(CurContext)) 4461 continue; 4462 MarkVariableReferenced(LC.getLocation(), VD); 4463 } else if (LC.getCaptureKind() == LCK_This) { 4464 QualType ThisTy = getCurrentThisType(); 4465 if (!ThisTy.isNull() && 4466 Context.typesAreCompatible(ThisTy, ThisCapture->getType())) 4467 CheckCXXThisCapture(LC.getLocation()); 4468 } 4469 } 4470 } 4471 DSAStack->setForceCaptureByReferenceInTargetExecutable( 4472 SavedForceCaptureByReferenceInTargetExecutable); 4473 } 4474 } 4475 } 4476 4477 static bool checkOrderedOrderSpecified(Sema &S, 4478 const ArrayRef<OMPClause *> Clauses) { 4479 const OMPOrderedClause *Ordered = nullptr; 4480 const OMPOrderClause *Order = nullptr; 4481 4482 for (const OMPClause *Clause : Clauses) { 4483 if (Clause->getClauseKind() == OMPC_ordered) 4484 Ordered = cast<OMPOrderedClause>(Clause); 4485 else if (Clause->getClauseKind() == OMPC_order) { 4486 Order = cast<OMPOrderClause>(Clause); 4487 if (Order->getKind() != OMPC_ORDER_concurrent) 4488 Order = nullptr; 4489 } 4490 if (Ordered && Order) 4491 break; 4492 } 4493 4494 if (Ordered && Order) { 4495 S.Diag(Order->getKindKwLoc(), 4496 diag::err_omp_simple_clause_incompatible_with_ordered) 4497 << getOpenMPClauseName(OMPC_order) 4498 << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent) 4499 << SourceRange(Order->getBeginLoc(), Order->getEndLoc()); 4500 S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param) 4501 << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc()); 4502 return true; 4503 } 4504 return false; 4505 } 4506 4507 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 4508 ArrayRef<OMPClause *> Clauses) { 4509 handleDeclareVariantConstructTrait(DSAStack, DSAStack->getCurrentDirective(), 4510 /* ScopeEntry */ false); 4511 if (DSAStack->getCurrentDirective() == OMPD_atomic || 4512 DSAStack->getCurrentDirective() == OMPD_critical || 4513 DSAStack->getCurrentDirective() == OMPD_section || 4514 DSAStack->getCurrentDirective() == OMPD_master || 4515 DSAStack->getCurrentDirective() == OMPD_masked) 4516 return S; 4517 4518 bool ErrorFound = false; 4519 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 4520 *this, ErrorFound, DSAStack->getCurrentDirective()); 4521 if (!S.isUsable()) { 4522 ErrorFound = true; 4523 return StmtError(); 4524 } 4525 4526 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 4527 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 4528 OMPOrderedClause *OC = nullptr; 4529 OMPScheduleClause *SC = nullptr; 4530 SmallVector<const OMPLinearClause *, 4> LCs; 4531 SmallVector<const OMPClauseWithPreInit *, 4> PICs; 4532 // This is required for proper codegen. 4533 for (OMPClause *Clause : Clauses) { 4534 if (!LangOpts.OpenMPSimd && 4535 isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) && 4536 Clause->getClauseKind() == OMPC_in_reduction) { 4537 // Capture taskgroup task_reduction descriptors inside the tasking regions 4538 // with the corresponding in_reduction items. 4539 auto *IRC = cast<OMPInReductionClause>(Clause); 4540 for (Expr *E : IRC->taskgroup_descriptors()) 4541 if (E) 4542 MarkDeclarationsReferencedInExpr(E); 4543 } 4544 if (isOpenMPPrivate(Clause->getClauseKind()) || 4545 Clause->getClauseKind() == OMPC_copyprivate || 4546 (getLangOpts().OpenMPUseTLS && 4547 getASTContext().getTargetInfo().isTLSSupported() && 4548 Clause->getClauseKind() == OMPC_copyin)) { 4549 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 4550 // Mark all variables in private list clauses as used in inner region. 4551 for (Stmt *VarRef : Clause->children()) { 4552 if (auto *E = cast_or_null<Expr>(VarRef)) { 4553 MarkDeclarationsReferencedInExpr(E); 4554 } 4555 } 4556 DSAStack->setForceVarCapturing(/*V=*/false); 4557 } else if (isOpenMPLoopTransformationDirective( 4558 DSAStack->getCurrentDirective())) { 4559 assert(CaptureRegions.empty() && 4560 "No captured regions in loop transformation directives."); 4561 } else if (CaptureRegions.size() > 1 || 4562 CaptureRegions.back() != OMPD_unknown) { 4563 if (auto *C = OMPClauseWithPreInit::get(Clause)) 4564 PICs.push_back(C); 4565 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 4566 if (Expr *E = C->getPostUpdateExpr()) 4567 MarkDeclarationsReferencedInExpr(E); 4568 } 4569 } 4570 if (Clause->getClauseKind() == OMPC_schedule) 4571 SC = cast<OMPScheduleClause>(Clause); 4572 else if (Clause->getClauseKind() == OMPC_ordered) 4573 OC = cast<OMPOrderedClause>(Clause); 4574 else if (Clause->getClauseKind() == OMPC_linear) 4575 LCs.push_back(cast<OMPLinearClause>(Clause)); 4576 } 4577 // Capture allocator expressions if used. 4578 for (Expr *E : DSAStack->getInnerAllocators()) 4579 MarkDeclarationsReferencedInExpr(E); 4580 // OpenMP, 2.7.1 Loop Construct, Restrictions 4581 // The nonmonotonic modifier cannot be specified if an ordered clause is 4582 // specified. 4583 if (SC && 4584 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 4585 SC->getSecondScheduleModifier() == 4586 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 4587 OC) { 4588 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 4589 ? SC->getFirstScheduleModifierLoc() 4590 : SC->getSecondScheduleModifierLoc(), 4591 diag::err_omp_simple_clause_incompatible_with_ordered) 4592 << getOpenMPClauseName(OMPC_schedule) 4593 << getOpenMPSimpleClauseTypeName(OMPC_schedule, 4594 OMPC_SCHEDULE_MODIFIER_nonmonotonic) 4595 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 4596 ErrorFound = true; 4597 } 4598 // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions. 4599 // If an order(concurrent) clause is present, an ordered clause may not appear 4600 // on the same directive. 4601 if (checkOrderedOrderSpecified(*this, Clauses)) 4602 ErrorFound = true; 4603 if (!LCs.empty() && OC && OC->getNumForLoops()) { 4604 for (const OMPLinearClause *C : LCs) { 4605 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered) 4606 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 4607 } 4608 ErrorFound = true; 4609 } 4610 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 4611 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 4612 OC->getNumForLoops()) { 4613 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd) 4614 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 4615 ErrorFound = true; 4616 } 4617 if (ErrorFound) { 4618 return StmtError(); 4619 } 4620 StmtResult SR = S; 4621 unsigned CompletedRegions = 0; 4622 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 4623 // Mark all variables in private list clauses as used in inner region. 4624 // Required for proper codegen of combined directives. 4625 // TODO: add processing for other clauses. 4626 if (ThisCaptureRegion != OMPD_unknown) { 4627 for (const clang::OMPClauseWithPreInit *C : PICs) { 4628 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 4629 // Find the particular capture region for the clause if the 4630 // directive is a combined one with multiple capture regions. 4631 // If the directive is not a combined one, the capture region 4632 // associated with the clause is OMPD_unknown and is generated 4633 // only once. 4634 if (CaptureRegion == ThisCaptureRegion || 4635 CaptureRegion == OMPD_unknown) { 4636 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 4637 for (Decl *D : DS->decls()) 4638 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 4639 } 4640 } 4641 } 4642 } 4643 if (ThisCaptureRegion == OMPD_target) { 4644 // Capture allocator traits in the target region. They are used implicitly 4645 // and, thus, are not captured by default. 4646 for (OMPClause *C : Clauses) { 4647 if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) { 4648 for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End; 4649 ++I) { 4650 OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I); 4651 if (Expr *E = D.AllocatorTraits) 4652 MarkDeclarationsReferencedInExpr(E); 4653 } 4654 continue; 4655 } 4656 } 4657 } 4658 if (ThisCaptureRegion == OMPD_parallel) { 4659 // Capture temp arrays for inscan reductions and locals in aligned 4660 // clauses. 4661 for (OMPClause *C : Clauses) { 4662 if (auto *RC = dyn_cast<OMPReductionClause>(C)) { 4663 if (RC->getModifier() != OMPC_REDUCTION_inscan) 4664 continue; 4665 for (Expr *E : RC->copy_array_temps()) 4666 MarkDeclarationsReferencedInExpr(E); 4667 } 4668 if (auto *AC = dyn_cast<OMPAlignedClause>(C)) { 4669 for (Expr *E : AC->varlists()) 4670 MarkDeclarationsReferencedInExpr(E); 4671 } 4672 } 4673 } 4674 if (++CompletedRegions == CaptureRegions.size()) 4675 DSAStack->setBodyComplete(); 4676 SR = ActOnCapturedRegionEnd(SR.get()); 4677 } 4678 return SR; 4679 } 4680 4681 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 4682 OpenMPDirectiveKind CancelRegion, 4683 SourceLocation StartLoc) { 4684 // CancelRegion is only needed for cancel and cancellation_point. 4685 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 4686 return false; 4687 4688 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 4689 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 4690 return false; 4691 4692 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 4693 << getOpenMPDirectiveName(CancelRegion); 4694 return true; 4695 } 4696 4697 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack, 4698 OpenMPDirectiveKind CurrentRegion, 4699 const DeclarationNameInfo &CurrentName, 4700 OpenMPDirectiveKind CancelRegion, 4701 OpenMPBindClauseKind BindKind, 4702 SourceLocation StartLoc) { 4703 if (Stack->getCurScope()) { 4704 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective(); 4705 OpenMPDirectiveKind OffendingRegion = ParentRegion; 4706 bool NestingProhibited = false; 4707 bool CloseNesting = true; 4708 bool OrphanSeen = false; 4709 enum { 4710 NoRecommend, 4711 ShouldBeInParallelRegion, 4712 ShouldBeInOrderedRegion, 4713 ShouldBeInTargetRegion, 4714 ShouldBeInTeamsRegion, 4715 ShouldBeInLoopSimdRegion, 4716 } Recommend = NoRecommend; 4717 if (isOpenMPSimdDirective(ParentRegion) && 4718 ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) || 4719 (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered && 4720 CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic && 4721 CurrentRegion != OMPD_scan))) { 4722 // OpenMP [2.16, Nesting of Regions] 4723 // OpenMP constructs may not be nested inside a simd region. 4724 // OpenMP [2.8.1,simd Construct, Restrictions] 4725 // An ordered construct with the simd clause is the only OpenMP 4726 // construct that can appear in the simd region. 4727 // Allowing a SIMD construct nested in another SIMD construct is an 4728 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 4729 // message. 4730 // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions] 4731 // The only OpenMP constructs that can be encountered during execution of 4732 // a simd region are the atomic construct, the loop construct, the simd 4733 // construct and the ordered construct with the simd clause. 4734 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 4735 ? diag::err_omp_prohibited_region_simd 4736 : diag::warn_omp_nesting_simd) 4737 << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0); 4738 return CurrentRegion != OMPD_simd; 4739 } 4740 if (ParentRegion == OMPD_atomic) { 4741 // OpenMP [2.16, Nesting of Regions] 4742 // OpenMP constructs may not be nested inside an atomic region. 4743 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 4744 return true; 4745 } 4746 if (CurrentRegion == OMPD_section) { 4747 // OpenMP [2.7.2, sections Construct, Restrictions] 4748 // Orphaned section directives are prohibited. That is, the section 4749 // directives must appear within the sections construct and must not be 4750 // encountered elsewhere in the sections region. 4751 if (ParentRegion != OMPD_sections && 4752 ParentRegion != OMPD_parallel_sections) { 4753 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 4754 << (ParentRegion != OMPD_unknown) 4755 << getOpenMPDirectiveName(ParentRegion); 4756 return true; 4757 } 4758 return false; 4759 } 4760 // Allow some constructs (except teams and cancellation constructs) to be 4761 // orphaned (they could be used in functions, called from OpenMP regions 4762 // with the required preconditions). 4763 if (ParentRegion == OMPD_unknown && 4764 !isOpenMPNestingTeamsDirective(CurrentRegion) && 4765 CurrentRegion != OMPD_cancellation_point && 4766 CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan) 4767 return false; 4768 if (CurrentRegion == OMPD_cancellation_point || 4769 CurrentRegion == OMPD_cancel) { 4770 // OpenMP [2.16, Nesting of Regions] 4771 // A cancellation point construct for which construct-type-clause is 4772 // taskgroup must be nested inside a task construct. A cancellation 4773 // point construct for which construct-type-clause is not taskgroup must 4774 // be closely nested inside an OpenMP construct that matches the type 4775 // specified in construct-type-clause. 4776 // A cancel construct for which construct-type-clause is taskgroup must be 4777 // nested inside a task construct. A cancel construct for which 4778 // construct-type-clause is not taskgroup must be closely nested inside an 4779 // OpenMP construct that matches the type specified in 4780 // construct-type-clause. 4781 NestingProhibited = 4782 !((CancelRegion == OMPD_parallel && 4783 (ParentRegion == OMPD_parallel || 4784 ParentRegion == OMPD_target_parallel)) || 4785 (CancelRegion == OMPD_for && 4786 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 4787 ParentRegion == OMPD_target_parallel_for || 4788 ParentRegion == OMPD_distribute_parallel_for || 4789 ParentRegion == OMPD_teams_distribute_parallel_for || 4790 ParentRegion == OMPD_target_teams_distribute_parallel_for)) || 4791 (CancelRegion == OMPD_taskgroup && 4792 (ParentRegion == OMPD_task || 4793 (SemaRef.getLangOpts().OpenMP >= 50 && 4794 (ParentRegion == OMPD_taskloop || 4795 ParentRegion == OMPD_master_taskloop || 4796 ParentRegion == OMPD_parallel_master_taskloop)))) || 4797 (CancelRegion == OMPD_sections && 4798 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 4799 ParentRegion == OMPD_parallel_sections))); 4800 OrphanSeen = ParentRegion == OMPD_unknown; 4801 } else if (CurrentRegion == OMPD_master || CurrentRegion == OMPD_masked) { 4802 // OpenMP 5.1 [2.22, Nesting of Regions] 4803 // A masked region may not be closely nested inside a worksharing, loop, 4804 // atomic, task, or taskloop region. 4805 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 4806 isOpenMPGenericLoopDirective(ParentRegion) || 4807 isOpenMPTaskingDirective(ParentRegion); 4808 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 4809 // OpenMP [2.16, Nesting of Regions] 4810 // A critical region may not be nested (closely or otherwise) inside a 4811 // critical region with the same name. Note that this restriction is not 4812 // sufficient to prevent deadlock. 4813 SourceLocation PreviousCriticalLoc; 4814 bool DeadLock = Stack->hasDirective( 4815 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 4816 const DeclarationNameInfo &DNI, 4817 SourceLocation Loc) { 4818 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 4819 PreviousCriticalLoc = Loc; 4820 return true; 4821 } 4822 return false; 4823 }, 4824 false /* skip top directive */); 4825 if (DeadLock) { 4826 SemaRef.Diag(StartLoc, 4827 diag::err_omp_prohibited_region_critical_same_name) 4828 << CurrentName.getName(); 4829 if (PreviousCriticalLoc.isValid()) 4830 SemaRef.Diag(PreviousCriticalLoc, 4831 diag::note_omp_previous_critical_region); 4832 return true; 4833 } 4834 } else if (CurrentRegion == OMPD_barrier) { 4835 // OpenMP 5.1 [2.22, Nesting of Regions] 4836 // A barrier region may not be closely nested inside a worksharing, loop, 4837 // task, taskloop, critical, ordered, atomic, or masked region. 4838 NestingProhibited = 4839 isOpenMPWorksharingDirective(ParentRegion) || 4840 isOpenMPGenericLoopDirective(ParentRegion) || 4841 isOpenMPTaskingDirective(ParentRegion) || 4842 ParentRegion == OMPD_master || ParentRegion == OMPD_masked || 4843 ParentRegion == OMPD_parallel_master || 4844 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered; 4845 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 4846 !isOpenMPParallelDirective(CurrentRegion) && 4847 !isOpenMPTeamsDirective(CurrentRegion)) { 4848 // OpenMP 5.1 [2.22, Nesting of Regions] 4849 // A loop region that binds to a parallel region or a worksharing region 4850 // may not be closely nested inside a worksharing, loop, task, taskloop, 4851 // critical, ordered, atomic, or masked region. 4852 NestingProhibited = 4853 isOpenMPWorksharingDirective(ParentRegion) || 4854 isOpenMPGenericLoopDirective(ParentRegion) || 4855 isOpenMPTaskingDirective(ParentRegion) || 4856 ParentRegion == OMPD_master || ParentRegion == OMPD_masked || 4857 ParentRegion == OMPD_parallel_master || 4858 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered; 4859 Recommend = ShouldBeInParallelRegion; 4860 } else if (CurrentRegion == OMPD_ordered) { 4861 // OpenMP [2.16, Nesting of Regions] 4862 // An ordered region may not be closely nested inside a critical, 4863 // atomic, or explicit task region. 4864 // An ordered region must be closely nested inside a loop region (or 4865 // parallel loop region) with an ordered clause. 4866 // OpenMP [2.8.1,simd Construct, Restrictions] 4867 // An ordered construct with the simd clause is the only OpenMP construct 4868 // that can appear in the simd region. 4869 NestingProhibited = ParentRegion == OMPD_critical || 4870 isOpenMPTaskingDirective(ParentRegion) || 4871 !(isOpenMPSimdDirective(ParentRegion) || 4872 Stack->isParentOrderedRegion()); 4873 Recommend = ShouldBeInOrderedRegion; 4874 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 4875 // OpenMP [2.16, Nesting of Regions] 4876 // If specified, a teams construct must be contained within a target 4877 // construct. 4878 NestingProhibited = 4879 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) || 4880 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown && 4881 ParentRegion != OMPD_target); 4882 OrphanSeen = ParentRegion == OMPD_unknown; 4883 Recommend = ShouldBeInTargetRegion; 4884 } else if (CurrentRegion == OMPD_scan) { 4885 // OpenMP [2.16, Nesting of Regions] 4886 // If specified, a teams construct must be contained within a target 4887 // construct. 4888 NestingProhibited = 4889 SemaRef.LangOpts.OpenMP < 50 || 4890 (ParentRegion != OMPD_simd && ParentRegion != OMPD_for && 4891 ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for && 4892 ParentRegion != OMPD_parallel_for_simd); 4893 OrphanSeen = ParentRegion == OMPD_unknown; 4894 Recommend = ShouldBeInLoopSimdRegion; 4895 } 4896 if (!NestingProhibited && 4897 !isOpenMPTargetExecutionDirective(CurrentRegion) && 4898 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 4899 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 4900 // OpenMP [5.1, 2.22, Nesting of Regions] 4901 // distribute, distribute simd, distribute parallel worksharing-loop, 4902 // distribute parallel worksharing-loop SIMD, loop, parallel regions, 4903 // including any parallel regions arising from combined constructs, 4904 // omp_get_num_teams() regions, and omp_get_team_num() regions are the 4905 // only OpenMP regions that may be strictly nested inside the teams 4906 // region. 4907 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 4908 !isOpenMPDistributeDirective(CurrentRegion) && 4909 CurrentRegion != OMPD_loop; 4910 Recommend = ShouldBeInParallelRegion; 4911 } 4912 if (!NestingProhibited && CurrentRegion == OMPD_loop) { 4913 // OpenMP [5.1, 2.11.7, loop Construct, Restrictions] 4914 // If the bind clause is present on the loop construct and binding is 4915 // teams then the corresponding loop region must be strictly nested inside 4916 // a teams region. 4917 NestingProhibited = BindKind == OMPC_BIND_teams && 4918 ParentRegion != OMPD_teams && 4919 ParentRegion != OMPD_target_teams; 4920 Recommend = ShouldBeInTeamsRegion; 4921 } 4922 if (!NestingProhibited && 4923 isOpenMPNestingDistributeDirective(CurrentRegion)) { 4924 // OpenMP 4.5 [2.17 Nesting of Regions] 4925 // The region associated with the distribute construct must be strictly 4926 // nested inside a teams region 4927 NestingProhibited = 4928 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 4929 Recommend = ShouldBeInTeamsRegion; 4930 } 4931 if (!NestingProhibited && 4932 (isOpenMPTargetExecutionDirective(CurrentRegion) || 4933 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 4934 // OpenMP 4.5 [2.17 Nesting of Regions] 4935 // If a target, target update, target data, target enter data, or 4936 // target exit data construct is encountered during execution of a 4937 // target region, the behavior is unspecified. 4938 NestingProhibited = Stack->hasDirective( 4939 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 4940 SourceLocation) { 4941 if (isOpenMPTargetExecutionDirective(K)) { 4942 OffendingRegion = K; 4943 return true; 4944 } 4945 return false; 4946 }, 4947 false /* don't skip top directive */); 4948 CloseNesting = false; 4949 } 4950 if (NestingProhibited) { 4951 if (OrphanSeen) { 4952 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 4953 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 4954 } else { 4955 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 4956 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 4957 << Recommend << getOpenMPDirectiveName(CurrentRegion); 4958 } 4959 return true; 4960 } 4961 } 4962 return false; 4963 } 4964 4965 struct Kind2Unsigned { 4966 using argument_type = OpenMPDirectiveKind; 4967 unsigned operator()(argument_type DK) { return unsigned(DK); } 4968 }; 4969 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 4970 ArrayRef<OMPClause *> Clauses, 4971 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 4972 bool ErrorFound = false; 4973 unsigned NamedModifiersNumber = 0; 4974 llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers; 4975 FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1); 4976 SmallVector<SourceLocation, 4> NameModifierLoc; 4977 for (const OMPClause *C : Clauses) { 4978 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 4979 // At most one if clause without a directive-name-modifier can appear on 4980 // the directive. 4981 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 4982 if (FoundNameModifiers[CurNM]) { 4983 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 4984 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 4985 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 4986 ErrorFound = true; 4987 } else if (CurNM != OMPD_unknown) { 4988 NameModifierLoc.push_back(IC->getNameModifierLoc()); 4989 ++NamedModifiersNumber; 4990 } 4991 FoundNameModifiers[CurNM] = IC; 4992 if (CurNM == OMPD_unknown) 4993 continue; 4994 // Check if the specified name modifier is allowed for the current 4995 // directive. 4996 // At most one if clause with the particular directive-name-modifier can 4997 // appear on the directive. 4998 if (!llvm::is_contained(AllowedNameModifiers, CurNM)) { 4999 S.Diag(IC->getNameModifierLoc(), 5000 diag::err_omp_wrong_if_directive_name_modifier) 5001 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 5002 ErrorFound = true; 5003 } 5004 } 5005 } 5006 // If any if clause on the directive includes a directive-name-modifier then 5007 // all if clauses on the directive must include a directive-name-modifier. 5008 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 5009 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 5010 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(), 5011 diag::err_omp_no_more_if_clause); 5012 } else { 5013 std::string Values; 5014 std::string Sep(", "); 5015 unsigned AllowedCnt = 0; 5016 unsigned TotalAllowedNum = 5017 AllowedNameModifiers.size() - NamedModifiersNumber; 5018 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 5019 ++Cnt) { 5020 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 5021 if (!FoundNameModifiers[NM]) { 5022 Values += "'"; 5023 Values += getOpenMPDirectiveName(NM); 5024 Values += "'"; 5025 if (AllowedCnt + 2 == TotalAllowedNum) 5026 Values += " or "; 5027 else if (AllowedCnt + 1 != TotalAllowedNum) 5028 Values += Sep; 5029 ++AllowedCnt; 5030 } 5031 } 5032 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(), 5033 diag::err_omp_unnamed_if_clause) 5034 << (TotalAllowedNum > 1) << Values; 5035 } 5036 for (SourceLocation Loc : NameModifierLoc) { 5037 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 5038 } 5039 ErrorFound = true; 5040 } 5041 return ErrorFound; 5042 } 5043 5044 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr, 5045 SourceLocation &ELoc, 5046 SourceRange &ERange, 5047 bool AllowArraySection) { 5048 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 5049 RefExpr->containsUnexpandedParameterPack()) 5050 return std::make_pair(nullptr, true); 5051 5052 // OpenMP [3.1, C/C++] 5053 // A list item is a variable name. 5054 // OpenMP [2.9.3.3, Restrictions, p.1] 5055 // A variable that is part of another variable (as an array or 5056 // structure element) cannot appear in a private clause. 5057 RefExpr = RefExpr->IgnoreParens(); 5058 enum { 5059 NoArrayExpr = -1, 5060 ArraySubscript = 0, 5061 OMPArraySection = 1 5062 } IsArrayExpr = NoArrayExpr; 5063 if (AllowArraySection) { 5064 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 5065 Expr *Base = ASE->getBase()->IgnoreParenImpCasts(); 5066 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 5067 Base = TempASE->getBase()->IgnoreParenImpCasts(); 5068 RefExpr = Base; 5069 IsArrayExpr = ArraySubscript; 5070 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 5071 Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 5072 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 5073 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 5074 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 5075 Base = TempASE->getBase()->IgnoreParenImpCasts(); 5076 RefExpr = Base; 5077 IsArrayExpr = OMPArraySection; 5078 } 5079 } 5080 ELoc = RefExpr->getExprLoc(); 5081 ERange = RefExpr->getSourceRange(); 5082 RefExpr = RefExpr->IgnoreParenImpCasts(); 5083 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 5084 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 5085 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 5086 (S.getCurrentThisType().isNull() || !ME || 5087 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 5088 !isa<FieldDecl>(ME->getMemberDecl()))) { 5089 if (IsArrayExpr != NoArrayExpr) { 5090 S.Diag(ELoc, diag::err_omp_expected_base_var_name) 5091 << IsArrayExpr << ERange; 5092 } else { 5093 S.Diag(ELoc, 5094 AllowArraySection 5095 ? diag::err_omp_expected_var_name_member_expr_or_array_item 5096 : diag::err_omp_expected_var_name_member_expr) 5097 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 5098 } 5099 return std::make_pair(nullptr, false); 5100 } 5101 return std::make_pair( 5102 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false); 5103 } 5104 5105 namespace { 5106 /// Checks if the allocator is used in uses_allocators clause to be allowed in 5107 /// target regions. 5108 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> { 5109 DSAStackTy *S = nullptr; 5110 5111 public: 5112 bool VisitDeclRefExpr(const DeclRefExpr *E) { 5113 return S->isUsesAllocatorsDecl(E->getDecl()) 5114 .getValueOr( 5115 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) == 5116 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait; 5117 } 5118 bool VisitStmt(const Stmt *S) { 5119 for (const Stmt *Child : S->children()) { 5120 if (Child && Visit(Child)) 5121 return true; 5122 } 5123 return false; 5124 } 5125 explicit AllocatorChecker(DSAStackTy *S) : S(S) {} 5126 }; 5127 } // namespace 5128 5129 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack, 5130 ArrayRef<OMPClause *> Clauses) { 5131 assert(!S.CurContext->isDependentContext() && 5132 "Expected non-dependent context."); 5133 auto AllocateRange = 5134 llvm::make_filter_range(Clauses, OMPAllocateClause::classof); 5135 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>> DeclToCopy; 5136 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) { 5137 return isOpenMPPrivate(C->getClauseKind()); 5138 }); 5139 for (OMPClause *Cl : PrivateRange) { 5140 MutableArrayRef<Expr *>::iterator I, It, Et; 5141 if (Cl->getClauseKind() == OMPC_private) { 5142 auto *PC = cast<OMPPrivateClause>(Cl); 5143 I = PC->private_copies().begin(); 5144 It = PC->varlist_begin(); 5145 Et = PC->varlist_end(); 5146 } else if (Cl->getClauseKind() == OMPC_firstprivate) { 5147 auto *PC = cast<OMPFirstprivateClause>(Cl); 5148 I = PC->private_copies().begin(); 5149 It = PC->varlist_begin(); 5150 Et = PC->varlist_end(); 5151 } else if (Cl->getClauseKind() == OMPC_lastprivate) { 5152 auto *PC = cast<OMPLastprivateClause>(Cl); 5153 I = PC->private_copies().begin(); 5154 It = PC->varlist_begin(); 5155 Et = PC->varlist_end(); 5156 } else if (Cl->getClauseKind() == OMPC_linear) { 5157 auto *PC = cast<OMPLinearClause>(Cl); 5158 I = PC->privates().begin(); 5159 It = PC->varlist_begin(); 5160 Et = PC->varlist_end(); 5161 } else if (Cl->getClauseKind() == OMPC_reduction) { 5162 auto *PC = cast<OMPReductionClause>(Cl); 5163 I = PC->privates().begin(); 5164 It = PC->varlist_begin(); 5165 Et = PC->varlist_end(); 5166 } else if (Cl->getClauseKind() == OMPC_task_reduction) { 5167 auto *PC = cast<OMPTaskReductionClause>(Cl); 5168 I = PC->privates().begin(); 5169 It = PC->varlist_begin(); 5170 Et = PC->varlist_end(); 5171 } else if (Cl->getClauseKind() == OMPC_in_reduction) { 5172 auto *PC = cast<OMPInReductionClause>(Cl); 5173 I = PC->privates().begin(); 5174 It = PC->varlist_begin(); 5175 Et = PC->varlist_end(); 5176 } else { 5177 llvm_unreachable("Expected private clause."); 5178 } 5179 for (Expr *E : llvm::make_range(It, Et)) { 5180 if (!*I) { 5181 ++I; 5182 continue; 5183 } 5184 SourceLocation ELoc; 5185 SourceRange ERange; 5186 Expr *SimpleRefExpr = E; 5187 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 5188 /*AllowArraySection=*/true); 5189 DeclToCopy.try_emplace(Res.first, 5190 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl())); 5191 ++I; 5192 } 5193 } 5194 for (OMPClause *C : AllocateRange) { 5195 auto *AC = cast<OMPAllocateClause>(C); 5196 if (S.getLangOpts().OpenMP >= 50 && 5197 !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() && 5198 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 5199 AC->getAllocator()) { 5200 Expr *Allocator = AC->getAllocator(); 5201 // OpenMP, 2.12.5 target Construct 5202 // Memory allocators that do not appear in a uses_allocators clause cannot 5203 // appear as an allocator in an allocate clause or be used in the target 5204 // region unless a requires directive with the dynamic_allocators clause 5205 // is present in the same compilation unit. 5206 AllocatorChecker Checker(Stack); 5207 if (Checker.Visit(Allocator)) 5208 S.Diag(Allocator->getExprLoc(), 5209 diag::err_omp_allocator_not_in_uses_allocators) 5210 << Allocator->getSourceRange(); 5211 } 5212 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind = 5213 getAllocatorKind(S, Stack, AC->getAllocator()); 5214 // OpenMP, 2.11.4 allocate Clause, Restrictions. 5215 // For task, taskloop or target directives, allocation requests to memory 5216 // allocators with the trait access set to thread result in unspecified 5217 // behavior. 5218 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc && 5219 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 5220 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) { 5221 S.Diag(AC->getAllocator()->getExprLoc(), 5222 diag::warn_omp_allocate_thread_on_task_target_directive) 5223 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 5224 } 5225 for (Expr *E : AC->varlists()) { 5226 SourceLocation ELoc; 5227 SourceRange ERange; 5228 Expr *SimpleRefExpr = E; 5229 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange); 5230 ValueDecl *VD = Res.first; 5231 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false); 5232 if (!isOpenMPPrivate(Data.CKind)) { 5233 S.Diag(E->getExprLoc(), 5234 diag::err_omp_expected_private_copy_for_allocate); 5235 continue; 5236 } 5237 VarDecl *PrivateVD = DeclToCopy[VD]; 5238 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD, 5239 AllocatorKind, AC->getAllocator())) 5240 continue; 5241 // Placeholder until allocate clause supports align modifier. 5242 Expr *Alignment = nullptr; 5243 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(), 5244 Alignment, E->getSourceRange()); 5245 } 5246 } 5247 } 5248 5249 namespace { 5250 /// Rewrite statements and expressions for Sema \p Actions CurContext. 5251 /// 5252 /// Used to wrap already parsed statements/expressions into a new CapturedStmt 5253 /// context. DeclRefExpr used inside the new context are changed to refer to the 5254 /// captured variable instead. 5255 class CaptureVars : public TreeTransform<CaptureVars> { 5256 using BaseTransform = TreeTransform<CaptureVars>; 5257 5258 public: 5259 CaptureVars(Sema &Actions) : BaseTransform(Actions) {} 5260 5261 bool AlwaysRebuild() { return true; } 5262 }; 5263 } // namespace 5264 5265 static VarDecl *precomputeExpr(Sema &Actions, 5266 SmallVectorImpl<Stmt *> &BodyStmts, Expr *E, 5267 StringRef Name) { 5268 Expr *NewE = AssertSuccess(CaptureVars(Actions).TransformExpr(E)); 5269 VarDecl *NewVar = buildVarDecl(Actions, {}, NewE->getType(), Name, nullptr, 5270 dyn_cast<DeclRefExpr>(E->IgnoreImplicit())); 5271 auto *NewDeclStmt = cast<DeclStmt>(AssertSuccess( 5272 Actions.ActOnDeclStmt(Actions.ConvertDeclToDeclGroup(NewVar), {}, {}))); 5273 Actions.AddInitializerToDecl(NewDeclStmt->getSingleDecl(), NewE, false); 5274 BodyStmts.push_back(NewDeclStmt); 5275 return NewVar; 5276 } 5277 5278 /// Create a closure that computes the number of iterations of a loop. 5279 /// 5280 /// \param Actions The Sema object. 5281 /// \param LogicalTy Type for the logical iteration number. 5282 /// \param Rel Comparison operator of the loop condition. 5283 /// \param StartExpr Value of the loop counter at the first iteration. 5284 /// \param StopExpr Expression the loop counter is compared against in the loop 5285 /// condition. \param StepExpr Amount of increment after each iteration. 5286 /// 5287 /// \return Closure (CapturedStmt) of the distance calculation. 5288 static CapturedStmt *buildDistanceFunc(Sema &Actions, QualType LogicalTy, 5289 BinaryOperator::Opcode Rel, 5290 Expr *StartExpr, Expr *StopExpr, 5291 Expr *StepExpr) { 5292 ASTContext &Ctx = Actions.getASTContext(); 5293 TypeSourceInfo *LogicalTSI = Ctx.getTrivialTypeSourceInfo(LogicalTy); 5294 5295 // Captured regions currently don't support return values, we use an 5296 // out-parameter instead. All inputs are implicit captures. 5297 // TODO: Instead of capturing each DeclRefExpr occurring in 5298 // StartExpr/StopExpr/Step, these could also be passed as a value capture. 5299 QualType ResultTy = Ctx.getLValueReferenceType(LogicalTy); 5300 Sema::CapturedParamNameType Params[] = {{"Distance", ResultTy}, 5301 {StringRef(), QualType()}}; 5302 Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params); 5303 5304 Stmt *Body; 5305 { 5306 Sema::CompoundScopeRAII CompoundScope(Actions); 5307 CapturedDecl *CS = cast<CapturedDecl>(Actions.CurContext); 5308 5309 // Get the LValue expression for the result. 5310 ImplicitParamDecl *DistParam = CS->getParam(0); 5311 DeclRefExpr *DistRef = Actions.BuildDeclRefExpr( 5312 DistParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr); 5313 5314 SmallVector<Stmt *, 4> BodyStmts; 5315 5316 // Capture all referenced variable references. 5317 // TODO: Instead of computing NewStart/NewStop/NewStep inside the 5318 // CapturedStmt, we could compute them before and capture the result, to be 5319 // used jointly with the LoopVar function. 5320 VarDecl *NewStart = precomputeExpr(Actions, BodyStmts, StartExpr, ".start"); 5321 VarDecl *NewStop = precomputeExpr(Actions, BodyStmts, StopExpr, ".stop"); 5322 VarDecl *NewStep = precomputeExpr(Actions, BodyStmts, StepExpr, ".step"); 5323 auto BuildVarRef = [&](VarDecl *VD) { 5324 return buildDeclRefExpr(Actions, VD, VD->getType(), {}); 5325 }; 5326 5327 IntegerLiteral *Zero = IntegerLiteral::Create( 5328 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 0), LogicalTy, {}); 5329 Expr *Dist; 5330 if (Rel == BO_NE) { 5331 // When using a != comparison, the increment can be +1 or -1. This can be 5332 // dynamic at runtime, so we need to check for the direction. 5333 Expr *IsNegStep = AssertSuccess( 5334 Actions.BuildBinOp(nullptr, {}, BO_LT, BuildVarRef(NewStep), Zero)); 5335 5336 // Positive increment. 5337 Expr *ForwardRange = AssertSuccess(Actions.BuildBinOp( 5338 nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart))); 5339 ForwardRange = AssertSuccess( 5340 Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, ForwardRange)); 5341 Expr *ForwardDist = AssertSuccess(Actions.BuildBinOp( 5342 nullptr, {}, BO_Div, ForwardRange, BuildVarRef(NewStep))); 5343 5344 // Negative increment. 5345 Expr *BackwardRange = AssertSuccess(Actions.BuildBinOp( 5346 nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop))); 5347 BackwardRange = AssertSuccess( 5348 Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, BackwardRange)); 5349 Expr *NegIncAmount = AssertSuccess( 5350 Actions.BuildUnaryOp(nullptr, {}, UO_Minus, BuildVarRef(NewStep))); 5351 Expr *BackwardDist = AssertSuccess( 5352 Actions.BuildBinOp(nullptr, {}, BO_Div, BackwardRange, NegIncAmount)); 5353 5354 // Use the appropriate case. 5355 Dist = AssertSuccess(Actions.ActOnConditionalOp( 5356 {}, {}, IsNegStep, BackwardDist, ForwardDist)); 5357 } else { 5358 assert((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) && 5359 "Expected one of these relational operators"); 5360 5361 // We can derive the direction from any other comparison operator. It is 5362 // non well-formed OpenMP if Step increments/decrements in the other 5363 // directions. Whether at least the first iteration passes the loop 5364 // condition. 5365 Expr *HasAnyIteration = AssertSuccess(Actions.BuildBinOp( 5366 nullptr, {}, Rel, BuildVarRef(NewStart), BuildVarRef(NewStop))); 5367 5368 // Compute the range between first and last counter value. 5369 Expr *Range; 5370 if (Rel == BO_GE || Rel == BO_GT) 5371 Range = AssertSuccess(Actions.BuildBinOp( 5372 nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop))); 5373 else 5374 Range = AssertSuccess(Actions.BuildBinOp( 5375 nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart))); 5376 5377 // Ensure unsigned range space. 5378 Range = 5379 AssertSuccess(Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, Range)); 5380 5381 if (Rel == BO_LE || Rel == BO_GE) { 5382 // Add one to the range if the relational operator is inclusive. 5383 Range = AssertSuccess(Actions.BuildBinOp( 5384 nullptr, {}, BO_Add, Range, 5385 Actions.ActOnIntegerConstant(SourceLocation(), 1).get())); 5386 } 5387 5388 // Divide by the absolute step amount. 5389 Expr *Divisor = BuildVarRef(NewStep); 5390 if (Rel == BO_GE || Rel == BO_GT) 5391 Divisor = 5392 AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Minus, Divisor)); 5393 Dist = AssertSuccess( 5394 Actions.BuildBinOp(nullptr, {}, BO_Div, Range, Divisor)); 5395 5396 // If there is not at least one iteration, the range contains garbage. Fix 5397 // to zero in this case. 5398 Dist = AssertSuccess( 5399 Actions.ActOnConditionalOp({}, {}, HasAnyIteration, Dist, Zero)); 5400 } 5401 5402 // Assign the result to the out-parameter. 5403 Stmt *ResultAssign = AssertSuccess(Actions.BuildBinOp( 5404 Actions.getCurScope(), {}, BO_Assign, DistRef, Dist)); 5405 BodyStmts.push_back(ResultAssign); 5406 5407 Body = AssertSuccess(Actions.ActOnCompoundStmt({}, {}, BodyStmts, false)); 5408 } 5409 5410 return cast<CapturedStmt>( 5411 AssertSuccess(Actions.ActOnCapturedRegionEnd(Body))); 5412 } 5413 5414 /// Create a closure that computes the loop variable from the logical iteration 5415 /// number. 5416 /// 5417 /// \param Actions The Sema object. 5418 /// \param LoopVarTy Type for the loop variable used for result value. 5419 /// \param LogicalTy Type for the logical iteration number. 5420 /// \param StartExpr Value of the loop counter at the first iteration. 5421 /// \param Step Amount of increment after each iteration. 5422 /// \param Deref Whether the loop variable is a dereference of the loop 5423 /// counter variable. 5424 /// 5425 /// \return Closure (CapturedStmt) of the loop value calculation. 5426 static CapturedStmt *buildLoopVarFunc(Sema &Actions, QualType LoopVarTy, 5427 QualType LogicalTy, 5428 DeclRefExpr *StartExpr, Expr *Step, 5429 bool Deref) { 5430 ASTContext &Ctx = Actions.getASTContext(); 5431 5432 // Pass the result as an out-parameter. Passing as return value would require 5433 // the OpenMPIRBuilder to know additional C/C++ semantics, such as how to 5434 // invoke a copy constructor. 5435 QualType TargetParamTy = Ctx.getLValueReferenceType(LoopVarTy); 5436 Sema::CapturedParamNameType Params[] = {{"LoopVar", TargetParamTy}, 5437 {"Logical", LogicalTy}, 5438 {StringRef(), QualType()}}; 5439 Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params); 5440 5441 // Capture the initial iterator which represents the LoopVar value at the 5442 // zero's logical iteration. Since the original ForStmt/CXXForRangeStmt update 5443 // it in every iteration, capture it by value before it is modified. 5444 VarDecl *StartVar = cast<VarDecl>(StartExpr->getDecl()); 5445 bool Invalid = Actions.tryCaptureVariable(StartVar, {}, 5446 Sema::TryCapture_ExplicitByVal, {}); 5447 (void)Invalid; 5448 assert(!Invalid && "Expecting capture-by-value to work."); 5449 5450 Expr *Body; 5451 { 5452 Sema::CompoundScopeRAII CompoundScope(Actions); 5453 auto *CS = cast<CapturedDecl>(Actions.CurContext); 5454 5455 ImplicitParamDecl *TargetParam = CS->getParam(0); 5456 DeclRefExpr *TargetRef = Actions.BuildDeclRefExpr( 5457 TargetParam, LoopVarTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr); 5458 ImplicitParamDecl *IndvarParam = CS->getParam(1); 5459 DeclRefExpr *LogicalRef = Actions.BuildDeclRefExpr( 5460 IndvarParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr); 5461 5462 // Capture the Start expression. 5463 CaptureVars Recap(Actions); 5464 Expr *NewStart = AssertSuccess(Recap.TransformExpr(StartExpr)); 5465 Expr *NewStep = AssertSuccess(Recap.TransformExpr(Step)); 5466 5467 Expr *Skip = AssertSuccess( 5468 Actions.BuildBinOp(nullptr, {}, BO_Mul, NewStep, LogicalRef)); 5469 // TODO: Explicitly cast to the iterator's difference_type instead of 5470 // relying on implicit conversion. 5471 Expr *Advanced = 5472 AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, NewStart, Skip)); 5473 5474 if (Deref) { 5475 // For range-based for-loops convert the loop counter value to a concrete 5476 // loop variable value by dereferencing the iterator. 5477 Advanced = 5478 AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Deref, Advanced)); 5479 } 5480 5481 // Assign the result to the output parameter. 5482 Body = AssertSuccess(Actions.BuildBinOp(Actions.getCurScope(), {}, 5483 BO_Assign, TargetRef, Advanced)); 5484 } 5485 return cast<CapturedStmt>( 5486 AssertSuccess(Actions.ActOnCapturedRegionEnd(Body))); 5487 } 5488 5489 StmtResult Sema::ActOnOpenMPCanonicalLoop(Stmt *AStmt) { 5490 ASTContext &Ctx = getASTContext(); 5491 5492 // Extract the common elements of ForStmt and CXXForRangeStmt: 5493 // Loop variable, repeat condition, increment 5494 Expr *Cond, *Inc; 5495 VarDecl *LIVDecl, *LUVDecl; 5496 if (auto *For = dyn_cast<ForStmt>(AStmt)) { 5497 Stmt *Init = For->getInit(); 5498 if (auto *LCVarDeclStmt = dyn_cast<DeclStmt>(Init)) { 5499 // For statement declares loop variable. 5500 LIVDecl = cast<VarDecl>(LCVarDeclStmt->getSingleDecl()); 5501 } else if (auto *LCAssign = dyn_cast<BinaryOperator>(Init)) { 5502 // For statement reuses variable. 5503 assert(LCAssign->getOpcode() == BO_Assign && 5504 "init part must be a loop variable assignment"); 5505 auto *CounterRef = cast<DeclRefExpr>(LCAssign->getLHS()); 5506 LIVDecl = cast<VarDecl>(CounterRef->getDecl()); 5507 } else 5508 llvm_unreachable("Cannot determine loop variable"); 5509 LUVDecl = LIVDecl; 5510 5511 Cond = For->getCond(); 5512 Inc = For->getInc(); 5513 } else if (auto *RangeFor = dyn_cast<CXXForRangeStmt>(AStmt)) { 5514 DeclStmt *BeginStmt = RangeFor->getBeginStmt(); 5515 LIVDecl = cast<VarDecl>(BeginStmt->getSingleDecl()); 5516 LUVDecl = RangeFor->getLoopVariable(); 5517 5518 Cond = RangeFor->getCond(); 5519 Inc = RangeFor->getInc(); 5520 } else 5521 llvm_unreachable("unhandled kind of loop"); 5522 5523 QualType CounterTy = LIVDecl->getType(); 5524 QualType LVTy = LUVDecl->getType(); 5525 5526 // Analyze the loop condition. 5527 Expr *LHS, *RHS; 5528 BinaryOperator::Opcode CondRel; 5529 Cond = Cond->IgnoreImplicit(); 5530 if (auto *CondBinExpr = dyn_cast<BinaryOperator>(Cond)) { 5531 LHS = CondBinExpr->getLHS(); 5532 RHS = CondBinExpr->getRHS(); 5533 CondRel = CondBinExpr->getOpcode(); 5534 } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Cond)) { 5535 assert(CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands"); 5536 LHS = CondCXXOp->getArg(0); 5537 RHS = CondCXXOp->getArg(1); 5538 switch (CondCXXOp->getOperator()) { 5539 case OO_ExclaimEqual: 5540 CondRel = BO_NE; 5541 break; 5542 case OO_Less: 5543 CondRel = BO_LT; 5544 break; 5545 case OO_LessEqual: 5546 CondRel = BO_LE; 5547 break; 5548 case OO_Greater: 5549 CondRel = BO_GT; 5550 break; 5551 case OO_GreaterEqual: 5552 CondRel = BO_GE; 5553 break; 5554 default: 5555 llvm_unreachable("unexpected iterator operator"); 5556 } 5557 } else 5558 llvm_unreachable("unexpected loop condition"); 5559 5560 // Normalize such that the loop counter is on the LHS. 5561 if (!isa<DeclRefExpr>(LHS->IgnoreImplicit()) || 5562 cast<DeclRefExpr>(LHS->IgnoreImplicit())->getDecl() != LIVDecl) { 5563 std::swap(LHS, RHS); 5564 CondRel = BinaryOperator::reverseComparisonOp(CondRel); 5565 } 5566 auto *CounterRef = cast<DeclRefExpr>(LHS->IgnoreImplicit()); 5567 5568 // Decide the bit width for the logical iteration counter. By default use the 5569 // unsigned ptrdiff_t integer size (for iterators and pointers). 5570 // TODO: For iterators, use iterator::difference_type, 5571 // std::iterator_traits<>::difference_type or decltype(it - end). 5572 QualType LogicalTy = Ctx.getUnsignedPointerDiffType(); 5573 if (CounterTy->isIntegerType()) { 5574 unsigned BitWidth = Ctx.getIntWidth(CounterTy); 5575 LogicalTy = Ctx.getIntTypeForBitwidth(BitWidth, false); 5576 } 5577 5578 // Analyze the loop increment. 5579 Expr *Step; 5580 if (auto *IncUn = dyn_cast<UnaryOperator>(Inc)) { 5581 int Direction; 5582 switch (IncUn->getOpcode()) { 5583 case UO_PreInc: 5584 case UO_PostInc: 5585 Direction = 1; 5586 break; 5587 case UO_PreDec: 5588 case UO_PostDec: 5589 Direction = -1; 5590 break; 5591 default: 5592 llvm_unreachable("unhandled unary increment operator"); 5593 } 5594 Step = IntegerLiteral::Create( 5595 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), Direction), LogicalTy, {}); 5596 } else if (auto *IncBin = dyn_cast<BinaryOperator>(Inc)) { 5597 if (IncBin->getOpcode() == BO_AddAssign) { 5598 Step = IncBin->getRHS(); 5599 } else if (IncBin->getOpcode() == BO_SubAssign) { 5600 Step = 5601 AssertSuccess(BuildUnaryOp(nullptr, {}, UO_Minus, IncBin->getRHS())); 5602 } else 5603 llvm_unreachable("unhandled binary increment operator"); 5604 } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Inc)) { 5605 switch (CondCXXOp->getOperator()) { 5606 case OO_PlusPlus: 5607 Step = IntegerLiteral::Create( 5608 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {}); 5609 break; 5610 case OO_MinusMinus: 5611 Step = IntegerLiteral::Create( 5612 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), -1), LogicalTy, {}); 5613 break; 5614 case OO_PlusEqual: 5615 Step = CondCXXOp->getArg(1); 5616 break; 5617 case OO_MinusEqual: 5618 Step = AssertSuccess( 5619 BuildUnaryOp(nullptr, {}, UO_Minus, CondCXXOp->getArg(1))); 5620 break; 5621 default: 5622 llvm_unreachable("unhandled overloaded increment operator"); 5623 } 5624 } else 5625 llvm_unreachable("unknown increment expression"); 5626 5627 CapturedStmt *DistanceFunc = 5628 buildDistanceFunc(*this, LogicalTy, CondRel, LHS, RHS, Step); 5629 CapturedStmt *LoopVarFunc = buildLoopVarFunc( 5630 *this, LVTy, LogicalTy, CounterRef, Step, isa<CXXForRangeStmt>(AStmt)); 5631 DeclRefExpr *LVRef = BuildDeclRefExpr(LUVDecl, LUVDecl->getType(), VK_LValue, 5632 {}, nullptr, nullptr, {}, nullptr); 5633 return OMPCanonicalLoop::create(getASTContext(), AStmt, DistanceFunc, 5634 LoopVarFunc, LVRef); 5635 } 5636 5637 StmtResult Sema::ActOnOpenMPLoopnest(Stmt *AStmt) { 5638 // Handle a literal loop. 5639 if (isa<ForStmt>(AStmt) || isa<CXXForRangeStmt>(AStmt)) 5640 return ActOnOpenMPCanonicalLoop(AStmt); 5641 5642 // If not a literal loop, it must be the result of a loop transformation. 5643 OMPExecutableDirective *LoopTransform = cast<OMPExecutableDirective>(AStmt); 5644 assert( 5645 isOpenMPLoopTransformationDirective(LoopTransform->getDirectiveKind()) && 5646 "Loop transformation directive expected"); 5647 return LoopTransform; 5648 } 5649 5650 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S, 5651 CXXScopeSpec &MapperIdScopeSpec, 5652 const DeclarationNameInfo &MapperId, 5653 QualType Type, 5654 Expr *UnresolvedMapper); 5655 5656 /// Perform DFS through the structure/class data members trying to find 5657 /// member(s) with user-defined 'default' mapper and generate implicit map 5658 /// clauses for such members with the found 'default' mapper. 5659 static void 5660 processImplicitMapsWithDefaultMappers(Sema &S, DSAStackTy *Stack, 5661 SmallVectorImpl<OMPClause *> &Clauses) { 5662 // Check for the deault mapper for data members. 5663 if (S.getLangOpts().OpenMP < 50) 5664 return; 5665 SmallVector<OMPClause *, 4> ImplicitMaps; 5666 for (int Cnt = 0, EndCnt = Clauses.size(); Cnt < EndCnt; ++Cnt) { 5667 auto *C = dyn_cast<OMPMapClause>(Clauses[Cnt]); 5668 if (!C) 5669 continue; 5670 SmallVector<Expr *, 4> SubExprs; 5671 auto *MI = C->mapperlist_begin(); 5672 for (auto I = C->varlist_begin(), End = C->varlist_end(); I != End; 5673 ++I, ++MI) { 5674 // Expression is mapped using mapper - skip it. 5675 if (*MI) 5676 continue; 5677 Expr *E = *I; 5678 // Expression is dependent - skip it, build the mapper when it gets 5679 // instantiated. 5680 if (E->isTypeDependent() || E->isValueDependent() || 5681 E->containsUnexpandedParameterPack()) 5682 continue; 5683 // Array section - need to check for the mapping of the array section 5684 // element. 5685 QualType CanonType = E->getType().getCanonicalType(); 5686 if (CanonType->isSpecificBuiltinType(BuiltinType::OMPArraySection)) { 5687 const auto *OASE = cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts()); 5688 QualType BaseType = 5689 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 5690 QualType ElemType; 5691 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 5692 ElemType = ATy->getElementType(); 5693 else 5694 ElemType = BaseType->getPointeeType(); 5695 CanonType = ElemType; 5696 } 5697 5698 // DFS over data members in structures/classes. 5699 SmallVector<std::pair<QualType, FieldDecl *>, 4> Types( 5700 1, {CanonType, nullptr}); 5701 llvm::DenseMap<const Type *, Expr *> Visited; 5702 SmallVector<std::pair<FieldDecl *, unsigned>, 4> ParentChain( 5703 1, {nullptr, 1}); 5704 while (!Types.empty()) { 5705 QualType BaseType; 5706 FieldDecl *CurFD; 5707 std::tie(BaseType, CurFD) = Types.pop_back_val(); 5708 while (ParentChain.back().second == 0) 5709 ParentChain.pop_back(); 5710 --ParentChain.back().second; 5711 if (BaseType.isNull()) 5712 continue; 5713 // Only structs/classes are allowed to have mappers. 5714 const RecordDecl *RD = BaseType.getCanonicalType()->getAsRecordDecl(); 5715 if (!RD) 5716 continue; 5717 auto It = Visited.find(BaseType.getTypePtr()); 5718 if (It == Visited.end()) { 5719 // Try to find the associated user-defined mapper. 5720 CXXScopeSpec MapperIdScopeSpec; 5721 DeclarationNameInfo DefaultMapperId; 5722 DefaultMapperId.setName(S.Context.DeclarationNames.getIdentifier( 5723 &S.Context.Idents.get("default"))); 5724 DefaultMapperId.setLoc(E->getExprLoc()); 5725 ExprResult ER = buildUserDefinedMapperRef( 5726 S, Stack->getCurScope(), MapperIdScopeSpec, DefaultMapperId, 5727 BaseType, /*UnresolvedMapper=*/nullptr); 5728 if (ER.isInvalid()) 5729 continue; 5730 It = Visited.try_emplace(BaseType.getTypePtr(), ER.get()).first; 5731 } 5732 // Found default mapper. 5733 if (It->second) { 5734 auto *OE = new (S.Context) OpaqueValueExpr(E->getExprLoc(), CanonType, 5735 VK_LValue, OK_Ordinary, E); 5736 OE->setIsUnique(/*V=*/true); 5737 Expr *BaseExpr = OE; 5738 for (const auto &P : ParentChain) { 5739 if (P.first) { 5740 BaseExpr = S.BuildMemberExpr( 5741 BaseExpr, /*IsArrow=*/false, E->getExprLoc(), 5742 NestedNameSpecifierLoc(), SourceLocation(), P.first, 5743 DeclAccessPair::make(P.first, P.first->getAccess()), 5744 /*HadMultipleCandidates=*/false, DeclarationNameInfo(), 5745 P.first->getType(), VK_LValue, OK_Ordinary); 5746 BaseExpr = S.DefaultLvalueConversion(BaseExpr).get(); 5747 } 5748 } 5749 if (CurFD) 5750 BaseExpr = S.BuildMemberExpr( 5751 BaseExpr, /*IsArrow=*/false, E->getExprLoc(), 5752 NestedNameSpecifierLoc(), SourceLocation(), CurFD, 5753 DeclAccessPair::make(CurFD, CurFD->getAccess()), 5754 /*HadMultipleCandidates=*/false, DeclarationNameInfo(), 5755 CurFD->getType(), VK_LValue, OK_Ordinary); 5756 SubExprs.push_back(BaseExpr); 5757 continue; 5758 } 5759 // Check for the "default" mapper for data members. 5760 bool FirstIter = true; 5761 for (FieldDecl *FD : RD->fields()) { 5762 if (!FD) 5763 continue; 5764 QualType FieldTy = FD->getType(); 5765 if (FieldTy.isNull() || 5766 !(FieldTy->isStructureOrClassType() || FieldTy->isUnionType())) 5767 continue; 5768 if (FirstIter) { 5769 FirstIter = false; 5770 ParentChain.emplace_back(CurFD, 1); 5771 } else { 5772 ++ParentChain.back().second; 5773 } 5774 Types.emplace_back(FieldTy, FD); 5775 } 5776 } 5777 } 5778 if (SubExprs.empty()) 5779 continue; 5780 CXXScopeSpec MapperIdScopeSpec; 5781 DeclarationNameInfo MapperId; 5782 if (OMPClause *NewClause = S.ActOnOpenMPMapClause( 5783 C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), 5784 MapperIdScopeSpec, MapperId, C->getMapType(), 5785 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(), 5786 SubExprs, OMPVarListLocTy())) 5787 Clauses.push_back(NewClause); 5788 } 5789 } 5790 5791 StmtResult Sema::ActOnOpenMPExecutableDirective( 5792 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 5793 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 5794 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 5795 StmtResult Res = StmtError(); 5796 OpenMPBindClauseKind BindKind = OMPC_BIND_unknown; 5797 if (const OMPBindClause *BC = 5798 OMPExecutableDirective::getSingleClause<OMPBindClause>(Clauses)) 5799 BindKind = BC->getBindKind(); 5800 // First check CancelRegion which is then used in checkNestingOfRegions. 5801 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 5802 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 5803 BindKind, StartLoc)) 5804 return StmtError(); 5805 5806 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 5807 VarsWithInheritedDSAType VarsWithInheritedDSA; 5808 bool ErrorFound = false; 5809 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 5810 if (AStmt && !CurContext->isDependentContext() && Kind != OMPD_atomic && 5811 Kind != OMPD_critical && Kind != OMPD_section && Kind != OMPD_master && 5812 Kind != OMPD_masked && !isOpenMPLoopTransformationDirective(Kind)) { 5813 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5814 5815 // Check default data sharing attributes for referenced variables. 5816 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 5817 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 5818 Stmt *S = AStmt; 5819 while (--ThisCaptureLevel >= 0) 5820 S = cast<CapturedStmt>(S)->getCapturedStmt(); 5821 DSAChecker.Visit(S); 5822 if (!isOpenMPTargetDataManagementDirective(Kind) && 5823 !isOpenMPTaskingDirective(Kind)) { 5824 // Visit subcaptures to generate implicit clauses for captured vars. 5825 auto *CS = cast<CapturedStmt>(AStmt); 5826 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 5827 getOpenMPCaptureRegions(CaptureRegions, Kind); 5828 // Ignore outer tasking regions for target directives. 5829 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task) 5830 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 5831 DSAChecker.visitSubCaptures(CS); 5832 } 5833 if (DSAChecker.isErrorFound()) 5834 return StmtError(); 5835 // Generate list of implicitly defined firstprivate variables. 5836 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 5837 5838 SmallVector<Expr *, 4> ImplicitFirstprivates( 5839 DSAChecker.getImplicitFirstprivate().begin(), 5840 DSAChecker.getImplicitFirstprivate().end()); 5841 const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1; 5842 SmallVector<Expr *, 4> ImplicitMaps[DefaultmapKindNum][OMPC_MAP_delete]; 5843 SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> 5844 ImplicitMapModifiers[DefaultmapKindNum]; 5845 SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers> 5846 ImplicitMapModifiersLoc[DefaultmapKindNum]; 5847 // Get the original location of present modifier from Defaultmap clause. 5848 SourceLocation PresentModifierLocs[DefaultmapKindNum]; 5849 for (OMPClause *C : Clauses) { 5850 if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C)) 5851 if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present) 5852 PresentModifierLocs[DMC->getDefaultmapKind()] = 5853 DMC->getDefaultmapModifierLoc(); 5854 } 5855 for (unsigned VC = 0; VC < DefaultmapKindNum; ++VC) { 5856 auto Kind = static_cast<OpenMPDefaultmapClauseKind>(VC); 5857 for (unsigned I = 0; I < OMPC_MAP_delete; ++I) { 5858 ArrayRef<Expr *> ImplicitMap = DSAChecker.getImplicitMap( 5859 Kind, static_cast<OpenMPMapClauseKind>(I)); 5860 ImplicitMaps[VC][I].append(ImplicitMap.begin(), ImplicitMap.end()); 5861 } 5862 ArrayRef<OpenMPMapModifierKind> ImplicitModifier = 5863 DSAChecker.getImplicitMapModifier(Kind); 5864 ImplicitMapModifiers[VC].append(ImplicitModifier.begin(), 5865 ImplicitModifier.end()); 5866 std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[VC]), 5867 ImplicitModifier.size(), PresentModifierLocs[VC]); 5868 } 5869 // Mark taskgroup task_reduction descriptors as implicitly firstprivate. 5870 for (OMPClause *C : Clauses) { 5871 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) { 5872 for (Expr *E : IRC->taskgroup_descriptors()) 5873 if (E) 5874 ImplicitFirstprivates.emplace_back(E); 5875 } 5876 // OpenMP 5.0, 2.10.1 task Construct 5877 // [detach clause]... The event-handle will be considered as if it was 5878 // specified on a firstprivate clause. 5879 if (auto *DC = dyn_cast<OMPDetachClause>(C)) 5880 ImplicitFirstprivates.push_back(DC->getEventHandler()); 5881 } 5882 if (!ImplicitFirstprivates.empty()) { 5883 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 5884 ImplicitFirstprivates, SourceLocation(), SourceLocation(), 5885 SourceLocation())) { 5886 ClausesWithImplicit.push_back(Implicit); 5887 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 5888 ImplicitFirstprivates.size(); 5889 } else { 5890 ErrorFound = true; 5891 } 5892 } 5893 // OpenMP 5.0 [2.19.7] 5894 // If a list item appears in a reduction, lastprivate or linear 5895 // clause on a combined target construct then it is treated as 5896 // if it also appears in a map clause with a map-type of tofrom 5897 if (getLangOpts().OpenMP >= 50 && Kind != OMPD_target && 5898 isOpenMPTargetExecutionDirective(Kind)) { 5899 SmallVector<Expr *, 4> ImplicitExprs; 5900 for (OMPClause *C : Clauses) { 5901 if (auto *RC = dyn_cast<OMPReductionClause>(C)) 5902 for (Expr *E : RC->varlists()) 5903 if (!isa<DeclRefExpr>(E->IgnoreParenImpCasts())) 5904 ImplicitExprs.emplace_back(E); 5905 } 5906 if (!ImplicitExprs.empty()) { 5907 ArrayRef<Expr *> Exprs = ImplicitExprs; 5908 CXXScopeSpec MapperIdScopeSpec; 5909 DeclarationNameInfo MapperId; 5910 if (OMPClause *Implicit = ActOnOpenMPMapClause( 5911 OMPC_MAP_MODIFIER_unknown, SourceLocation(), MapperIdScopeSpec, 5912 MapperId, OMPC_MAP_tofrom, 5913 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(), 5914 Exprs, OMPVarListLocTy(), /*NoDiagnose=*/true)) 5915 ClausesWithImplicit.emplace_back(Implicit); 5916 } 5917 } 5918 for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) { 5919 int ClauseKindCnt = -1; 5920 for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) { 5921 ++ClauseKindCnt; 5922 if (ImplicitMap.empty()) 5923 continue; 5924 CXXScopeSpec MapperIdScopeSpec; 5925 DeclarationNameInfo MapperId; 5926 auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt); 5927 if (OMPClause *Implicit = ActOnOpenMPMapClause( 5928 ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I], 5929 MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true, 5930 SourceLocation(), SourceLocation(), ImplicitMap, 5931 OMPVarListLocTy())) { 5932 ClausesWithImplicit.emplace_back(Implicit); 5933 ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() != 5934 ImplicitMap.size(); 5935 } else { 5936 ErrorFound = true; 5937 } 5938 } 5939 } 5940 // Build expressions for implicit maps of data members with 'default' 5941 // mappers. 5942 if (LangOpts.OpenMP >= 50) 5943 processImplicitMapsWithDefaultMappers(*this, DSAStack, 5944 ClausesWithImplicit); 5945 } 5946 5947 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 5948 switch (Kind) { 5949 case OMPD_parallel: 5950 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 5951 EndLoc); 5952 AllowedNameModifiers.push_back(OMPD_parallel); 5953 break; 5954 case OMPD_simd: 5955 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 5956 VarsWithInheritedDSA); 5957 if (LangOpts.OpenMP >= 50) 5958 AllowedNameModifiers.push_back(OMPD_simd); 5959 break; 5960 case OMPD_tile: 5961 Res = 5962 ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 5963 break; 5964 case OMPD_unroll: 5965 Res = ActOnOpenMPUnrollDirective(ClausesWithImplicit, AStmt, StartLoc, 5966 EndLoc); 5967 break; 5968 case OMPD_for: 5969 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 5970 VarsWithInheritedDSA); 5971 break; 5972 case OMPD_for_simd: 5973 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 5974 EndLoc, VarsWithInheritedDSA); 5975 if (LangOpts.OpenMP >= 50) 5976 AllowedNameModifiers.push_back(OMPD_simd); 5977 break; 5978 case OMPD_sections: 5979 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 5980 EndLoc); 5981 break; 5982 case OMPD_section: 5983 assert(ClausesWithImplicit.empty() && 5984 "No clauses are allowed for 'omp section' directive"); 5985 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 5986 break; 5987 case OMPD_single: 5988 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 5989 EndLoc); 5990 break; 5991 case OMPD_master: 5992 assert(ClausesWithImplicit.empty() && 5993 "No clauses are allowed for 'omp master' directive"); 5994 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 5995 break; 5996 case OMPD_masked: 5997 Res = ActOnOpenMPMaskedDirective(ClausesWithImplicit, AStmt, StartLoc, 5998 EndLoc); 5999 break; 6000 case OMPD_critical: 6001 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 6002 StartLoc, EndLoc); 6003 break; 6004 case OMPD_parallel_for: 6005 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 6006 EndLoc, VarsWithInheritedDSA); 6007 AllowedNameModifiers.push_back(OMPD_parallel); 6008 break; 6009 case OMPD_parallel_for_simd: 6010 Res = ActOnOpenMPParallelForSimdDirective( 6011 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6012 AllowedNameModifiers.push_back(OMPD_parallel); 6013 if (LangOpts.OpenMP >= 50) 6014 AllowedNameModifiers.push_back(OMPD_simd); 6015 break; 6016 case OMPD_parallel_master: 6017 Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt, 6018 StartLoc, EndLoc); 6019 AllowedNameModifiers.push_back(OMPD_parallel); 6020 break; 6021 case OMPD_parallel_sections: 6022 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 6023 StartLoc, EndLoc); 6024 AllowedNameModifiers.push_back(OMPD_parallel); 6025 break; 6026 case OMPD_task: 6027 Res = 6028 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 6029 AllowedNameModifiers.push_back(OMPD_task); 6030 break; 6031 case OMPD_taskyield: 6032 assert(ClausesWithImplicit.empty() && 6033 "No clauses are allowed for 'omp taskyield' directive"); 6034 assert(AStmt == nullptr && 6035 "No associated statement allowed for 'omp taskyield' directive"); 6036 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 6037 break; 6038 case OMPD_barrier: 6039 assert(ClausesWithImplicit.empty() && 6040 "No clauses are allowed for 'omp barrier' directive"); 6041 assert(AStmt == nullptr && 6042 "No associated statement allowed for 'omp barrier' directive"); 6043 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 6044 break; 6045 case OMPD_taskwait: 6046 assert(AStmt == nullptr && 6047 "No associated statement allowed for 'omp taskwait' directive"); 6048 Res = ActOnOpenMPTaskwaitDirective(ClausesWithImplicit, StartLoc, EndLoc); 6049 break; 6050 case OMPD_taskgroup: 6051 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, 6052 EndLoc); 6053 break; 6054 case OMPD_flush: 6055 assert(AStmt == nullptr && 6056 "No associated statement allowed for 'omp flush' directive"); 6057 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 6058 break; 6059 case OMPD_depobj: 6060 assert(AStmt == nullptr && 6061 "No associated statement allowed for 'omp depobj' directive"); 6062 Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc); 6063 break; 6064 case OMPD_scan: 6065 assert(AStmt == nullptr && 6066 "No associated statement allowed for 'omp scan' directive"); 6067 Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc); 6068 break; 6069 case OMPD_ordered: 6070 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 6071 EndLoc); 6072 break; 6073 case OMPD_atomic: 6074 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 6075 EndLoc); 6076 break; 6077 case OMPD_teams: 6078 Res = 6079 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 6080 break; 6081 case OMPD_target: 6082 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 6083 EndLoc); 6084 AllowedNameModifiers.push_back(OMPD_target); 6085 break; 6086 case OMPD_target_parallel: 6087 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 6088 StartLoc, EndLoc); 6089 AllowedNameModifiers.push_back(OMPD_target); 6090 AllowedNameModifiers.push_back(OMPD_parallel); 6091 break; 6092 case OMPD_target_parallel_for: 6093 Res = ActOnOpenMPTargetParallelForDirective( 6094 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6095 AllowedNameModifiers.push_back(OMPD_target); 6096 AllowedNameModifiers.push_back(OMPD_parallel); 6097 break; 6098 case OMPD_cancellation_point: 6099 assert(ClausesWithImplicit.empty() && 6100 "No clauses are allowed for 'omp cancellation point' directive"); 6101 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 6102 "cancellation point' directive"); 6103 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 6104 break; 6105 case OMPD_cancel: 6106 assert(AStmt == nullptr && 6107 "No associated statement allowed for 'omp cancel' directive"); 6108 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 6109 CancelRegion); 6110 AllowedNameModifiers.push_back(OMPD_cancel); 6111 break; 6112 case OMPD_target_data: 6113 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 6114 EndLoc); 6115 AllowedNameModifiers.push_back(OMPD_target_data); 6116 break; 6117 case OMPD_target_enter_data: 6118 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 6119 EndLoc, AStmt); 6120 AllowedNameModifiers.push_back(OMPD_target_enter_data); 6121 break; 6122 case OMPD_target_exit_data: 6123 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 6124 EndLoc, AStmt); 6125 AllowedNameModifiers.push_back(OMPD_target_exit_data); 6126 break; 6127 case OMPD_taskloop: 6128 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 6129 EndLoc, VarsWithInheritedDSA); 6130 AllowedNameModifiers.push_back(OMPD_taskloop); 6131 break; 6132 case OMPD_taskloop_simd: 6133 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 6134 EndLoc, VarsWithInheritedDSA); 6135 AllowedNameModifiers.push_back(OMPD_taskloop); 6136 if (LangOpts.OpenMP >= 50) 6137 AllowedNameModifiers.push_back(OMPD_simd); 6138 break; 6139 case OMPD_master_taskloop: 6140 Res = ActOnOpenMPMasterTaskLoopDirective( 6141 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6142 AllowedNameModifiers.push_back(OMPD_taskloop); 6143 break; 6144 case OMPD_master_taskloop_simd: 6145 Res = ActOnOpenMPMasterTaskLoopSimdDirective( 6146 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6147 AllowedNameModifiers.push_back(OMPD_taskloop); 6148 if (LangOpts.OpenMP >= 50) 6149 AllowedNameModifiers.push_back(OMPD_simd); 6150 break; 6151 case OMPD_parallel_master_taskloop: 6152 Res = ActOnOpenMPParallelMasterTaskLoopDirective( 6153 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6154 AllowedNameModifiers.push_back(OMPD_taskloop); 6155 AllowedNameModifiers.push_back(OMPD_parallel); 6156 break; 6157 case OMPD_parallel_master_taskloop_simd: 6158 Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective( 6159 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6160 AllowedNameModifiers.push_back(OMPD_taskloop); 6161 AllowedNameModifiers.push_back(OMPD_parallel); 6162 if (LangOpts.OpenMP >= 50) 6163 AllowedNameModifiers.push_back(OMPD_simd); 6164 break; 6165 case OMPD_distribute: 6166 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 6167 EndLoc, VarsWithInheritedDSA); 6168 break; 6169 case OMPD_target_update: 6170 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, 6171 EndLoc, AStmt); 6172 AllowedNameModifiers.push_back(OMPD_target_update); 6173 break; 6174 case OMPD_distribute_parallel_for: 6175 Res = ActOnOpenMPDistributeParallelForDirective( 6176 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6177 AllowedNameModifiers.push_back(OMPD_parallel); 6178 break; 6179 case OMPD_distribute_parallel_for_simd: 6180 Res = ActOnOpenMPDistributeParallelForSimdDirective( 6181 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6182 AllowedNameModifiers.push_back(OMPD_parallel); 6183 if (LangOpts.OpenMP >= 50) 6184 AllowedNameModifiers.push_back(OMPD_simd); 6185 break; 6186 case OMPD_distribute_simd: 6187 Res = ActOnOpenMPDistributeSimdDirective( 6188 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6189 if (LangOpts.OpenMP >= 50) 6190 AllowedNameModifiers.push_back(OMPD_simd); 6191 break; 6192 case OMPD_target_parallel_for_simd: 6193 Res = ActOnOpenMPTargetParallelForSimdDirective( 6194 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6195 AllowedNameModifiers.push_back(OMPD_target); 6196 AllowedNameModifiers.push_back(OMPD_parallel); 6197 if (LangOpts.OpenMP >= 50) 6198 AllowedNameModifiers.push_back(OMPD_simd); 6199 break; 6200 case OMPD_target_simd: 6201 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 6202 EndLoc, VarsWithInheritedDSA); 6203 AllowedNameModifiers.push_back(OMPD_target); 6204 if (LangOpts.OpenMP >= 50) 6205 AllowedNameModifiers.push_back(OMPD_simd); 6206 break; 6207 case OMPD_teams_distribute: 6208 Res = ActOnOpenMPTeamsDistributeDirective( 6209 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6210 break; 6211 case OMPD_teams_distribute_simd: 6212 Res = ActOnOpenMPTeamsDistributeSimdDirective( 6213 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6214 if (LangOpts.OpenMP >= 50) 6215 AllowedNameModifiers.push_back(OMPD_simd); 6216 break; 6217 case OMPD_teams_distribute_parallel_for_simd: 6218 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 6219 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6220 AllowedNameModifiers.push_back(OMPD_parallel); 6221 if (LangOpts.OpenMP >= 50) 6222 AllowedNameModifiers.push_back(OMPD_simd); 6223 break; 6224 case OMPD_teams_distribute_parallel_for: 6225 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 6226 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6227 AllowedNameModifiers.push_back(OMPD_parallel); 6228 break; 6229 case OMPD_target_teams: 6230 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 6231 EndLoc); 6232 AllowedNameModifiers.push_back(OMPD_target); 6233 break; 6234 case OMPD_target_teams_distribute: 6235 Res = ActOnOpenMPTargetTeamsDistributeDirective( 6236 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6237 AllowedNameModifiers.push_back(OMPD_target); 6238 break; 6239 case OMPD_target_teams_distribute_parallel_for: 6240 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 6241 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6242 AllowedNameModifiers.push_back(OMPD_target); 6243 AllowedNameModifiers.push_back(OMPD_parallel); 6244 break; 6245 case OMPD_target_teams_distribute_parallel_for_simd: 6246 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 6247 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6248 AllowedNameModifiers.push_back(OMPD_target); 6249 AllowedNameModifiers.push_back(OMPD_parallel); 6250 if (LangOpts.OpenMP >= 50) 6251 AllowedNameModifiers.push_back(OMPD_simd); 6252 break; 6253 case OMPD_target_teams_distribute_simd: 6254 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 6255 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6256 AllowedNameModifiers.push_back(OMPD_target); 6257 if (LangOpts.OpenMP >= 50) 6258 AllowedNameModifiers.push_back(OMPD_simd); 6259 break; 6260 case OMPD_interop: 6261 assert(AStmt == nullptr && 6262 "No associated statement allowed for 'omp interop' directive"); 6263 Res = ActOnOpenMPInteropDirective(ClausesWithImplicit, StartLoc, EndLoc); 6264 break; 6265 case OMPD_dispatch: 6266 Res = ActOnOpenMPDispatchDirective(ClausesWithImplicit, AStmt, StartLoc, 6267 EndLoc); 6268 break; 6269 case OMPD_loop: 6270 Res = ActOnOpenMPGenericLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 6271 EndLoc, VarsWithInheritedDSA); 6272 break; 6273 case OMPD_declare_target: 6274 case OMPD_end_declare_target: 6275 case OMPD_threadprivate: 6276 case OMPD_allocate: 6277 case OMPD_declare_reduction: 6278 case OMPD_declare_mapper: 6279 case OMPD_declare_simd: 6280 case OMPD_requires: 6281 case OMPD_declare_variant: 6282 case OMPD_begin_declare_variant: 6283 case OMPD_end_declare_variant: 6284 llvm_unreachable("OpenMP Directive is not allowed"); 6285 case OMPD_unknown: 6286 default: 6287 llvm_unreachable("Unknown OpenMP directive"); 6288 } 6289 6290 ErrorFound = Res.isInvalid() || ErrorFound; 6291 6292 // Check variables in the clauses if default(none) or 6293 // default(firstprivate) was specified. 6294 if (DSAStack->getDefaultDSA() == DSA_none || 6295 DSAStack->getDefaultDSA() == DSA_firstprivate) { 6296 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr); 6297 for (OMPClause *C : Clauses) { 6298 switch (C->getClauseKind()) { 6299 case OMPC_num_threads: 6300 case OMPC_dist_schedule: 6301 // Do not analyse if no parent teams directive. 6302 if (isOpenMPTeamsDirective(Kind)) 6303 break; 6304 continue; 6305 case OMPC_if: 6306 if (isOpenMPTeamsDirective(Kind) && 6307 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target) 6308 break; 6309 if (isOpenMPParallelDirective(Kind) && 6310 isOpenMPTaskLoopDirective(Kind) && 6311 cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel) 6312 break; 6313 continue; 6314 case OMPC_schedule: 6315 case OMPC_detach: 6316 break; 6317 case OMPC_grainsize: 6318 case OMPC_num_tasks: 6319 case OMPC_final: 6320 case OMPC_priority: 6321 case OMPC_novariants: 6322 case OMPC_nocontext: 6323 // Do not analyze if no parent parallel directive. 6324 if (isOpenMPParallelDirective(Kind)) 6325 break; 6326 continue; 6327 case OMPC_ordered: 6328 case OMPC_device: 6329 case OMPC_num_teams: 6330 case OMPC_thread_limit: 6331 case OMPC_hint: 6332 case OMPC_collapse: 6333 case OMPC_safelen: 6334 case OMPC_simdlen: 6335 case OMPC_sizes: 6336 case OMPC_default: 6337 case OMPC_proc_bind: 6338 case OMPC_private: 6339 case OMPC_firstprivate: 6340 case OMPC_lastprivate: 6341 case OMPC_shared: 6342 case OMPC_reduction: 6343 case OMPC_task_reduction: 6344 case OMPC_in_reduction: 6345 case OMPC_linear: 6346 case OMPC_aligned: 6347 case OMPC_copyin: 6348 case OMPC_copyprivate: 6349 case OMPC_nowait: 6350 case OMPC_untied: 6351 case OMPC_mergeable: 6352 case OMPC_allocate: 6353 case OMPC_read: 6354 case OMPC_write: 6355 case OMPC_update: 6356 case OMPC_capture: 6357 case OMPC_seq_cst: 6358 case OMPC_acq_rel: 6359 case OMPC_acquire: 6360 case OMPC_release: 6361 case OMPC_relaxed: 6362 case OMPC_depend: 6363 case OMPC_threads: 6364 case OMPC_simd: 6365 case OMPC_map: 6366 case OMPC_nogroup: 6367 case OMPC_defaultmap: 6368 case OMPC_to: 6369 case OMPC_from: 6370 case OMPC_use_device_ptr: 6371 case OMPC_use_device_addr: 6372 case OMPC_is_device_ptr: 6373 case OMPC_nontemporal: 6374 case OMPC_order: 6375 case OMPC_destroy: 6376 case OMPC_inclusive: 6377 case OMPC_exclusive: 6378 case OMPC_uses_allocators: 6379 case OMPC_affinity: 6380 case OMPC_bind: 6381 continue; 6382 case OMPC_allocator: 6383 case OMPC_flush: 6384 case OMPC_depobj: 6385 case OMPC_threadprivate: 6386 case OMPC_uniform: 6387 case OMPC_unknown: 6388 case OMPC_unified_address: 6389 case OMPC_unified_shared_memory: 6390 case OMPC_reverse_offload: 6391 case OMPC_dynamic_allocators: 6392 case OMPC_atomic_default_mem_order: 6393 case OMPC_device_type: 6394 case OMPC_match: 6395 case OMPC_when: 6396 default: 6397 llvm_unreachable("Unexpected clause"); 6398 } 6399 for (Stmt *CC : C->children()) { 6400 if (CC) 6401 DSAChecker.Visit(CC); 6402 } 6403 } 6404 for (const auto &P : DSAChecker.getVarsWithInheritedDSA()) 6405 VarsWithInheritedDSA[P.getFirst()] = P.getSecond(); 6406 } 6407 for (const auto &P : VarsWithInheritedDSA) { 6408 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst())) 6409 continue; 6410 ErrorFound = true; 6411 if (DSAStack->getDefaultDSA() == DSA_none || 6412 DSAStack->getDefaultDSA() == DSA_firstprivate) { 6413 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 6414 << P.first << P.second->getSourceRange(); 6415 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none); 6416 } else if (getLangOpts().OpenMP >= 50) { 6417 Diag(P.second->getExprLoc(), 6418 diag::err_omp_defaultmap_no_attr_for_variable) 6419 << P.first << P.second->getSourceRange(); 6420 Diag(DSAStack->getDefaultDSALocation(), 6421 diag::note_omp_defaultmap_attr_none); 6422 } 6423 } 6424 6425 if (!AllowedNameModifiers.empty()) 6426 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 6427 ErrorFound; 6428 6429 if (ErrorFound) 6430 return StmtError(); 6431 6432 if (!CurContext->isDependentContext() && 6433 isOpenMPTargetExecutionDirective(Kind) && 6434 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || 6435 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() || 6436 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() || 6437 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) { 6438 // Register target to DSA Stack. 6439 DSAStack->addTargetDirLocation(StartLoc); 6440 } 6441 6442 return Res; 6443 } 6444 6445 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 6446 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 6447 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 6448 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 6449 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 6450 assert(Aligneds.size() == Alignments.size()); 6451 assert(Linears.size() == LinModifiers.size()); 6452 assert(Linears.size() == Steps.size()); 6453 if (!DG || DG.get().isNull()) 6454 return DeclGroupPtrTy(); 6455 6456 const int SimdId = 0; 6457 if (!DG.get().isSingleDecl()) { 6458 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant) 6459 << SimdId; 6460 return DG; 6461 } 6462 Decl *ADecl = DG.get().getSingleDecl(); 6463 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 6464 ADecl = FTD->getTemplatedDecl(); 6465 6466 auto *FD = dyn_cast<FunctionDecl>(ADecl); 6467 if (!FD) { 6468 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId; 6469 return DeclGroupPtrTy(); 6470 } 6471 6472 // OpenMP [2.8.2, declare simd construct, Description] 6473 // The parameter of the simdlen clause must be a constant positive integer 6474 // expression. 6475 ExprResult SL; 6476 if (Simdlen) 6477 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 6478 // OpenMP [2.8.2, declare simd construct, Description] 6479 // The special this pointer can be used as if was one of the arguments to the 6480 // function in any of the linear, aligned, or uniform clauses. 6481 // The uniform clause declares one or more arguments to have an invariant 6482 // value for all concurrent invocations of the function in the execution of a 6483 // single SIMD loop. 6484 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs; 6485 const Expr *UniformedLinearThis = nullptr; 6486 for (const Expr *E : Uniforms) { 6487 E = E->IgnoreParenImpCasts(); 6488 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 6489 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 6490 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 6491 FD->getParamDecl(PVD->getFunctionScopeIndex()) 6492 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 6493 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E); 6494 continue; 6495 } 6496 if (isa<CXXThisExpr>(E)) { 6497 UniformedLinearThis = E; 6498 continue; 6499 } 6500 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 6501 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 6502 } 6503 // OpenMP [2.8.2, declare simd construct, Description] 6504 // The aligned clause declares that the object to which each list item points 6505 // is aligned to the number of bytes expressed in the optional parameter of 6506 // the aligned clause. 6507 // The special this pointer can be used as if was one of the arguments to the 6508 // function in any of the linear, aligned, or uniform clauses. 6509 // The type of list items appearing in the aligned clause must be array, 6510 // pointer, reference to array, or reference to pointer. 6511 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs; 6512 const Expr *AlignedThis = nullptr; 6513 for (const Expr *E : Aligneds) { 6514 E = E->IgnoreParenImpCasts(); 6515 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 6516 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 6517 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 6518 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 6519 FD->getParamDecl(PVD->getFunctionScopeIndex()) 6520 ->getCanonicalDecl() == CanonPVD) { 6521 // OpenMP [2.8.1, simd construct, Restrictions] 6522 // A list-item cannot appear in more than one aligned clause. 6523 if (AlignedArgs.count(CanonPVD) > 0) { 6524 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice) 6525 << 1 << getOpenMPClauseName(OMPC_aligned) 6526 << E->getSourceRange(); 6527 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 6528 diag::note_omp_explicit_dsa) 6529 << getOpenMPClauseName(OMPC_aligned); 6530 continue; 6531 } 6532 AlignedArgs[CanonPVD] = E; 6533 QualType QTy = PVD->getType() 6534 .getNonReferenceType() 6535 .getUnqualifiedType() 6536 .getCanonicalType(); 6537 const Type *Ty = QTy.getTypePtrOrNull(); 6538 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 6539 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 6540 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 6541 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 6542 } 6543 continue; 6544 } 6545 } 6546 if (isa<CXXThisExpr>(E)) { 6547 if (AlignedThis) { 6548 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice) 6549 << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange(); 6550 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 6551 << getOpenMPClauseName(OMPC_aligned); 6552 } 6553 AlignedThis = E; 6554 continue; 6555 } 6556 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 6557 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 6558 } 6559 // The optional parameter of the aligned clause, alignment, must be a constant 6560 // positive integer expression. If no optional parameter is specified, 6561 // implementation-defined default alignments for SIMD instructions on the 6562 // target platforms are assumed. 6563 SmallVector<const Expr *, 4> NewAligns; 6564 for (Expr *E : Alignments) { 6565 ExprResult Align; 6566 if (E) 6567 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 6568 NewAligns.push_back(Align.get()); 6569 } 6570 // OpenMP [2.8.2, declare simd construct, Description] 6571 // The linear clause declares one or more list items to be private to a SIMD 6572 // lane and to have a linear relationship with respect to the iteration space 6573 // of a loop. 6574 // The special this pointer can be used as if was one of the arguments to the 6575 // function in any of the linear, aligned, or uniform clauses. 6576 // When a linear-step expression is specified in a linear clause it must be 6577 // either a constant integer expression or an integer-typed parameter that is 6578 // specified in a uniform clause on the directive. 6579 llvm::DenseMap<const Decl *, const Expr *> LinearArgs; 6580 const bool IsUniformedThis = UniformedLinearThis != nullptr; 6581 auto MI = LinModifiers.begin(); 6582 for (const Expr *E : Linears) { 6583 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 6584 ++MI; 6585 E = E->IgnoreParenImpCasts(); 6586 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 6587 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 6588 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 6589 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 6590 FD->getParamDecl(PVD->getFunctionScopeIndex()) 6591 ->getCanonicalDecl() == CanonPVD) { 6592 // OpenMP [2.15.3.7, linear Clause, Restrictions] 6593 // A list-item cannot appear in more than one linear clause. 6594 if (LinearArgs.count(CanonPVD) > 0) { 6595 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 6596 << getOpenMPClauseName(OMPC_linear) 6597 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 6598 Diag(LinearArgs[CanonPVD]->getExprLoc(), 6599 diag::note_omp_explicit_dsa) 6600 << getOpenMPClauseName(OMPC_linear); 6601 continue; 6602 } 6603 // Each argument can appear in at most one uniform or linear clause. 6604 if (UniformedArgs.count(CanonPVD) > 0) { 6605 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 6606 << getOpenMPClauseName(OMPC_linear) 6607 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 6608 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 6609 diag::note_omp_explicit_dsa) 6610 << getOpenMPClauseName(OMPC_uniform); 6611 continue; 6612 } 6613 LinearArgs[CanonPVD] = E; 6614 if (E->isValueDependent() || E->isTypeDependent() || 6615 E->isInstantiationDependent() || 6616 E->containsUnexpandedParameterPack()) 6617 continue; 6618 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 6619 PVD->getOriginalType(), 6620 /*IsDeclareSimd=*/true); 6621 continue; 6622 } 6623 } 6624 if (isa<CXXThisExpr>(E)) { 6625 if (UniformedLinearThis) { 6626 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 6627 << getOpenMPClauseName(OMPC_linear) 6628 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 6629 << E->getSourceRange(); 6630 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 6631 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 6632 : OMPC_linear); 6633 continue; 6634 } 6635 UniformedLinearThis = E; 6636 if (E->isValueDependent() || E->isTypeDependent() || 6637 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 6638 continue; 6639 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 6640 E->getType(), /*IsDeclareSimd=*/true); 6641 continue; 6642 } 6643 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 6644 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 6645 } 6646 Expr *Step = nullptr; 6647 Expr *NewStep = nullptr; 6648 SmallVector<Expr *, 4> NewSteps; 6649 for (Expr *E : Steps) { 6650 // Skip the same step expression, it was checked already. 6651 if (Step == E || !E) { 6652 NewSteps.push_back(E ? NewStep : nullptr); 6653 continue; 6654 } 6655 Step = E; 6656 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step)) 6657 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 6658 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 6659 if (UniformedArgs.count(CanonPVD) == 0) { 6660 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 6661 << Step->getSourceRange(); 6662 } else if (E->isValueDependent() || E->isTypeDependent() || 6663 E->isInstantiationDependent() || 6664 E->containsUnexpandedParameterPack() || 6665 CanonPVD->getType()->hasIntegerRepresentation()) { 6666 NewSteps.push_back(Step); 6667 } else { 6668 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 6669 << Step->getSourceRange(); 6670 } 6671 continue; 6672 } 6673 NewStep = Step; 6674 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 6675 !Step->isInstantiationDependent() && 6676 !Step->containsUnexpandedParameterPack()) { 6677 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 6678 .get(); 6679 if (NewStep) 6680 NewStep = 6681 VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get(); 6682 } 6683 NewSteps.push_back(NewStep); 6684 } 6685 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 6686 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 6687 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 6688 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 6689 const_cast<Expr **>(Linears.data()), Linears.size(), 6690 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 6691 NewSteps.data(), NewSteps.size(), SR); 6692 ADecl->addAttr(NewAttr); 6693 return DG; 6694 } 6695 6696 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto, 6697 QualType NewType) { 6698 assert(NewType->isFunctionProtoType() && 6699 "Expected function type with prototype."); 6700 assert(FD->getType()->isFunctionNoProtoType() && 6701 "Expected function with type with no prototype."); 6702 assert(FDWithProto->getType()->isFunctionProtoType() && 6703 "Expected function with prototype."); 6704 // Synthesize parameters with the same types. 6705 FD->setType(NewType); 6706 SmallVector<ParmVarDecl *, 16> Params; 6707 for (const ParmVarDecl *P : FDWithProto->parameters()) { 6708 auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(), 6709 SourceLocation(), nullptr, P->getType(), 6710 /*TInfo=*/nullptr, SC_None, nullptr); 6711 Param->setScopeInfo(0, Params.size()); 6712 Param->setImplicit(); 6713 Params.push_back(Param); 6714 } 6715 6716 FD->setParams(Params); 6717 } 6718 6719 void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) { 6720 if (D->isInvalidDecl()) 6721 return; 6722 FunctionDecl *FD = nullptr; 6723 if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D)) 6724 FD = UTemplDecl->getTemplatedDecl(); 6725 else 6726 FD = cast<FunctionDecl>(D); 6727 assert(FD && "Expected a function declaration!"); 6728 6729 // If we are instantiating templates we do *not* apply scoped assumptions but 6730 // only global ones. We apply scoped assumption to the template definition 6731 // though. 6732 if (!inTemplateInstantiation()) { 6733 for (AssumptionAttr *AA : OMPAssumeScoped) 6734 FD->addAttr(AA); 6735 } 6736 for (AssumptionAttr *AA : OMPAssumeGlobal) 6737 FD->addAttr(AA); 6738 } 6739 6740 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI) 6741 : TI(&TI), NameSuffix(TI.getMangledName()) {} 6742 6743 void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 6744 Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, 6745 SmallVectorImpl<FunctionDecl *> &Bases) { 6746 if (!D.getIdentifier()) 6747 return; 6748 6749 OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back(); 6750 6751 // Template specialization is an extension, check if we do it. 6752 bool IsTemplated = !TemplateParamLists.empty(); 6753 if (IsTemplated & 6754 !DVScope.TI->isExtensionActive( 6755 llvm::omp::TraitProperty::implementation_extension_allow_templates)) 6756 return; 6757 6758 IdentifierInfo *BaseII = D.getIdentifier(); 6759 LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(), 6760 LookupOrdinaryName); 6761 LookupParsedName(Lookup, S, &D.getCXXScopeSpec()); 6762 6763 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6764 QualType FType = TInfo->getType(); 6765 6766 bool IsConstexpr = 6767 D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr; 6768 bool IsConsteval = 6769 D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval; 6770 6771 for (auto *Candidate : Lookup) { 6772 auto *CandidateDecl = Candidate->getUnderlyingDecl(); 6773 FunctionDecl *UDecl = nullptr; 6774 if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl)) { 6775 auto *FTD = cast<FunctionTemplateDecl>(CandidateDecl); 6776 if (FTD->getTemplateParameters()->size() == TemplateParamLists.size()) 6777 UDecl = FTD->getTemplatedDecl(); 6778 } else if (!IsTemplated) 6779 UDecl = dyn_cast<FunctionDecl>(CandidateDecl); 6780 if (!UDecl) 6781 continue; 6782 6783 // Don't specialize constexpr/consteval functions with 6784 // non-constexpr/consteval functions. 6785 if (UDecl->isConstexpr() && !IsConstexpr) 6786 continue; 6787 if (UDecl->isConsteval() && !IsConsteval) 6788 continue; 6789 6790 QualType UDeclTy = UDecl->getType(); 6791 if (!UDeclTy->isDependentType()) { 6792 QualType NewType = Context.mergeFunctionTypes( 6793 FType, UDeclTy, /* OfBlockPointer */ false, 6794 /* Unqualified */ false, /* AllowCXX */ true); 6795 if (NewType.isNull()) 6796 continue; 6797 } 6798 6799 // Found a base! 6800 Bases.push_back(UDecl); 6801 } 6802 6803 bool UseImplicitBase = !DVScope.TI->isExtensionActive( 6804 llvm::omp::TraitProperty::implementation_extension_disable_implicit_base); 6805 // If no base was found we create a declaration that we use as base. 6806 if (Bases.empty() && UseImplicitBase) { 6807 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 6808 Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists); 6809 BaseD->setImplicit(true); 6810 if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD)) 6811 Bases.push_back(BaseTemplD->getTemplatedDecl()); 6812 else 6813 Bases.push_back(cast<FunctionDecl>(BaseD)); 6814 } 6815 6816 std::string MangledName; 6817 MangledName += D.getIdentifier()->getName(); 6818 MangledName += getOpenMPVariantManglingSeparatorStr(); 6819 MangledName += DVScope.NameSuffix; 6820 IdentifierInfo &VariantII = Context.Idents.get(MangledName); 6821 6822 VariantII.setMangledOpenMPVariantName(true); 6823 D.SetIdentifier(&VariantII, D.getBeginLoc()); 6824 } 6825 6826 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 6827 Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) { 6828 // Do not mark function as is used to prevent its emission if this is the 6829 // only place where it is used. 6830 EnterExpressionEvaluationContext Unevaluated( 6831 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6832 6833 FunctionDecl *FD = nullptr; 6834 if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D)) 6835 FD = UTemplDecl->getTemplatedDecl(); 6836 else 6837 FD = cast<FunctionDecl>(D); 6838 auto *VariantFuncRef = DeclRefExpr::Create( 6839 Context, NestedNameSpecifierLoc(), SourceLocation(), FD, 6840 /* RefersToEnclosingVariableOrCapture */ false, 6841 /* NameLoc */ FD->getLocation(), FD->getType(), 6842 ExprValueKind::VK_PRValue); 6843 6844 OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back(); 6845 auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit( 6846 Context, VariantFuncRef, DVScope.TI, 6847 /*NothingArgs=*/nullptr, /*NothingArgsSize=*/0, 6848 /*NeedDevicePtrArgs=*/nullptr, /*NeedDevicePtrArgsSize=*/0, 6849 /*AppendArgs=*/nullptr, /*AppendArgsSize=*/0); 6850 for (FunctionDecl *BaseFD : Bases) 6851 BaseFD->addAttr(OMPDeclareVariantA); 6852 } 6853 6854 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope, 6855 SourceLocation LParenLoc, 6856 MultiExprArg ArgExprs, 6857 SourceLocation RParenLoc, Expr *ExecConfig) { 6858 // The common case is a regular call we do not want to specialize at all. Try 6859 // to make that case fast by bailing early. 6860 CallExpr *CE = dyn_cast<CallExpr>(Call.get()); 6861 if (!CE) 6862 return Call; 6863 6864 FunctionDecl *CalleeFnDecl = CE->getDirectCallee(); 6865 if (!CalleeFnDecl) 6866 return Call; 6867 6868 if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>()) 6869 return Call; 6870 6871 ASTContext &Context = getASTContext(); 6872 std::function<void(StringRef)> DiagUnknownTrait = [this, 6873 CE](StringRef ISATrait) { 6874 // TODO Track the selector locations in a way that is accessible here to 6875 // improve the diagnostic location. 6876 Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait) 6877 << ISATrait; 6878 }; 6879 TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait), 6880 getCurFunctionDecl(), DSAStack->getConstructTraits()); 6881 6882 QualType CalleeFnType = CalleeFnDecl->getType(); 6883 6884 SmallVector<Expr *, 4> Exprs; 6885 SmallVector<VariantMatchInfo, 4> VMIs; 6886 while (CalleeFnDecl) { 6887 for (OMPDeclareVariantAttr *A : 6888 CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) { 6889 Expr *VariantRef = A->getVariantFuncRef(); 6890 6891 VariantMatchInfo VMI; 6892 OMPTraitInfo &TI = A->getTraitInfo(); 6893 TI.getAsVariantMatchInfo(Context, VMI); 6894 if (!isVariantApplicableInContext(VMI, OMPCtx, 6895 /* DeviceSetOnly */ false)) 6896 continue; 6897 6898 VMIs.push_back(VMI); 6899 Exprs.push_back(VariantRef); 6900 } 6901 6902 CalleeFnDecl = CalleeFnDecl->getPreviousDecl(); 6903 } 6904 6905 ExprResult NewCall; 6906 do { 6907 int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx); 6908 if (BestIdx < 0) 6909 return Call; 6910 Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]); 6911 Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl(); 6912 6913 { 6914 // Try to build a (member) call expression for the current best applicable 6915 // variant expression. We allow this to fail in which case we continue 6916 // with the next best variant expression. The fail case is part of the 6917 // implementation defined behavior in the OpenMP standard when it talks 6918 // about what differences in the function prototypes: "Any differences 6919 // that the specific OpenMP context requires in the prototype of the 6920 // variant from the base function prototype are implementation defined." 6921 // This wording is there to allow the specialized variant to have a 6922 // different type than the base function. This is intended and OK but if 6923 // we cannot create a call the difference is not in the "implementation 6924 // defined range" we allow. 6925 Sema::TentativeAnalysisScope Trap(*this); 6926 6927 if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) { 6928 auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE); 6929 BestExpr = MemberExpr::CreateImplicit( 6930 Context, MemberCall->getImplicitObjectArgument(), 6931 /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy, 6932 MemberCall->getValueKind(), MemberCall->getObjectKind()); 6933 } 6934 NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc, 6935 ExecConfig); 6936 if (NewCall.isUsable()) { 6937 if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) { 6938 FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee(); 6939 QualType NewType = Context.mergeFunctionTypes( 6940 CalleeFnType, NewCalleeFnDecl->getType(), 6941 /* OfBlockPointer */ false, 6942 /* Unqualified */ false, /* AllowCXX */ true); 6943 if (!NewType.isNull()) 6944 break; 6945 // Don't use the call if the function type was not compatible. 6946 NewCall = nullptr; 6947 } 6948 } 6949 } 6950 6951 VMIs.erase(VMIs.begin() + BestIdx); 6952 Exprs.erase(Exprs.begin() + BestIdx); 6953 } while (!VMIs.empty()); 6954 6955 if (!NewCall.isUsable()) 6956 return Call; 6957 return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0); 6958 } 6959 6960 Optional<std::pair<FunctionDecl *, Expr *>> 6961 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG, 6962 Expr *VariantRef, OMPTraitInfo &TI, 6963 unsigned NumAppendArgs, 6964 SourceRange SR) { 6965 if (!DG || DG.get().isNull()) 6966 return None; 6967 6968 const int VariantId = 1; 6969 // Must be applied only to single decl. 6970 if (!DG.get().isSingleDecl()) { 6971 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant) 6972 << VariantId << SR; 6973 return None; 6974 } 6975 Decl *ADecl = DG.get().getSingleDecl(); 6976 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 6977 ADecl = FTD->getTemplatedDecl(); 6978 6979 // Decl must be a function. 6980 auto *FD = dyn_cast<FunctionDecl>(ADecl); 6981 if (!FD) { 6982 Diag(ADecl->getLocation(), diag::err_omp_function_expected) 6983 << VariantId << SR; 6984 return None; 6985 } 6986 6987 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) { 6988 return FD->hasAttrs() && 6989 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() || 6990 FD->hasAttr<TargetAttr>()); 6991 }; 6992 // OpenMP is not compatible with CPU-specific attributes. 6993 if (HasMultiVersionAttributes(FD)) { 6994 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes) 6995 << SR; 6996 return None; 6997 } 6998 6999 // Allow #pragma omp declare variant only if the function is not used. 7000 if (FD->isUsed(false)) 7001 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used) 7002 << FD->getLocation(); 7003 7004 // Check if the function was emitted already. 7005 const FunctionDecl *Definition; 7006 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) && 7007 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition))) 7008 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted) 7009 << FD->getLocation(); 7010 7011 // The VariantRef must point to function. 7012 if (!VariantRef) { 7013 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId; 7014 return None; 7015 } 7016 7017 auto ShouldDelayChecks = [](Expr *&E, bool) { 7018 return E && (E->isTypeDependent() || E->isValueDependent() || 7019 E->containsUnexpandedParameterPack() || 7020 E->isInstantiationDependent()); 7021 }; 7022 // Do not check templates, wait until instantiation. 7023 if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) || 7024 TI.anyScoreOrCondition(ShouldDelayChecks)) 7025 return std::make_pair(FD, VariantRef); 7026 7027 // Deal with non-constant score and user condition expressions. 7028 auto HandleNonConstantScoresAndConditions = [this](Expr *&E, 7029 bool IsScore) -> bool { 7030 if (!E || E->isIntegerConstantExpr(Context)) 7031 return false; 7032 7033 if (IsScore) { 7034 // We warn on non-constant scores and pretend they were not present. 7035 Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant) 7036 << E; 7037 E = nullptr; 7038 } else { 7039 // We could replace a non-constant user condition with "false" but we 7040 // will soon need to handle these anyway for the dynamic version of 7041 // OpenMP context selectors. 7042 Diag(E->getExprLoc(), 7043 diag::err_omp_declare_variant_user_condition_not_constant) 7044 << E; 7045 } 7046 return true; 7047 }; 7048 if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions)) 7049 return None; 7050 7051 QualType AdjustedFnType = FD->getType(); 7052 if (NumAppendArgs) { 7053 if (isa<FunctionNoProtoType>(FD->getType())) { 7054 Diag(FD->getLocation(), diag::err_omp_declare_variant_prototype_required) 7055 << SR; 7056 return None; 7057 } 7058 // Adjust the function type to account for an extra omp_interop_t for each 7059 // specified in the append_args clause. 7060 const TypeDecl *TD = nullptr; 7061 LookupResult Result(*this, &Context.Idents.get("omp_interop_t"), 7062 SR.getBegin(), Sema::LookupOrdinaryName); 7063 if (LookupName(Result, getCurScope())) { 7064 NamedDecl *ND = Result.getFoundDecl(); 7065 TD = dyn_cast_or_null<TypeDecl>(ND); 7066 } 7067 if (!TD) { 7068 Diag(SR.getBegin(), diag::err_omp_interop_type_not_found) << SR; 7069 return None; 7070 } 7071 QualType InteropType = QualType(TD->getTypeForDecl(), 0); 7072 auto *PTy = cast<FunctionProtoType>(FD->getType()); 7073 if (PTy->isVariadic()) { 7074 Diag(FD->getLocation(), diag::err_omp_append_args_with_varargs) << SR; 7075 return None; 7076 } 7077 llvm::SmallVector<QualType, 8> Params; 7078 Params.append(PTy->param_type_begin(), PTy->param_type_end()); 7079 Params.insert(Params.end(), NumAppendArgs, InteropType); 7080 AdjustedFnType = Context.getFunctionType(PTy->getReturnType(), Params, 7081 PTy->getExtProtoInfo()); 7082 } 7083 7084 // Convert VariantRef expression to the type of the original function to 7085 // resolve possible conflicts. 7086 ExprResult VariantRefCast = VariantRef; 7087 if (LangOpts.CPlusPlus) { 7088 QualType FnPtrType; 7089 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7090 if (Method && !Method->isStatic()) { 7091 const Type *ClassType = 7092 Context.getTypeDeclType(Method->getParent()).getTypePtr(); 7093 FnPtrType = Context.getMemberPointerType(AdjustedFnType, ClassType); 7094 ExprResult ER; 7095 { 7096 // Build adrr_of unary op to correctly handle type checks for member 7097 // functions. 7098 Sema::TentativeAnalysisScope Trap(*this); 7099 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf, 7100 VariantRef); 7101 } 7102 if (!ER.isUsable()) { 7103 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7104 << VariantId << VariantRef->getSourceRange(); 7105 return None; 7106 } 7107 VariantRef = ER.get(); 7108 } else { 7109 FnPtrType = Context.getPointerType(AdjustedFnType); 7110 } 7111 QualType VarianPtrType = Context.getPointerType(VariantRef->getType()); 7112 if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) { 7113 ImplicitConversionSequence ICS = TryImplicitConversion( 7114 VariantRef, FnPtrType.getUnqualifiedType(), 7115 /*SuppressUserConversions=*/false, AllowedExplicit::None, 7116 /*InOverloadResolution=*/false, 7117 /*CStyle=*/false, 7118 /*AllowObjCWritebackConversion=*/false); 7119 if (ICS.isFailure()) { 7120 Diag(VariantRef->getExprLoc(), 7121 diag::err_omp_declare_variant_incompat_types) 7122 << VariantRef->getType() 7123 << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType()) 7124 << (NumAppendArgs ? 1 : 0) << VariantRef->getSourceRange(); 7125 return None; 7126 } 7127 VariantRefCast = PerformImplicitConversion( 7128 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting); 7129 if (!VariantRefCast.isUsable()) 7130 return None; 7131 } 7132 // Drop previously built artificial addr_of unary op for member functions. 7133 if (Method && !Method->isStatic()) { 7134 Expr *PossibleAddrOfVariantRef = VariantRefCast.get(); 7135 if (auto *UO = dyn_cast<UnaryOperator>( 7136 PossibleAddrOfVariantRef->IgnoreImplicit())) 7137 VariantRefCast = UO->getSubExpr(); 7138 } 7139 } 7140 7141 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get()); 7142 if (!ER.isUsable() || 7143 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) { 7144 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7145 << VariantId << VariantRef->getSourceRange(); 7146 return None; 7147 } 7148 7149 // The VariantRef must point to function. 7150 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts()); 7151 if (!DRE) { 7152 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7153 << VariantId << VariantRef->getSourceRange(); 7154 return None; 7155 } 7156 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl()); 7157 if (!NewFD) { 7158 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7159 << VariantId << VariantRef->getSourceRange(); 7160 return None; 7161 } 7162 7163 // Check if function types are compatible in C. 7164 if (!LangOpts.CPlusPlus) { 7165 QualType NewType = 7166 Context.mergeFunctionTypes(AdjustedFnType, NewFD->getType()); 7167 if (NewType.isNull()) { 7168 Diag(VariantRef->getExprLoc(), 7169 diag::err_omp_declare_variant_incompat_types) 7170 << NewFD->getType() << FD->getType() << (NumAppendArgs ? 1 : 0) 7171 << VariantRef->getSourceRange(); 7172 return None; 7173 } 7174 if (NewType->isFunctionProtoType()) { 7175 if (FD->getType()->isFunctionNoProtoType()) 7176 setPrototype(*this, FD, NewFD, NewType); 7177 else if (NewFD->getType()->isFunctionNoProtoType()) 7178 setPrototype(*this, NewFD, FD, NewType); 7179 } 7180 } 7181 7182 // Check if variant function is not marked with declare variant directive. 7183 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) { 7184 Diag(VariantRef->getExprLoc(), 7185 diag::warn_omp_declare_variant_marked_as_declare_variant) 7186 << VariantRef->getSourceRange(); 7187 SourceRange SR = 7188 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange(); 7189 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR; 7190 return None; 7191 } 7192 7193 enum DoesntSupport { 7194 VirtFuncs = 1, 7195 Constructors = 3, 7196 Destructors = 4, 7197 DeletedFuncs = 5, 7198 DefaultedFuncs = 6, 7199 ConstexprFuncs = 7, 7200 ConstevalFuncs = 8, 7201 }; 7202 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) { 7203 if (CXXFD->isVirtual()) { 7204 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7205 << VirtFuncs; 7206 return None; 7207 } 7208 7209 if (isa<CXXConstructorDecl>(FD)) { 7210 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7211 << Constructors; 7212 return None; 7213 } 7214 7215 if (isa<CXXDestructorDecl>(FD)) { 7216 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7217 << Destructors; 7218 return None; 7219 } 7220 } 7221 7222 if (FD->isDeleted()) { 7223 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7224 << DeletedFuncs; 7225 return None; 7226 } 7227 7228 if (FD->isDefaulted()) { 7229 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7230 << DefaultedFuncs; 7231 return None; 7232 } 7233 7234 if (FD->isConstexpr()) { 7235 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7236 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 7237 return None; 7238 } 7239 7240 // Check general compatibility. 7241 if (areMultiversionVariantFunctionsCompatible( 7242 FD, NewFD, PartialDiagnostic::NullDiagnostic(), 7243 PartialDiagnosticAt(SourceLocation(), 7244 PartialDiagnostic::NullDiagnostic()), 7245 PartialDiagnosticAt( 7246 VariantRef->getExprLoc(), 7247 PDiag(diag::err_omp_declare_variant_doesnt_support)), 7248 PartialDiagnosticAt(VariantRef->getExprLoc(), 7249 PDiag(diag::err_omp_declare_variant_diff) 7250 << FD->getLocation()), 7251 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false, 7252 /*CLinkageMayDiffer=*/true)) 7253 return None; 7254 return std::make_pair(FD, cast<Expr>(DRE)); 7255 } 7256 7257 void Sema::ActOnOpenMPDeclareVariantDirective( 7258 FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, 7259 ArrayRef<Expr *> AdjustArgsNothing, 7260 ArrayRef<Expr *> AdjustArgsNeedDevicePtr, 7261 ArrayRef<OMPDeclareVariantAttr::InteropType> AppendArgs, 7262 SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc, 7263 SourceRange SR) { 7264 7265 // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions] 7266 // An adjust_args clause or append_args clause can only be specified if the 7267 // dispatch selector of the construct selector set appears in the match 7268 // clause. 7269 7270 SmallVector<Expr *, 8> AllAdjustArgs; 7271 llvm::append_range(AllAdjustArgs, AdjustArgsNothing); 7272 llvm::append_range(AllAdjustArgs, AdjustArgsNeedDevicePtr); 7273 7274 if (!AllAdjustArgs.empty() || !AppendArgs.empty()) { 7275 VariantMatchInfo VMI; 7276 TI.getAsVariantMatchInfo(Context, VMI); 7277 if (!llvm::is_contained( 7278 VMI.ConstructTraits, 7279 llvm::omp::TraitProperty::construct_dispatch_dispatch)) { 7280 if (!AllAdjustArgs.empty()) 7281 Diag(AdjustArgsLoc, diag::err_omp_clause_requires_dispatch_construct) 7282 << getOpenMPClauseName(OMPC_adjust_args); 7283 if (!AppendArgs.empty()) 7284 Diag(AppendArgsLoc, diag::err_omp_clause_requires_dispatch_construct) 7285 << getOpenMPClauseName(OMPC_append_args); 7286 return; 7287 } 7288 } 7289 7290 // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions] 7291 // Each argument can only appear in a single adjust_args clause for each 7292 // declare variant directive. 7293 llvm::SmallPtrSet<const VarDecl *, 4> AdjustVars; 7294 7295 for (Expr *E : AllAdjustArgs) { 7296 E = E->IgnoreParenImpCasts(); 7297 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) { 7298 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 7299 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 7300 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 7301 FD->getParamDecl(PVD->getFunctionScopeIndex()) 7302 ->getCanonicalDecl() == CanonPVD) { 7303 // It's a parameter of the function, check duplicates. 7304 if (!AdjustVars.insert(CanonPVD).second) { 7305 Diag(DRE->getLocation(), diag::err_omp_adjust_arg_multiple_clauses) 7306 << PVD; 7307 return; 7308 } 7309 continue; 7310 } 7311 } 7312 } 7313 // Anything that is not a function parameter is an error. 7314 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) << FD << 0; 7315 return; 7316 } 7317 7318 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit( 7319 Context, VariantRef, &TI, const_cast<Expr **>(AdjustArgsNothing.data()), 7320 AdjustArgsNothing.size(), 7321 const_cast<Expr **>(AdjustArgsNeedDevicePtr.data()), 7322 AdjustArgsNeedDevicePtr.size(), 7323 const_cast<OMPDeclareVariantAttr::InteropType *>(AppendArgs.data()), 7324 AppendArgs.size(), SR); 7325 FD->addAttr(NewAttr); 7326 } 7327 7328 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 7329 Stmt *AStmt, 7330 SourceLocation StartLoc, 7331 SourceLocation EndLoc) { 7332 if (!AStmt) 7333 return StmtError(); 7334 7335 auto *CS = cast<CapturedStmt>(AStmt); 7336 // 1.2.2 OpenMP Language Terminology 7337 // Structured block - An executable statement with a single entry at the 7338 // top and a single exit at the bottom. 7339 // The point of exit cannot be a branch out of the structured block. 7340 // longjmp() and throw() must not violate the entry/exit criteria. 7341 CS->getCapturedDecl()->setNothrow(); 7342 7343 setFunctionHasBranchProtectedScope(); 7344 7345 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 7346 DSAStack->getTaskgroupReductionRef(), 7347 DSAStack->isCancelRegion()); 7348 } 7349 7350 namespace { 7351 /// Iteration space of a single for loop. 7352 struct LoopIterationSpace final { 7353 /// True if the condition operator is the strict compare operator (<, > or 7354 /// !=). 7355 bool IsStrictCompare = false; 7356 /// Condition of the loop. 7357 Expr *PreCond = nullptr; 7358 /// This expression calculates the number of iterations in the loop. 7359 /// It is always possible to calculate it before starting the loop. 7360 Expr *NumIterations = nullptr; 7361 /// The loop counter variable. 7362 Expr *CounterVar = nullptr; 7363 /// Private loop counter variable. 7364 Expr *PrivateCounterVar = nullptr; 7365 /// This is initializer for the initial value of #CounterVar. 7366 Expr *CounterInit = nullptr; 7367 /// This is step for the #CounterVar used to generate its update: 7368 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 7369 Expr *CounterStep = nullptr; 7370 /// Should step be subtracted? 7371 bool Subtract = false; 7372 /// Source range of the loop init. 7373 SourceRange InitSrcRange; 7374 /// Source range of the loop condition. 7375 SourceRange CondSrcRange; 7376 /// Source range of the loop increment. 7377 SourceRange IncSrcRange; 7378 /// Minimum value that can have the loop control variable. Used to support 7379 /// non-rectangular loops. Applied only for LCV with the non-iterator types, 7380 /// since only such variables can be used in non-loop invariant expressions. 7381 Expr *MinValue = nullptr; 7382 /// Maximum value that can have the loop control variable. Used to support 7383 /// non-rectangular loops. Applied only for LCV with the non-iterator type, 7384 /// since only such variables can be used in non-loop invariant expressions. 7385 Expr *MaxValue = nullptr; 7386 /// true, if the lower bound depends on the outer loop control var. 7387 bool IsNonRectangularLB = false; 7388 /// true, if the upper bound depends on the outer loop control var. 7389 bool IsNonRectangularUB = false; 7390 /// Index of the loop this loop depends on and forms non-rectangular loop 7391 /// nest. 7392 unsigned LoopDependentIdx = 0; 7393 /// Final condition for the non-rectangular loop nest support. It is used to 7394 /// check that the number of iterations for this particular counter must be 7395 /// finished. 7396 Expr *FinalCondition = nullptr; 7397 }; 7398 7399 /// Helper class for checking canonical form of the OpenMP loops and 7400 /// extracting iteration space of each loop in the loop nest, that will be used 7401 /// for IR generation. 7402 class OpenMPIterationSpaceChecker { 7403 /// Reference to Sema. 7404 Sema &SemaRef; 7405 /// Does the loop associated directive support non-rectangular loops? 7406 bool SupportsNonRectangular; 7407 /// Data-sharing stack. 7408 DSAStackTy &Stack; 7409 /// A location for diagnostics (when there is no some better location). 7410 SourceLocation DefaultLoc; 7411 /// A location for diagnostics (when increment is not compatible). 7412 SourceLocation ConditionLoc; 7413 /// A source location for referring to loop init later. 7414 SourceRange InitSrcRange; 7415 /// A source location for referring to condition later. 7416 SourceRange ConditionSrcRange; 7417 /// A source location for referring to increment later. 7418 SourceRange IncrementSrcRange; 7419 /// Loop variable. 7420 ValueDecl *LCDecl = nullptr; 7421 /// Reference to loop variable. 7422 Expr *LCRef = nullptr; 7423 /// Lower bound (initializer for the var). 7424 Expr *LB = nullptr; 7425 /// Upper bound. 7426 Expr *UB = nullptr; 7427 /// Loop step (increment). 7428 Expr *Step = nullptr; 7429 /// This flag is true when condition is one of: 7430 /// Var < UB 7431 /// Var <= UB 7432 /// UB > Var 7433 /// UB >= Var 7434 /// This will have no value when the condition is != 7435 llvm::Optional<bool> TestIsLessOp; 7436 /// This flag is true when condition is strict ( < or > ). 7437 bool TestIsStrictOp = false; 7438 /// This flag is true when step is subtracted on each iteration. 7439 bool SubtractStep = false; 7440 /// The outer loop counter this loop depends on (if any). 7441 const ValueDecl *DepDecl = nullptr; 7442 /// Contains number of loop (starts from 1) on which loop counter init 7443 /// expression of this loop depends on. 7444 Optional<unsigned> InitDependOnLC; 7445 /// Contains number of loop (starts from 1) on which loop counter condition 7446 /// expression of this loop depends on. 7447 Optional<unsigned> CondDependOnLC; 7448 /// Checks if the provide statement depends on the loop counter. 7449 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer); 7450 /// Original condition required for checking of the exit condition for 7451 /// non-rectangular loop. 7452 Expr *Condition = nullptr; 7453 7454 public: 7455 OpenMPIterationSpaceChecker(Sema &SemaRef, bool SupportsNonRectangular, 7456 DSAStackTy &Stack, SourceLocation DefaultLoc) 7457 : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular), 7458 Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 7459 /// Check init-expr for canonical loop form and save loop counter 7460 /// variable - #Var and its initialization value - #LB. 7461 bool checkAndSetInit(Stmt *S, bool EmitDiags = true); 7462 /// Check test-expr for canonical form, save upper-bound (#UB), flags 7463 /// for less/greater and for strict/non-strict comparison. 7464 bool checkAndSetCond(Expr *S); 7465 /// Check incr-expr for canonical loop form and return true if it 7466 /// does not conform, otherwise save loop step (#Step). 7467 bool checkAndSetInc(Expr *S); 7468 /// Return the loop counter variable. 7469 ValueDecl *getLoopDecl() const { return LCDecl; } 7470 /// Return the reference expression to loop counter variable. 7471 Expr *getLoopDeclRefExpr() const { return LCRef; } 7472 /// Source range of the loop init. 7473 SourceRange getInitSrcRange() const { return InitSrcRange; } 7474 /// Source range of the loop condition. 7475 SourceRange getConditionSrcRange() const { return ConditionSrcRange; } 7476 /// Source range of the loop increment. 7477 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; } 7478 /// True if the step should be subtracted. 7479 bool shouldSubtractStep() const { return SubtractStep; } 7480 /// True, if the compare operator is strict (<, > or !=). 7481 bool isStrictTestOp() const { return TestIsStrictOp; } 7482 /// Build the expression to calculate the number of iterations. 7483 Expr *buildNumIterations( 7484 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType, 7485 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 7486 /// Build the precondition expression for the loops. 7487 Expr * 7488 buildPreCond(Scope *S, Expr *Cond, 7489 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 7490 /// Build reference expression to the counter be used for codegen. 7491 DeclRefExpr * 7492 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 7493 DSAStackTy &DSA) const; 7494 /// Build reference expression to the private counter be used for 7495 /// codegen. 7496 Expr *buildPrivateCounterVar() const; 7497 /// Build initialization of the counter be used for codegen. 7498 Expr *buildCounterInit() const; 7499 /// Build step of the counter be used for codegen. 7500 Expr *buildCounterStep() const; 7501 /// Build loop data with counter value for depend clauses in ordered 7502 /// directives. 7503 Expr * 7504 buildOrderedLoopData(Scope *S, Expr *Counter, 7505 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 7506 SourceLocation Loc, Expr *Inc = nullptr, 7507 OverloadedOperatorKind OOK = OO_Amp); 7508 /// Builds the minimum value for the loop counter. 7509 std::pair<Expr *, Expr *> buildMinMaxValues( 7510 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 7511 /// Builds final condition for the non-rectangular loops. 7512 Expr *buildFinalCondition(Scope *S) const; 7513 /// Return true if any expression is dependent. 7514 bool dependent() const; 7515 /// Returns true if the initializer forms non-rectangular loop. 7516 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); } 7517 /// Returns true if the condition forms non-rectangular loop. 7518 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); } 7519 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise. 7520 unsigned getLoopDependentIdx() const { 7521 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0)); 7522 } 7523 7524 private: 7525 /// Check the right-hand side of an assignment in the increment 7526 /// expression. 7527 bool checkAndSetIncRHS(Expr *RHS); 7528 /// Helper to set loop counter variable and its initializer. 7529 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB, 7530 bool EmitDiags); 7531 /// Helper to set upper bound. 7532 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp, 7533 SourceRange SR, SourceLocation SL); 7534 /// Helper to set loop increment. 7535 bool setStep(Expr *NewStep, bool Subtract); 7536 }; 7537 7538 bool OpenMPIterationSpaceChecker::dependent() const { 7539 if (!LCDecl) { 7540 assert(!LB && !UB && !Step); 7541 return false; 7542 } 7543 return LCDecl->getType()->isDependentType() || 7544 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 7545 (Step && Step->isValueDependent()); 7546 } 7547 7548 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl, 7549 Expr *NewLCRefExpr, 7550 Expr *NewLB, bool EmitDiags) { 7551 // State consistency checking to ensure correct usage. 7552 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 7553 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 7554 if (!NewLCDecl || !NewLB || NewLB->containsErrors()) 7555 return true; 7556 LCDecl = getCanonicalDecl(NewLCDecl); 7557 LCRef = NewLCRefExpr; 7558 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 7559 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 7560 if ((Ctor->isCopyOrMoveConstructor() || 7561 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 7562 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 7563 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 7564 LB = NewLB; 7565 if (EmitDiags) 7566 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true); 7567 return false; 7568 } 7569 7570 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, 7571 llvm::Optional<bool> LessOp, 7572 bool StrictOp, SourceRange SR, 7573 SourceLocation SL) { 7574 // State consistency checking to ensure correct usage. 7575 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 7576 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 7577 if (!NewUB || NewUB->containsErrors()) 7578 return true; 7579 UB = NewUB; 7580 if (LessOp) 7581 TestIsLessOp = LessOp; 7582 TestIsStrictOp = StrictOp; 7583 ConditionSrcRange = SR; 7584 ConditionLoc = SL; 7585 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false); 7586 return false; 7587 } 7588 7589 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) { 7590 // State consistency checking to ensure correct usage. 7591 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 7592 if (!NewStep || NewStep->containsErrors()) 7593 return true; 7594 if (!NewStep->isValueDependent()) { 7595 // Check that the step is integer expression. 7596 SourceLocation StepLoc = NewStep->getBeginLoc(); 7597 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( 7598 StepLoc, getExprAsWritten(NewStep)); 7599 if (Val.isInvalid()) 7600 return true; 7601 NewStep = Val.get(); 7602 7603 // OpenMP [2.6, Canonical Loop Form, Restrictions] 7604 // If test-expr is of form var relational-op b and relational-op is < or 7605 // <= then incr-expr must cause var to increase on each iteration of the 7606 // loop. If test-expr is of form var relational-op b and relational-op is 7607 // > or >= then incr-expr must cause var to decrease on each iteration of 7608 // the loop. 7609 // If test-expr is of form b relational-op var and relational-op is < or 7610 // <= then incr-expr must cause var to decrease on each iteration of the 7611 // loop. If test-expr is of form b relational-op var and relational-op is 7612 // > or >= then incr-expr must cause var to increase on each iteration of 7613 // the loop. 7614 Optional<llvm::APSInt> Result = 7615 NewStep->getIntegerConstantExpr(SemaRef.Context); 7616 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 7617 bool IsConstNeg = 7618 Result && Result->isSigned() && (Subtract != Result->isNegative()); 7619 bool IsConstPos = 7620 Result && Result->isSigned() && (Subtract == Result->isNegative()); 7621 bool IsConstZero = Result && !Result->getBoolValue(); 7622 7623 // != with increment is treated as <; != with decrement is treated as > 7624 if (!TestIsLessOp.hasValue()) 7625 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract); 7626 if (UB && 7627 (IsConstZero || (TestIsLessOp.getValue() 7628 ? (IsConstNeg || (IsUnsigned && Subtract)) 7629 : (IsConstPos || (IsUnsigned && !Subtract))))) { 7630 SemaRef.Diag(NewStep->getExprLoc(), 7631 diag::err_omp_loop_incr_not_compatible) 7632 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange(); 7633 SemaRef.Diag(ConditionLoc, 7634 diag::note_omp_loop_cond_requres_compatible_incr) 7635 << TestIsLessOp.getValue() << ConditionSrcRange; 7636 return true; 7637 } 7638 if (TestIsLessOp.getValue() == Subtract) { 7639 NewStep = 7640 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 7641 .get(); 7642 Subtract = !Subtract; 7643 } 7644 } 7645 7646 Step = NewStep; 7647 SubtractStep = Subtract; 7648 return false; 7649 } 7650 7651 namespace { 7652 /// Checker for the non-rectangular loops. Checks if the initializer or 7653 /// condition expression references loop counter variable. 7654 class LoopCounterRefChecker final 7655 : public ConstStmtVisitor<LoopCounterRefChecker, bool> { 7656 Sema &SemaRef; 7657 DSAStackTy &Stack; 7658 const ValueDecl *CurLCDecl = nullptr; 7659 const ValueDecl *DepDecl = nullptr; 7660 const ValueDecl *PrevDepDecl = nullptr; 7661 bool IsInitializer = true; 7662 bool SupportsNonRectangular; 7663 unsigned BaseLoopId = 0; 7664 bool checkDecl(const Expr *E, const ValueDecl *VD) { 7665 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) { 7666 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter) 7667 << (IsInitializer ? 0 : 1); 7668 return false; 7669 } 7670 const auto &&Data = Stack.isLoopControlVariable(VD); 7671 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions. 7672 // The type of the loop iterator on which we depend may not have a random 7673 // access iterator type. 7674 if (Data.first && VD->getType()->isRecordType()) { 7675 SmallString<128> Name; 7676 llvm::raw_svector_ostream OS(Name); 7677 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(), 7678 /*Qualified=*/true); 7679 SemaRef.Diag(E->getExprLoc(), 7680 diag::err_omp_wrong_dependency_iterator_type) 7681 << OS.str(); 7682 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD; 7683 return false; 7684 } 7685 if (Data.first && !SupportsNonRectangular) { 7686 SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency); 7687 return false; 7688 } 7689 if (Data.first && 7690 (DepDecl || (PrevDepDecl && 7691 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) { 7692 if (!DepDecl && PrevDepDecl) 7693 DepDecl = PrevDepDecl; 7694 SmallString<128> Name; 7695 llvm::raw_svector_ostream OS(Name); 7696 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(), 7697 /*Qualified=*/true); 7698 SemaRef.Diag(E->getExprLoc(), 7699 diag::err_omp_invariant_or_linear_dependency) 7700 << OS.str(); 7701 return false; 7702 } 7703 if (Data.first) { 7704 DepDecl = VD; 7705 BaseLoopId = Data.first; 7706 } 7707 return Data.first; 7708 } 7709 7710 public: 7711 bool VisitDeclRefExpr(const DeclRefExpr *E) { 7712 const ValueDecl *VD = E->getDecl(); 7713 if (isa<VarDecl>(VD)) 7714 return checkDecl(E, VD); 7715 return false; 7716 } 7717 bool VisitMemberExpr(const MemberExpr *E) { 7718 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 7719 const ValueDecl *VD = E->getMemberDecl(); 7720 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD)) 7721 return checkDecl(E, VD); 7722 } 7723 return false; 7724 } 7725 bool VisitStmt(const Stmt *S) { 7726 bool Res = false; 7727 for (const Stmt *Child : S->children()) 7728 Res = (Child && Visit(Child)) || Res; 7729 return Res; 7730 } 7731 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack, 7732 const ValueDecl *CurLCDecl, bool IsInitializer, 7733 const ValueDecl *PrevDepDecl = nullptr, 7734 bool SupportsNonRectangular = true) 7735 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl), 7736 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer), 7737 SupportsNonRectangular(SupportsNonRectangular) {} 7738 unsigned getBaseLoopId() const { 7739 assert(CurLCDecl && "Expected loop dependency."); 7740 return BaseLoopId; 7741 } 7742 const ValueDecl *getDepDecl() const { 7743 assert(CurLCDecl && "Expected loop dependency."); 7744 return DepDecl; 7745 } 7746 }; 7747 } // namespace 7748 7749 Optional<unsigned> 7750 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S, 7751 bool IsInitializer) { 7752 // Check for the non-rectangular loops. 7753 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer, 7754 DepDecl, SupportsNonRectangular); 7755 if (LoopStmtChecker.Visit(S)) { 7756 DepDecl = LoopStmtChecker.getDepDecl(); 7757 return LoopStmtChecker.getBaseLoopId(); 7758 } 7759 return llvm::None; 7760 } 7761 7762 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) { 7763 // Check init-expr for canonical loop form and save loop counter 7764 // variable - #Var and its initialization value - #LB. 7765 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 7766 // var = lb 7767 // integer-type var = lb 7768 // random-access-iterator-type var = lb 7769 // pointer-type var = lb 7770 // 7771 if (!S) { 7772 if (EmitDiags) { 7773 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 7774 } 7775 return true; 7776 } 7777 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 7778 if (!ExprTemp->cleanupsHaveSideEffects()) 7779 S = ExprTemp->getSubExpr(); 7780 7781 InitSrcRange = S->getSourceRange(); 7782 if (Expr *E = dyn_cast<Expr>(S)) 7783 S = E->IgnoreParens(); 7784 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 7785 if (BO->getOpcode() == BO_Assign) { 7786 Expr *LHS = BO->getLHS()->IgnoreParens(); 7787 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 7788 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 7789 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 7790 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7791 EmitDiags); 7792 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags); 7793 } 7794 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 7795 if (ME->isArrow() && 7796 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7797 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7798 EmitDiags); 7799 } 7800 } 7801 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 7802 if (DS->isSingleDecl()) { 7803 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 7804 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 7805 // Accept non-canonical init form here but emit ext. warning. 7806 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 7807 SemaRef.Diag(S->getBeginLoc(), 7808 diag::ext_omp_loop_not_canonical_init) 7809 << S->getSourceRange(); 7810 return setLCDeclAndLB( 7811 Var, 7812 buildDeclRefExpr(SemaRef, Var, 7813 Var->getType().getNonReferenceType(), 7814 DS->getBeginLoc()), 7815 Var->getInit(), EmitDiags); 7816 } 7817 } 7818 } 7819 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 7820 if (CE->getOperator() == OO_Equal) { 7821 Expr *LHS = CE->getArg(0); 7822 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 7823 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 7824 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 7825 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7826 EmitDiags); 7827 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags); 7828 } 7829 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 7830 if (ME->isArrow() && 7831 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7832 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7833 EmitDiags); 7834 } 7835 } 7836 } 7837 7838 if (dependent() || SemaRef.CurContext->isDependentContext()) 7839 return false; 7840 if (EmitDiags) { 7841 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init) 7842 << S->getSourceRange(); 7843 } 7844 return true; 7845 } 7846 7847 /// Ignore parenthesizes, implicit casts, copy constructor and return the 7848 /// variable (which may be the loop variable) if possible. 7849 static const ValueDecl *getInitLCDecl(const Expr *E) { 7850 if (!E) 7851 return nullptr; 7852 E = getExprAsWritten(E); 7853 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 7854 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 7855 if ((Ctor->isCopyOrMoveConstructor() || 7856 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 7857 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 7858 E = CE->getArg(0)->IgnoreParenImpCasts(); 7859 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 7860 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 7861 return getCanonicalDecl(VD); 7862 } 7863 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E)) 7864 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7865 return getCanonicalDecl(ME->getMemberDecl()); 7866 return nullptr; 7867 } 7868 7869 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) { 7870 // Check test-expr for canonical form, save upper-bound UB, flags for 7871 // less/greater and for strict/non-strict comparison. 7872 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following: 7873 // var relational-op b 7874 // b relational-op var 7875 // 7876 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50; 7877 if (!S) { 7878 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) 7879 << (IneqCondIsCanonical ? 1 : 0) << LCDecl; 7880 return true; 7881 } 7882 Condition = S; 7883 S = getExprAsWritten(S); 7884 SourceLocation CondLoc = S->getBeginLoc(); 7885 auto &&CheckAndSetCond = [this, IneqCondIsCanonical]( 7886 BinaryOperatorKind Opcode, const Expr *LHS, 7887 const Expr *RHS, SourceRange SR, 7888 SourceLocation OpLoc) -> llvm::Optional<bool> { 7889 if (BinaryOperator::isRelationalOp(Opcode)) { 7890 if (getInitLCDecl(LHS) == LCDecl) 7891 return setUB(const_cast<Expr *>(RHS), 7892 (Opcode == BO_LT || Opcode == BO_LE), 7893 (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc); 7894 if (getInitLCDecl(RHS) == LCDecl) 7895 return setUB(const_cast<Expr *>(LHS), 7896 (Opcode == BO_GT || Opcode == BO_GE), 7897 (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc); 7898 } else if (IneqCondIsCanonical && Opcode == BO_NE) { 7899 return setUB(const_cast<Expr *>(getInitLCDecl(LHS) == LCDecl ? RHS : LHS), 7900 /*LessOp=*/llvm::None, 7901 /*StrictOp=*/true, SR, OpLoc); 7902 } 7903 return llvm::None; 7904 }; 7905 llvm::Optional<bool> Res; 7906 if (auto *RBO = dyn_cast<CXXRewrittenBinaryOperator>(S)) { 7907 CXXRewrittenBinaryOperator::DecomposedForm DF = RBO->getDecomposedForm(); 7908 Res = CheckAndSetCond(DF.Opcode, DF.LHS, DF.RHS, RBO->getSourceRange(), 7909 RBO->getOperatorLoc()); 7910 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 7911 Res = CheckAndSetCond(BO->getOpcode(), BO->getLHS(), BO->getRHS(), 7912 BO->getSourceRange(), BO->getOperatorLoc()); 7913 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 7914 if (CE->getNumArgs() == 2) { 7915 Res = CheckAndSetCond( 7916 BinaryOperator::getOverloadedOpcode(CE->getOperator()), CE->getArg(0), 7917 CE->getArg(1), CE->getSourceRange(), CE->getOperatorLoc()); 7918 } 7919 } 7920 if (Res.hasValue()) 7921 return *Res; 7922 if (dependent() || SemaRef.CurContext->isDependentContext()) 7923 return false; 7924 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 7925 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl; 7926 return true; 7927 } 7928 7929 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) { 7930 // RHS of canonical loop form increment can be: 7931 // var + incr 7932 // incr + var 7933 // var - incr 7934 // 7935 RHS = RHS->IgnoreParenImpCasts(); 7936 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 7937 if (BO->isAdditiveOp()) { 7938 bool IsAdd = BO->getOpcode() == BO_Add; 7939 if (getInitLCDecl(BO->getLHS()) == LCDecl) 7940 return setStep(BO->getRHS(), !IsAdd); 7941 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl) 7942 return setStep(BO->getLHS(), /*Subtract=*/false); 7943 } 7944 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 7945 bool IsAdd = CE->getOperator() == OO_Plus; 7946 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 7947 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 7948 return setStep(CE->getArg(1), !IsAdd); 7949 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl) 7950 return setStep(CE->getArg(0), /*Subtract=*/false); 7951 } 7952 } 7953 if (dependent() || SemaRef.CurContext->isDependentContext()) 7954 return false; 7955 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 7956 << RHS->getSourceRange() << LCDecl; 7957 return true; 7958 } 7959 7960 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) { 7961 // Check incr-expr for canonical loop form and return true if it 7962 // does not conform. 7963 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 7964 // ++var 7965 // var++ 7966 // --var 7967 // var-- 7968 // var += incr 7969 // var -= incr 7970 // var = var + incr 7971 // var = incr + var 7972 // var = var - incr 7973 // 7974 if (!S) { 7975 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 7976 return true; 7977 } 7978 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 7979 if (!ExprTemp->cleanupsHaveSideEffects()) 7980 S = ExprTemp->getSubExpr(); 7981 7982 IncrementSrcRange = S->getSourceRange(); 7983 S = S->IgnoreParens(); 7984 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 7985 if (UO->isIncrementDecrementOp() && 7986 getInitLCDecl(UO->getSubExpr()) == LCDecl) 7987 return setStep(SemaRef 7988 .ActOnIntegerConstant(UO->getBeginLoc(), 7989 (UO->isDecrementOp() ? -1 : 1)) 7990 .get(), 7991 /*Subtract=*/false); 7992 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 7993 switch (BO->getOpcode()) { 7994 case BO_AddAssign: 7995 case BO_SubAssign: 7996 if (getInitLCDecl(BO->getLHS()) == LCDecl) 7997 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 7998 break; 7999 case BO_Assign: 8000 if (getInitLCDecl(BO->getLHS()) == LCDecl) 8001 return checkAndSetIncRHS(BO->getRHS()); 8002 break; 8003 default: 8004 break; 8005 } 8006 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 8007 switch (CE->getOperator()) { 8008 case OO_PlusPlus: 8009 case OO_MinusMinus: 8010 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 8011 return setStep(SemaRef 8012 .ActOnIntegerConstant( 8013 CE->getBeginLoc(), 8014 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 8015 .get(), 8016 /*Subtract=*/false); 8017 break; 8018 case OO_PlusEqual: 8019 case OO_MinusEqual: 8020 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 8021 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 8022 break; 8023 case OO_Equal: 8024 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 8025 return checkAndSetIncRHS(CE->getArg(1)); 8026 break; 8027 default: 8028 break; 8029 } 8030 } 8031 if (dependent() || SemaRef.CurContext->isDependentContext()) 8032 return false; 8033 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 8034 << S->getSourceRange() << LCDecl; 8035 return true; 8036 } 8037 8038 static ExprResult 8039 tryBuildCapture(Sema &SemaRef, Expr *Capture, 8040 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8041 if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors()) 8042 return Capture; 8043 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 8044 return SemaRef.PerformImplicitConversion( 8045 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 8046 /*AllowExplicit=*/true); 8047 auto I = Captures.find(Capture); 8048 if (I != Captures.end()) 8049 return buildCapture(SemaRef, Capture, I->second); 8050 DeclRefExpr *Ref = nullptr; 8051 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 8052 Captures[Capture] = Ref; 8053 return Res; 8054 } 8055 8056 /// Calculate number of iterations, transforming to unsigned, if number of 8057 /// iterations may be larger than the original type. 8058 static Expr * 8059 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc, 8060 Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy, 8061 bool TestIsStrictOp, bool RoundToStep, 8062 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8063 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 8064 if (!NewStep.isUsable()) 8065 return nullptr; 8066 llvm::APSInt LRes, SRes; 8067 bool IsLowerConst = false, IsStepConst = false; 8068 if (Optional<llvm::APSInt> Res = 8069 Lower->getIntegerConstantExpr(SemaRef.Context)) { 8070 LRes = *Res; 8071 IsLowerConst = true; 8072 } 8073 if (Optional<llvm::APSInt> Res = 8074 Step->getIntegerConstantExpr(SemaRef.Context)) { 8075 SRes = *Res; 8076 IsStepConst = true; 8077 } 8078 bool NoNeedToConvert = IsLowerConst && !RoundToStep && 8079 ((!TestIsStrictOp && LRes.isNonNegative()) || 8080 (TestIsStrictOp && LRes.isStrictlyPositive())); 8081 bool NeedToReorganize = false; 8082 // Check if any subexpressions in Lower -Step [+ 1] lead to overflow. 8083 if (!NoNeedToConvert && IsLowerConst && 8084 (TestIsStrictOp || (RoundToStep && IsStepConst))) { 8085 NoNeedToConvert = true; 8086 if (RoundToStep) { 8087 unsigned BW = LRes.getBitWidth() > SRes.getBitWidth() 8088 ? LRes.getBitWidth() 8089 : SRes.getBitWidth(); 8090 LRes = LRes.extend(BW + 1); 8091 LRes.setIsSigned(true); 8092 SRes = SRes.extend(BW + 1); 8093 SRes.setIsSigned(true); 8094 LRes -= SRes; 8095 NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes; 8096 LRes = LRes.trunc(BW); 8097 } 8098 if (TestIsStrictOp) { 8099 unsigned BW = LRes.getBitWidth(); 8100 LRes = LRes.extend(BW + 1); 8101 LRes.setIsSigned(true); 8102 ++LRes; 8103 NoNeedToConvert = 8104 NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes; 8105 // truncate to the original bitwidth. 8106 LRes = LRes.trunc(BW); 8107 } 8108 NeedToReorganize = NoNeedToConvert; 8109 } 8110 llvm::APSInt URes; 8111 bool IsUpperConst = false; 8112 if (Optional<llvm::APSInt> Res = 8113 Upper->getIntegerConstantExpr(SemaRef.Context)) { 8114 URes = *Res; 8115 IsUpperConst = true; 8116 } 8117 if (NoNeedToConvert && IsLowerConst && IsUpperConst && 8118 (!RoundToStep || IsStepConst)) { 8119 unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth() 8120 : URes.getBitWidth(); 8121 LRes = LRes.extend(BW + 1); 8122 LRes.setIsSigned(true); 8123 URes = URes.extend(BW + 1); 8124 URes.setIsSigned(true); 8125 URes -= LRes; 8126 NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes; 8127 NeedToReorganize = NoNeedToConvert; 8128 } 8129 // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant 8130 // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to 8131 // unsigned. 8132 if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) && 8133 !LCTy->isDependentType() && LCTy->isIntegerType()) { 8134 QualType LowerTy = Lower->getType(); 8135 QualType UpperTy = Upper->getType(); 8136 uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy); 8137 uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy); 8138 if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) || 8139 (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) { 8140 QualType CastType = SemaRef.Context.getIntTypeForBitwidth( 8141 LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0); 8142 Upper = 8143 SemaRef 8144 .PerformImplicitConversion( 8145 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(), 8146 CastType, Sema::AA_Converting) 8147 .get(); 8148 Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(); 8149 NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get()); 8150 } 8151 } 8152 if (!Lower || !Upper || NewStep.isInvalid()) 8153 return nullptr; 8154 8155 ExprResult Diff; 8156 // If need to reorganize, then calculate the form as Upper - (Lower - Step [+ 8157 // 1]). 8158 if (NeedToReorganize) { 8159 Diff = Lower; 8160 8161 if (RoundToStep) { 8162 // Lower - Step 8163 Diff = 8164 SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get()); 8165 if (!Diff.isUsable()) 8166 return nullptr; 8167 } 8168 8169 // Lower - Step [+ 1] 8170 if (TestIsStrictOp) 8171 Diff = SemaRef.BuildBinOp( 8172 S, DefaultLoc, BO_Add, Diff.get(), 8173 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 8174 if (!Diff.isUsable()) 8175 return nullptr; 8176 8177 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8178 if (!Diff.isUsable()) 8179 return nullptr; 8180 8181 // Upper - (Lower - Step [+ 1]). 8182 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get()); 8183 if (!Diff.isUsable()) 8184 return nullptr; 8185 } else { 8186 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 8187 8188 if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) { 8189 // BuildBinOp already emitted error, this one is to point user to upper 8190 // and lower bound, and to tell what is passed to 'operator-'. 8191 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx) 8192 << Upper->getSourceRange() << Lower->getSourceRange(); 8193 return nullptr; 8194 } 8195 8196 if (!Diff.isUsable()) 8197 return nullptr; 8198 8199 // Upper - Lower [- 1] 8200 if (TestIsStrictOp) 8201 Diff = SemaRef.BuildBinOp( 8202 S, DefaultLoc, BO_Sub, Diff.get(), 8203 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 8204 if (!Diff.isUsable()) 8205 return nullptr; 8206 8207 if (RoundToStep) { 8208 // Upper - Lower [- 1] + Step 8209 Diff = 8210 SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 8211 if (!Diff.isUsable()) 8212 return nullptr; 8213 } 8214 } 8215 8216 // Parentheses (for dumping/debugging purposes only). 8217 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8218 if (!Diff.isUsable()) 8219 return nullptr; 8220 8221 // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step 8222 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 8223 if (!Diff.isUsable()) 8224 return nullptr; 8225 8226 return Diff.get(); 8227 } 8228 8229 /// Build the expression to calculate the number of iterations. 8230 Expr *OpenMPIterationSpaceChecker::buildNumIterations( 8231 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType, 8232 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 8233 QualType VarType = LCDecl->getType().getNonReferenceType(); 8234 if (!VarType->isIntegerType() && !VarType->isPointerType() && 8235 !SemaRef.getLangOpts().CPlusPlus) 8236 return nullptr; 8237 Expr *LBVal = LB; 8238 Expr *UBVal = UB; 8239 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) : 8240 // max(LB(MinVal), LB(MaxVal)) 8241 if (InitDependOnLC) { 8242 const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1]; 8243 if (!IS.MinValue || !IS.MaxValue) 8244 return nullptr; 8245 // OuterVar = Min 8246 ExprResult MinValue = 8247 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue); 8248 if (!MinValue.isUsable()) 8249 return nullptr; 8250 8251 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8252 IS.CounterVar, MinValue.get()); 8253 if (!LBMinVal.isUsable()) 8254 return nullptr; 8255 // OuterVar = Min, LBVal 8256 LBMinVal = 8257 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal); 8258 if (!LBMinVal.isUsable()) 8259 return nullptr; 8260 // (OuterVar = Min, LBVal) 8261 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get()); 8262 if (!LBMinVal.isUsable()) 8263 return nullptr; 8264 8265 // OuterVar = Max 8266 ExprResult MaxValue = 8267 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue); 8268 if (!MaxValue.isUsable()) 8269 return nullptr; 8270 8271 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8272 IS.CounterVar, MaxValue.get()); 8273 if (!LBMaxVal.isUsable()) 8274 return nullptr; 8275 // OuterVar = Max, LBVal 8276 LBMaxVal = 8277 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal); 8278 if (!LBMaxVal.isUsable()) 8279 return nullptr; 8280 // (OuterVar = Max, LBVal) 8281 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get()); 8282 if (!LBMaxVal.isUsable()) 8283 return nullptr; 8284 8285 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get(); 8286 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get(); 8287 if (!LBMin || !LBMax) 8288 return nullptr; 8289 // LB(MinVal) < LB(MaxVal) 8290 ExprResult MinLessMaxRes = 8291 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax); 8292 if (!MinLessMaxRes.isUsable()) 8293 return nullptr; 8294 Expr *MinLessMax = 8295 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get(); 8296 if (!MinLessMax) 8297 return nullptr; 8298 if (TestIsLessOp.getValue()) { 8299 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal), 8300 // LB(MaxVal)) 8301 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc, 8302 MinLessMax, LBMin, LBMax); 8303 if (!MinLB.isUsable()) 8304 return nullptr; 8305 LBVal = MinLB.get(); 8306 } else { 8307 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal), 8308 // LB(MaxVal)) 8309 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc, 8310 MinLessMax, LBMax, LBMin); 8311 if (!MaxLB.isUsable()) 8312 return nullptr; 8313 LBVal = MaxLB.get(); 8314 } 8315 } 8316 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) : 8317 // min(UB(MinVal), UB(MaxVal)) 8318 if (CondDependOnLC) { 8319 const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1]; 8320 if (!IS.MinValue || !IS.MaxValue) 8321 return nullptr; 8322 // OuterVar = Min 8323 ExprResult MinValue = 8324 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue); 8325 if (!MinValue.isUsable()) 8326 return nullptr; 8327 8328 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8329 IS.CounterVar, MinValue.get()); 8330 if (!UBMinVal.isUsable()) 8331 return nullptr; 8332 // OuterVar = Min, UBVal 8333 UBMinVal = 8334 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal); 8335 if (!UBMinVal.isUsable()) 8336 return nullptr; 8337 // (OuterVar = Min, UBVal) 8338 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get()); 8339 if (!UBMinVal.isUsable()) 8340 return nullptr; 8341 8342 // OuterVar = Max 8343 ExprResult MaxValue = 8344 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue); 8345 if (!MaxValue.isUsable()) 8346 return nullptr; 8347 8348 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8349 IS.CounterVar, MaxValue.get()); 8350 if (!UBMaxVal.isUsable()) 8351 return nullptr; 8352 // OuterVar = Max, UBVal 8353 UBMaxVal = 8354 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal); 8355 if (!UBMaxVal.isUsable()) 8356 return nullptr; 8357 // (OuterVar = Max, UBVal) 8358 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get()); 8359 if (!UBMaxVal.isUsable()) 8360 return nullptr; 8361 8362 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get(); 8363 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get(); 8364 if (!UBMin || !UBMax) 8365 return nullptr; 8366 // UB(MinVal) > UB(MaxVal) 8367 ExprResult MinGreaterMaxRes = 8368 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax); 8369 if (!MinGreaterMaxRes.isUsable()) 8370 return nullptr; 8371 Expr *MinGreaterMax = 8372 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get(); 8373 if (!MinGreaterMax) 8374 return nullptr; 8375 if (TestIsLessOp.getValue()) { 8376 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal), 8377 // UB(MaxVal)) 8378 ExprResult MaxUB = SemaRef.ActOnConditionalOp( 8379 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax); 8380 if (!MaxUB.isUsable()) 8381 return nullptr; 8382 UBVal = MaxUB.get(); 8383 } else { 8384 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal), 8385 // UB(MaxVal)) 8386 ExprResult MinUB = SemaRef.ActOnConditionalOp( 8387 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin); 8388 if (!MinUB.isUsable()) 8389 return nullptr; 8390 UBVal = MinUB.get(); 8391 } 8392 } 8393 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal; 8394 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal; 8395 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 8396 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 8397 if (!Upper || !Lower) 8398 return nullptr; 8399 8400 ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, 8401 Step, VarType, TestIsStrictOp, 8402 /*RoundToStep=*/true, Captures); 8403 if (!Diff.isUsable()) 8404 return nullptr; 8405 8406 // OpenMP runtime requires 32-bit or 64-bit loop variables. 8407 QualType Type = Diff.get()->getType(); 8408 ASTContext &C = SemaRef.Context; 8409 bool UseVarType = VarType->hasIntegerRepresentation() && 8410 C.getTypeSize(Type) > C.getTypeSize(VarType); 8411 if (!Type->isIntegerType() || UseVarType) { 8412 unsigned NewSize = 8413 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 8414 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 8415 : Type->hasSignedIntegerRepresentation(); 8416 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 8417 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 8418 Diff = SemaRef.PerformImplicitConversion( 8419 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 8420 if (!Diff.isUsable()) 8421 return nullptr; 8422 } 8423 } 8424 if (LimitedType) { 8425 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 8426 if (NewSize != C.getTypeSize(Type)) { 8427 if (NewSize < C.getTypeSize(Type)) { 8428 assert(NewSize == 64 && "incorrect loop var size"); 8429 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 8430 << InitSrcRange << ConditionSrcRange; 8431 } 8432 QualType NewType = C.getIntTypeForBitwidth( 8433 NewSize, Type->hasSignedIntegerRepresentation() || 8434 C.getTypeSize(Type) < NewSize); 8435 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 8436 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 8437 Sema::AA_Converting, true); 8438 if (!Diff.isUsable()) 8439 return nullptr; 8440 } 8441 } 8442 } 8443 8444 return Diff.get(); 8445 } 8446 8447 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues( 8448 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 8449 // Do not build for iterators, they cannot be used in non-rectangular loop 8450 // nests. 8451 if (LCDecl->getType()->isRecordType()) 8452 return std::make_pair(nullptr, nullptr); 8453 // If we subtract, the min is in the condition, otherwise the min is in the 8454 // init value. 8455 Expr *MinExpr = nullptr; 8456 Expr *MaxExpr = nullptr; 8457 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB; 8458 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB; 8459 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue() 8460 : CondDependOnLC.hasValue(); 8461 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue() 8462 : InitDependOnLC.hasValue(); 8463 Expr *Lower = 8464 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get(); 8465 Expr *Upper = 8466 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get(); 8467 if (!Upper || !Lower) 8468 return std::make_pair(nullptr, nullptr); 8469 8470 if (TestIsLessOp.getValue()) 8471 MinExpr = Lower; 8472 else 8473 MaxExpr = Upper; 8474 8475 // Build minimum/maximum value based on number of iterations. 8476 QualType VarType = LCDecl->getType().getNonReferenceType(); 8477 8478 ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, 8479 Step, VarType, TestIsStrictOp, 8480 /*RoundToStep=*/false, Captures); 8481 if (!Diff.isUsable()) 8482 return std::make_pair(nullptr, nullptr); 8483 8484 // ((Upper - Lower [- 1]) / Step) * Step 8485 // Parentheses (for dumping/debugging purposes only). 8486 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8487 if (!Diff.isUsable()) 8488 return std::make_pair(nullptr, nullptr); 8489 8490 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 8491 if (!NewStep.isUsable()) 8492 return std::make_pair(nullptr, nullptr); 8493 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get()); 8494 if (!Diff.isUsable()) 8495 return std::make_pair(nullptr, nullptr); 8496 8497 // Parentheses (for dumping/debugging purposes only). 8498 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8499 if (!Diff.isUsable()) 8500 return std::make_pair(nullptr, nullptr); 8501 8502 // Convert to the ptrdiff_t, if original type is pointer. 8503 if (VarType->isAnyPointerType() && 8504 !SemaRef.Context.hasSameType( 8505 Diff.get()->getType(), 8506 SemaRef.Context.getUnsignedPointerDiffType())) { 8507 Diff = SemaRef.PerformImplicitConversion( 8508 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(), 8509 Sema::AA_Converting, /*AllowExplicit=*/true); 8510 } 8511 if (!Diff.isUsable()) 8512 return std::make_pair(nullptr, nullptr); 8513 8514 if (TestIsLessOp.getValue()) { 8515 // MinExpr = Lower; 8516 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step) 8517 Diff = SemaRef.BuildBinOp( 8518 S, DefaultLoc, BO_Add, 8519 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(), 8520 Diff.get()); 8521 if (!Diff.isUsable()) 8522 return std::make_pair(nullptr, nullptr); 8523 } else { 8524 // MaxExpr = Upper; 8525 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step) 8526 Diff = SemaRef.BuildBinOp( 8527 S, DefaultLoc, BO_Sub, 8528 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(), 8529 Diff.get()); 8530 if (!Diff.isUsable()) 8531 return std::make_pair(nullptr, nullptr); 8532 } 8533 8534 // Convert to the original type. 8535 if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) 8536 Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType, 8537 Sema::AA_Converting, 8538 /*AllowExplicit=*/true); 8539 if (!Diff.isUsable()) 8540 return std::make_pair(nullptr, nullptr); 8541 8542 Sema::TentativeAnalysisScope Trap(SemaRef); 8543 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false); 8544 if (!Diff.isUsable()) 8545 return std::make_pair(nullptr, nullptr); 8546 8547 if (TestIsLessOp.getValue()) 8548 MaxExpr = Diff.get(); 8549 else 8550 MinExpr = Diff.get(); 8551 8552 return std::make_pair(MinExpr, MaxExpr); 8553 } 8554 8555 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const { 8556 if (InitDependOnLC || CondDependOnLC) 8557 return Condition; 8558 return nullptr; 8559 } 8560 8561 Expr *OpenMPIterationSpaceChecker::buildPreCond( 8562 Scope *S, Expr *Cond, 8563 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 8564 // Do not build a precondition when the condition/initialization is dependent 8565 // to prevent pessimistic early loop exit. 8566 // TODO: this can be improved by calculating min/max values but not sure that 8567 // it will be very effective. 8568 if (CondDependOnLC || InitDependOnLC) 8569 return SemaRef 8570 .PerformImplicitConversion( 8571 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(), 8572 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 8573 /*AllowExplicit=*/true) 8574 .get(); 8575 8576 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 8577 Sema::TentativeAnalysisScope Trap(SemaRef); 8578 8579 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures); 8580 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures); 8581 if (!NewLB.isUsable() || !NewUB.isUsable()) 8582 return nullptr; 8583 8584 ExprResult CondExpr = SemaRef.BuildBinOp( 8585 S, DefaultLoc, 8586 TestIsLessOp.getValue() ? (TestIsStrictOp ? BO_LT : BO_LE) 8587 : (TestIsStrictOp ? BO_GT : BO_GE), 8588 NewLB.get(), NewUB.get()); 8589 if (CondExpr.isUsable()) { 8590 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 8591 SemaRef.Context.BoolTy)) 8592 CondExpr = SemaRef.PerformImplicitConversion( 8593 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 8594 /*AllowExplicit=*/true); 8595 } 8596 8597 // Otherwise use original loop condition and evaluate it in runtime. 8598 return CondExpr.isUsable() ? CondExpr.get() : Cond; 8599 } 8600 8601 /// Build reference expression to the counter be used for codegen. 8602 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar( 8603 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 8604 DSAStackTy &DSA) const { 8605 auto *VD = dyn_cast<VarDecl>(LCDecl); 8606 if (!VD) { 8607 VD = SemaRef.isOpenMPCapturedDecl(LCDecl); 8608 DeclRefExpr *Ref = buildDeclRefExpr( 8609 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 8610 const DSAStackTy::DSAVarData Data = 8611 DSA.getTopDSA(LCDecl, /*FromParent=*/false); 8612 // If the loop control decl is explicitly marked as private, do not mark it 8613 // as captured again. 8614 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 8615 Captures.insert(std::make_pair(LCRef, Ref)); 8616 return Ref; 8617 } 8618 return cast<DeclRefExpr>(LCRef); 8619 } 8620 8621 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const { 8622 if (LCDecl && !LCDecl->isInvalidDecl()) { 8623 QualType Type = LCDecl->getType().getNonReferenceType(); 8624 VarDecl *PrivateVar = buildVarDecl( 8625 SemaRef, DefaultLoc, Type, LCDecl->getName(), 8626 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr, 8627 isa<VarDecl>(LCDecl) 8628 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc) 8629 : nullptr); 8630 if (PrivateVar->isInvalidDecl()) 8631 return nullptr; 8632 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 8633 } 8634 return nullptr; 8635 } 8636 8637 /// Build initialization of the counter to be used for codegen. 8638 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; } 8639 8640 /// Build step of the counter be used for codegen. 8641 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; } 8642 8643 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData( 8644 Scope *S, Expr *Counter, 8645 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc, 8646 Expr *Inc, OverloadedOperatorKind OOK) { 8647 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get(); 8648 if (!Cnt) 8649 return nullptr; 8650 if (Inc) { 8651 assert((OOK == OO_Plus || OOK == OO_Minus) && 8652 "Expected only + or - operations for depend clauses."); 8653 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub; 8654 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get(); 8655 if (!Cnt) 8656 return nullptr; 8657 } 8658 QualType VarType = LCDecl->getType().getNonReferenceType(); 8659 if (!VarType->isIntegerType() && !VarType->isPointerType() && 8660 !SemaRef.getLangOpts().CPlusPlus) 8661 return nullptr; 8662 // Upper - Lower 8663 Expr *Upper = TestIsLessOp.getValue() 8664 ? Cnt 8665 : tryBuildCapture(SemaRef, LB, Captures).get(); 8666 Expr *Lower = TestIsLessOp.getValue() 8667 ? tryBuildCapture(SemaRef, LB, Captures).get() 8668 : Cnt; 8669 if (!Upper || !Lower) 8670 return nullptr; 8671 8672 ExprResult Diff = calculateNumIters( 8673 SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType, 8674 /*TestIsStrictOp=*/false, /*RoundToStep=*/false, Captures); 8675 if (!Diff.isUsable()) 8676 return nullptr; 8677 8678 return Diff.get(); 8679 } 8680 } // namespace 8681 8682 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 8683 assert(getLangOpts().OpenMP && "OpenMP is not active."); 8684 assert(Init && "Expected loop in canonical form."); 8685 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 8686 if (AssociatedLoops > 0 && 8687 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 8688 DSAStack->loopStart(); 8689 OpenMPIterationSpaceChecker ISC(*this, /*SupportsNonRectangular=*/true, 8690 *DSAStack, ForLoc); 8691 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) { 8692 if (ValueDecl *D = ISC.getLoopDecl()) { 8693 auto *VD = dyn_cast<VarDecl>(D); 8694 DeclRefExpr *PrivateRef = nullptr; 8695 if (!VD) { 8696 if (VarDecl *Private = isOpenMPCapturedDecl(D)) { 8697 VD = Private; 8698 } else { 8699 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(), 8700 /*WithInit=*/false); 8701 VD = cast<VarDecl>(PrivateRef->getDecl()); 8702 } 8703 } 8704 DSAStack->addLoopControlVariable(D, VD); 8705 const Decl *LD = DSAStack->getPossiblyLoopCunter(); 8706 if (LD != D->getCanonicalDecl()) { 8707 DSAStack->resetPossibleLoopCounter(); 8708 if (auto *Var = dyn_cast_or_null<VarDecl>(LD)) 8709 MarkDeclarationsReferencedInExpr( 8710 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var), 8711 Var->getType().getNonLValueExprType(Context), 8712 ForLoc, /*RefersToCapture=*/true)); 8713 } 8714 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 8715 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables 8716 // Referenced in a Construct, C/C++]. The loop iteration variable in the 8717 // associated for-loop of a simd construct with just one associated 8718 // for-loop may be listed in a linear clause with a constant-linear-step 8719 // that is the increment of the associated for-loop. The loop iteration 8720 // variable(s) in the associated for-loop(s) of a for or parallel for 8721 // construct may be listed in a private or lastprivate clause. 8722 DSAStackTy::DSAVarData DVar = 8723 DSAStack->getTopDSA(D, /*FromParent=*/false); 8724 // If LoopVarRefExpr is nullptr it means the corresponding loop variable 8725 // is declared in the loop and it is predetermined as a private. 8726 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr(); 8727 OpenMPClauseKind PredeterminedCKind = 8728 isOpenMPSimdDirective(DKind) 8729 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear) 8730 : OMPC_private; 8731 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 8732 DVar.CKind != PredeterminedCKind && DVar.RefExpr && 8733 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate && 8734 DVar.CKind != OMPC_private))) || 8735 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 8736 DKind == OMPD_master_taskloop || 8737 DKind == OMPD_parallel_master_taskloop || 8738 isOpenMPDistributeDirective(DKind)) && 8739 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 8740 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 8741 (DVar.CKind != OMPC_private || DVar.RefExpr)) { 8742 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa) 8743 << getOpenMPClauseName(DVar.CKind) 8744 << getOpenMPDirectiveName(DKind) 8745 << getOpenMPClauseName(PredeterminedCKind); 8746 if (DVar.RefExpr == nullptr) 8747 DVar.CKind = PredeterminedCKind; 8748 reportOriginalDsa(*this, DSAStack, D, DVar, 8749 /*IsLoopIterVar=*/true); 8750 } else if (LoopDeclRefExpr) { 8751 // Make the loop iteration variable private (for worksharing 8752 // constructs), linear (for simd directives with the only one 8753 // associated loop) or lastprivate (for simd directives with several 8754 // collapsed or ordered loops). 8755 if (DVar.CKind == OMPC_unknown) 8756 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind, 8757 PrivateRef); 8758 } 8759 } 8760 } 8761 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 8762 } 8763 } 8764 8765 /// Called on a for stmt to check and extract its iteration space 8766 /// for further processing (such as collapsing). 8767 static bool checkOpenMPIterationSpace( 8768 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 8769 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 8770 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr, 8771 Expr *OrderedLoopCountExpr, 8772 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 8773 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces, 8774 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8775 bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind); 8776 // OpenMP [2.9.1, Canonical Loop Form] 8777 // for (init-expr; test-expr; incr-expr) structured-block 8778 // for (range-decl: range-expr) structured-block 8779 if (auto *CanonLoop = dyn_cast_or_null<OMPCanonicalLoop>(S)) 8780 S = CanonLoop->getLoopStmt(); 8781 auto *For = dyn_cast_or_null<ForStmt>(S); 8782 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S); 8783 // Ranged for is supported only in OpenMP 5.0. 8784 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) { 8785 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for) 8786 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 8787 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount 8788 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 8789 if (TotalNestedLoopCount > 1) { 8790 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 8791 SemaRef.Diag(DSA.getConstructLoc(), 8792 diag::note_omp_collapse_ordered_expr) 8793 << 2 << CollapseLoopCountExpr->getSourceRange() 8794 << OrderedLoopCountExpr->getSourceRange(); 8795 else if (CollapseLoopCountExpr) 8796 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 8797 diag::note_omp_collapse_ordered_expr) 8798 << 0 << CollapseLoopCountExpr->getSourceRange(); 8799 else 8800 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 8801 diag::note_omp_collapse_ordered_expr) 8802 << 1 << OrderedLoopCountExpr->getSourceRange(); 8803 } 8804 return true; 8805 } 8806 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) && 8807 "No loop body."); 8808 // Postpone analysis in dependent contexts for ranged for loops. 8809 if (CXXFor && SemaRef.CurContext->isDependentContext()) 8810 return false; 8811 8812 OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA, 8813 For ? For->getForLoc() : CXXFor->getForLoc()); 8814 8815 // Check init. 8816 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt(); 8817 if (ISC.checkAndSetInit(Init)) 8818 return true; 8819 8820 bool HasErrors = false; 8821 8822 // Check loop variable's type. 8823 if (ValueDecl *LCDecl = ISC.getLoopDecl()) { 8824 // OpenMP [2.6, Canonical Loop Form] 8825 // Var is one of the following: 8826 // A variable of signed or unsigned integer type. 8827 // For C++, a variable of a random access iterator type. 8828 // For C, a variable of a pointer type. 8829 QualType VarType = LCDecl->getType().getNonReferenceType(); 8830 if (!VarType->isDependentType() && !VarType->isIntegerType() && 8831 !VarType->isPointerType() && 8832 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 8833 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type) 8834 << SemaRef.getLangOpts().CPlusPlus; 8835 HasErrors = true; 8836 } 8837 8838 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 8839 // a Construct 8840 // The loop iteration variable(s) in the associated for-loop(s) of a for or 8841 // parallel for construct is (are) private. 8842 // The loop iteration variable in the associated for-loop of a simd 8843 // construct with just one associated for-loop is linear with a 8844 // constant-linear-step that is the increment of the associated for-loop. 8845 // Exclude loop var from the list of variables with implicitly defined data 8846 // sharing attributes. 8847 VarsWithImplicitDSA.erase(LCDecl); 8848 8849 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 8850 8851 // Check test-expr. 8852 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond()); 8853 8854 // Check incr-expr. 8855 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc()); 8856 } 8857 8858 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 8859 return HasErrors; 8860 8861 // Build the loop's iteration space representation. 8862 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond( 8863 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures); 8864 ResultIterSpaces[CurrentNestedLoopCount].NumIterations = 8865 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces, 8866 (isOpenMPWorksharingDirective(DKind) || 8867 isOpenMPGenericLoopDirective(DKind) || 8868 isOpenMPTaskLoopDirective(DKind) || 8869 isOpenMPDistributeDirective(DKind) || 8870 isOpenMPLoopTransformationDirective(DKind)), 8871 Captures); 8872 ResultIterSpaces[CurrentNestedLoopCount].CounterVar = 8873 ISC.buildCounterVar(Captures, DSA); 8874 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar = 8875 ISC.buildPrivateCounterVar(); 8876 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit(); 8877 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep(); 8878 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange(); 8879 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange = 8880 ISC.getConditionSrcRange(); 8881 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange = 8882 ISC.getIncrementSrcRange(); 8883 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep(); 8884 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare = 8885 ISC.isStrictTestOp(); 8886 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue, 8887 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) = 8888 ISC.buildMinMaxValues(DSA.getCurScope(), Captures); 8889 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition = 8890 ISC.buildFinalCondition(DSA.getCurScope()); 8891 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB = 8892 ISC.doesInitDependOnLC(); 8893 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB = 8894 ISC.doesCondDependOnLC(); 8895 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx = 8896 ISC.getLoopDependentIdx(); 8897 8898 HasErrors |= 8899 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr || 8900 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr || 8901 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr || 8902 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr || 8903 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr || 8904 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr); 8905 if (!HasErrors && DSA.isOrderedRegion()) { 8906 if (DSA.getOrderedRegionParam().second->getNumForLoops()) { 8907 if (CurrentNestedLoopCount < 8908 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) { 8909 DSA.getOrderedRegionParam().second->setLoopNumIterations( 8910 CurrentNestedLoopCount, 8911 ResultIterSpaces[CurrentNestedLoopCount].NumIterations); 8912 DSA.getOrderedRegionParam().second->setLoopCounter( 8913 CurrentNestedLoopCount, 8914 ResultIterSpaces[CurrentNestedLoopCount].CounterVar); 8915 } 8916 } 8917 for (auto &Pair : DSA.getDoacrossDependClauses()) { 8918 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) { 8919 // Erroneous case - clause has some problems. 8920 continue; 8921 } 8922 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink && 8923 Pair.second.size() <= CurrentNestedLoopCount) { 8924 // Erroneous case - clause has some problems. 8925 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr); 8926 continue; 8927 } 8928 Expr *CntValue; 8929 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 8930 CntValue = ISC.buildOrderedLoopData( 8931 DSA.getCurScope(), 8932 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures, 8933 Pair.first->getDependencyLoc()); 8934 else 8935 CntValue = ISC.buildOrderedLoopData( 8936 DSA.getCurScope(), 8937 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures, 8938 Pair.first->getDependencyLoc(), 8939 Pair.second[CurrentNestedLoopCount].first, 8940 Pair.second[CurrentNestedLoopCount].second); 8941 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue); 8942 } 8943 } 8944 8945 return HasErrors; 8946 } 8947 8948 /// Build 'VarRef = Start. 8949 static ExprResult 8950 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 8951 ExprResult Start, bool IsNonRectangularLB, 8952 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8953 // Build 'VarRef = Start. 8954 ExprResult NewStart = IsNonRectangularLB 8955 ? Start.get() 8956 : tryBuildCapture(SemaRef, Start.get(), Captures); 8957 if (!NewStart.isUsable()) 8958 return ExprError(); 8959 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 8960 VarRef.get()->getType())) { 8961 NewStart = SemaRef.PerformImplicitConversion( 8962 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 8963 /*AllowExplicit=*/true); 8964 if (!NewStart.isUsable()) 8965 return ExprError(); 8966 } 8967 8968 ExprResult Init = 8969 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 8970 return Init; 8971 } 8972 8973 /// Build 'VarRef = Start + Iter * Step'. 8974 static ExprResult buildCounterUpdate( 8975 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 8976 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract, 8977 bool IsNonRectangularLB, 8978 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) { 8979 // Add parentheses (for debugging purposes only). 8980 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 8981 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 8982 !Step.isUsable()) 8983 return ExprError(); 8984 8985 ExprResult NewStep = Step; 8986 if (Captures) 8987 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 8988 if (NewStep.isInvalid()) 8989 return ExprError(); 8990 ExprResult Update = 8991 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 8992 if (!Update.isUsable()) 8993 return ExprError(); 8994 8995 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 8996 // 'VarRef = Start (+|-) Iter * Step'. 8997 if (!Start.isUsable()) 8998 return ExprError(); 8999 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get()); 9000 if (!NewStart.isUsable()) 9001 return ExprError(); 9002 if (Captures && !IsNonRectangularLB) 9003 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 9004 if (NewStart.isInvalid()) 9005 return ExprError(); 9006 9007 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 9008 ExprResult SavedUpdate = Update; 9009 ExprResult UpdateVal; 9010 if (VarRef.get()->getType()->isOverloadableType() || 9011 NewStart.get()->getType()->isOverloadableType() || 9012 Update.get()->getType()->isOverloadableType()) { 9013 Sema::TentativeAnalysisScope Trap(SemaRef); 9014 9015 Update = 9016 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 9017 if (Update.isUsable()) { 9018 UpdateVal = 9019 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 9020 VarRef.get(), SavedUpdate.get()); 9021 if (UpdateVal.isUsable()) { 9022 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 9023 UpdateVal.get()); 9024 } 9025 } 9026 } 9027 9028 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 9029 if (!Update.isUsable() || !UpdateVal.isUsable()) { 9030 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 9031 NewStart.get(), SavedUpdate.get()); 9032 if (!Update.isUsable()) 9033 return ExprError(); 9034 9035 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 9036 VarRef.get()->getType())) { 9037 Update = SemaRef.PerformImplicitConversion( 9038 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 9039 if (!Update.isUsable()) 9040 return ExprError(); 9041 } 9042 9043 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 9044 } 9045 return Update; 9046 } 9047 9048 /// Convert integer expression \a E to make it have at least \a Bits 9049 /// bits. 9050 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 9051 if (E == nullptr) 9052 return ExprError(); 9053 ASTContext &C = SemaRef.Context; 9054 QualType OldType = E->getType(); 9055 unsigned HasBits = C.getTypeSize(OldType); 9056 if (HasBits >= Bits) 9057 return ExprResult(E); 9058 // OK to convert to signed, because new type has more bits than old. 9059 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 9060 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 9061 true); 9062 } 9063 9064 /// Check if the given expression \a E is a constant integer that fits 9065 /// into \a Bits bits. 9066 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) { 9067 if (E == nullptr) 9068 return false; 9069 if (Optional<llvm::APSInt> Result = 9070 E->getIntegerConstantExpr(SemaRef.Context)) 9071 return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits); 9072 return false; 9073 } 9074 9075 /// Build preinits statement for the given declarations. 9076 static Stmt *buildPreInits(ASTContext &Context, 9077 MutableArrayRef<Decl *> PreInits) { 9078 if (!PreInits.empty()) { 9079 return new (Context) DeclStmt( 9080 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 9081 SourceLocation(), SourceLocation()); 9082 } 9083 return nullptr; 9084 } 9085 9086 /// Build preinits statement for the given declarations. 9087 static Stmt * 9088 buildPreInits(ASTContext &Context, 9089 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 9090 if (!Captures.empty()) { 9091 SmallVector<Decl *, 16> PreInits; 9092 for (const auto &Pair : Captures) 9093 PreInits.push_back(Pair.second->getDecl()); 9094 return buildPreInits(Context, PreInits); 9095 } 9096 return nullptr; 9097 } 9098 9099 /// Build postupdate expression for the given list of postupdates expressions. 9100 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 9101 Expr *PostUpdate = nullptr; 9102 if (!PostUpdates.empty()) { 9103 for (Expr *E : PostUpdates) { 9104 Expr *ConvE = S.BuildCStyleCastExpr( 9105 E->getExprLoc(), 9106 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 9107 E->getExprLoc(), E) 9108 .get(); 9109 PostUpdate = PostUpdate 9110 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 9111 PostUpdate, ConvE) 9112 .get() 9113 : ConvE; 9114 } 9115 } 9116 return PostUpdate; 9117 } 9118 9119 /// Called on a for stmt to check itself and nested loops (if any). 9120 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 9121 /// number of collapsed loops otherwise. 9122 static unsigned 9123 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 9124 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 9125 DSAStackTy &DSA, 9126 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 9127 OMPLoopBasedDirective::HelperExprs &Built) { 9128 unsigned NestedLoopCount = 1; 9129 bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) && 9130 !isOpenMPLoopTransformationDirective(DKind); 9131 9132 if (CollapseLoopCountExpr) { 9133 // Found 'collapse' clause - calculate collapse number. 9134 Expr::EvalResult Result; 9135 if (!CollapseLoopCountExpr->isValueDependent() && 9136 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 9137 NestedLoopCount = Result.Val.getInt().getLimitedValue(); 9138 } else { 9139 Built.clear(/*Size=*/1); 9140 return 1; 9141 } 9142 } 9143 unsigned OrderedLoopCount = 1; 9144 if (OrderedLoopCountExpr) { 9145 // Found 'ordered' clause - calculate collapse number. 9146 Expr::EvalResult EVResult; 9147 if (!OrderedLoopCountExpr->isValueDependent() && 9148 OrderedLoopCountExpr->EvaluateAsInt(EVResult, 9149 SemaRef.getASTContext())) { 9150 llvm::APSInt Result = EVResult.Val.getInt(); 9151 if (Result.getLimitedValue() < NestedLoopCount) { 9152 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 9153 diag::err_omp_wrong_ordered_loop_count) 9154 << OrderedLoopCountExpr->getSourceRange(); 9155 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 9156 diag::note_collapse_loop_count) 9157 << CollapseLoopCountExpr->getSourceRange(); 9158 } 9159 OrderedLoopCount = Result.getLimitedValue(); 9160 } else { 9161 Built.clear(/*Size=*/1); 9162 return 1; 9163 } 9164 } 9165 // This is helper routine for loop directives (e.g., 'for', 'simd', 9166 // 'for simd', etc.). 9167 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 9168 unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount); 9169 SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops); 9170 if (!OMPLoopBasedDirective::doForAllLoops( 9171 AStmt->IgnoreContainers(!isOpenMPLoopTransformationDirective(DKind)), 9172 SupportsNonPerfectlyNested, NumLoops, 9173 [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount, 9174 CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA, 9175 &IterSpaces, &Captures](unsigned Cnt, Stmt *CurStmt) { 9176 if (checkOpenMPIterationSpace( 9177 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 9178 NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr, 9179 VarsWithImplicitDSA, IterSpaces, Captures)) 9180 return true; 9181 if (Cnt > 0 && Cnt >= NestedLoopCount && 9182 IterSpaces[Cnt].CounterVar) { 9183 // Handle initialization of captured loop iterator variables. 9184 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar); 9185 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) { 9186 Captures[DRE] = DRE; 9187 } 9188 } 9189 return false; 9190 }, 9191 [&SemaRef, &Captures](OMPLoopTransformationDirective *Transform) { 9192 Stmt *DependentPreInits = Transform->getPreInits(); 9193 if (!DependentPreInits) 9194 return; 9195 for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) { 9196 auto *D = cast<VarDecl>(C); 9197 DeclRefExpr *Ref = buildDeclRefExpr(SemaRef, D, D->getType(), 9198 Transform->getBeginLoc()); 9199 Captures[Ref] = Ref; 9200 } 9201 })) 9202 return 0; 9203 9204 Built.clear(/* size */ NestedLoopCount); 9205 9206 if (SemaRef.CurContext->isDependentContext()) 9207 return NestedLoopCount; 9208 9209 // An example of what is generated for the following code: 9210 // 9211 // #pragma omp simd collapse(2) ordered(2) 9212 // for (i = 0; i < NI; ++i) 9213 // for (k = 0; k < NK; ++k) 9214 // for (j = J0; j < NJ; j+=2) { 9215 // <loop body> 9216 // } 9217 // 9218 // We generate the code below. 9219 // Note: the loop body may be outlined in CodeGen. 9220 // Note: some counters may be C++ classes, operator- is used to find number of 9221 // iterations and operator+= to calculate counter value. 9222 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 9223 // or i64 is currently supported). 9224 // 9225 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 9226 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 9227 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 9228 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 9229 // // similar updates for vars in clauses (e.g. 'linear') 9230 // <loop body (using local i and j)> 9231 // } 9232 // i = NI; // assign final values of counters 9233 // j = NJ; 9234 // 9235 9236 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 9237 // the iteration counts of the collapsed for loops. 9238 // Precondition tests if there is at least one iteration (all conditions are 9239 // true). 9240 auto PreCond = ExprResult(IterSpaces[0].PreCond); 9241 Expr *N0 = IterSpaces[0].NumIterations; 9242 ExprResult LastIteration32 = 9243 widenIterationCount(/*Bits=*/32, 9244 SemaRef 9245 .PerformImplicitConversion( 9246 N0->IgnoreImpCasts(), N0->getType(), 9247 Sema::AA_Converting, /*AllowExplicit=*/true) 9248 .get(), 9249 SemaRef); 9250 ExprResult LastIteration64 = widenIterationCount( 9251 /*Bits=*/64, 9252 SemaRef 9253 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(), 9254 Sema::AA_Converting, 9255 /*AllowExplicit=*/true) 9256 .get(), 9257 SemaRef); 9258 9259 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 9260 return NestedLoopCount; 9261 9262 ASTContext &C = SemaRef.Context; 9263 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 9264 9265 Scope *CurScope = DSA.getCurScope(); 9266 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 9267 if (PreCond.isUsable()) { 9268 PreCond = 9269 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 9270 PreCond.get(), IterSpaces[Cnt].PreCond); 9271 } 9272 Expr *N = IterSpaces[Cnt].NumIterations; 9273 SourceLocation Loc = N->getExprLoc(); 9274 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 9275 if (LastIteration32.isUsable()) 9276 LastIteration32 = SemaRef.BuildBinOp( 9277 CurScope, Loc, BO_Mul, LastIteration32.get(), 9278 SemaRef 9279 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 9280 Sema::AA_Converting, 9281 /*AllowExplicit=*/true) 9282 .get()); 9283 if (LastIteration64.isUsable()) 9284 LastIteration64 = SemaRef.BuildBinOp( 9285 CurScope, Loc, BO_Mul, LastIteration64.get(), 9286 SemaRef 9287 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 9288 Sema::AA_Converting, 9289 /*AllowExplicit=*/true) 9290 .get()); 9291 } 9292 9293 // Choose either the 32-bit or 64-bit version. 9294 ExprResult LastIteration = LastIteration64; 9295 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse || 9296 (LastIteration32.isUsable() && 9297 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 9298 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 9299 fitsInto( 9300 /*Bits=*/32, 9301 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 9302 LastIteration64.get(), SemaRef)))) 9303 LastIteration = LastIteration32; 9304 QualType VType = LastIteration.get()->getType(); 9305 QualType RealVType = VType; 9306 QualType StrideVType = VType; 9307 if (isOpenMPTaskLoopDirective(DKind)) { 9308 VType = 9309 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 9310 StrideVType = 9311 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 9312 } 9313 9314 if (!LastIteration.isUsable()) 9315 return 0; 9316 9317 // Save the number of iterations. 9318 ExprResult NumIterations = LastIteration; 9319 { 9320 LastIteration = SemaRef.BuildBinOp( 9321 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 9322 LastIteration.get(), 9323 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 9324 if (!LastIteration.isUsable()) 9325 return 0; 9326 } 9327 9328 // Calculate the last iteration number beforehand instead of doing this on 9329 // each iteration. Do not do this if the number of iterations may be kfold-ed. 9330 bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context); 9331 ExprResult CalcLastIteration; 9332 if (!IsConstant) { 9333 ExprResult SaveRef = 9334 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 9335 LastIteration = SaveRef; 9336 9337 // Prepare SaveRef + 1. 9338 NumIterations = SemaRef.BuildBinOp( 9339 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 9340 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 9341 if (!NumIterations.isUsable()) 9342 return 0; 9343 } 9344 9345 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 9346 9347 // Build variables passed into runtime, necessary for worksharing directives. 9348 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 9349 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 9350 isOpenMPDistributeDirective(DKind) || 9351 isOpenMPGenericLoopDirective(DKind) || 9352 isOpenMPLoopTransformationDirective(DKind)) { 9353 // Lower bound variable, initialized with zero. 9354 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 9355 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 9356 SemaRef.AddInitializerToDecl(LBDecl, 9357 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 9358 /*DirectInit*/ false); 9359 9360 // Upper bound variable, initialized with last iteration number. 9361 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 9362 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 9363 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 9364 /*DirectInit*/ false); 9365 9366 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 9367 // This will be used to implement clause 'lastprivate'. 9368 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 9369 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 9370 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 9371 SemaRef.AddInitializerToDecl(ILDecl, 9372 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 9373 /*DirectInit*/ false); 9374 9375 // Stride variable returned by runtime (we initialize it to 1 by default). 9376 VarDecl *STDecl = 9377 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 9378 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 9379 SemaRef.AddInitializerToDecl(STDecl, 9380 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 9381 /*DirectInit*/ false); 9382 9383 // Build expression: UB = min(UB, LastIteration) 9384 // It is necessary for CodeGen of directives with static scheduling. 9385 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 9386 UB.get(), LastIteration.get()); 9387 ExprResult CondOp = SemaRef.ActOnConditionalOp( 9388 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(), 9389 LastIteration.get(), UB.get()); 9390 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 9391 CondOp.get()); 9392 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false); 9393 9394 // If we have a combined directive that combines 'distribute', 'for' or 9395 // 'simd' we need to be able to access the bounds of the schedule of the 9396 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 9397 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 9398 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9399 // Lower bound variable, initialized with zero. 9400 VarDecl *CombLBDecl = 9401 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 9402 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 9403 SemaRef.AddInitializerToDecl( 9404 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 9405 /*DirectInit*/ false); 9406 9407 // Upper bound variable, initialized with last iteration number. 9408 VarDecl *CombUBDecl = 9409 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 9410 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 9411 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 9412 /*DirectInit*/ false); 9413 9414 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 9415 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 9416 ExprResult CombCondOp = 9417 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 9418 LastIteration.get(), CombUB.get()); 9419 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 9420 CombCondOp.get()); 9421 CombEUB = 9422 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false); 9423 9424 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 9425 // We expect to have at least 2 more parameters than the 'parallel' 9426 // directive does - the lower and upper bounds of the previous schedule. 9427 assert(CD->getNumParams() >= 4 && 9428 "Unexpected number of parameters in loop combined directive"); 9429 9430 // Set the proper type for the bounds given what we learned from the 9431 // enclosed loops. 9432 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 9433 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 9434 9435 // Previous lower and upper bounds are obtained from the region 9436 // parameters. 9437 PrevLB = 9438 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 9439 PrevUB = 9440 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 9441 } 9442 } 9443 9444 // Build the iteration variable and its initialization before loop. 9445 ExprResult IV; 9446 ExprResult Init, CombInit; 9447 { 9448 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 9449 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 9450 Expr *RHS = (isOpenMPWorksharingDirective(DKind) || 9451 isOpenMPGenericLoopDirective(DKind) || 9452 isOpenMPTaskLoopDirective(DKind) || 9453 isOpenMPDistributeDirective(DKind) || 9454 isOpenMPLoopTransformationDirective(DKind)) 9455 ? LB.get() 9456 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 9457 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 9458 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false); 9459 9460 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9461 Expr *CombRHS = 9462 (isOpenMPWorksharingDirective(DKind) || 9463 isOpenMPGenericLoopDirective(DKind) || 9464 isOpenMPTaskLoopDirective(DKind) || 9465 isOpenMPDistributeDirective(DKind)) 9466 ? CombLB.get() 9467 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 9468 CombInit = 9469 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 9470 CombInit = 9471 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false); 9472 } 9473 } 9474 9475 bool UseStrictCompare = 9476 RealVType->hasUnsignedIntegerRepresentation() && 9477 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) { 9478 return LIS.IsStrictCompare; 9479 }); 9480 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for 9481 // unsigned IV)) for worksharing loops. 9482 SourceLocation CondLoc = AStmt->getBeginLoc(); 9483 Expr *BoundUB = UB.get(); 9484 if (UseStrictCompare) { 9485 BoundUB = 9486 SemaRef 9487 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB, 9488 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 9489 .get(); 9490 BoundUB = 9491 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get(); 9492 } 9493 ExprResult Cond = 9494 (isOpenMPWorksharingDirective(DKind) || 9495 isOpenMPGenericLoopDirective(DKind) || 9496 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind) || 9497 isOpenMPLoopTransformationDirective(DKind)) 9498 ? SemaRef.BuildBinOp(CurScope, CondLoc, 9499 UseStrictCompare ? BO_LT : BO_LE, IV.get(), 9500 BoundUB) 9501 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 9502 NumIterations.get()); 9503 ExprResult CombDistCond; 9504 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9505 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 9506 NumIterations.get()); 9507 } 9508 9509 ExprResult CombCond; 9510 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9511 Expr *BoundCombUB = CombUB.get(); 9512 if (UseStrictCompare) { 9513 BoundCombUB = 9514 SemaRef 9515 .BuildBinOp( 9516 CurScope, CondLoc, BO_Add, BoundCombUB, 9517 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 9518 .get(); 9519 BoundCombUB = 9520 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false) 9521 .get(); 9522 } 9523 CombCond = 9524 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 9525 IV.get(), BoundCombUB); 9526 } 9527 // Loop increment (IV = IV + 1) 9528 SourceLocation IncLoc = AStmt->getBeginLoc(); 9529 ExprResult Inc = 9530 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 9531 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 9532 if (!Inc.isUsable()) 9533 return 0; 9534 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 9535 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false); 9536 if (!Inc.isUsable()) 9537 return 0; 9538 9539 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 9540 // Used for directives with static scheduling. 9541 // In combined construct, add combined version that use CombLB and CombUB 9542 // base variables for the update 9543 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 9544 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 9545 isOpenMPGenericLoopDirective(DKind) || 9546 isOpenMPDistributeDirective(DKind) || 9547 isOpenMPLoopTransformationDirective(DKind)) { 9548 // LB + ST 9549 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 9550 if (!NextLB.isUsable()) 9551 return 0; 9552 // LB = LB + ST 9553 NextLB = 9554 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 9555 NextLB = 9556 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false); 9557 if (!NextLB.isUsable()) 9558 return 0; 9559 // UB + ST 9560 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 9561 if (!NextUB.isUsable()) 9562 return 0; 9563 // UB = UB + ST 9564 NextUB = 9565 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 9566 NextUB = 9567 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false); 9568 if (!NextUB.isUsable()) 9569 return 0; 9570 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9571 CombNextLB = 9572 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 9573 if (!NextLB.isUsable()) 9574 return 0; 9575 // LB = LB + ST 9576 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 9577 CombNextLB.get()); 9578 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(), 9579 /*DiscardedValue*/ false); 9580 if (!CombNextLB.isUsable()) 9581 return 0; 9582 // UB + ST 9583 CombNextUB = 9584 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 9585 if (!CombNextUB.isUsable()) 9586 return 0; 9587 // UB = UB + ST 9588 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 9589 CombNextUB.get()); 9590 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(), 9591 /*DiscardedValue*/ false); 9592 if (!CombNextUB.isUsable()) 9593 return 0; 9594 } 9595 } 9596 9597 // Create increment expression for distribute loop when combined in a same 9598 // directive with for as IV = IV + ST; ensure upper bound expression based 9599 // on PrevUB instead of NumIterations - used to implement 'for' when found 9600 // in combination with 'distribute', like in 'distribute parallel for' 9601 SourceLocation DistIncLoc = AStmt->getBeginLoc(); 9602 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond; 9603 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9604 DistCond = SemaRef.BuildBinOp( 9605 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB); 9606 assert(DistCond.isUsable() && "distribute cond expr was not built"); 9607 9608 DistInc = 9609 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 9610 assert(DistInc.isUsable() && "distribute inc expr was not built"); 9611 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 9612 DistInc.get()); 9613 DistInc = 9614 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false); 9615 assert(DistInc.isUsable() && "distribute inc expr was not built"); 9616 9617 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 9618 // construct 9619 ExprResult NewPrevUB = PrevUB; 9620 SourceLocation DistEUBLoc = AStmt->getBeginLoc(); 9621 if (!SemaRef.Context.hasSameType(UB.get()->getType(), 9622 PrevUB.get()->getType())) { 9623 NewPrevUB = SemaRef.BuildCStyleCastExpr( 9624 DistEUBLoc, 9625 SemaRef.Context.getTrivialTypeSourceInfo(UB.get()->getType()), 9626 DistEUBLoc, NewPrevUB.get()); 9627 if (!NewPrevUB.isUsable()) 9628 return 0; 9629 } 9630 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, 9631 UB.get(), NewPrevUB.get()); 9632 ExprResult CondOp = SemaRef.ActOnConditionalOp( 9633 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), NewPrevUB.get(), UB.get()); 9634 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 9635 CondOp.get()); 9636 PrevEUB = 9637 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false); 9638 9639 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in 9640 // parallel for is in combination with a distribute directive with 9641 // schedule(static, 1) 9642 Expr *BoundPrevUB = PrevUB.get(); 9643 if (UseStrictCompare) { 9644 BoundPrevUB = 9645 SemaRef 9646 .BuildBinOp( 9647 CurScope, CondLoc, BO_Add, BoundPrevUB, 9648 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 9649 .get(); 9650 BoundPrevUB = 9651 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false) 9652 .get(); 9653 } 9654 ParForInDistCond = 9655 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 9656 IV.get(), BoundPrevUB); 9657 } 9658 9659 // Build updates and final values of the loop counters. 9660 bool HasErrors = false; 9661 Built.Counters.resize(NestedLoopCount); 9662 Built.Inits.resize(NestedLoopCount); 9663 Built.Updates.resize(NestedLoopCount); 9664 Built.Finals.resize(NestedLoopCount); 9665 Built.DependentCounters.resize(NestedLoopCount); 9666 Built.DependentInits.resize(NestedLoopCount); 9667 Built.FinalsConditions.resize(NestedLoopCount); 9668 { 9669 // We implement the following algorithm for obtaining the 9670 // original loop iteration variable values based on the 9671 // value of the collapsed loop iteration variable IV. 9672 // 9673 // Let n+1 be the number of collapsed loops in the nest. 9674 // Iteration variables (I0, I1, .... In) 9675 // Iteration counts (N0, N1, ... Nn) 9676 // 9677 // Acc = IV; 9678 // 9679 // To compute Ik for loop k, 0 <= k <= n, generate: 9680 // Prod = N(k+1) * N(k+2) * ... * Nn; 9681 // Ik = Acc / Prod; 9682 // Acc -= Ik * Prod; 9683 // 9684 ExprResult Acc = IV; 9685 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 9686 LoopIterationSpace &IS = IterSpaces[Cnt]; 9687 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 9688 ExprResult Iter; 9689 9690 // Compute prod 9691 ExprResult Prod = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 9692 for (unsigned int K = Cnt + 1; K < NestedLoopCount; ++K) 9693 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(), 9694 IterSpaces[K].NumIterations); 9695 9696 // Iter = Acc / Prod 9697 // If there is at least one more inner loop to avoid 9698 // multiplication by 1. 9699 if (Cnt + 1 < NestedLoopCount) 9700 Iter = 9701 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, Acc.get(), Prod.get()); 9702 else 9703 Iter = Acc; 9704 if (!Iter.isUsable()) { 9705 HasErrors = true; 9706 break; 9707 } 9708 9709 // Update Acc: 9710 // Acc -= Iter * Prod 9711 // Check if there is at least one more inner loop to avoid 9712 // multiplication by 1. 9713 if (Cnt + 1 < NestedLoopCount) 9714 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Iter.get(), 9715 Prod.get()); 9716 else 9717 Prod = Iter; 9718 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, Acc.get(), Prod.get()); 9719 9720 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 9721 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 9722 DeclRefExpr *CounterVar = buildDeclRefExpr( 9723 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(), 9724 /*RefersToCapture=*/true); 9725 ExprResult Init = 9726 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 9727 IS.CounterInit, IS.IsNonRectangularLB, Captures); 9728 if (!Init.isUsable()) { 9729 HasErrors = true; 9730 break; 9731 } 9732 ExprResult Update = buildCounterUpdate( 9733 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 9734 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures); 9735 if (!Update.isUsable()) { 9736 HasErrors = true; 9737 break; 9738 } 9739 9740 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 9741 ExprResult Final = 9742 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar, 9743 IS.CounterInit, IS.NumIterations, IS.CounterStep, 9744 IS.Subtract, IS.IsNonRectangularLB, &Captures); 9745 if (!Final.isUsable()) { 9746 HasErrors = true; 9747 break; 9748 } 9749 9750 if (!Update.isUsable() || !Final.isUsable()) { 9751 HasErrors = true; 9752 break; 9753 } 9754 // Save results 9755 Built.Counters[Cnt] = IS.CounterVar; 9756 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 9757 Built.Inits[Cnt] = Init.get(); 9758 Built.Updates[Cnt] = Update.get(); 9759 Built.Finals[Cnt] = Final.get(); 9760 Built.DependentCounters[Cnt] = nullptr; 9761 Built.DependentInits[Cnt] = nullptr; 9762 Built.FinalsConditions[Cnt] = nullptr; 9763 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) { 9764 Built.DependentCounters[Cnt] = 9765 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx]; 9766 Built.DependentInits[Cnt] = 9767 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx]; 9768 Built.FinalsConditions[Cnt] = IS.FinalCondition; 9769 } 9770 } 9771 } 9772 9773 if (HasErrors) 9774 return 0; 9775 9776 // Save results 9777 Built.IterationVarRef = IV.get(); 9778 Built.LastIteration = LastIteration.get(); 9779 Built.NumIterations = NumIterations.get(); 9780 Built.CalcLastIteration = SemaRef 9781 .ActOnFinishFullExpr(CalcLastIteration.get(), 9782 /*DiscardedValue=*/false) 9783 .get(); 9784 Built.PreCond = PreCond.get(); 9785 Built.PreInits = buildPreInits(C, Captures); 9786 Built.Cond = Cond.get(); 9787 Built.Init = Init.get(); 9788 Built.Inc = Inc.get(); 9789 Built.LB = LB.get(); 9790 Built.UB = UB.get(); 9791 Built.IL = IL.get(); 9792 Built.ST = ST.get(); 9793 Built.EUB = EUB.get(); 9794 Built.NLB = NextLB.get(); 9795 Built.NUB = NextUB.get(); 9796 Built.PrevLB = PrevLB.get(); 9797 Built.PrevUB = PrevUB.get(); 9798 Built.DistInc = DistInc.get(); 9799 Built.PrevEUB = PrevEUB.get(); 9800 Built.DistCombinedFields.LB = CombLB.get(); 9801 Built.DistCombinedFields.UB = CombUB.get(); 9802 Built.DistCombinedFields.EUB = CombEUB.get(); 9803 Built.DistCombinedFields.Init = CombInit.get(); 9804 Built.DistCombinedFields.Cond = CombCond.get(); 9805 Built.DistCombinedFields.NLB = CombNextLB.get(); 9806 Built.DistCombinedFields.NUB = CombNextUB.get(); 9807 Built.DistCombinedFields.DistCond = CombDistCond.get(); 9808 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get(); 9809 9810 return NestedLoopCount; 9811 } 9812 9813 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 9814 auto CollapseClauses = 9815 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 9816 if (CollapseClauses.begin() != CollapseClauses.end()) 9817 return (*CollapseClauses.begin())->getNumForLoops(); 9818 return nullptr; 9819 } 9820 9821 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 9822 auto OrderedClauses = 9823 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 9824 if (OrderedClauses.begin() != OrderedClauses.end()) 9825 return (*OrderedClauses.begin())->getNumForLoops(); 9826 return nullptr; 9827 } 9828 9829 static bool checkSimdlenSafelenSpecified(Sema &S, 9830 const ArrayRef<OMPClause *> Clauses) { 9831 const OMPSafelenClause *Safelen = nullptr; 9832 const OMPSimdlenClause *Simdlen = nullptr; 9833 9834 for (const OMPClause *Clause : Clauses) { 9835 if (Clause->getClauseKind() == OMPC_safelen) 9836 Safelen = cast<OMPSafelenClause>(Clause); 9837 else if (Clause->getClauseKind() == OMPC_simdlen) 9838 Simdlen = cast<OMPSimdlenClause>(Clause); 9839 if (Safelen && Simdlen) 9840 break; 9841 } 9842 9843 if (Simdlen && Safelen) { 9844 const Expr *SimdlenLength = Simdlen->getSimdlen(); 9845 const Expr *SafelenLength = Safelen->getSafelen(); 9846 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 9847 SimdlenLength->isInstantiationDependent() || 9848 SimdlenLength->containsUnexpandedParameterPack()) 9849 return false; 9850 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 9851 SafelenLength->isInstantiationDependent() || 9852 SafelenLength->containsUnexpandedParameterPack()) 9853 return false; 9854 Expr::EvalResult SimdlenResult, SafelenResult; 9855 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context); 9856 SafelenLength->EvaluateAsInt(SafelenResult, S.Context); 9857 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt(); 9858 llvm::APSInt SafelenRes = SafelenResult.Val.getInt(); 9859 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 9860 // If both simdlen and safelen clauses are specified, the value of the 9861 // simdlen parameter must be less than or equal to the value of the safelen 9862 // parameter. 9863 if (SimdlenRes > SafelenRes) { 9864 S.Diag(SimdlenLength->getExprLoc(), 9865 diag::err_omp_wrong_simdlen_safelen_values) 9866 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 9867 return true; 9868 } 9869 } 9870 return false; 9871 } 9872 9873 StmtResult 9874 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 9875 SourceLocation StartLoc, SourceLocation EndLoc, 9876 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9877 if (!AStmt) 9878 return StmtError(); 9879 9880 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9881 OMPLoopBasedDirective::HelperExprs B; 9882 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9883 // define the nested loops number. 9884 unsigned NestedLoopCount = checkOpenMPLoop( 9885 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 9886 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 9887 if (NestedLoopCount == 0) 9888 return StmtError(); 9889 9890 assert((CurContext->isDependentContext() || B.builtAll()) && 9891 "omp simd loop exprs were not built"); 9892 9893 if (!CurContext->isDependentContext()) { 9894 // Finalize the clauses that need pre-built expressions for CodeGen. 9895 for (OMPClause *C : Clauses) { 9896 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9897 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9898 B.NumIterations, *this, CurScope, 9899 DSAStack)) 9900 return StmtError(); 9901 } 9902 } 9903 9904 if (checkSimdlenSafelenSpecified(*this, Clauses)) 9905 return StmtError(); 9906 9907 setFunctionHasBranchProtectedScope(); 9908 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 9909 Clauses, AStmt, B); 9910 } 9911 9912 StmtResult 9913 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 9914 SourceLocation StartLoc, SourceLocation EndLoc, 9915 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9916 if (!AStmt) 9917 return StmtError(); 9918 9919 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9920 OMPLoopBasedDirective::HelperExprs B; 9921 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9922 // define the nested loops number. 9923 unsigned NestedLoopCount = checkOpenMPLoop( 9924 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 9925 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 9926 if (NestedLoopCount == 0) 9927 return StmtError(); 9928 9929 assert((CurContext->isDependentContext() || B.builtAll()) && 9930 "omp for loop exprs were not built"); 9931 9932 if (!CurContext->isDependentContext()) { 9933 // Finalize the clauses that need pre-built expressions for CodeGen. 9934 for (OMPClause *C : Clauses) { 9935 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9936 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9937 B.NumIterations, *this, CurScope, 9938 DSAStack)) 9939 return StmtError(); 9940 } 9941 } 9942 9943 setFunctionHasBranchProtectedScope(); 9944 return OMPForDirective::Create( 9945 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 9946 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 9947 } 9948 9949 StmtResult Sema::ActOnOpenMPForSimdDirective( 9950 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 9951 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9952 if (!AStmt) 9953 return StmtError(); 9954 9955 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9956 OMPLoopBasedDirective::HelperExprs B; 9957 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9958 // define the nested loops number. 9959 unsigned NestedLoopCount = 9960 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 9961 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 9962 VarsWithImplicitDSA, B); 9963 if (NestedLoopCount == 0) 9964 return StmtError(); 9965 9966 assert((CurContext->isDependentContext() || B.builtAll()) && 9967 "omp for simd loop exprs were not built"); 9968 9969 if (!CurContext->isDependentContext()) { 9970 // Finalize the clauses that need pre-built expressions for CodeGen. 9971 for (OMPClause *C : Clauses) { 9972 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9973 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9974 B.NumIterations, *this, CurScope, 9975 DSAStack)) 9976 return StmtError(); 9977 } 9978 } 9979 9980 if (checkSimdlenSafelenSpecified(*this, Clauses)) 9981 return StmtError(); 9982 9983 setFunctionHasBranchProtectedScope(); 9984 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 9985 Clauses, AStmt, B); 9986 } 9987 9988 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 9989 Stmt *AStmt, 9990 SourceLocation StartLoc, 9991 SourceLocation EndLoc) { 9992 if (!AStmt) 9993 return StmtError(); 9994 9995 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9996 auto BaseStmt = AStmt; 9997 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 9998 BaseStmt = CS->getCapturedStmt(); 9999 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 10000 auto S = C->children(); 10001 if (S.begin() == S.end()) 10002 return StmtError(); 10003 // All associated statements must be '#pragma omp section' except for 10004 // the first one. 10005 for (Stmt *SectionStmt : llvm::drop_begin(S)) { 10006 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 10007 if (SectionStmt) 10008 Diag(SectionStmt->getBeginLoc(), 10009 diag::err_omp_sections_substmt_not_section); 10010 return StmtError(); 10011 } 10012 cast<OMPSectionDirective>(SectionStmt) 10013 ->setHasCancel(DSAStack->isCancelRegion()); 10014 } 10015 } else { 10016 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt); 10017 return StmtError(); 10018 } 10019 10020 setFunctionHasBranchProtectedScope(); 10021 10022 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 10023 DSAStack->getTaskgroupReductionRef(), 10024 DSAStack->isCancelRegion()); 10025 } 10026 10027 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 10028 SourceLocation StartLoc, 10029 SourceLocation EndLoc) { 10030 if (!AStmt) 10031 return StmtError(); 10032 10033 setFunctionHasBranchProtectedScope(); 10034 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 10035 10036 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 10037 DSAStack->isCancelRegion()); 10038 } 10039 10040 static Expr *getDirectCallExpr(Expr *E) { 10041 E = E->IgnoreParenCasts()->IgnoreImplicit(); 10042 if (auto *CE = dyn_cast<CallExpr>(E)) 10043 if (CE->getDirectCallee()) 10044 return E; 10045 return nullptr; 10046 } 10047 10048 StmtResult Sema::ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses, 10049 Stmt *AStmt, 10050 SourceLocation StartLoc, 10051 SourceLocation EndLoc) { 10052 if (!AStmt) 10053 return StmtError(); 10054 10055 Stmt *S = cast<CapturedStmt>(AStmt)->getCapturedStmt(); 10056 10057 // 5.1 OpenMP 10058 // expression-stmt : an expression statement with one of the following forms: 10059 // expression = target-call ( [expression-list] ); 10060 // target-call ( [expression-list] ); 10061 10062 SourceLocation TargetCallLoc; 10063 10064 if (!CurContext->isDependentContext()) { 10065 Expr *TargetCall = nullptr; 10066 10067 auto *E = dyn_cast<Expr>(S); 10068 if (!E) { 10069 Diag(S->getBeginLoc(), diag::err_omp_dispatch_statement_call); 10070 return StmtError(); 10071 } 10072 10073 E = E->IgnoreParenCasts()->IgnoreImplicit(); 10074 10075 if (auto *BO = dyn_cast<BinaryOperator>(E)) { 10076 if (BO->getOpcode() == BO_Assign) 10077 TargetCall = getDirectCallExpr(BO->getRHS()); 10078 } else { 10079 if (auto *COCE = dyn_cast<CXXOperatorCallExpr>(E)) 10080 if (COCE->getOperator() == OO_Equal) 10081 TargetCall = getDirectCallExpr(COCE->getArg(1)); 10082 if (!TargetCall) 10083 TargetCall = getDirectCallExpr(E); 10084 } 10085 if (!TargetCall) { 10086 Diag(E->getBeginLoc(), diag::err_omp_dispatch_statement_call); 10087 return StmtError(); 10088 } 10089 TargetCallLoc = TargetCall->getExprLoc(); 10090 } 10091 10092 setFunctionHasBranchProtectedScope(); 10093 10094 return OMPDispatchDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 10095 TargetCallLoc); 10096 } 10097 10098 StmtResult Sema::ActOnOpenMPGenericLoopDirective( 10099 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10100 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10101 if (!AStmt) 10102 return StmtError(); 10103 10104 // OpenMP 5.1 [2.11.7, loop construct] 10105 // A list item may not appear in a lastprivate clause unless it is the 10106 // loop iteration variable of a loop that is associated with the construct. 10107 for (OMPClause *C : Clauses) { 10108 if (auto *LPC = dyn_cast<OMPLastprivateClause>(C)) { 10109 for (Expr *RefExpr : LPC->varlists()) { 10110 SourceLocation ELoc; 10111 SourceRange ERange; 10112 Expr *SimpleRefExpr = RefExpr; 10113 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 10114 if (ValueDecl *D = Res.first) { 10115 auto &&Info = DSAStack->isLoopControlVariable(D); 10116 if (!Info.first) { 10117 Diag(ELoc, diag::err_omp_lastprivate_loop_var_non_loop_iteration); 10118 return StmtError(); 10119 } 10120 } 10121 } 10122 } 10123 } 10124 10125 auto *CS = cast<CapturedStmt>(AStmt); 10126 // 1.2.2 OpenMP Language Terminology 10127 // Structured block - An executable statement with a single entry at the 10128 // top and a single exit at the bottom. 10129 // The point of exit cannot be a branch out of the structured block. 10130 // longjmp() and throw() must not violate the entry/exit criteria. 10131 CS->getCapturedDecl()->setNothrow(); 10132 10133 OMPLoopDirective::HelperExprs B; 10134 // In presence of clause 'collapse', it will define the nested loops number. 10135 unsigned NestedLoopCount = checkOpenMPLoop( 10136 OMPD_loop, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 10137 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 10138 if (NestedLoopCount == 0) 10139 return StmtError(); 10140 10141 assert((CurContext->isDependentContext() || B.builtAll()) && 10142 "omp loop exprs were not built"); 10143 10144 setFunctionHasBranchProtectedScope(); 10145 return OMPGenericLoopDirective::Create(Context, StartLoc, EndLoc, 10146 NestedLoopCount, Clauses, AStmt, B); 10147 } 10148 10149 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 10150 Stmt *AStmt, 10151 SourceLocation StartLoc, 10152 SourceLocation EndLoc) { 10153 if (!AStmt) 10154 return StmtError(); 10155 10156 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10157 10158 setFunctionHasBranchProtectedScope(); 10159 10160 // OpenMP [2.7.3, single Construct, Restrictions] 10161 // The copyprivate clause must not be used with the nowait clause. 10162 const OMPClause *Nowait = nullptr; 10163 const OMPClause *Copyprivate = nullptr; 10164 for (const OMPClause *Clause : Clauses) { 10165 if (Clause->getClauseKind() == OMPC_nowait) 10166 Nowait = Clause; 10167 else if (Clause->getClauseKind() == OMPC_copyprivate) 10168 Copyprivate = Clause; 10169 if (Copyprivate && Nowait) { 10170 Diag(Copyprivate->getBeginLoc(), 10171 diag::err_omp_single_copyprivate_with_nowait); 10172 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here); 10173 return StmtError(); 10174 } 10175 } 10176 10177 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10178 } 10179 10180 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 10181 SourceLocation StartLoc, 10182 SourceLocation EndLoc) { 10183 if (!AStmt) 10184 return StmtError(); 10185 10186 setFunctionHasBranchProtectedScope(); 10187 10188 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 10189 } 10190 10191 StmtResult Sema::ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses, 10192 Stmt *AStmt, 10193 SourceLocation StartLoc, 10194 SourceLocation EndLoc) { 10195 if (!AStmt) 10196 return StmtError(); 10197 10198 setFunctionHasBranchProtectedScope(); 10199 10200 return OMPMaskedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10201 } 10202 10203 StmtResult Sema::ActOnOpenMPCriticalDirective( 10204 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 10205 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 10206 if (!AStmt) 10207 return StmtError(); 10208 10209 bool ErrorFound = false; 10210 llvm::APSInt Hint; 10211 SourceLocation HintLoc; 10212 bool DependentHint = false; 10213 for (const OMPClause *C : Clauses) { 10214 if (C->getClauseKind() == OMPC_hint) { 10215 if (!DirName.getName()) { 10216 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name); 10217 ErrorFound = true; 10218 } 10219 Expr *E = cast<OMPHintClause>(C)->getHint(); 10220 if (E->isTypeDependent() || E->isValueDependent() || 10221 E->isInstantiationDependent()) { 10222 DependentHint = true; 10223 } else { 10224 Hint = E->EvaluateKnownConstInt(Context); 10225 HintLoc = C->getBeginLoc(); 10226 } 10227 } 10228 } 10229 if (ErrorFound) 10230 return StmtError(); 10231 const auto Pair = DSAStack->getCriticalWithHint(DirName); 10232 if (Pair.first && DirName.getName() && !DependentHint) { 10233 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 10234 Diag(StartLoc, diag::err_omp_critical_with_hint); 10235 if (HintLoc.isValid()) 10236 Diag(HintLoc, diag::note_omp_critical_hint_here) 10237 << 0 << toString(Hint, /*Radix=*/10, /*Signed=*/false); 10238 else 10239 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 10240 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 10241 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here) 10242 << 1 10243 << toString(C->getHint()->EvaluateKnownConstInt(Context), 10244 /*Radix=*/10, /*Signed=*/false); 10245 } else { 10246 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1; 10247 } 10248 } 10249 } 10250 10251 setFunctionHasBranchProtectedScope(); 10252 10253 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 10254 Clauses, AStmt); 10255 if (!Pair.first && DirName.getName() && !DependentHint) 10256 DSAStack->addCriticalWithHint(Dir, Hint); 10257 return Dir; 10258 } 10259 10260 StmtResult Sema::ActOnOpenMPParallelForDirective( 10261 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10262 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10263 if (!AStmt) 10264 return StmtError(); 10265 10266 auto *CS = cast<CapturedStmt>(AStmt); 10267 // 1.2.2 OpenMP Language Terminology 10268 // Structured block - An executable statement with a single entry at the 10269 // top and a single exit at the bottom. 10270 // The point of exit cannot be a branch out of the structured block. 10271 // longjmp() and throw() must not violate the entry/exit criteria. 10272 CS->getCapturedDecl()->setNothrow(); 10273 10274 OMPLoopBasedDirective::HelperExprs B; 10275 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10276 // define the nested loops number. 10277 unsigned NestedLoopCount = 10278 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 10279 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 10280 VarsWithImplicitDSA, B); 10281 if (NestedLoopCount == 0) 10282 return StmtError(); 10283 10284 assert((CurContext->isDependentContext() || B.builtAll()) && 10285 "omp parallel for loop exprs were not built"); 10286 10287 if (!CurContext->isDependentContext()) { 10288 // Finalize the clauses that need pre-built expressions for CodeGen. 10289 for (OMPClause *C : Clauses) { 10290 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10291 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10292 B.NumIterations, *this, CurScope, 10293 DSAStack)) 10294 return StmtError(); 10295 } 10296 } 10297 10298 setFunctionHasBranchProtectedScope(); 10299 return OMPParallelForDirective::Create( 10300 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 10301 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 10302 } 10303 10304 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 10305 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10306 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10307 if (!AStmt) 10308 return StmtError(); 10309 10310 auto *CS = cast<CapturedStmt>(AStmt); 10311 // 1.2.2 OpenMP Language Terminology 10312 // Structured block - An executable statement with a single entry at the 10313 // top and a single exit at the bottom. 10314 // The point of exit cannot be a branch out of the structured block. 10315 // longjmp() and throw() must not violate the entry/exit criteria. 10316 CS->getCapturedDecl()->setNothrow(); 10317 10318 OMPLoopBasedDirective::HelperExprs B; 10319 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10320 // define the nested loops number. 10321 unsigned NestedLoopCount = 10322 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 10323 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 10324 VarsWithImplicitDSA, B); 10325 if (NestedLoopCount == 0) 10326 return StmtError(); 10327 10328 if (!CurContext->isDependentContext()) { 10329 // Finalize the clauses that need pre-built expressions for CodeGen. 10330 for (OMPClause *C : Clauses) { 10331 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10332 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10333 B.NumIterations, *this, CurScope, 10334 DSAStack)) 10335 return StmtError(); 10336 } 10337 } 10338 10339 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10340 return StmtError(); 10341 10342 setFunctionHasBranchProtectedScope(); 10343 return OMPParallelForSimdDirective::Create( 10344 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 10345 } 10346 10347 StmtResult 10348 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, 10349 Stmt *AStmt, SourceLocation StartLoc, 10350 SourceLocation EndLoc) { 10351 if (!AStmt) 10352 return StmtError(); 10353 10354 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10355 auto *CS = cast<CapturedStmt>(AStmt); 10356 // 1.2.2 OpenMP Language Terminology 10357 // Structured block - An executable statement with a single entry at the 10358 // top and a single exit at the bottom. 10359 // The point of exit cannot be a branch out of the structured block. 10360 // longjmp() and throw() must not violate the entry/exit criteria. 10361 CS->getCapturedDecl()->setNothrow(); 10362 10363 setFunctionHasBranchProtectedScope(); 10364 10365 return OMPParallelMasterDirective::Create( 10366 Context, StartLoc, EndLoc, Clauses, AStmt, 10367 DSAStack->getTaskgroupReductionRef()); 10368 } 10369 10370 StmtResult 10371 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 10372 Stmt *AStmt, SourceLocation StartLoc, 10373 SourceLocation EndLoc) { 10374 if (!AStmt) 10375 return StmtError(); 10376 10377 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10378 auto BaseStmt = AStmt; 10379 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 10380 BaseStmt = CS->getCapturedStmt(); 10381 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 10382 auto S = C->children(); 10383 if (S.begin() == S.end()) 10384 return StmtError(); 10385 // All associated statements must be '#pragma omp section' except for 10386 // the first one. 10387 for (Stmt *SectionStmt : llvm::drop_begin(S)) { 10388 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 10389 if (SectionStmt) 10390 Diag(SectionStmt->getBeginLoc(), 10391 diag::err_omp_parallel_sections_substmt_not_section); 10392 return StmtError(); 10393 } 10394 cast<OMPSectionDirective>(SectionStmt) 10395 ->setHasCancel(DSAStack->isCancelRegion()); 10396 } 10397 } else { 10398 Diag(AStmt->getBeginLoc(), 10399 diag::err_omp_parallel_sections_not_compound_stmt); 10400 return StmtError(); 10401 } 10402 10403 setFunctionHasBranchProtectedScope(); 10404 10405 return OMPParallelSectionsDirective::Create( 10406 Context, StartLoc, EndLoc, Clauses, AStmt, 10407 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 10408 } 10409 10410 /// Find and diagnose mutually exclusive clause kinds. 10411 static bool checkMutuallyExclusiveClauses( 10412 Sema &S, ArrayRef<OMPClause *> Clauses, 10413 ArrayRef<OpenMPClauseKind> MutuallyExclusiveClauses) { 10414 const OMPClause *PrevClause = nullptr; 10415 bool ErrorFound = false; 10416 for (const OMPClause *C : Clauses) { 10417 if (llvm::is_contained(MutuallyExclusiveClauses, C->getClauseKind())) { 10418 if (!PrevClause) { 10419 PrevClause = C; 10420 } else if (PrevClause->getClauseKind() != C->getClauseKind()) { 10421 S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive) 10422 << getOpenMPClauseName(C->getClauseKind()) 10423 << getOpenMPClauseName(PrevClause->getClauseKind()); 10424 S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause) 10425 << getOpenMPClauseName(PrevClause->getClauseKind()); 10426 ErrorFound = true; 10427 } 10428 } 10429 } 10430 return ErrorFound; 10431 } 10432 10433 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 10434 Stmt *AStmt, SourceLocation StartLoc, 10435 SourceLocation EndLoc) { 10436 if (!AStmt) 10437 return StmtError(); 10438 10439 // OpenMP 5.0, 2.10.1 task Construct 10440 // If a detach clause appears on the directive, then a mergeable clause cannot 10441 // appear on the same directive. 10442 if (checkMutuallyExclusiveClauses(*this, Clauses, 10443 {OMPC_detach, OMPC_mergeable})) 10444 return StmtError(); 10445 10446 auto *CS = cast<CapturedStmt>(AStmt); 10447 // 1.2.2 OpenMP Language Terminology 10448 // Structured block - An executable statement with a single entry at the 10449 // top and a single exit at the bottom. 10450 // The point of exit cannot be a branch out of the structured block. 10451 // longjmp() and throw() must not violate the entry/exit criteria. 10452 CS->getCapturedDecl()->setNothrow(); 10453 10454 setFunctionHasBranchProtectedScope(); 10455 10456 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 10457 DSAStack->isCancelRegion()); 10458 } 10459 10460 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 10461 SourceLocation EndLoc) { 10462 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 10463 } 10464 10465 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 10466 SourceLocation EndLoc) { 10467 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 10468 } 10469 10470 StmtResult Sema::ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses, 10471 SourceLocation StartLoc, 10472 SourceLocation EndLoc) { 10473 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc, Clauses); 10474 } 10475 10476 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 10477 Stmt *AStmt, 10478 SourceLocation StartLoc, 10479 SourceLocation EndLoc) { 10480 if (!AStmt) 10481 return StmtError(); 10482 10483 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10484 10485 setFunctionHasBranchProtectedScope(); 10486 10487 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, 10488 AStmt, 10489 DSAStack->getTaskgroupReductionRef()); 10490 } 10491 10492 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 10493 SourceLocation StartLoc, 10494 SourceLocation EndLoc) { 10495 OMPFlushClause *FC = nullptr; 10496 OMPClause *OrderClause = nullptr; 10497 for (OMPClause *C : Clauses) { 10498 if (C->getClauseKind() == OMPC_flush) 10499 FC = cast<OMPFlushClause>(C); 10500 else 10501 OrderClause = C; 10502 } 10503 OpenMPClauseKind MemOrderKind = OMPC_unknown; 10504 SourceLocation MemOrderLoc; 10505 for (const OMPClause *C : Clauses) { 10506 if (C->getClauseKind() == OMPC_acq_rel || 10507 C->getClauseKind() == OMPC_acquire || 10508 C->getClauseKind() == OMPC_release) { 10509 if (MemOrderKind != OMPC_unknown) { 10510 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses) 10511 << getOpenMPDirectiveName(OMPD_flush) << 1 10512 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 10513 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 10514 << getOpenMPClauseName(MemOrderKind); 10515 } else { 10516 MemOrderKind = C->getClauseKind(); 10517 MemOrderLoc = C->getBeginLoc(); 10518 } 10519 } 10520 } 10521 if (FC && OrderClause) { 10522 Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list) 10523 << getOpenMPClauseName(OrderClause->getClauseKind()); 10524 Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here) 10525 << getOpenMPClauseName(OrderClause->getClauseKind()); 10526 return StmtError(); 10527 } 10528 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 10529 } 10530 10531 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, 10532 SourceLocation StartLoc, 10533 SourceLocation EndLoc) { 10534 if (Clauses.empty()) { 10535 Diag(StartLoc, diag::err_omp_depobj_expected); 10536 return StmtError(); 10537 } else if (Clauses[0]->getClauseKind() != OMPC_depobj) { 10538 Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected); 10539 return StmtError(); 10540 } 10541 // Only depobj expression and another single clause is allowed. 10542 if (Clauses.size() > 2) { 10543 Diag(Clauses[2]->getBeginLoc(), 10544 diag::err_omp_depobj_single_clause_expected); 10545 return StmtError(); 10546 } else if (Clauses.size() < 1) { 10547 Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected); 10548 return StmtError(); 10549 } 10550 return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses); 10551 } 10552 10553 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, 10554 SourceLocation StartLoc, 10555 SourceLocation EndLoc) { 10556 // Check that exactly one clause is specified. 10557 if (Clauses.size() != 1) { 10558 Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(), 10559 diag::err_omp_scan_single_clause_expected); 10560 return StmtError(); 10561 } 10562 // Check that scan directive is used in the scopeof the OpenMP loop body. 10563 if (Scope *S = DSAStack->getCurScope()) { 10564 Scope *ParentS = S->getParent(); 10565 if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() || 10566 !ParentS->getBreakParent()->isOpenMPLoopScope()) 10567 return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive) 10568 << getOpenMPDirectiveName(OMPD_scan) << 5); 10569 } 10570 // Check that only one instance of scan directives is used in the same outer 10571 // region. 10572 if (DSAStack->doesParentHasScanDirective()) { 10573 Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan"; 10574 Diag(DSAStack->getParentScanDirectiveLoc(), 10575 diag::note_omp_previous_directive) 10576 << "scan"; 10577 return StmtError(); 10578 } 10579 DSAStack->setParentHasScanDirective(StartLoc); 10580 return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses); 10581 } 10582 10583 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 10584 Stmt *AStmt, 10585 SourceLocation StartLoc, 10586 SourceLocation EndLoc) { 10587 const OMPClause *DependFound = nullptr; 10588 const OMPClause *DependSourceClause = nullptr; 10589 const OMPClause *DependSinkClause = nullptr; 10590 bool ErrorFound = false; 10591 const OMPThreadsClause *TC = nullptr; 10592 const OMPSIMDClause *SC = nullptr; 10593 for (const OMPClause *C : Clauses) { 10594 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 10595 DependFound = C; 10596 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 10597 if (DependSourceClause) { 10598 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 10599 << getOpenMPDirectiveName(OMPD_ordered) 10600 << getOpenMPClauseName(OMPC_depend) << 2; 10601 ErrorFound = true; 10602 } else { 10603 DependSourceClause = C; 10604 } 10605 if (DependSinkClause) { 10606 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 10607 << 0; 10608 ErrorFound = true; 10609 } 10610 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 10611 if (DependSourceClause) { 10612 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 10613 << 1; 10614 ErrorFound = true; 10615 } 10616 DependSinkClause = C; 10617 } 10618 } else if (C->getClauseKind() == OMPC_threads) { 10619 TC = cast<OMPThreadsClause>(C); 10620 } else if (C->getClauseKind() == OMPC_simd) { 10621 SC = cast<OMPSIMDClause>(C); 10622 } 10623 } 10624 if (!ErrorFound && !SC && 10625 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 10626 // OpenMP [2.8.1,simd Construct, Restrictions] 10627 // An ordered construct with the simd clause is the only OpenMP construct 10628 // that can appear in the simd region. 10629 Diag(StartLoc, diag::err_omp_prohibited_region_simd) 10630 << (LangOpts.OpenMP >= 50 ? 1 : 0); 10631 ErrorFound = true; 10632 } else if (DependFound && (TC || SC)) { 10633 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd) 10634 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 10635 ErrorFound = true; 10636 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) { 10637 Diag(DependFound->getBeginLoc(), 10638 diag::err_omp_ordered_directive_without_param); 10639 ErrorFound = true; 10640 } else if (TC || Clauses.empty()) { 10641 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) { 10642 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc; 10643 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 10644 << (TC != nullptr); 10645 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1; 10646 ErrorFound = true; 10647 } 10648 } 10649 if ((!AStmt && !DependFound) || ErrorFound) 10650 return StmtError(); 10651 10652 // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions. 10653 // During execution of an iteration of a worksharing-loop or a loop nest 10654 // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread 10655 // must not execute more than one ordered region corresponding to an ordered 10656 // construct without a depend clause. 10657 if (!DependFound) { 10658 if (DSAStack->doesParentHasOrderedDirective()) { 10659 Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered"; 10660 Diag(DSAStack->getParentOrderedDirectiveLoc(), 10661 diag::note_omp_previous_directive) 10662 << "ordered"; 10663 return StmtError(); 10664 } 10665 DSAStack->setParentHasOrderedDirective(StartLoc); 10666 } 10667 10668 if (AStmt) { 10669 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10670 10671 setFunctionHasBranchProtectedScope(); 10672 } 10673 10674 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10675 } 10676 10677 namespace { 10678 /// Helper class for checking expression in 'omp atomic [update]' 10679 /// construct. 10680 class OpenMPAtomicUpdateChecker { 10681 /// Error results for atomic update expressions. 10682 enum ExprAnalysisErrorCode { 10683 /// A statement is not an expression statement. 10684 NotAnExpression, 10685 /// Expression is not builtin binary or unary operation. 10686 NotABinaryOrUnaryExpression, 10687 /// Unary operation is not post-/pre- increment/decrement operation. 10688 NotAnUnaryIncDecExpression, 10689 /// An expression is not of scalar type. 10690 NotAScalarType, 10691 /// A binary operation is not an assignment operation. 10692 NotAnAssignmentOp, 10693 /// RHS part of the binary operation is not a binary expression. 10694 NotABinaryExpression, 10695 /// RHS part is not additive/multiplicative/shift/biwise binary 10696 /// expression. 10697 NotABinaryOperator, 10698 /// RHS binary operation does not have reference to the updated LHS 10699 /// part. 10700 NotAnUpdateExpression, 10701 /// No errors is found. 10702 NoError 10703 }; 10704 /// Reference to Sema. 10705 Sema &SemaRef; 10706 /// A location for note diagnostics (when error is found). 10707 SourceLocation NoteLoc; 10708 /// 'x' lvalue part of the source atomic expression. 10709 Expr *X; 10710 /// 'expr' rvalue part of the source atomic expression. 10711 Expr *E; 10712 /// Helper expression of the form 10713 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 10714 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 10715 Expr *UpdateExpr; 10716 /// Is 'x' a LHS in a RHS part of full update expression. It is 10717 /// important for non-associative operations. 10718 bool IsXLHSInRHSPart; 10719 BinaryOperatorKind Op; 10720 SourceLocation OpLoc; 10721 /// true if the source expression is a postfix unary operation, false 10722 /// if it is a prefix unary operation. 10723 bool IsPostfixUpdate; 10724 10725 public: 10726 OpenMPAtomicUpdateChecker(Sema &SemaRef) 10727 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 10728 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 10729 /// Check specified statement that it is suitable for 'atomic update' 10730 /// constructs and extract 'x', 'expr' and Operation from the original 10731 /// expression. If DiagId and NoteId == 0, then only check is performed 10732 /// without error notification. 10733 /// \param DiagId Diagnostic which should be emitted if error is found. 10734 /// \param NoteId Diagnostic note for the main error message. 10735 /// \return true if statement is not an update expression, false otherwise. 10736 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 10737 /// Return the 'x' lvalue part of the source atomic expression. 10738 Expr *getX() const { return X; } 10739 /// Return the 'expr' rvalue part of the source atomic expression. 10740 Expr *getExpr() const { return E; } 10741 /// Return the update expression used in calculation of the updated 10742 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 10743 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 10744 Expr *getUpdateExpr() const { return UpdateExpr; } 10745 /// Return true if 'x' is LHS in RHS part of full update expression, 10746 /// false otherwise. 10747 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 10748 10749 /// true if the source expression is a postfix unary operation, false 10750 /// if it is a prefix unary operation. 10751 bool isPostfixUpdate() const { return IsPostfixUpdate; } 10752 10753 private: 10754 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 10755 unsigned NoteId = 0); 10756 }; 10757 } // namespace 10758 10759 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 10760 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 10761 ExprAnalysisErrorCode ErrorFound = NoError; 10762 SourceLocation ErrorLoc, NoteLoc; 10763 SourceRange ErrorRange, NoteRange; 10764 // Allowed constructs are: 10765 // x = x binop expr; 10766 // x = expr binop x; 10767 if (AtomicBinOp->getOpcode() == BO_Assign) { 10768 X = AtomicBinOp->getLHS(); 10769 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 10770 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 10771 if (AtomicInnerBinOp->isMultiplicativeOp() || 10772 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 10773 AtomicInnerBinOp->isBitwiseOp()) { 10774 Op = AtomicInnerBinOp->getOpcode(); 10775 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 10776 Expr *LHS = AtomicInnerBinOp->getLHS(); 10777 Expr *RHS = AtomicInnerBinOp->getRHS(); 10778 llvm::FoldingSetNodeID XId, LHSId, RHSId; 10779 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 10780 /*Canonical=*/true); 10781 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 10782 /*Canonical=*/true); 10783 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 10784 /*Canonical=*/true); 10785 if (XId == LHSId) { 10786 E = RHS; 10787 IsXLHSInRHSPart = true; 10788 } else if (XId == RHSId) { 10789 E = LHS; 10790 IsXLHSInRHSPart = false; 10791 } else { 10792 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 10793 ErrorRange = AtomicInnerBinOp->getSourceRange(); 10794 NoteLoc = X->getExprLoc(); 10795 NoteRange = X->getSourceRange(); 10796 ErrorFound = NotAnUpdateExpression; 10797 } 10798 } else { 10799 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 10800 ErrorRange = AtomicInnerBinOp->getSourceRange(); 10801 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 10802 NoteRange = SourceRange(NoteLoc, NoteLoc); 10803 ErrorFound = NotABinaryOperator; 10804 } 10805 } else { 10806 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 10807 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 10808 ErrorFound = NotABinaryExpression; 10809 } 10810 } else { 10811 ErrorLoc = AtomicBinOp->getExprLoc(); 10812 ErrorRange = AtomicBinOp->getSourceRange(); 10813 NoteLoc = AtomicBinOp->getOperatorLoc(); 10814 NoteRange = SourceRange(NoteLoc, NoteLoc); 10815 ErrorFound = NotAnAssignmentOp; 10816 } 10817 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 10818 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 10819 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 10820 return true; 10821 } 10822 if (SemaRef.CurContext->isDependentContext()) 10823 E = X = UpdateExpr = nullptr; 10824 return ErrorFound != NoError; 10825 } 10826 10827 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 10828 unsigned NoteId) { 10829 ExprAnalysisErrorCode ErrorFound = NoError; 10830 SourceLocation ErrorLoc, NoteLoc; 10831 SourceRange ErrorRange, NoteRange; 10832 // Allowed constructs are: 10833 // x++; 10834 // x--; 10835 // ++x; 10836 // --x; 10837 // x binop= expr; 10838 // x = x binop expr; 10839 // x = expr binop x; 10840 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 10841 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 10842 if (AtomicBody->getType()->isScalarType() || 10843 AtomicBody->isInstantiationDependent()) { 10844 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 10845 AtomicBody->IgnoreParenImpCasts())) { 10846 // Check for Compound Assignment Operation 10847 Op = BinaryOperator::getOpForCompoundAssignment( 10848 AtomicCompAssignOp->getOpcode()); 10849 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 10850 E = AtomicCompAssignOp->getRHS(); 10851 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 10852 IsXLHSInRHSPart = true; 10853 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 10854 AtomicBody->IgnoreParenImpCasts())) { 10855 // Check for Binary Operation 10856 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 10857 return true; 10858 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 10859 AtomicBody->IgnoreParenImpCasts())) { 10860 // Check for Unary Operation 10861 if (AtomicUnaryOp->isIncrementDecrementOp()) { 10862 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 10863 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 10864 OpLoc = AtomicUnaryOp->getOperatorLoc(); 10865 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 10866 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 10867 IsXLHSInRHSPart = true; 10868 } else { 10869 ErrorFound = NotAnUnaryIncDecExpression; 10870 ErrorLoc = AtomicUnaryOp->getExprLoc(); 10871 ErrorRange = AtomicUnaryOp->getSourceRange(); 10872 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 10873 NoteRange = SourceRange(NoteLoc, NoteLoc); 10874 } 10875 } else if (!AtomicBody->isInstantiationDependent()) { 10876 ErrorFound = NotABinaryOrUnaryExpression; 10877 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 10878 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 10879 } 10880 } else { 10881 ErrorFound = NotAScalarType; 10882 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc(); 10883 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 10884 } 10885 } else { 10886 ErrorFound = NotAnExpression; 10887 NoteLoc = ErrorLoc = S->getBeginLoc(); 10888 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 10889 } 10890 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 10891 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 10892 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 10893 return true; 10894 } 10895 if (SemaRef.CurContext->isDependentContext()) 10896 E = X = UpdateExpr = nullptr; 10897 if (ErrorFound == NoError && E && X) { 10898 // Build an update expression of form 'OpaqueValueExpr(x) binop 10899 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 10900 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 10901 auto *OVEX = new (SemaRef.getASTContext()) 10902 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_PRValue); 10903 auto *OVEExpr = new (SemaRef.getASTContext()) 10904 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_PRValue); 10905 ExprResult Update = 10906 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 10907 IsXLHSInRHSPart ? OVEExpr : OVEX); 10908 if (Update.isInvalid()) 10909 return true; 10910 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 10911 Sema::AA_Casting); 10912 if (Update.isInvalid()) 10913 return true; 10914 UpdateExpr = Update.get(); 10915 } 10916 return ErrorFound != NoError; 10917 } 10918 10919 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 10920 Stmt *AStmt, 10921 SourceLocation StartLoc, 10922 SourceLocation EndLoc) { 10923 // Register location of the first atomic directive. 10924 DSAStack->addAtomicDirectiveLoc(StartLoc); 10925 if (!AStmt) 10926 return StmtError(); 10927 10928 // 1.2.2 OpenMP Language Terminology 10929 // Structured block - An executable statement with a single entry at the 10930 // top and a single exit at the bottom. 10931 // The point of exit cannot be a branch out of the structured block. 10932 // longjmp() and throw() must not violate the entry/exit criteria. 10933 OpenMPClauseKind AtomicKind = OMPC_unknown; 10934 SourceLocation AtomicKindLoc; 10935 OpenMPClauseKind MemOrderKind = OMPC_unknown; 10936 SourceLocation MemOrderLoc; 10937 for (const OMPClause *C : Clauses) { 10938 switch (C->getClauseKind()) { 10939 case OMPC_read: 10940 case OMPC_write: 10941 case OMPC_update: 10942 case OMPC_capture: { 10943 if (AtomicKind != OMPC_unknown) { 10944 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses) 10945 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 10946 Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause) 10947 << getOpenMPClauseName(AtomicKind); 10948 } else { 10949 AtomicKind = C->getClauseKind(); 10950 AtomicKindLoc = C->getBeginLoc(); 10951 } 10952 break; 10953 } 10954 case OMPC_seq_cst: 10955 case OMPC_acq_rel: 10956 case OMPC_acquire: 10957 case OMPC_release: 10958 case OMPC_relaxed: { 10959 if (MemOrderKind != OMPC_unknown) { 10960 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses) 10961 << getOpenMPDirectiveName(OMPD_atomic) << 0 10962 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 10963 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 10964 << getOpenMPClauseName(MemOrderKind); 10965 } else { 10966 MemOrderKind = C->getClauseKind(); 10967 MemOrderLoc = C->getBeginLoc(); 10968 } 10969 break; 10970 } 10971 // The following clauses are allowed, but we don't need to do anything here. 10972 case OMPC_hint: 10973 break; 10974 default: 10975 llvm_unreachable("unknown clause is encountered"); 10976 } 10977 } 10978 // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions 10979 // If atomic-clause is read then memory-order-clause must not be acq_rel or 10980 // release. 10981 // If atomic-clause is write then memory-order-clause must not be acq_rel or 10982 // acquire. 10983 // If atomic-clause is update or not present then memory-order-clause must not 10984 // be acq_rel or acquire. 10985 if ((AtomicKind == OMPC_read && 10986 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) || 10987 ((AtomicKind == OMPC_write || AtomicKind == OMPC_update || 10988 AtomicKind == OMPC_unknown) && 10989 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) { 10990 SourceLocation Loc = AtomicKindLoc; 10991 if (AtomicKind == OMPC_unknown) 10992 Loc = StartLoc; 10993 Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause) 10994 << getOpenMPClauseName(AtomicKind) 10995 << (AtomicKind == OMPC_unknown ? 1 : 0) 10996 << getOpenMPClauseName(MemOrderKind); 10997 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 10998 << getOpenMPClauseName(MemOrderKind); 10999 } 11000 11001 Stmt *Body = AStmt; 11002 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 11003 Body = EWC->getSubExpr(); 11004 11005 Expr *X = nullptr; 11006 Expr *V = nullptr; 11007 Expr *E = nullptr; 11008 Expr *UE = nullptr; 11009 bool IsXLHSInRHSPart = false; 11010 bool IsPostfixUpdate = false; 11011 // OpenMP [2.12.6, atomic Construct] 11012 // In the next expressions: 11013 // * x and v (as applicable) are both l-value expressions with scalar type. 11014 // * During the execution of an atomic region, multiple syntactic 11015 // occurrences of x must designate the same storage location. 11016 // * Neither of v and expr (as applicable) may access the storage location 11017 // designated by x. 11018 // * Neither of x and expr (as applicable) may access the storage location 11019 // designated by v. 11020 // * expr is an expression with scalar type. 11021 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 11022 // * binop, binop=, ++, and -- are not overloaded operators. 11023 // * The expression x binop expr must be numerically equivalent to x binop 11024 // (expr). This requirement is satisfied if the operators in expr have 11025 // precedence greater than binop, or by using parentheses around expr or 11026 // subexpressions of expr. 11027 // * The expression expr binop x must be numerically equivalent to (expr) 11028 // binop x. This requirement is satisfied if the operators in expr have 11029 // precedence equal to or greater than binop, or by using parentheses around 11030 // expr or subexpressions of expr. 11031 // * For forms that allow multiple occurrences of x, the number of times 11032 // that x is evaluated is unspecified. 11033 if (AtomicKind == OMPC_read) { 11034 enum { 11035 NotAnExpression, 11036 NotAnAssignmentOp, 11037 NotAScalarType, 11038 NotAnLValue, 11039 NoError 11040 } ErrorFound = NoError; 11041 SourceLocation ErrorLoc, NoteLoc; 11042 SourceRange ErrorRange, NoteRange; 11043 // If clause is read: 11044 // v = x; 11045 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 11046 const auto *AtomicBinOp = 11047 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 11048 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 11049 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 11050 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 11051 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 11052 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 11053 if (!X->isLValue() || !V->isLValue()) { 11054 const Expr *NotLValueExpr = X->isLValue() ? V : X; 11055 ErrorFound = NotAnLValue; 11056 ErrorLoc = AtomicBinOp->getExprLoc(); 11057 ErrorRange = AtomicBinOp->getSourceRange(); 11058 NoteLoc = NotLValueExpr->getExprLoc(); 11059 NoteRange = NotLValueExpr->getSourceRange(); 11060 } 11061 } else if (!X->isInstantiationDependent() || 11062 !V->isInstantiationDependent()) { 11063 const Expr *NotScalarExpr = 11064 (X->isInstantiationDependent() || X->getType()->isScalarType()) 11065 ? V 11066 : X; 11067 ErrorFound = NotAScalarType; 11068 ErrorLoc = AtomicBinOp->getExprLoc(); 11069 ErrorRange = AtomicBinOp->getSourceRange(); 11070 NoteLoc = NotScalarExpr->getExprLoc(); 11071 NoteRange = NotScalarExpr->getSourceRange(); 11072 } 11073 } else if (!AtomicBody->isInstantiationDependent()) { 11074 ErrorFound = NotAnAssignmentOp; 11075 ErrorLoc = AtomicBody->getExprLoc(); 11076 ErrorRange = AtomicBody->getSourceRange(); 11077 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 11078 : AtomicBody->getExprLoc(); 11079 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 11080 : AtomicBody->getSourceRange(); 11081 } 11082 } else { 11083 ErrorFound = NotAnExpression; 11084 NoteLoc = ErrorLoc = Body->getBeginLoc(); 11085 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 11086 } 11087 if (ErrorFound != NoError) { 11088 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 11089 << ErrorRange; 11090 Diag(NoteLoc, diag::note_omp_atomic_read_write) 11091 << ErrorFound << NoteRange; 11092 return StmtError(); 11093 } 11094 if (CurContext->isDependentContext()) 11095 V = X = nullptr; 11096 } else if (AtomicKind == OMPC_write) { 11097 enum { 11098 NotAnExpression, 11099 NotAnAssignmentOp, 11100 NotAScalarType, 11101 NotAnLValue, 11102 NoError 11103 } ErrorFound = NoError; 11104 SourceLocation ErrorLoc, NoteLoc; 11105 SourceRange ErrorRange, NoteRange; 11106 // If clause is write: 11107 // x = expr; 11108 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 11109 const auto *AtomicBinOp = 11110 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 11111 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 11112 X = AtomicBinOp->getLHS(); 11113 E = AtomicBinOp->getRHS(); 11114 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 11115 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 11116 if (!X->isLValue()) { 11117 ErrorFound = NotAnLValue; 11118 ErrorLoc = AtomicBinOp->getExprLoc(); 11119 ErrorRange = AtomicBinOp->getSourceRange(); 11120 NoteLoc = X->getExprLoc(); 11121 NoteRange = X->getSourceRange(); 11122 } 11123 } else if (!X->isInstantiationDependent() || 11124 !E->isInstantiationDependent()) { 11125 const Expr *NotScalarExpr = 11126 (X->isInstantiationDependent() || X->getType()->isScalarType()) 11127 ? E 11128 : X; 11129 ErrorFound = NotAScalarType; 11130 ErrorLoc = AtomicBinOp->getExprLoc(); 11131 ErrorRange = AtomicBinOp->getSourceRange(); 11132 NoteLoc = NotScalarExpr->getExprLoc(); 11133 NoteRange = NotScalarExpr->getSourceRange(); 11134 } 11135 } else if (!AtomicBody->isInstantiationDependent()) { 11136 ErrorFound = NotAnAssignmentOp; 11137 ErrorLoc = AtomicBody->getExprLoc(); 11138 ErrorRange = AtomicBody->getSourceRange(); 11139 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 11140 : AtomicBody->getExprLoc(); 11141 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 11142 : AtomicBody->getSourceRange(); 11143 } 11144 } else { 11145 ErrorFound = NotAnExpression; 11146 NoteLoc = ErrorLoc = Body->getBeginLoc(); 11147 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 11148 } 11149 if (ErrorFound != NoError) { 11150 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 11151 << ErrorRange; 11152 Diag(NoteLoc, diag::note_omp_atomic_read_write) 11153 << ErrorFound << NoteRange; 11154 return StmtError(); 11155 } 11156 if (CurContext->isDependentContext()) 11157 E = X = nullptr; 11158 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 11159 // If clause is update: 11160 // x++; 11161 // x--; 11162 // ++x; 11163 // --x; 11164 // x binop= expr; 11165 // x = x binop expr; 11166 // x = expr binop x; 11167 OpenMPAtomicUpdateChecker Checker(*this); 11168 if (Checker.checkStatement( 11169 Body, 11170 (AtomicKind == OMPC_update) 11171 ? diag::err_omp_atomic_update_not_expression_statement 11172 : diag::err_omp_atomic_not_expression_statement, 11173 diag::note_omp_atomic_update)) 11174 return StmtError(); 11175 if (!CurContext->isDependentContext()) { 11176 E = Checker.getExpr(); 11177 X = Checker.getX(); 11178 UE = Checker.getUpdateExpr(); 11179 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 11180 } 11181 } else if (AtomicKind == OMPC_capture) { 11182 enum { 11183 NotAnAssignmentOp, 11184 NotACompoundStatement, 11185 NotTwoSubstatements, 11186 NotASpecificExpression, 11187 NoError 11188 } ErrorFound = NoError; 11189 SourceLocation ErrorLoc, NoteLoc; 11190 SourceRange ErrorRange, NoteRange; 11191 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 11192 // If clause is a capture: 11193 // v = x++; 11194 // v = x--; 11195 // v = ++x; 11196 // v = --x; 11197 // v = x binop= expr; 11198 // v = x = x binop expr; 11199 // v = x = expr binop x; 11200 const auto *AtomicBinOp = 11201 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 11202 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 11203 V = AtomicBinOp->getLHS(); 11204 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 11205 OpenMPAtomicUpdateChecker Checker(*this); 11206 if (Checker.checkStatement( 11207 Body, diag::err_omp_atomic_capture_not_expression_statement, 11208 diag::note_omp_atomic_update)) 11209 return StmtError(); 11210 E = Checker.getExpr(); 11211 X = Checker.getX(); 11212 UE = Checker.getUpdateExpr(); 11213 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 11214 IsPostfixUpdate = Checker.isPostfixUpdate(); 11215 } else if (!AtomicBody->isInstantiationDependent()) { 11216 ErrorLoc = AtomicBody->getExprLoc(); 11217 ErrorRange = AtomicBody->getSourceRange(); 11218 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 11219 : AtomicBody->getExprLoc(); 11220 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 11221 : AtomicBody->getSourceRange(); 11222 ErrorFound = NotAnAssignmentOp; 11223 } 11224 if (ErrorFound != NoError) { 11225 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 11226 << ErrorRange; 11227 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 11228 return StmtError(); 11229 } 11230 if (CurContext->isDependentContext()) 11231 UE = V = E = X = nullptr; 11232 } else { 11233 // If clause is a capture: 11234 // { v = x; x = expr; } 11235 // { v = x; x++; } 11236 // { v = x; x--; } 11237 // { v = x; ++x; } 11238 // { v = x; --x; } 11239 // { v = x; x binop= expr; } 11240 // { v = x; x = x binop expr; } 11241 // { v = x; x = expr binop x; } 11242 // { x++; v = x; } 11243 // { x--; v = x; } 11244 // { ++x; v = x; } 11245 // { --x; v = x; } 11246 // { x binop= expr; v = x; } 11247 // { x = x binop expr; v = x; } 11248 // { x = expr binop x; v = x; } 11249 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 11250 // Check that this is { expr1; expr2; } 11251 if (CS->size() == 2) { 11252 Stmt *First = CS->body_front(); 11253 Stmt *Second = CS->body_back(); 11254 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 11255 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 11256 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 11257 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 11258 // Need to find what subexpression is 'v' and what is 'x'. 11259 OpenMPAtomicUpdateChecker Checker(*this); 11260 bool IsUpdateExprFound = !Checker.checkStatement(Second); 11261 BinaryOperator *BinOp = nullptr; 11262 if (IsUpdateExprFound) { 11263 BinOp = dyn_cast<BinaryOperator>(First); 11264 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 11265 } 11266 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 11267 // { v = x; x++; } 11268 // { v = x; x--; } 11269 // { v = x; ++x; } 11270 // { v = x; --x; } 11271 // { v = x; x binop= expr; } 11272 // { v = x; x = x binop expr; } 11273 // { v = x; x = expr binop x; } 11274 // Check that the first expression has form v = x. 11275 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 11276 llvm::FoldingSetNodeID XId, PossibleXId; 11277 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 11278 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 11279 IsUpdateExprFound = XId == PossibleXId; 11280 if (IsUpdateExprFound) { 11281 V = BinOp->getLHS(); 11282 X = Checker.getX(); 11283 E = Checker.getExpr(); 11284 UE = Checker.getUpdateExpr(); 11285 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 11286 IsPostfixUpdate = true; 11287 } 11288 } 11289 if (!IsUpdateExprFound) { 11290 IsUpdateExprFound = !Checker.checkStatement(First); 11291 BinOp = nullptr; 11292 if (IsUpdateExprFound) { 11293 BinOp = dyn_cast<BinaryOperator>(Second); 11294 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 11295 } 11296 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 11297 // { x++; v = x; } 11298 // { x--; v = x; } 11299 // { ++x; v = x; } 11300 // { --x; v = x; } 11301 // { x binop= expr; v = x; } 11302 // { x = x binop expr; v = x; } 11303 // { x = expr binop x; v = x; } 11304 // Check that the second expression has form v = x. 11305 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 11306 llvm::FoldingSetNodeID XId, PossibleXId; 11307 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 11308 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 11309 IsUpdateExprFound = XId == PossibleXId; 11310 if (IsUpdateExprFound) { 11311 V = BinOp->getLHS(); 11312 X = Checker.getX(); 11313 E = Checker.getExpr(); 11314 UE = Checker.getUpdateExpr(); 11315 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 11316 IsPostfixUpdate = false; 11317 } 11318 } 11319 } 11320 if (!IsUpdateExprFound) { 11321 // { v = x; x = expr; } 11322 auto *FirstExpr = dyn_cast<Expr>(First); 11323 auto *SecondExpr = dyn_cast<Expr>(Second); 11324 if (!FirstExpr || !SecondExpr || 11325 !(FirstExpr->isInstantiationDependent() || 11326 SecondExpr->isInstantiationDependent())) { 11327 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 11328 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 11329 ErrorFound = NotAnAssignmentOp; 11330 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 11331 : First->getBeginLoc(); 11332 NoteRange = ErrorRange = FirstBinOp 11333 ? FirstBinOp->getSourceRange() 11334 : SourceRange(ErrorLoc, ErrorLoc); 11335 } else { 11336 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 11337 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 11338 ErrorFound = NotAnAssignmentOp; 11339 NoteLoc = ErrorLoc = SecondBinOp 11340 ? SecondBinOp->getOperatorLoc() 11341 : Second->getBeginLoc(); 11342 NoteRange = ErrorRange = 11343 SecondBinOp ? SecondBinOp->getSourceRange() 11344 : SourceRange(ErrorLoc, ErrorLoc); 11345 } else { 11346 Expr *PossibleXRHSInFirst = 11347 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 11348 Expr *PossibleXLHSInSecond = 11349 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 11350 llvm::FoldingSetNodeID X1Id, X2Id; 11351 PossibleXRHSInFirst->Profile(X1Id, Context, 11352 /*Canonical=*/true); 11353 PossibleXLHSInSecond->Profile(X2Id, Context, 11354 /*Canonical=*/true); 11355 IsUpdateExprFound = X1Id == X2Id; 11356 if (IsUpdateExprFound) { 11357 V = FirstBinOp->getLHS(); 11358 X = SecondBinOp->getLHS(); 11359 E = SecondBinOp->getRHS(); 11360 UE = nullptr; 11361 IsXLHSInRHSPart = false; 11362 IsPostfixUpdate = true; 11363 } else { 11364 ErrorFound = NotASpecificExpression; 11365 ErrorLoc = FirstBinOp->getExprLoc(); 11366 ErrorRange = FirstBinOp->getSourceRange(); 11367 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 11368 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 11369 } 11370 } 11371 } 11372 } 11373 } 11374 } else { 11375 NoteLoc = ErrorLoc = Body->getBeginLoc(); 11376 NoteRange = ErrorRange = 11377 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 11378 ErrorFound = NotTwoSubstatements; 11379 } 11380 } else { 11381 NoteLoc = ErrorLoc = Body->getBeginLoc(); 11382 NoteRange = ErrorRange = 11383 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 11384 ErrorFound = NotACompoundStatement; 11385 } 11386 if (ErrorFound != NoError) { 11387 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 11388 << ErrorRange; 11389 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 11390 return StmtError(); 11391 } 11392 if (CurContext->isDependentContext()) 11393 UE = V = E = X = nullptr; 11394 } 11395 } 11396 11397 setFunctionHasBranchProtectedScope(); 11398 11399 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 11400 X, V, E, UE, IsXLHSInRHSPart, 11401 IsPostfixUpdate); 11402 } 11403 11404 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 11405 Stmt *AStmt, 11406 SourceLocation StartLoc, 11407 SourceLocation EndLoc) { 11408 if (!AStmt) 11409 return StmtError(); 11410 11411 auto *CS = cast<CapturedStmt>(AStmt); 11412 // 1.2.2 OpenMP Language Terminology 11413 // Structured block - An executable statement with a single entry at the 11414 // top and a single exit at the bottom. 11415 // The point of exit cannot be a branch out of the structured block. 11416 // longjmp() and throw() must not violate the entry/exit criteria. 11417 CS->getCapturedDecl()->setNothrow(); 11418 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target); 11419 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11420 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11421 // 1.2.2 OpenMP Language Terminology 11422 // Structured block - An executable statement with a single entry at the 11423 // top and a single exit at the bottom. 11424 // The point of exit cannot be a branch out of the structured block. 11425 // longjmp() and throw() must not violate the entry/exit criteria. 11426 CS->getCapturedDecl()->setNothrow(); 11427 } 11428 11429 // OpenMP [2.16, Nesting of Regions] 11430 // If specified, a teams construct must be contained within a target 11431 // construct. That target construct must contain no statements or directives 11432 // outside of the teams construct. 11433 if (DSAStack->hasInnerTeamsRegion()) { 11434 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true); 11435 bool OMPTeamsFound = true; 11436 if (const auto *CS = dyn_cast<CompoundStmt>(S)) { 11437 auto I = CS->body_begin(); 11438 while (I != CS->body_end()) { 11439 const auto *OED = dyn_cast<OMPExecutableDirective>(*I); 11440 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) || 11441 OMPTeamsFound) { 11442 11443 OMPTeamsFound = false; 11444 break; 11445 } 11446 ++I; 11447 } 11448 assert(I != CS->body_end() && "Not found statement"); 11449 S = *I; 11450 } else { 11451 const auto *OED = dyn_cast<OMPExecutableDirective>(S); 11452 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 11453 } 11454 if (!OMPTeamsFound) { 11455 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 11456 Diag(DSAStack->getInnerTeamsRegionLoc(), 11457 diag::note_omp_nested_teams_construct_here); 11458 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here) 11459 << isa<OMPExecutableDirective>(S); 11460 return StmtError(); 11461 } 11462 } 11463 11464 setFunctionHasBranchProtectedScope(); 11465 11466 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 11467 } 11468 11469 StmtResult 11470 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 11471 Stmt *AStmt, SourceLocation StartLoc, 11472 SourceLocation EndLoc) { 11473 if (!AStmt) 11474 return StmtError(); 11475 11476 auto *CS = cast<CapturedStmt>(AStmt); 11477 // 1.2.2 OpenMP Language Terminology 11478 // Structured block - An executable statement with a single entry at the 11479 // top and a single exit at the bottom. 11480 // The point of exit cannot be a branch out of the structured block. 11481 // longjmp() and throw() must not violate the entry/exit criteria. 11482 CS->getCapturedDecl()->setNothrow(); 11483 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel); 11484 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11485 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11486 // 1.2.2 OpenMP Language Terminology 11487 // Structured block - An executable statement with a single entry at the 11488 // top and a single exit at the bottom. 11489 // The point of exit cannot be a branch out of the structured block. 11490 // longjmp() and throw() must not violate the entry/exit criteria. 11491 CS->getCapturedDecl()->setNothrow(); 11492 } 11493 11494 setFunctionHasBranchProtectedScope(); 11495 11496 return OMPTargetParallelDirective::Create( 11497 Context, StartLoc, EndLoc, Clauses, AStmt, 11498 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 11499 } 11500 11501 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 11502 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11503 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11504 if (!AStmt) 11505 return StmtError(); 11506 11507 auto *CS = cast<CapturedStmt>(AStmt); 11508 // 1.2.2 OpenMP Language Terminology 11509 // Structured block - An executable statement with a single entry at the 11510 // top and a single exit at the bottom. 11511 // The point of exit cannot be a branch out of the structured block. 11512 // longjmp() and throw() must not violate the entry/exit criteria. 11513 CS->getCapturedDecl()->setNothrow(); 11514 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 11515 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11516 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11517 // 1.2.2 OpenMP Language Terminology 11518 // Structured block - An executable statement with a single entry at the 11519 // top and a single exit at the bottom. 11520 // The point of exit cannot be a branch out of the structured block. 11521 // longjmp() and throw() must not violate the entry/exit criteria. 11522 CS->getCapturedDecl()->setNothrow(); 11523 } 11524 11525 OMPLoopBasedDirective::HelperExprs B; 11526 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11527 // define the nested loops number. 11528 unsigned NestedLoopCount = 11529 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 11530 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 11531 VarsWithImplicitDSA, B); 11532 if (NestedLoopCount == 0) 11533 return StmtError(); 11534 11535 assert((CurContext->isDependentContext() || B.builtAll()) && 11536 "omp target parallel for loop exprs were not built"); 11537 11538 if (!CurContext->isDependentContext()) { 11539 // Finalize the clauses that need pre-built expressions for CodeGen. 11540 for (OMPClause *C : Clauses) { 11541 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11542 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11543 B.NumIterations, *this, CurScope, 11544 DSAStack)) 11545 return StmtError(); 11546 } 11547 } 11548 11549 setFunctionHasBranchProtectedScope(); 11550 return OMPTargetParallelForDirective::Create( 11551 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 11552 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 11553 } 11554 11555 /// Check for existence of a map clause in the list of clauses. 11556 static bool hasClauses(ArrayRef<OMPClause *> Clauses, 11557 const OpenMPClauseKind K) { 11558 return llvm::any_of( 11559 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); 11560 } 11561 11562 template <typename... Params> 11563 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, 11564 const Params... ClauseTypes) { 11565 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); 11566 } 11567 11568 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 11569 Stmt *AStmt, 11570 SourceLocation StartLoc, 11571 SourceLocation EndLoc) { 11572 if (!AStmt) 11573 return StmtError(); 11574 11575 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11576 11577 // OpenMP [2.12.2, target data Construct, Restrictions] 11578 // At least one map, use_device_addr or use_device_ptr clause must appear on 11579 // the directive. 11580 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) && 11581 (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) { 11582 StringRef Expected; 11583 if (LangOpts.OpenMP < 50) 11584 Expected = "'map' or 'use_device_ptr'"; 11585 else 11586 Expected = "'map', 'use_device_ptr', or 'use_device_addr'"; 11587 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 11588 << Expected << getOpenMPDirectiveName(OMPD_target_data); 11589 return StmtError(); 11590 } 11591 11592 setFunctionHasBranchProtectedScope(); 11593 11594 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 11595 AStmt); 11596 } 11597 11598 StmtResult 11599 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 11600 SourceLocation StartLoc, 11601 SourceLocation EndLoc, Stmt *AStmt) { 11602 if (!AStmt) 11603 return StmtError(); 11604 11605 auto *CS = cast<CapturedStmt>(AStmt); 11606 // 1.2.2 OpenMP Language Terminology 11607 // Structured block - An executable statement with a single entry at the 11608 // top and a single exit at the bottom. 11609 // The point of exit cannot be a branch out of the structured block. 11610 // longjmp() and throw() must not violate the entry/exit criteria. 11611 CS->getCapturedDecl()->setNothrow(); 11612 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data); 11613 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11614 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11615 // 1.2.2 OpenMP Language Terminology 11616 // Structured block - An executable statement with a single entry at the 11617 // top and a single exit at the bottom. 11618 // The point of exit cannot be a branch out of the structured block. 11619 // longjmp() and throw() must not violate the entry/exit criteria. 11620 CS->getCapturedDecl()->setNothrow(); 11621 } 11622 11623 // OpenMP [2.10.2, Restrictions, p. 99] 11624 // At least one map clause must appear on the directive. 11625 if (!hasClauses(Clauses, OMPC_map)) { 11626 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 11627 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); 11628 return StmtError(); 11629 } 11630 11631 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 11632 AStmt); 11633 } 11634 11635 StmtResult 11636 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 11637 SourceLocation StartLoc, 11638 SourceLocation EndLoc, Stmt *AStmt) { 11639 if (!AStmt) 11640 return StmtError(); 11641 11642 auto *CS = cast<CapturedStmt>(AStmt); 11643 // 1.2.2 OpenMP Language Terminology 11644 // Structured block - An executable statement with a single entry at the 11645 // top and a single exit at the bottom. 11646 // The point of exit cannot be a branch out of the structured block. 11647 // longjmp() and throw() must not violate the entry/exit criteria. 11648 CS->getCapturedDecl()->setNothrow(); 11649 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data); 11650 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11651 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11652 // 1.2.2 OpenMP Language Terminology 11653 // Structured block - An executable statement with a single entry at the 11654 // top and a single exit at the bottom. 11655 // The point of exit cannot be a branch out of the structured block. 11656 // longjmp() and throw() must not violate the entry/exit criteria. 11657 CS->getCapturedDecl()->setNothrow(); 11658 } 11659 11660 // OpenMP [2.10.3, Restrictions, p. 102] 11661 // At least one map clause must appear on the directive. 11662 if (!hasClauses(Clauses, OMPC_map)) { 11663 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 11664 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data); 11665 return StmtError(); 11666 } 11667 11668 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 11669 AStmt); 11670 } 11671 11672 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 11673 SourceLocation StartLoc, 11674 SourceLocation EndLoc, 11675 Stmt *AStmt) { 11676 if (!AStmt) 11677 return StmtError(); 11678 11679 auto *CS = cast<CapturedStmt>(AStmt); 11680 // 1.2.2 OpenMP Language Terminology 11681 // Structured block - An executable statement with a single entry at the 11682 // top and a single exit at the bottom. 11683 // The point of exit cannot be a branch out of the structured block. 11684 // longjmp() and throw() must not violate the entry/exit criteria. 11685 CS->getCapturedDecl()->setNothrow(); 11686 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update); 11687 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11688 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11689 // 1.2.2 OpenMP Language Terminology 11690 // Structured block - An executable statement with a single entry at the 11691 // top and a single exit at the bottom. 11692 // The point of exit cannot be a branch out of the structured block. 11693 // longjmp() and throw() must not violate the entry/exit criteria. 11694 CS->getCapturedDecl()->setNothrow(); 11695 } 11696 11697 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { 11698 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 11699 return StmtError(); 11700 } 11701 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses, 11702 AStmt); 11703 } 11704 11705 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 11706 Stmt *AStmt, SourceLocation StartLoc, 11707 SourceLocation EndLoc) { 11708 if (!AStmt) 11709 return StmtError(); 11710 11711 auto *CS = cast<CapturedStmt>(AStmt); 11712 // 1.2.2 OpenMP Language Terminology 11713 // Structured block - An executable statement with a single entry at the 11714 // top and a single exit at the bottom. 11715 // The point of exit cannot be a branch out of the structured block. 11716 // longjmp() and throw() must not violate the entry/exit criteria. 11717 CS->getCapturedDecl()->setNothrow(); 11718 11719 setFunctionHasBranchProtectedScope(); 11720 11721 DSAStack->setParentTeamsRegionLoc(StartLoc); 11722 11723 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 11724 } 11725 11726 StmtResult 11727 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 11728 SourceLocation EndLoc, 11729 OpenMPDirectiveKind CancelRegion) { 11730 if (DSAStack->isParentNowaitRegion()) { 11731 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 11732 return StmtError(); 11733 } 11734 if (DSAStack->isParentOrderedRegion()) { 11735 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 11736 return StmtError(); 11737 } 11738 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 11739 CancelRegion); 11740 } 11741 11742 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 11743 SourceLocation StartLoc, 11744 SourceLocation EndLoc, 11745 OpenMPDirectiveKind CancelRegion) { 11746 if (DSAStack->isParentNowaitRegion()) { 11747 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 11748 return StmtError(); 11749 } 11750 if (DSAStack->isParentOrderedRegion()) { 11751 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 11752 return StmtError(); 11753 } 11754 DSAStack->setParentCancelRegion(/*Cancel=*/true); 11755 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 11756 CancelRegion); 11757 } 11758 11759 static bool checkReductionClauseWithNogroup(Sema &S, 11760 ArrayRef<OMPClause *> Clauses) { 11761 const OMPClause *ReductionClause = nullptr; 11762 const OMPClause *NogroupClause = nullptr; 11763 for (const OMPClause *C : Clauses) { 11764 if (C->getClauseKind() == OMPC_reduction) { 11765 ReductionClause = C; 11766 if (NogroupClause) 11767 break; 11768 continue; 11769 } 11770 if (C->getClauseKind() == OMPC_nogroup) { 11771 NogroupClause = C; 11772 if (ReductionClause) 11773 break; 11774 continue; 11775 } 11776 } 11777 if (ReductionClause && NogroupClause) { 11778 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup) 11779 << SourceRange(NogroupClause->getBeginLoc(), 11780 NogroupClause->getEndLoc()); 11781 return true; 11782 } 11783 return false; 11784 } 11785 11786 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 11787 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11788 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11789 if (!AStmt) 11790 return StmtError(); 11791 11792 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11793 OMPLoopBasedDirective::HelperExprs B; 11794 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11795 // define the nested loops number. 11796 unsigned NestedLoopCount = 11797 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 11798 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 11799 VarsWithImplicitDSA, B); 11800 if (NestedLoopCount == 0) 11801 return StmtError(); 11802 11803 assert((CurContext->isDependentContext() || B.builtAll()) && 11804 "omp for loop exprs were not built"); 11805 11806 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11807 // The grainsize clause and num_tasks clause are mutually exclusive and may 11808 // not appear on the same taskloop directive. 11809 if (checkMutuallyExclusiveClauses(*this, Clauses, 11810 {OMPC_grainsize, OMPC_num_tasks})) 11811 return StmtError(); 11812 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11813 // If a reduction clause is present on the taskloop directive, the nogroup 11814 // clause must not be specified. 11815 if (checkReductionClauseWithNogroup(*this, Clauses)) 11816 return StmtError(); 11817 11818 setFunctionHasBranchProtectedScope(); 11819 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 11820 NestedLoopCount, Clauses, AStmt, B, 11821 DSAStack->isCancelRegion()); 11822 } 11823 11824 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 11825 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11826 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11827 if (!AStmt) 11828 return StmtError(); 11829 11830 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11831 OMPLoopBasedDirective::HelperExprs B; 11832 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11833 // define the nested loops number. 11834 unsigned NestedLoopCount = 11835 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 11836 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 11837 VarsWithImplicitDSA, B); 11838 if (NestedLoopCount == 0) 11839 return StmtError(); 11840 11841 assert((CurContext->isDependentContext() || B.builtAll()) && 11842 "omp for loop exprs were not built"); 11843 11844 if (!CurContext->isDependentContext()) { 11845 // Finalize the clauses that need pre-built expressions for CodeGen. 11846 for (OMPClause *C : Clauses) { 11847 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11848 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11849 B.NumIterations, *this, CurScope, 11850 DSAStack)) 11851 return StmtError(); 11852 } 11853 } 11854 11855 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11856 // The grainsize clause and num_tasks clause are mutually exclusive and may 11857 // not appear on the same taskloop directive. 11858 if (checkMutuallyExclusiveClauses(*this, Clauses, 11859 {OMPC_grainsize, OMPC_num_tasks})) 11860 return StmtError(); 11861 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11862 // If a reduction clause is present on the taskloop directive, the nogroup 11863 // clause must not be specified. 11864 if (checkReductionClauseWithNogroup(*this, Clauses)) 11865 return StmtError(); 11866 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11867 return StmtError(); 11868 11869 setFunctionHasBranchProtectedScope(); 11870 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 11871 NestedLoopCount, Clauses, AStmt, B); 11872 } 11873 11874 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective( 11875 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11876 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11877 if (!AStmt) 11878 return StmtError(); 11879 11880 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11881 OMPLoopBasedDirective::HelperExprs B; 11882 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11883 // define the nested loops number. 11884 unsigned NestedLoopCount = 11885 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses), 11886 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 11887 VarsWithImplicitDSA, B); 11888 if (NestedLoopCount == 0) 11889 return StmtError(); 11890 11891 assert((CurContext->isDependentContext() || B.builtAll()) && 11892 "omp for loop exprs were not built"); 11893 11894 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11895 // The grainsize clause and num_tasks clause are mutually exclusive and may 11896 // not appear on the same taskloop directive. 11897 if (checkMutuallyExclusiveClauses(*this, Clauses, 11898 {OMPC_grainsize, OMPC_num_tasks})) 11899 return StmtError(); 11900 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11901 // If a reduction clause is present on the taskloop directive, the nogroup 11902 // clause must not be specified. 11903 if (checkReductionClauseWithNogroup(*this, Clauses)) 11904 return StmtError(); 11905 11906 setFunctionHasBranchProtectedScope(); 11907 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc, 11908 NestedLoopCount, Clauses, AStmt, B, 11909 DSAStack->isCancelRegion()); 11910 } 11911 11912 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective( 11913 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11914 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11915 if (!AStmt) 11916 return StmtError(); 11917 11918 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11919 OMPLoopBasedDirective::HelperExprs B; 11920 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11921 // define the nested loops number. 11922 unsigned NestedLoopCount = 11923 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses), 11924 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 11925 VarsWithImplicitDSA, B); 11926 if (NestedLoopCount == 0) 11927 return StmtError(); 11928 11929 assert((CurContext->isDependentContext() || B.builtAll()) && 11930 "omp for loop exprs were not built"); 11931 11932 if (!CurContext->isDependentContext()) { 11933 // Finalize the clauses that need pre-built expressions for CodeGen. 11934 for (OMPClause *C : Clauses) { 11935 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11936 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11937 B.NumIterations, *this, CurScope, 11938 DSAStack)) 11939 return StmtError(); 11940 } 11941 } 11942 11943 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11944 // The grainsize clause and num_tasks clause are mutually exclusive and may 11945 // not appear on the same taskloop directive. 11946 if (checkMutuallyExclusiveClauses(*this, Clauses, 11947 {OMPC_grainsize, OMPC_num_tasks})) 11948 return StmtError(); 11949 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11950 // If a reduction clause is present on the taskloop directive, the nogroup 11951 // clause must not be specified. 11952 if (checkReductionClauseWithNogroup(*this, Clauses)) 11953 return StmtError(); 11954 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11955 return StmtError(); 11956 11957 setFunctionHasBranchProtectedScope(); 11958 return OMPMasterTaskLoopSimdDirective::Create( 11959 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11960 } 11961 11962 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective( 11963 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11964 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11965 if (!AStmt) 11966 return StmtError(); 11967 11968 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11969 auto *CS = cast<CapturedStmt>(AStmt); 11970 // 1.2.2 OpenMP Language Terminology 11971 // Structured block - An executable statement with a single entry at the 11972 // top and a single exit at the bottom. 11973 // The point of exit cannot be a branch out of the structured block. 11974 // longjmp() and throw() must not violate the entry/exit criteria. 11975 CS->getCapturedDecl()->setNothrow(); 11976 for (int ThisCaptureLevel = 11977 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop); 11978 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11979 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11980 // 1.2.2 OpenMP Language Terminology 11981 // Structured block - An executable statement with a single entry at the 11982 // top and a single exit at the bottom. 11983 // The point of exit cannot be a branch out of the structured block. 11984 // longjmp() and throw() must not violate the entry/exit criteria. 11985 CS->getCapturedDecl()->setNothrow(); 11986 } 11987 11988 OMPLoopBasedDirective::HelperExprs B; 11989 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11990 // define the nested loops number. 11991 unsigned NestedLoopCount = checkOpenMPLoop( 11992 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses), 11993 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 11994 VarsWithImplicitDSA, B); 11995 if (NestedLoopCount == 0) 11996 return StmtError(); 11997 11998 assert((CurContext->isDependentContext() || B.builtAll()) && 11999 "omp for loop exprs were not built"); 12000 12001 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12002 // The grainsize clause and num_tasks clause are mutually exclusive and may 12003 // not appear on the same taskloop directive. 12004 if (checkMutuallyExclusiveClauses(*this, Clauses, 12005 {OMPC_grainsize, OMPC_num_tasks})) 12006 return StmtError(); 12007 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12008 // If a reduction clause is present on the taskloop directive, the nogroup 12009 // clause must not be specified. 12010 if (checkReductionClauseWithNogroup(*this, Clauses)) 12011 return StmtError(); 12012 12013 setFunctionHasBranchProtectedScope(); 12014 return OMPParallelMasterTaskLoopDirective::Create( 12015 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 12016 DSAStack->isCancelRegion()); 12017 } 12018 12019 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective( 12020 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12021 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12022 if (!AStmt) 12023 return StmtError(); 12024 12025 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 12026 auto *CS = cast<CapturedStmt>(AStmt); 12027 // 1.2.2 OpenMP Language Terminology 12028 // Structured block - An executable statement with a single entry at the 12029 // top and a single exit at the bottom. 12030 // The point of exit cannot be a branch out of the structured block. 12031 // longjmp() and throw() must not violate the entry/exit criteria. 12032 CS->getCapturedDecl()->setNothrow(); 12033 for (int ThisCaptureLevel = 12034 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd); 12035 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12036 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12037 // 1.2.2 OpenMP Language Terminology 12038 // Structured block - An executable statement with a single entry at the 12039 // top and a single exit at the bottom. 12040 // The point of exit cannot be a branch out of the structured block. 12041 // longjmp() and throw() must not violate the entry/exit criteria. 12042 CS->getCapturedDecl()->setNothrow(); 12043 } 12044 12045 OMPLoopBasedDirective::HelperExprs B; 12046 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 12047 // define the nested loops number. 12048 unsigned NestedLoopCount = checkOpenMPLoop( 12049 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses), 12050 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 12051 VarsWithImplicitDSA, B); 12052 if (NestedLoopCount == 0) 12053 return StmtError(); 12054 12055 assert((CurContext->isDependentContext() || B.builtAll()) && 12056 "omp for loop exprs were not built"); 12057 12058 if (!CurContext->isDependentContext()) { 12059 // Finalize the clauses that need pre-built expressions for CodeGen. 12060 for (OMPClause *C : Clauses) { 12061 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12062 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12063 B.NumIterations, *this, CurScope, 12064 DSAStack)) 12065 return StmtError(); 12066 } 12067 } 12068 12069 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12070 // The grainsize clause and num_tasks clause are mutually exclusive and may 12071 // not appear on the same taskloop directive. 12072 if (checkMutuallyExclusiveClauses(*this, Clauses, 12073 {OMPC_grainsize, OMPC_num_tasks})) 12074 return StmtError(); 12075 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12076 // If a reduction clause is present on the taskloop directive, the nogroup 12077 // clause must not be specified. 12078 if (checkReductionClauseWithNogroup(*this, Clauses)) 12079 return StmtError(); 12080 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12081 return StmtError(); 12082 12083 setFunctionHasBranchProtectedScope(); 12084 return OMPParallelMasterTaskLoopSimdDirective::Create( 12085 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12086 } 12087 12088 StmtResult Sema::ActOnOpenMPDistributeDirective( 12089 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12090 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12091 if (!AStmt) 12092 return StmtError(); 12093 12094 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 12095 OMPLoopBasedDirective::HelperExprs B; 12096 // In presence of clause 'collapse' with number of loops, it will 12097 // define the nested loops number. 12098 unsigned NestedLoopCount = 12099 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 12100 nullptr /*ordered not a clause on distribute*/, AStmt, 12101 *this, *DSAStack, VarsWithImplicitDSA, B); 12102 if (NestedLoopCount == 0) 12103 return StmtError(); 12104 12105 assert((CurContext->isDependentContext() || B.builtAll()) && 12106 "omp for loop exprs were not built"); 12107 12108 setFunctionHasBranchProtectedScope(); 12109 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 12110 NestedLoopCount, Clauses, AStmt, B); 12111 } 12112 12113 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 12114 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12115 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12116 if (!AStmt) 12117 return StmtError(); 12118 12119 auto *CS = cast<CapturedStmt>(AStmt); 12120 // 1.2.2 OpenMP Language Terminology 12121 // Structured block - An executable statement with a single entry at the 12122 // top and a single exit at the bottom. 12123 // The point of exit cannot be a branch out of the structured block. 12124 // longjmp() and throw() must not violate the entry/exit criteria. 12125 CS->getCapturedDecl()->setNothrow(); 12126 for (int ThisCaptureLevel = 12127 getOpenMPCaptureLevels(OMPD_distribute_parallel_for); 12128 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12129 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12130 // 1.2.2 OpenMP Language Terminology 12131 // Structured block - An executable statement with a single entry at the 12132 // top and a single exit at the bottom. 12133 // The point of exit cannot be a branch out of the structured block. 12134 // longjmp() and throw() must not violate the entry/exit criteria. 12135 CS->getCapturedDecl()->setNothrow(); 12136 } 12137 12138 OMPLoopBasedDirective::HelperExprs B; 12139 // In presence of clause 'collapse' with number of loops, it will 12140 // define the nested loops number. 12141 unsigned NestedLoopCount = checkOpenMPLoop( 12142 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 12143 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12144 VarsWithImplicitDSA, B); 12145 if (NestedLoopCount == 0) 12146 return StmtError(); 12147 12148 assert((CurContext->isDependentContext() || B.builtAll()) && 12149 "omp for loop exprs were not built"); 12150 12151 setFunctionHasBranchProtectedScope(); 12152 return OMPDistributeParallelForDirective::Create( 12153 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 12154 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 12155 } 12156 12157 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 12158 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12159 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12160 if (!AStmt) 12161 return StmtError(); 12162 12163 auto *CS = cast<CapturedStmt>(AStmt); 12164 // 1.2.2 OpenMP Language Terminology 12165 // Structured block - An executable statement with a single entry at the 12166 // top and a single exit at the bottom. 12167 // The point of exit cannot be a branch out of the structured block. 12168 // longjmp() and throw() must not violate the entry/exit criteria. 12169 CS->getCapturedDecl()->setNothrow(); 12170 for (int ThisCaptureLevel = 12171 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd); 12172 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12173 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12174 // 1.2.2 OpenMP Language Terminology 12175 // Structured block - An executable statement with a single entry at the 12176 // top and a single exit at the bottom. 12177 // The point of exit cannot be a branch out of the structured block. 12178 // longjmp() and throw() must not violate the entry/exit criteria. 12179 CS->getCapturedDecl()->setNothrow(); 12180 } 12181 12182 OMPLoopBasedDirective::HelperExprs B; 12183 // In presence of clause 'collapse' with number of loops, it will 12184 // define the nested loops number. 12185 unsigned NestedLoopCount = checkOpenMPLoop( 12186 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 12187 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12188 VarsWithImplicitDSA, B); 12189 if (NestedLoopCount == 0) 12190 return StmtError(); 12191 12192 assert((CurContext->isDependentContext() || B.builtAll()) && 12193 "omp for loop exprs were not built"); 12194 12195 if (!CurContext->isDependentContext()) { 12196 // Finalize the clauses that need pre-built expressions for CodeGen. 12197 for (OMPClause *C : Clauses) { 12198 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12199 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12200 B.NumIterations, *this, CurScope, 12201 DSAStack)) 12202 return StmtError(); 12203 } 12204 } 12205 12206 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12207 return StmtError(); 12208 12209 setFunctionHasBranchProtectedScope(); 12210 return OMPDistributeParallelForSimdDirective::Create( 12211 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12212 } 12213 12214 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 12215 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12216 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12217 if (!AStmt) 12218 return StmtError(); 12219 12220 auto *CS = cast<CapturedStmt>(AStmt); 12221 // 1.2.2 OpenMP Language Terminology 12222 // Structured block - An executable statement with a single entry at the 12223 // top and a single exit at the bottom. 12224 // The point of exit cannot be a branch out of the structured block. 12225 // longjmp() and throw() must not violate the entry/exit criteria. 12226 CS->getCapturedDecl()->setNothrow(); 12227 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd); 12228 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12229 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12230 // 1.2.2 OpenMP Language Terminology 12231 // Structured block - An executable statement with a single entry at the 12232 // top and a single exit at the bottom. 12233 // The point of exit cannot be a branch out of the structured block. 12234 // longjmp() and throw() must not violate the entry/exit criteria. 12235 CS->getCapturedDecl()->setNothrow(); 12236 } 12237 12238 OMPLoopBasedDirective::HelperExprs B; 12239 // In presence of clause 'collapse' with number of loops, it will 12240 // define the nested loops number. 12241 unsigned NestedLoopCount = 12242 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 12243 nullptr /*ordered not a clause on distribute*/, CS, *this, 12244 *DSAStack, VarsWithImplicitDSA, B); 12245 if (NestedLoopCount == 0) 12246 return StmtError(); 12247 12248 assert((CurContext->isDependentContext() || B.builtAll()) && 12249 "omp for loop exprs were not built"); 12250 12251 if (!CurContext->isDependentContext()) { 12252 // Finalize the clauses that need pre-built expressions for CodeGen. 12253 for (OMPClause *C : Clauses) { 12254 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12255 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12256 B.NumIterations, *this, CurScope, 12257 DSAStack)) 12258 return StmtError(); 12259 } 12260 } 12261 12262 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12263 return StmtError(); 12264 12265 setFunctionHasBranchProtectedScope(); 12266 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 12267 NestedLoopCount, Clauses, AStmt, B); 12268 } 12269 12270 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 12271 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12272 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12273 if (!AStmt) 12274 return StmtError(); 12275 12276 auto *CS = cast<CapturedStmt>(AStmt); 12277 // 1.2.2 OpenMP Language Terminology 12278 // Structured block - An executable statement with a single entry at the 12279 // top and a single exit at the bottom. 12280 // The point of exit cannot be a branch out of the structured block. 12281 // longjmp() and throw() must not violate the entry/exit criteria. 12282 CS->getCapturedDecl()->setNothrow(); 12283 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 12284 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12285 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12286 // 1.2.2 OpenMP Language Terminology 12287 // Structured block - An executable statement with a single entry at the 12288 // top and a single exit at the bottom. 12289 // The point of exit cannot be a branch out of the structured block. 12290 // longjmp() and throw() must not violate the entry/exit criteria. 12291 CS->getCapturedDecl()->setNothrow(); 12292 } 12293 12294 OMPLoopBasedDirective::HelperExprs B; 12295 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 12296 // define the nested loops number. 12297 unsigned NestedLoopCount = checkOpenMPLoop( 12298 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 12299 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, VarsWithImplicitDSA, 12300 B); 12301 if (NestedLoopCount == 0) 12302 return StmtError(); 12303 12304 assert((CurContext->isDependentContext() || B.builtAll()) && 12305 "omp target parallel for simd loop exprs were not built"); 12306 12307 if (!CurContext->isDependentContext()) { 12308 // Finalize the clauses that need pre-built expressions for CodeGen. 12309 for (OMPClause *C : Clauses) { 12310 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12311 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12312 B.NumIterations, *this, CurScope, 12313 DSAStack)) 12314 return StmtError(); 12315 } 12316 } 12317 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12318 return StmtError(); 12319 12320 setFunctionHasBranchProtectedScope(); 12321 return OMPTargetParallelForSimdDirective::Create( 12322 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12323 } 12324 12325 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 12326 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12327 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12328 if (!AStmt) 12329 return StmtError(); 12330 12331 auto *CS = cast<CapturedStmt>(AStmt); 12332 // 1.2.2 OpenMP Language Terminology 12333 // Structured block - An executable statement with a single entry at the 12334 // top and a single exit at the bottom. 12335 // The point of exit cannot be a branch out of the structured block. 12336 // longjmp() and throw() must not violate the entry/exit criteria. 12337 CS->getCapturedDecl()->setNothrow(); 12338 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd); 12339 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12340 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12341 // 1.2.2 OpenMP Language Terminology 12342 // Structured block - An executable statement with a single entry at the 12343 // top and a single exit at the bottom. 12344 // The point of exit cannot be a branch out of the structured block. 12345 // longjmp() and throw() must not violate the entry/exit criteria. 12346 CS->getCapturedDecl()->setNothrow(); 12347 } 12348 12349 OMPLoopBasedDirective::HelperExprs B; 12350 // In presence of clause 'collapse' with number of loops, it will define the 12351 // nested loops number. 12352 unsigned NestedLoopCount = 12353 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 12354 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 12355 VarsWithImplicitDSA, B); 12356 if (NestedLoopCount == 0) 12357 return StmtError(); 12358 12359 assert((CurContext->isDependentContext() || B.builtAll()) && 12360 "omp target simd loop exprs were not built"); 12361 12362 if (!CurContext->isDependentContext()) { 12363 // Finalize the clauses that need pre-built expressions for CodeGen. 12364 for (OMPClause *C : Clauses) { 12365 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12366 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12367 B.NumIterations, *this, CurScope, 12368 DSAStack)) 12369 return StmtError(); 12370 } 12371 } 12372 12373 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12374 return StmtError(); 12375 12376 setFunctionHasBranchProtectedScope(); 12377 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 12378 NestedLoopCount, Clauses, AStmt, B); 12379 } 12380 12381 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 12382 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12383 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12384 if (!AStmt) 12385 return StmtError(); 12386 12387 auto *CS = cast<CapturedStmt>(AStmt); 12388 // 1.2.2 OpenMP Language Terminology 12389 // Structured block - An executable statement with a single entry at the 12390 // top and a single exit at the bottom. 12391 // The point of exit cannot be a branch out of the structured block. 12392 // longjmp() and throw() must not violate the entry/exit criteria. 12393 CS->getCapturedDecl()->setNothrow(); 12394 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute); 12395 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12396 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12397 // 1.2.2 OpenMP Language Terminology 12398 // Structured block - An executable statement with a single entry at the 12399 // top and a single exit at the bottom. 12400 // The point of exit cannot be a branch out of the structured block. 12401 // longjmp() and throw() must not violate the entry/exit criteria. 12402 CS->getCapturedDecl()->setNothrow(); 12403 } 12404 12405 OMPLoopBasedDirective::HelperExprs B; 12406 // In presence of clause 'collapse' with number of loops, it will 12407 // define the nested loops number. 12408 unsigned NestedLoopCount = 12409 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 12410 nullptr /*ordered not a clause on distribute*/, CS, *this, 12411 *DSAStack, VarsWithImplicitDSA, B); 12412 if (NestedLoopCount == 0) 12413 return StmtError(); 12414 12415 assert((CurContext->isDependentContext() || B.builtAll()) && 12416 "omp teams distribute loop exprs were not built"); 12417 12418 setFunctionHasBranchProtectedScope(); 12419 12420 DSAStack->setParentTeamsRegionLoc(StartLoc); 12421 12422 return OMPTeamsDistributeDirective::Create( 12423 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12424 } 12425 12426 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 12427 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12428 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12429 if (!AStmt) 12430 return StmtError(); 12431 12432 auto *CS = cast<CapturedStmt>(AStmt); 12433 // 1.2.2 OpenMP Language Terminology 12434 // Structured block - An executable statement with a single entry at the 12435 // top and a single exit at the bottom. 12436 // The point of exit cannot be a branch out of the structured block. 12437 // longjmp() and throw() must not violate the entry/exit criteria. 12438 CS->getCapturedDecl()->setNothrow(); 12439 for (int ThisCaptureLevel = 12440 getOpenMPCaptureLevels(OMPD_teams_distribute_simd); 12441 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12442 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12443 // 1.2.2 OpenMP Language Terminology 12444 // Structured block - An executable statement with a single entry at the 12445 // top and a single exit at the bottom. 12446 // The point of exit cannot be a branch out of the structured block. 12447 // longjmp() and throw() must not violate the entry/exit criteria. 12448 CS->getCapturedDecl()->setNothrow(); 12449 } 12450 12451 OMPLoopBasedDirective::HelperExprs B; 12452 // In presence of clause 'collapse' with number of loops, it will 12453 // define the nested loops number. 12454 unsigned NestedLoopCount = checkOpenMPLoop( 12455 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 12456 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12457 VarsWithImplicitDSA, B); 12458 12459 if (NestedLoopCount == 0) 12460 return StmtError(); 12461 12462 assert((CurContext->isDependentContext() || B.builtAll()) && 12463 "omp teams distribute simd loop exprs were not built"); 12464 12465 if (!CurContext->isDependentContext()) { 12466 // Finalize the clauses that need pre-built expressions for CodeGen. 12467 for (OMPClause *C : Clauses) { 12468 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12469 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12470 B.NumIterations, *this, CurScope, 12471 DSAStack)) 12472 return StmtError(); 12473 } 12474 } 12475 12476 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12477 return StmtError(); 12478 12479 setFunctionHasBranchProtectedScope(); 12480 12481 DSAStack->setParentTeamsRegionLoc(StartLoc); 12482 12483 return OMPTeamsDistributeSimdDirective::Create( 12484 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12485 } 12486 12487 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 12488 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12489 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12490 if (!AStmt) 12491 return StmtError(); 12492 12493 auto *CS = cast<CapturedStmt>(AStmt); 12494 // 1.2.2 OpenMP Language Terminology 12495 // Structured block - An executable statement with a single entry at the 12496 // top and a single exit at the bottom. 12497 // The point of exit cannot be a branch out of the structured block. 12498 // longjmp() and throw() must not violate the entry/exit criteria. 12499 CS->getCapturedDecl()->setNothrow(); 12500 12501 for (int ThisCaptureLevel = 12502 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd); 12503 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12504 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12505 // 1.2.2 OpenMP Language Terminology 12506 // Structured block - An executable statement with a single entry at the 12507 // top and a single exit at the bottom. 12508 // The point of exit cannot be a branch out of the structured block. 12509 // longjmp() and throw() must not violate the entry/exit criteria. 12510 CS->getCapturedDecl()->setNothrow(); 12511 } 12512 12513 OMPLoopBasedDirective::HelperExprs B; 12514 // In presence of clause 'collapse' with number of loops, it will 12515 // define the nested loops number. 12516 unsigned NestedLoopCount = checkOpenMPLoop( 12517 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 12518 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12519 VarsWithImplicitDSA, B); 12520 12521 if (NestedLoopCount == 0) 12522 return StmtError(); 12523 12524 assert((CurContext->isDependentContext() || B.builtAll()) && 12525 "omp for loop exprs were not built"); 12526 12527 if (!CurContext->isDependentContext()) { 12528 // Finalize the clauses that need pre-built expressions for CodeGen. 12529 for (OMPClause *C : Clauses) { 12530 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12531 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12532 B.NumIterations, *this, CurScope, 12533 DSAStack)) 12534 return StmtError(); 12535 } 12536 } 12537 12538 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12539 return StmtError(); 12540 12541 setFunctionHasBranchProtectedScope(); 12542 12543 DSAStack->setParentTeamsRegionLoc(StartLoc); 12544 12545 return OMPTeamsDistributeParallelForSimdDirective::Create( 12546 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12547 } 12548 12549 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 12550 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12551 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12552 if (!AStmt) 12553 return StmtError(); 12554 12555 auto *CS = cast<CapturedStmt>(AStmt); 12556 // 1.2.2 OpenMP Language Terminology 12557 // Structured block - An executable statement with a single entry at the 12558 // top and a single exit at the bottom. 12559 // The point of exit cannot be a branch out of the structured block. 12560 // longjmp() and throw() must not violate the entry/exit criteria. 12561 CS->getCapturedDecl()->setNothrow(); 12562 12563 for (int ThisCaptureLevel = 12564 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for); 12565 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12566 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12567 // 1.2.2 OpenMP Language Terminology 12568 // Structured block - An executable statement with a single entry at the 12569 // top and a single exit at the bottom. 12570 // The point of exit cannot be a branch out of the structured block. 12571 // longjmp() and throw() must not violate the entry/exit criteria. 12572 CS->getCapturedDecl()->setNothrow(); 12573 } 12574 12575 OMPLoopBasedDirective::HelperExprs B; 12576 // In presence of clause 'collapse' with number of loops, it will 12577 // define the nested loops number. 12578 unsigned NestedLoopCount = checkOpenMPLoop( 12579 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 12580 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12581 VarsWithImplicitDSA, B); 12582 12583 if (NestedLoopCount == 0) 12584 return StmtError(); 12585 12586 assert((CurContext->isDependentContext() || B.builtAll()) && 12587 "omp for loop exprs were not built"); 12588 12589 setFunctionHasBranchProtectedScope(); 12590 12591 DSAStack->setParentTeamsRegionLoc(StartLoc); 12592 12593 return OMPTeamsDistributeParallelForDirective::Create( 12594 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 12595 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 12596 } 12597 12598 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 12599 Stmt *AStmt, 12600 SourceLocation StartLoc, 12601 SourceLocation EndLoc) { 12602 if (!AStmt) 12603 return StmtError(); 12604 12605 auto *CS = cast<CapturedStmt>(AStmt); 12606 // 1.2.2 OpenMP Language Terminology 12607 // Structured block - An executable statement with a single entry at the 12608 // top and a single exit at the bottom. 12609 // The point of exit cannot be a branch out of the structured block. 12610 // longjmp() and throw() must not violate the entry/exit criteria. 12611 CS->getCapturedDecl()->setNothrow(); 12612 12613 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams); 12614 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12615 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12616 // 1.2.2 OpenMP Language Terminology 12617 // Structured block - An executable statement with a single entry at the 12618 // top and a single exit at the bottom. 12619 // The point of exit cannot be a branch out of the structured block. 12620 // longjmp() and throw() must not violate the entry/exit criteria. 12621 CS->getCapturedDecl()->setNothrow(); 12622 } 12623 setFunctionHasBranchProtectedScope(); 12624 12625 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 12626 AStmt); 12627 } 12628 12629 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 12630 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12631 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12632 if (!AStmt) 12633 return StmtError(); 12634 12635 auto *CS = cast<CapturedStmt>(AStmt); 12636 // 1.2.2 OpenMP Language Terminology 12637 // Structured block - An executable statement with a single entry at the 12638 // top and a single exit at the bottom. 12639 // The point of exit cannot be a branch out of the structured block. 12640 // longjmp() and throw() must not violate the entry/exit criteria. 12641 CS->getCapturedDecl()->setNothrow(); 12642 for (int ThisCaptureLevel = 12643 getOpenMPCaptureLevels(OMPD_target_teams_distribute); 12644 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12645 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12646 // 1.2.2 OpenMP Language Terminology 12647 // Structured block - An executable statement with a single entry at the 12648 // top and a single exit at the bottom. 12649 // The point of exit cannot be a branch out of the structured block. 12650 // longjmp() and throw() must not violate the entry/exit criteria. 12651 CS->getCapturedDecl()->setNothrow(); 12652 } 12653 12654 OMPLoopBasedDirective::HelperExprs B; 12655 // In presence of clause 'collapse' with number of loops, it will 12656 // define the nested loops number. 12657 unsigned NestedLoopCount = checkOpenMPLoop( 12658 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses), 12659 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12660 VarsWithImplicitDSA, B); 12661 if (NestedLoopCount == 0) 12662 return StmtError(); 12663 12664 assert((CurContext->isDependentContext() || B.builtAll()) && 12665 "omp target teams distribute loop exprs were not built"); 12666 12667 setFunctionHasBranchProtectedScope(); 12668 return OMPTargetTeamsDistributeDirective::Create( 12669 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12670 } 12671 12672 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 12673 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12674 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12675 if (!AStmt) 12676 return StmtError(); 12677 12678 auto *CS = cast<CapturedStmt>(AStmt); 12679 // 1.2.2 OpenMP Language Terminology 12680 // Structured block - An executable statement with a single entry at the 12681 // top and a single exit at the bottom. 12682 // The point of exit cannot be a branch out of the structured block. 12683 // longjmp() and throw() must not violate the entry/exit criteria. 12684 CS->getCapturedDecl()->setNothrow(); 12685 for (int ThisCaptureLevel = 12686 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for); 12687 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12688 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12689 // 1.2.2 OpenMP Language Terminology 12690 // Structured block - An executable statement with a single entry at the 12691 // top and a single exit at the bottom. 12692 // The point of exit cannot be a branch out of the structured block. 12693 // longjmp() and throw() must not violate the entry/exit criteria. 12694 CS->getCapturedDecl()->setNothrow(); 12695 } 12696 12697 OMPLoopBasedDirective::HelperExprs B; 12698 // In presence of clause 'collapse' with number of loops, it will 12699 // define the nested loops number. 12700 unsigned NestedLoopCount = checkOpenMPLoop( 12701 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 12702 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12703 VarsWithImplicitDSA, B); 12704 if (NestedLoopCount == 0) 12705 return StmtError(); 12706 12707 assert((CurContext->isDependentContext() || B.builtAll()) && 12708 "omp target teams distribute parallel for loop exprs were not built"); 12709 12710 if (!CurContext->isDependentContext()) { 12711 // Finalize the clauses that need pre-built expressions for CodeGen. 12712 for (OMPClause *C : Clauses) { 12713 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12714 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12715 B.NumIterations, *this, CurScope, 12716 DSAStack)) 12717 return StmtError(); 12718 } 12719 } 12720 12721 setFunctionHasBranchProtectedScope(); 12722 return OMPTargetTeamsDistributeParallelForDirective::Create( 12723 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 12724 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 12725 } 12726 12727 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 12728 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12729 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12730 if (!AStmt) 12731 return StmtError(); 12732 12733 auto *CS = cast<CapturedStmt>(AStmt); 12734 // 1.2.2 OpenMP Language Terminology 12735 // Structured block - An executable statement with a single entry at the 12736 // top and a single exit at the bottom. 12737 // The point of exit cannot be a branch out of the structured block. 12738 // longjmp() and throw() must not violate the entry/exit criteria. 12739 CS->getCapturedDecl()->setNothrow(); 12740 for (int ThisCaptureLevel = getOpenMPCaptureLevels( 12741 OMPD_target_teams_distribute_parallel_for_simd); 12742 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12743 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12744 // 1.2.2 OpenMP Language Terminology 12745 // Structured block - An executable statement with a single entry at the 12746 // top and a single exit at the bottom. 12747 // The point of exit cannot be a branch out of the structured block. 12748 // longjmp() and throw() must not violate the entry/exit criteria. 12749 CS->getCapturedDecl()->setNothrow(); 12750 } 12751 12752 OMPLoopBasedDirective::HelperExprs B; 12753 // In presence of clause 'collapse' with number of loops, it will 12754 // define the nested loops number. 12755 unsigned NestedLoopCount = 12756 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd, 12757 getCollapseNumberExpr(Clauses), 12758 nullptr /*ordered not a clause on distribute*/, CS, *this, 12759 *DSAStack, VarsWithImplicitDSA, B); 12760 if (NestedLoopCount == 0) 12761 return StmtError(); 12762 12763 assert((CurContext->isDependentContext() || B.builtAll()) && 12764 "omp target teams distribute parallel for simd loop exprs were not " 12765 "built"); 12766 12767 if (!CurContext->isDependentContext()) { 12768 // Finalize the clauses that need pre-built expressions for CodeGen. 12769 for (OMPClause *C : Clauses) { 12770 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12771 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12772 B.NumIterations, *this, CurScope, 12773 DSAStack)) 12774 return StmtError(); 12775 } 12776 } 12777 12778 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12779 return StmtError(); 12780 12781 setFunctionHasBranchProtectedScope(); 12782 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 12783 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12784 } 12785 12786 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 12787 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12788 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12789 if (!AStmt) 12790 return StmtError(); 12791 12792 auto *CS = cast<CapturedStmt>(AStmt); 12793 // 1.2.2 OpenMP Language Terminology 12794 // Structured block - An executable statement with a single entry at the 12795 // top and a single exit at the bottom. 12796 // The point of exit cannot be a branch out of the structured block. 12797 // longjmp() and throw() must not violate the entry/exit criteria. 12798 CS->getCapturedDecl()->setNothrow(); 12799 for (int ThisCaptureLevel = 12800 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd); 12801 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12802 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12803 // 1.2.2 OpenMP Language Terminology 12804 // Structured block - An executable statement with a single entry at the 12805 // top and a single exit at the bottom. 12806 // The point of exit cannot be a branch out of the structured block. 12807 // longjmp() and throw() must not violate the entry/exit criteria. 12808 CS->getCapturedDecl()->setNothrow(); 12809 } 12810 12811 OMPLoopBasedDirective::HelperExprs B; 12812 // In presence of clause 'collapse' with number of loops, it will 12813 // define the nested loops number. 12814 unsigned NestedLoopCount = checkOpenMPLoop( 12815 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 12816 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12817 VarsWithImplicitDSA, B); 12818 if (NestedLoopCount == 0) 12819 return StmtError(); 12820 12821 assert((CurContext->isDependentContext() || B.builtAll()) && 12822 "omp target teams distribute simd loop exprs were not built"); 12823 12824 if (!CurContext->isDependentContext()) { 12825 // Finalize the clauses that need pre-built expressions for CodeGen. 12826 for (OMPClause *C : Clauses) { 12827 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12828 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12829 B.NumIterations, *this, CurScope, 12830 DSAStack)) 12831 return StmtError(); 12832 } 12833 } 12834 12835 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12836 return StmtError(); 12837 12838 setFunctionHasBranchProtectedScope(); 12839 return OMPTargetTeamsDistributeSimdDirective::Create( 12840 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12841 } 12842 12843 bool Sema::checkTransformableLoopNest( 12844 OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops, 12845 SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers, 12846 Stmt *&Body, 12847 SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>> 12848 &OriginalInits) { 12849 OriginalInits.emplace_back(); 12850 bool Result = OMPLoopBasedDirective::doForAllLoops( 12851 AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false, NumLoops, 12852 [this, &LoopHelpers, &Body, &OriginalInits, Kind](unsigned Cnt, 12853 Stmt *CurStmt) { 12854 VarsWithInheritedDSAType TmpDSA; 12855 unsigned SingleNumLoops = 12856 checkOpenMPLoop(Kind, nullptr, nullptr, CurStmt, *this, *DSAStack, 12857 TmpDSA, LoopHelpers[Cnt]); 12858 if (SingleNumLoops == 0) 12859 return true; 12860 assert(SingleNumLoops == 1 && "Expect single loop iteration space"); 12861 if (auto *For = dyn_cast<ForStmt>(CurStmt)) { 12862 OriginalInits.back().push_back(For->getInit()); 12863 Body = For->getBody(); 12864 } else { 12865 assert(isa<CXXForRangeStmt>(CurStmt) && 12866 "Expected canonical for or range-based for loops."); 12867 auto *CXXFor = cast<CXXForRangeStmt>(CurStmt); 12868 OriginalInits.back().push_back(CXXFor->getBeginStmt()); 12869 Body = CXXFor->getBody(); 12870 } 12871 OriginalInits.emplace_back(); 12872 return false; 12873 }, 12874 [&OriginalInits](OMPLoopBasedDirective *Transform) { 12875 Stmt *DependentPreInits; 12876 if (auto *Dir = dyn_cast<OMPTileDirective>(Transform)) 12877 DependentPreInits = Dir->getPreInits(); 12878 else if (auto *Dir = dyn_cast<OMPUnrollDirective>(Transform)) 12879 DependentPreInits = Dir->getPreInits(); 12880 else 12881 llvm_unreachable("Unhandled loop transformation"); 12882 if (!DependentPreInits) 12883 return; 12884 for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) 12885 OriginalInits.back().push_back(C); 12886 }); 12887 assert(OriginalInits.back().empty() && "No preinit after innermost loop"); 12888 OriginalInits.pop_back(); 12889 return Result; 12890 } 12891 12892 StmtResult Sema::ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses, 12893 Stmt *AStmt, SourceLocation StartLoc, 12894 SourceLocation EndLoc) { 12895 auto SizesClauses = 12896 OMPExecutableDirective::getClausesOfKind<OMPSizesClause>(Clauses); 12897 if (SizesClauses.empty()) { 12898 // A missing 'sizes' clause is already reported by the parser. 12899 return StmtError(); 12900 } 12901 const OMPSizesClause *SizesClause = *SizesClauses.begin(); 12902 unsigned NumLoops = SizesClause->getNumSizes(); 12903 12904 // Empty statement should only be possible if there already was an error. 12905 if (!AStmt) 12906 return StmtError(); 12907 12908 // Verify and diagnose loop nest. 12909 SmallVector<OMPLoopBasedDirective::HelperExprs, 4> LoopHelpers(NumLoops); 12910 Stmt *Body = nullptr; 12911 SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, 4> 12912 OriginalInits; 12913 if (!checkTransformableLoopNest(OMPD_tile, AStmt, NumLoops, LoopHelpers, Body, 12914 OriginalInits)) 12915 return StmtError(); 12916 12917 // Delay tiling to when template is completely instantiated. 12918 if (CurContext->isDependentContext()) 12919 return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, 12920 NumLoops, AStmt, nullptr, nullptr); 12921 12922 SmallVector<Decl *, 4> PreInits; 12923 12924 // Create iteration variables for the generated loops. 12925 SmallVector<VarDecl *, 4> FloorIndVars; 12926 SmallVector<VarDecl *, 4> TileIndVars; 12927 FloorIndVars.resize(NumLoops); 12928 TileIndVars.resize(NumLoops); 12929 for (unsigned I = 0; I < NumLoops; ++I) { 12930 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I]; 12931 12932 assert(LoopHelper.Counters.size() == 1 && 12933 "Expect single-dimensional loop iteration space"); 12934 auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front()); 12935 std::string OrigVarName = OrigCntVar->getNameInfo().getAsString(); 12936 DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef); 12937 QualType CntTy = IterVarRef->getType(); 12938 12939 // Iteration variable for the floor (i.e. outer) loop. 12940 { 12941 std::string FloorCntName = 12942 (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str(); 12943 VarDecl *FloorCntDecl = 12944 buildVarDecl(*this, {}, CntTy, FloorCntName, nullptr, OrigCntVar); 12945 FloorIndVars[I] = FloorCntDecl; 12946 } 12947 12948 // Iteration variable for the tile (i.e. inner) loop. 12949 { 12950 std::string TileCntName = 12951 (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str(); 12952 12953 // Reuse the iteration variable created by checkOpenMPLoop. It is also 12954 // used by the expressions to derive the original iteration variable's 12955 // value from the logical iteration number. 12956 auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl()); 12957 TileCntDecl->setDeclName(&PP.getIdentifierTable().get(TileCntName)); 12958 TileIndVars[I] = TileCntDecl; 12959 } 12960 for (auto &P : OriginalInits[I]) { 12961 if (auto *D = P.dyn_cast<Decl *>()) 12962 PreInits.push_back(D); 12963 else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>())) 12964 PreInits.append(PI->decl_begin(), PI->decl_end()); 12965 } 12966 if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits)) 12967 PreInits.append(PI->decl_begin(), PI->decl_end()); 12968 // Gather declarations for the data members used as counters. 12969 for (Expr *CounterRef : LoopHelper.Counters) { 12970 auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl(); 12971 if (isa<OMPCapturedExprDecl>(CounterDecl)) 12972 PreInits.push_back(CounterDecl); 12973 } 12974 } 12975 12976 // Once the original iteration values are set, append the innermost body. 12977 Stmt *Inner = Body; 12978 12979 // Create tile loops from the inside to the outside. 12980 for (int I = NumLoops - 1; I >= 0; --I) { 12981 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I]; 12982 Expr *NumIterations = LoopHelper.NumIterations; 12983 auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]); 12984 QualType CntTy = OrigCntVar->getType(); 12985 Expr *DimTileSize = SizesClause->getSizesRefs()[I]; 12986 Scope *CurScope = getCurScope(); 12987 12988 // Commonly used variables. 12989 DeclRefExpr *TileIV = buildDeclRefExpr(*this, TileIndVars[I], CntTy, 12990 OrigCntVar->getExprLoc()); 12991 DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy, 12992 OrigCntVar->getExprLoc()); 12993 12994 // For init-statement: auto .tile.iv = .floor.iv 12995 AddInitializerToDecl(TileIndVars[I], DefaultLvalueConversion(FloorIV).get(), 12996 /*DirectInit=*/false); 12997 Decl *CounterDecl = TileIndVars[I]; 12998 StmtResult InitStmt = new (Context) 12999 DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1), 13000 OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc()); 13001 if (!InitStmt.isUsable()) 13002 return StmtError(); 13003 13004 // For cond-expression: .tile.iv < min(.floor.iv + DimTileSize, 13005 // NumIterations) 13006 ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13007 BO_Add, FloorIV, DimTileSize); 13008 if (!EndOfTile.isUsable()) 13009 return StmtError(); 13010 ExprResult IsPartialTile = 13011 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, 13012 NumIterations, EndOfTile.get()); 13013 if (!IsPartialTile.isUsable()) 13014 return StmtError(); 13015 ExprResult MinTileAndIterSpace = ActOnConditionalOp( 13016 LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(), 13017 IsPartialTile.get(), NumIterations, EndOfTile.get()); 13018 if (!MinTileAndIterSpace.isUsable()) 13019 return StmtError(); 13020 ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13021 BO_LT, TileIV, MinTileAndIterSpace.get()); 13022 if (!CondExpr.isUsable()) 13023 return StmtError(); 13024 13025 // For incr-statement: ++.tile.iv 13026 ExprResult IncrStmt = 13027 BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV); 13028 if (!IncrStmt.isUsable()) 13029 return StmtError(); 13030 13031 // Statements to set the original iteration variable's value from the 13032 // logical iteration number. 13033 // Generated for loop is: 13034 // Original_for_init; 13035 // for (auto .tile.iv = .floor.iv; .tile.iv < min(.floor.iv + DimTileSize, 13036 // NumIterations); ++.tile.iv) { 13037 // Original_Body; 13038 // Original_counter_update; 13039 // } 13040 // FIXME: If the innermost body is an loop itself, inserting these 13041 // statements stops it being recognized as a perfectly nested loop (e.g. 13042 // for applying tiling again). If this is the case, sink the expressions 13043 // further into the inner loop. 13044 SmallVector<Stmt *, 4> BodyParts; 13045 BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end()); 13046 BodyParts.push_back(Inner); 13047 Inner = CompoundStmt::Create(Context, BodyParts, Inner->getBeginLoc(), 13048 Inner->getEndLoc()); 13049 Inner = new (Context) 13050 ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr, 13051 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(), 13052 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 13053 } 13054 13055 // Create floor loops from the inside to the outside. 13056 for (int I = NumLoops - 1; I >= 0; --I) { 13057 auto &LoopHelper = LoopHelpers[I]; 13058 Expr *NumIterations = LoopHelper.NumIterations; 13059 DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]); 13060 QualType CntTy = OrigCntVar->getType(); 13061 Expr *DimTileSize = SizesClause->getSizesRefs()[I]; 13062 Scope *CurScope = getCurScope(); 13063 13064 // Commonly used variables. 13065 DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy, 13066 OrigCntVar->getExprLoc()); 13067 13068 // For init-statement: auto .floor.iv = 0 13069 AddInitializerToDecl( 13070 FloorIndVars[I], 13071 ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(), 13072 /*DirectInit=*/false); 13073 Decl *CounterDecl = FloorIndVars[I]; 13074 StmtResult InitStmt = new (Context) 13075 DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1), 13076 OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc()); 13077 if (!InitStmt.isUsable()) 13078 return StmtError(); 13079 13080 // For cond-expression: .floor.iv < NumIterations 13081 ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13082 BO_LT, FloorIV, NumIterations); 13083 if (!CondExpr.isUsable()) 13084 return StmtError(); 13085 13086 // For incr-statement: .floor.iv += DimTileSize 13087 ExprResult IncrStmt = BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), 13088 BO_AddAssign, FloorIV, DimTileSize); 13089 if (!IncrStmt.isUsable()) 13090 return StmtError(); 13091 13092 Inner = new (Context) 13093 ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr, 13094 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(), 13095 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 13096 } 13097 13098 return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, NumLoops, 13099 AStmt, Inner, 13100 buildPreInits(Context, PreInits)); 13101 } 13102 13103 StmtResult Sema::ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses, 13104 Stmt *AStmt, 13105 SourceLocation StartLoc, 13106 SourceLocation EndLoc) { 13107 // Empty statement should only be possible if there already was an error. 13108 if (!AStmt) 13109 return StmtError(); 13110 13111 if (checkMutuallyExclusiveClauses(*this, Clauses, {OMPC_partial, OMPC_full})) 13112 return StmtError(); 13113 13114 const OMPFullClause *FullClause = 13115 OMPExecutableDirective::getSingleClause<OMPFullClause>(Clauses); 13116 const OMPPartialClause *PartialClause = 13117 OMPExecutableDirective::getSingleClause<OMPPartialClause>(Clauses); 13118 assert(!(FullClause && PartialClause) && 13119 "mutual exclusivity must have been checked before"); 13120 13121 constexpr unsigned NumLoops = 1; 13122 Stmt *Body = nullptr; 13123 SmallVector<OMPLoopBasedDirective::HelperExprs, NumLoops> LoopHelpers( 13124 NumLoops); 13125 SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, NumLoops + 1> 13126 OriginalInits; 13127 if (!checkTransformableLoopNest(OMPD_unroll, AStmt, NumLoops, LoopHelpers, 13128 Body, OriginalInits)) 13129 return StmtError(); 13130 13131 unsigned NumGeneratedLoops = PartialClause ? 1 : 0; 13132 13133 // Delay unrolling to when template is completely instantiated. 13134 if (CurContext->isDependentContext()) 13135 return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 13136 NumGeneratedLoops, nullptr, nullptr); 13137 13138 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers.front(); 13139 13140 if (FullClause) { 13141 if (!VerifyPositiveIntegerConstantInClause( 13142 LoopHelper.NumIterations, OMPC_full, /*StrictlyPositive=*/false, 13143 /*SuppressExprDigs=*/true) 13144 .isUsable()) { 13145 Diag(AStmt->getBeginLoc(), diag::err_omp_unroll_full_variable_trip_count); 13146 Diag(FullClause->getBeginLoc(), diag::note_omp_directive_here) 13147 << "#pragma omp unroll full"; 13148 return StmtError(); 13149 } 13150 } 13151 13152 // The generated loop may only be passed to other loop-associated directive 13153 // when a partial clause is specified. Without the requirement it is 13154 // sufficient to generate loop unroll metadata at code-generation. 13155 if (NumGeneratedLoops == 0) 13156 return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 13157 NumGeneratedLoops, nullptr, nullptr); 13158 13159 // Otherwise, we need to provide a de-sugared/transformed AST that can be 13160 // associated with another loop directive. 13161 // 13162 // The canonical loop analysis return by checkTransformableLoopNest assumes 13163 // the following structure to be the same loop without transformations or 13164 // directives applied: \code OriginalInits; LoopHelper.PreInits; 13165 // LoopHelper.Counters; 13166 // for (; IV < LoopHelper.NumIterations; ++IV) { 13167 // LoopHelper.Updates; 13168 // Body; 13169 // } 13170 // \endcode 13171 // where IV is a variable declared and initialized to 0 in LoopHelper.PreInits 13172 // and referenced by LoopHelper.IterationVarRef. 13173 // 13174 // The unrolling directive transforms this into the following loop: 13175 // \code 13176 // OriginalInits; \ 13177 // LoopHelper.PreInits; > NewPreInits 13178 // LoopHelper.Counters; / 13179 // for (auto UIV = 0; UIV < LoopHelper.NumIterations; UIV+=Factor) { 13180 // #pragma clang loop unroll_count(Factor) 13181 // for (IV = UIV; IV < UIV + Factor && UIV < LoopHelper.NumIterations; ++IV) 13182 // { 13183 // LoopHelper.Updates; 13184 // Body; 13185 // } 13186 // } 13187 // \endcode 13188 // where UIV is a new logical iteration counter. IV must be the same VarDecl 13189 // as the original LoopHelper.IterationVarRef because LoopHelper.Updates 13190 // references it. If the partially unrolled loop is associated with another 13191 // loop directive (like an OMPForDirective), it will use checkOpenMPLoop to 13192 // analyze this loop, i.e. the outer loop must fulfill the constraints of an 13193 // OpenMP canonical loop. The inner loop is not an associable canonical loop 13194 // and only exists to defer its unrolling to LLVM's LoopUnroll instead of 13195 // doing it in the frontend (by adding loop metadata). NewPreInits becomes a 13196 // property of the OMPLoopBasedDirective instead of statements in 13197 // CompoundStatement. This is to allow the loop to become a non-outermost loop 13198 // of a canonical loop nest where these PreInits are emitted before the 13199 // outermost directive. 13200 13201 // Determine the PreInit declarations. 13202 SmallVector<Decl *, 4> PreInits; 13203 assert(OriginalInits.size() == 1 && 13204 "Expecting a single-dimensional loop iteration space"); 13205 for (auto &P : OriginalInits[0]) { 13206 if (auto *D = P.dyn_cast<Decl *>()) 13207 PreInits.push_back(D); 13208 else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>())) 13209 PreInits.append(PI->decl_begin(), PI->decl_end()); 13210 } 13211 if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits)) 13212 PreInits.append(PI->decl_begin(), PI->decl_end()); 13213 // Gather declarations for the data members used as counters. 13214 for (Expr *CounterRef : LoopHelper.Counters) { 13215 auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl(); 13216 if (isa<OMPCapturedExprDecl>(CounterDecl)) 13217 PreInits.push_back(CounterDecl); 13218 } 13219 13220 auto *IterationVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef); 13221 QualType IVTy = IterationVarRef->getType(); 13222 assert(LoopHelper.Counters.size() == 1 && 13223 "Expecting a single-dimensional loop iteration space"); 13224 auto *OrigVar = cast<DeclRefExpr>(LoopHelper.Counters.front()); 13225 13226 // Determine the unroll factor. 13227 uint64_t Factor; 13228 SourceLocation FactorLoc; 13229 if (Expr *FactorVal = PartialClause->getFactor()) { 13230 Factor = 13231 FactorVal->getIntegerConstantExpr(Context).getValue().getZExtValue(); 13232 FactorLoc = FactorVal->getExprLoc(); 13233 } else { 13234 // TODO: Use a better profitability model. 13235 Factor = 2; 13236 } 13237 assert(Factor > 0 && "Expected positive unroll factor"); 13238 auto MakeFactorExpr = [this, Factor, IVTy, FactorLoc]() { 13239 return IntegerLiteral::Create( 13240 Context, llvm::APInt(Context.getIntWidth(IVTy), Factor), IVTy, 13241 FactorLoc); 13242 }; 13243 13244 // Iteration variable SourceLocations. 13245 SourceLocation OrigVarLoc = OrigVar->getExprLoc(); 13246 SourceLocation OrigVarLocBegin = OrigVar->getBeginLoc(); 13247 SourceLocation OrigVarLocEnd = OrigVar->getEndLoc(); 13248 13249 // Internal variable names. 13250 std::string OrigVarName = OrigVar->getNameInfo().getAsString(); 13251 std::string OuterIVName = (Twine(".unrolled.iv.") + OrigVarName).str(); 13252 std::string InnerIVName = (Twine(".unroll_inner.iv.") + OrigVarName).str(); 13253 std::string InnerTripCountName = 13254 (Twine(".unroll_inner.tripcount.") + OrigVarName).str(); 13255 13256 // Create the iteration variable for the unrolled loop. 13257 VarDecl *OuterIVDecl = 13258 buildVarDecl(*this, {}, IVTy, OuterIVName, nullptr, OrigVar); 13259 auto MakeOuterRef = [this, OuterIVDecl, IVTy, OrigVarLoc]() { 13260 return buildDeclRefExpr(*this, OuterIVDecl, IVTy, OrigVarLoc); 13261 }; 13262 13263 // Iteration variable for the inner loop: Reuse the iteration variable created 13264 // by checkOpenMPLoop. 13265 auto *InnerIVDecl = cast<VarDecl>(IterationVarRef->getDecl()); 13266 InnerIVDecl->setDeclName(&PP.getIdentifierTable().get(InnerIVName)); 13267 auto MakeInnerRef = [this, InnerIVDecl, IVTy, OrigVarLoc]() { 13268 return buildDeclRefExpr(*this, InnerIVDecl, IVTy, OrigVarLoc); 13269 }; 13270 13271 // Make a copy of the NumIterations expression for each use: By the AST 13272 // constraints, every expression object in a DeclContext must be unique. 13273 CaptureVars CopyTransformer(*this); 13274 auto MakeNumIterations = [&CopyTransformer, &LoopHelper]() -> Expr * { 13275 return AssertSuccess( 13276 CopyTransformer.TransformExpr(LoopHelper.NumIterations)); 13277 }; 13278 13279 // Inner For init-statement: auto .unroll_inner.iv = .unrolled.iv 13280 ExprResult LValueConv = DefaultLvalueConversion(MakeOuterRef()); 13281 AddInitializerToDecl(InnerIVDecl, LValueConv.get(), /*DirectInit=*/false); 13282 StmtResult InnerInit = new (Context) 13283 DeclStmt(DeclGroupRef(InnerIVDecl), OrigVarLocBegin, OrigVarLocEnd); 13284 if (!InnerInit.isUsable()) 13285 return StmtError(); 13286 13287 // Inner For cond-expression: 13288 // \code 13289 // .unroll_inner.iv < .unrolled.iv + Factor && 13290 // .unroll_inner.iv < NumIterations 13291 // \endcode 13292 // This conjunction of two conditions allows ScalarEvolution to derive the 13293 // maximum trip count of the inner loop. 13294 ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13295 BO_Add, MakeOuterRef(), MakeFactorExpr()); 13296 if (!EndOfTile.isUsable()) 13297 return StmtError(); 13298 ExprResult InnerCond1 = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13299 BO_LE, MakeInnerRef(), EndOfTile.get()); 13300 if (!InnerCond1.isUsable()) 13301 return StmtError(); 13302 ExprResult InnerCond2 = 13303 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LE, MakeInnerRef(), 13304 MakeNumIterations()); 13305 if (!InnerCond2.isUsable()) 13306 return StmtError(); 13307 ExprResult InnerCond = 13308 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LAnd, 13309 InnerCond1.get(), InnerCond2.get()); 13310 if (!InnerCond.isUsable()) 13311 return StmtError(); 13312 13313 // Inner For incr-statement: ++.unroll_inner.iv 13314 ExprResult InnerIncr = BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), 13315 UO_PreInc, MakeInnerRef()); 13316 if (!InnerIncr.isUsable()) 13317 return StmtError(); 13318 13319 // Inner For statement. 13320 SmallVector<Stmt *> InnerBodyStmts; 13321 InnerBodyStmts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end()); 13322 InnerBodyStmts.push_back(Body); 13323 CompoundStmt *InnerBody = CompoundStmt::Create( 13324 Context, InnerBodyStmts, Body->getBeginLoc(), Body->getEndLoc()); 13325 ForStmt *InnerFor = new (Context) 13326 ForStmt(Context, InnerInit.get(), InnerCond.get(), nullptr, 13327 InnerIncr.get(), InnerBody, LoopHelper.Init->getBeginLoc(), 13328 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 13329 13330 // Unroll metadata for the inner loop. 13331 // This needs to take into account the remainder portion of the unrolled loop, 13332 // hence `unroll(full)` does not apply here, even though the LoopUnroll pass 13333 // supports multiple loop exits. Instead, unroll using a factor equivalent to 13334 // the maximum trip count, which will also generate a remainder loop. Just 13335 // `unroll(enable)` (which could have been useful if the user has not 13336 // specified a concrete factor; even though the outer loop cannot be 13337 // influenced anymore, would avoid more code bloat than necessary) will refuse 13338 // the loop because "Won't unroll; remainder loop could not be generated when 13339 // assuming runtime trip count". Even if it did work, it must not choose a 13340 // larger unroll factor than the maximum loop length, or it would always just 13341 // execute the remainder loop. 13342 LoopHintAttr *UnrollHintAttr = 13343 LoopHintAttr::CreateImplicit(Context, LoopHintAttr::UnrollCount, 13344 LoopHintAttr::Numeric, MakeFactorExpr()); 13345 AttributedStmt *InnerUnrolled = 13346 AttributedStmt::Create(Context, StartLoc, {UnrollHintAttr}, InnerFor); 13347 13348 // Outer For init-statement: auto .unrolled.iv = 0 13349 AddInitializerToDecl( 13350 OuterIVDecl, ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(), 13351 /*DirectInit=*/false); 13352 StmtResult OuterInit = new (Context) 13353 DeclStmt(DeclGroupRef(OuterIVDecl), OrigVarLocBegin, OrigVarLocEnd); 13354 if (!OuterInit.isUsable()) 13355 return StmtError(); 13356 13357 // Outer For cond-expression: .unrolled.iv < NumIterations 13358 ExprResult OuterConde = 13359 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, MakeOuterRef(), 13360 MakeNumIterations()); 13361 if (!OuterConde.isUsable()) 13362 return StmtError(); 13363 13364 // Outer For incr-statement: .unrolled.iv += Factor 13365 ExprResult OuterIncr = 13366 BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), BO_AddAssign, 13367 MakeOuterRef(), MakeFactorExpr()); 13368 if (!OuterIncr.isUsable()) 13369 return StmtError(); 13370 13371 // Outer For statement. 13372 ForStmt *OuterFor = new (Context) 13373 ForStmt(Context, OuterInit.get(), OuterConde.get(), nullptr, 13374 OuterIncr.get(), InnerUnrolled, LoopHelper.Init->getBeginLoc(), 13375 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 13376 13377 return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 13378 NumGeneratedLoops, OuterFor, 13379 buildPreInits(Context, PreInits)); 13380 } 13381 13382 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 13383 SourceLocation StartLoc, 13384 SourceLocation LParenLoc, 13385 SourceLocation EndLoc) { 13386 OMPClause *Res = nullptr; 13387 switch (Kind) { 13388 case OMPC_final: 13389 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 13390 break; 13391 case OMPC_num_threads: 13392 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 13393 break; 13394 case OMPC_safelen: 13395 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 13396 break; 13397 case OMPC_simdlen: 13398 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 13399 break; 13400 case OMPC_allocator: 13401 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc); 13402 break; 13403 case OMPC_collapse: 13404 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 13405 break; 13406 case OMPC_ordered: 13407 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 13408 break; 13409 case OMPC_num_teams: 13410 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 13411 break; 13412 case OMPC_thread_limit: 13413 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 13414 break; 13415 case OMPC_priority: 13416 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 13417 break; 13418 case OMPC_grainsize: 13419 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 13420 break; 13421 case OMPC_num_tasks: 13422 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 13423 break; 13424 case OMPC_hint: 13425 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 13426 break; 13427 case OMPC_depobj: 13428 Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc); 13429 break; 13430 case OMPC_detach: 13431 Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc); 13432 break; 13433 case OMPC_novariants: 13434 Res = ActOnOpenMPNovariantsClause(Expr, StartLoc, LParenLoc, EndLoc); 13435 break; 13436 case OMPC_nocontext: 13437 Res = ActOnOpenMPNocontextClause(Expr, StartLoc, LParenLoc, EndLoc); 13438 break; 13439 case OMPC_filter: 13440 Res = ActOnOpenMPFilterClause(Expr, StartLoc, LParenLoc, EndLoc); 13441 break; 13442 case OMPC_partial: 13443 Res = ActOnOpenMPPartialClause(Expr, StartLoc, LParenLoc, EndLoc); 13444 break; 13445 case OMPC_align: 13446 Res = ActOnOpenMPAlignClause(Expr, StartLoc, LParenLoc, EndLoc); 13447 break; 13448 case OMPC_device: 13449 case OMPC_if: 13450 case OMPC_default: 13451 case OMPC_proc_bind: 13452 case OMPC_schedule: 13453 case OMPC_private: 13454 case OMPC_firstprivate: 13455 case OMPC_lastprivate: 13456 case OMPC_shared: 13457 case OMPC_reduction: 13458 case OMPC_task_reduction: 13459 case OMPC_in_reduction: 13460 case OMPC_linear: 13461 case OMPC_aligned: 13462 case OMPC_copyin: 13463 case OMPC_copyprivate: 13464 case OMPC_nowait: 13465 case OMPC_untied: 13466 case OMPC_mergeable: 13467 case OMPC_threadprivate: 13468 case OMPC_sizes: 13469 case OMPC_allocate: 13470 case OMPC_flush: 13471 case OMPC_read: 13472 case OMPC_write: 13473 case OMPC_update: 13474 case OMPC_capture: 13475 case OMPC_seq_cst: 13476 case OMPC_acq_rel: 13477 case OMPC_acquire: 13478 case OMPC_release: 13479 case OMPC_relaxed: 13480 case OMPC_depend: 13481 case OMPC_threads: 13482 case OMPC_simd: 13483 case OMPC_map: 13484 case OMPC_nogroup: 13485 case OMPC_dist_schedule: 13486 case OMPC_defaultmap: 13487 case OMPC_unknown: 13488 case OMPC_uniform: 13489 case OMPC_to: 13490 case OMPC_from: 13491 case OMPC_use_device_ptr: 13492 case OMPC_use_device_addr: 13493 case OMPC_is_device_ptr: 13494 case OMPC_unified_address: 13495 case OMPC_unified_shared_memory: 13496 case OMPC_reverse_offload: 13497 case OMPC_dynamic_allocators: 13498 case OMPC_atomic_default_mem_order: 13499 case OMPC_device_type: 13500 case OMPC_match: 13501 case OMPC_nontemporal: 13502 case OMPC_order: 13503 case OMPC_destroy: 13504 case OMPC_inclusive: 13505 case OMPC_exclusive: 13506 case OMPC_uses_allocators: 13507 case OMPC_affinity: 13508 case OMPC_when: 13509 case OMPC_bind: 13510 default: 13511 llvm_unreachable("Clause is not allowed."); 13512 } 13513 return Res; 13514 } 13515 13516 // An OpenMP directive such as 'target parallel' has two captured regions: 13517 // for the 'target' and 'parallel' respectively. This function returns 13518 // the region in which to capture expressions associated with a clause. 13519 // A return value of OMPD_unknown signifies that the expression should not 13520 // be captured. 13521 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 13522 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion, 13523 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 13524 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 13525 switch (CKind) { 13526 case OMPC_if: 13527 switch (DKind) { 13528 case OMPD_target_parallel_for_simd: 13529 if (OpenMPVersion >= 50 && 13530 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 13531 CaptureRegion = OMPD_parallel; 13532 break; 13533 } 13534 LLVM_FALLTHROUGH; 13535 case OMPD_target_parallel: 13536 case OMPD_target_parallel_for: 13537 // If this clause applies to the nested 'parallel' region, capture within 13538 // the 'target' region, otherwise do not capture. 13539 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 13540 CaptureRegion = OMPD_target; 13541 break; 13542 case OMPD_target_teams_distribute_parallel_for_simd: 13543 if (OpenMPVersion >= 50 && 13544 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 13545 CaptureRegion = OMPD_parallel; 13546 break; 13547 } 13548 LLVM_FALLTHROUGH; 13549 case OMPD_target_teams_distribute_parallel_for: 13550 // If this clause applies to the nested 'parallel' region, capture within 13551 // the 'teams' region, otherwise do not capture. 13552 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 13553 CaptureRegion = OMPD_teams; 13554 break; 13555 case OMPD_teams_distribute_parallel_for_simd: 13556 if (OpenMPVersion >= 50 && 13557 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 13558 CaptureRegion = OMPD_parallel; 13559 break; 13560 } 13561 LLVM_FALLTHROUGH; 13562 case OMPD_teams_distribute_parallel_for: 13563 CaptureRegion = OMPD_teams; 13564 break; 13565 case OMPD_target_update: 13566 case OMPD_target_enter_data: 13567 case OMPD_target_exit_data: 13568 CaptureRegion = OMPD_task; 13569 break; 13570 case OMPD_parallel_master_taskloop: 13571 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop) 13572 CaptureRegion = OMPD_parallel; 13573 break; 13574 case OMPD_parallel_master_taskloop_simd: 13575 if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) || 13576 NameModifier == OMPD_taskloop) { 13577 CaptureRegion = OMPD_parallel; 13578 break; 13579 } 13580 if (OpenMPVersion <= 45) 13581 break; 13582 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 13583 CaptureRegion = OMPD_taskloop; 13584 break; 13585 case OMPD_parallel_for_simd: 13586 if (OpenMPVersion <= 45) 13587 break; 13588 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 13589 CaptureRegion = OMPD_parallel; 13590 break; 13591 case OMPD_taskloop_simd: 13592 case OMPD_master_taskloop_simd: 13593 if (OpenMPVersion <= 45) 13594 break; 13595 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 13596 CaptureRegion = OMPD_taskloop; 13597 break; 13598 case OMPD_distribute_parallel_for_simd: 13599 if (OpenMPVersion <= 45) 13600 break; 13601 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 13602 CaptureRegion = OMPD_parallel; 13603 break; 13604 case OMPD_target_simd: 13605 if (OpenMPVersion >= 50 && 13606 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) 13607 CaptureRegion = OMPD_target; 13608 break; 13609 case OMPD_teams_distribute_simd: 13610 case OMPD_target_teams_distribute_simd: 13611 if (OpenMPVersion >= 50 && 13612 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) 13613 CaptureRegion = OMPD_teams; 13614 break; 13615 case OMPD_cancel: 13616 case OMPD_parallel: 13617 case OMPD_parallel_master: 13618 case OMPD_parallel_sections: 13619 case OMPD_parallel_for: 13620 case OMPD_target: 13621 case OMPD_target_teams: 13622 case OMPD_target_teams_distribute: 13623 case OMPD_distribute_parallel_for: 13624 case OMPD_task: 13625 case OMPD_taskloop: 13626 case OMPD_master_taskloop: 13627 case OMPD_target_data: 13628 case OMPD_simd: 13629 case OMPD_for_simd: 13630 case OMPD_distribute_simd: 13631 // Do not capture if-clause expressions. 13632 break; 13633 case OMPD_threadprivate: 13634 case OMPD_allocate: 13635 case OMPD_taskyield: 13636 case OMPD_barrier: 13637 case OMPD_taskwait: 13638 case OMPD_cancellation_point: 13639 case OMPD_flush: 13640 case OMPD_depobj: 13641 case OMPD_scan: 13642 case OMPD_declare_reduction: 13643 case OMPD_declare_mapper: 13644 case OMPD_declare_simd: 13645 case OMPD_declare_variant: 13646 case OMPD_begin_declare_variant: 13647 case OMPD_end_declare_variant: 13648 case OMPD_declare_target: 13649 case OMPD_end_declare_target: 13650 case OMPD_loop: 13651 case OMPD_teams: 13652 case OMPD_tile: 13653 case OMPD_unroll: 13654 case OMPD_for: 13655 case OMPD_sections: 13656 case OMPD_section: 13657 case OMPD_single: 13658 case OMPD_master: 13659 case OMPD_masked: 13660 case OMPD_critical: 13661 case OMPD_taskgroup: 13662 case OMPD_distribute: 13663 case OMPD_ordered: 13664 case OMPD_atomic: 13665 case OMPD_teams_distribute: 13666 case OMPD_requires: 13667 case OMPD_metadirective: 13668 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 13669 case OMPD_unknown: 13670 default: 13671 llvm_unreachable("Unknown OpenMP directive"); 13672 } 13673 break; 13674 case OMPC_num_threads: 13675 switch (DKind) { 13676 case OMPD_target_parallel: 13677 case OMPD_target_parallel_for: 13678 case OMPD_target_parallel_for_simd: 13679 CaptureRegion = OMPD_target; 13680 break; 13681 case OMPD_teams_distribute_parallel_for: 13682 case OMPD_teams_distribute_parallel_for_simd: 13683 case OMPD_target_teams_distribute_parallel_for: 13684 case OMPD_target_teams_distribute_parallel_for_simd: 13685 CaptureRegion = OMPD_teams; 13686 break; 13687 case OMPD_parallel: 13688 case OMPD_parallel_master: 13689 case OMPD_parallel_sections: 13690 case OMPD_parallel_for: 13691 case OMPD_parallel_for_simd: 13692 case OMPD_distribute_parallel_for: 13693 case OMPD_distribute_parallel_for_simd: 13694 case OMPD_parallel_master_taskloop: 13695 case OMPD_parallel_master_taskloop_simd: 13696 // Do not capture num_threads-clause expressions. 13697 break; 13698 case OMPD_target_data: 13699 case OMPD_target_enter_data: 13700 case OMPD_target_exit_data: 13701 case OMPD_target_update: 13702 case OMPD_target: 13703 case OMPD_target_simd: 13704 case OMPD_target_teams: 13705 case OMPD_target_teams_distribute: 13706 case OMPD_target_teams_distribute_simd: 13707 case OMPD_cancel: 13708 case OMPD_task: 13709 case OMPD_taskloop: 13710 case OMPD_taskloop_simd: 13711 case OMPD_master_taskloop: 13712 case OMPD_master_taskloop_simd: 13713 case OMPD_threadprivate: 13714 case OMPD_allocate: 13715 case OMPD_taskyield: 13716 case OMPD_barrier: 13717 case OMPD_taskwait: 13718 case OMPD_cancellation_point: 13719 case OMPD_flush: 13720 case OMPD_depobj: 13721 case OMPD_scan: 13722 case OMPD_declare_reduction: 13723 case OMPD_declare_mapper: 13724 case OMPD_declare_simd: 13725 case OMPD_declare_variant: 13726 case OMPD_begin_declare_variant: 13727 case OMPD_end_declare_variant: 13728 case OMPD_declare_target: 13729 case OMPD_end_declare_target: 13730 case OMPD_loop: 13731 case OMPD_teams: 13732 case OMPD_simd: 13733 case OMPD_tile: 13734 case OMPD_unroll: 13735 case OMPD_for: 13736 case OMPD_for_simd: 13737 case OMPD_sections: 13738 case OMPD_section: 13739 case OMPD_single: 13740 case OMPD_master: 13741 case OMPD_masked: 13742 case OMPD_critical: 13743 case OMPD_taskgroup: 13744 case OMPD_distribute: 13745 case OMPD_ordered: 13746 case OMPD_atomic: 13747 case OMPD_distribute_simd: 13748 case OMPD_teams_distribute: 13749 case OMPD_teams_distribute_simd: 13750 case OMPD_requires: 13751 case OMPD_metadirective: 13752 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 13753 case OMPD_unknown: 13754 default: 13755 llvm_unreachable("Unknown OpenMP directive"); 13756 } 13757 break; 13758 case OMPC_num_teams: 13759 switch (DKind) { 13760 case OMPD_target_teams: 13761 case OMPD_target_teams_distribute: 13762 case OMPD_target_teams_distribute_simd: 13763 case OMPD_target_teams_distribute_parallel_for: 13764 case OMPD_target_teams_distribute_parallel_for_simd: 13765 CaptureRegion = OMPD_target; 13766 break; 13767 case OMPD_teams_distribute_parallel_for: 13768 case OMPD_teams_distribute_parallel_for_simd: 13769 case OMPD_teams: 13770 case OMPD_teams_distribute: 13771 case OMPD_teams_distribute_simd: 13772 // Do not capture num_teams-clause expressions. 13773 break; 13774 case OMPD_distribute_parallel_for: 13775 case OMPD_distribute_parallel_for_simd: 13776 case OMPD_task: 13777 case OMPD_taskloop: 13778 case OMPD_taskloop_simd: 13779 case OMPD_master_taskloop: 13780 case OMPD_master_taskloop_simd: 13781 case OMPD_parallel_master_taskloop: 13782 case OMPD_parallel_master_taskloop_simd: 13783 case OMPD_target_data: 13784 case OMPD_target_enter_data: 13785 case OMPD_target_exit_data: 13786 case OMPD_target_update: 13787 case OMPD_cancel: 13788 case OMPD_parallel: 13789 case OMPD_parallel_master: 13790 case OMPD_parallel_sections: 13791 case OMPD_parallel_for: 13792 case OMPD_parallel_for_simd: 13793 case OMPD_target: 13794 case OMPD_target_simd: 13795 case OMPD_target_parallel: 13796 case OMPD_target_parallel_for: 13797 case OMPD_target_parallel_for_simd: 13798 case OMPD_threadprivate: 13799 case OMPD_allocate: 13800 case OMPD_taskyield: 13801 case OMPD_barrier: 13802 case OMPD_taskwait: 13803 case OMPD_cancellation_point: 13804 case OMPD_flush: 13805 case OMPD_depobj: 13806 case OMPD_scan: 13807 case OMPD_declare_reduction: 13808 case OMPD_declare_mapper: 13809 case OMPD_declare_simd: 13810 case OMPD_declare_variant: 13811 case OMPD_begin_declare_variant: 13812 case OMPD_end_declare_variant: 13813 case OMPD_declare_target: 13814 case OMPD_end_declare_target: 13815 case OMPD_loop: 13816 case OMPD_simd: 13817 case OMPD_tile: 13818 case OMPD_unroll: 13819 case OMPD_for: 13820 case OMPD_for_simd: 13821 case OMPD_sections: 13822 case OMPD_section: 13823 case OMPD_single: 13824 case OMPD_master: 13825 case OMPD_masked: 13826 case OMPD_critical: 13827 case OMPD_taskgroup: 13828 case OMPD_distribute: 13829 case OMPD_ordered: 13830 case OMPD_atomic: 13831 case OMPD_distribute_simd: 13832 case OMPD_requires: 13833 case OMPD_metadirective: 13834 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 13835 case OMPD_unknown: 13836 default: 13837 llvm_unreachable("Unknown OpenMP directive"); 13838 } 13839 break; 13840 case OMPC_thread_limit: 13841 switch (DKind) { 13842 case OMPD_target_teams: 13843 case OMPD_target_teams_distribute: 13844 case OMPD_target_teams_distribute_simd: 13845 case OMPD_target_teams_distribute_parallel_for: 13846 case OMPD_target_teams_distribute_parallel_for_simd: 13847 CaptureRegion = OMPD_target; 13848 break; 13849 case OMPD_teams_distribute_parallel_for: 13850 case OMPD_teams_distribute_parallel_for_simd: 13851 case OMPD_teams: 13852 case OMPD_teams_distribute: 13853 case OMPD_teams_distribute_simd: 13854 // Do not capture thread_limit-clause expressions. 13855 break; 13856 case OMPD_distribute_parallel_for: 13857 case OMPD_distribute_parallel_for_simd: 13858 case OMPD_task: 13859 case OMPD_taskloop: 13860 case OMPD_taskloop_simd: 13861 case OMPD_master_taskloop: 13862 case OMPD_master_taskloop_simd: 13863 case OMPD_parallel_master_taskloop: 13864 case OMPD_parallel_master_taskloop_simd: 13865 case OMPD_target_data: 13866 case OMPD_target_enter_data: 13867 case OMPD_target_exit_data: 13868 case OMPD_target_update: 13869 case OMPD_cancel: 13870 case OMPD_parallel: 13871 case OMPD_parallel_master: 13872 case OMPD_parallel_sections: 13873 case OMPD_parallel_for: 13874 case OMPD_parallel_for_simd: 13875 case OMPD_target: 13876 case OMPD_target_simd: 13877 case OMPD_target_parallel: 13878 case OMPD_target_parallel_for: 13879 case OMPD_target_parallel_for_simd: 13880 case OMPD_threadprivate: 13881 case OMPD_allocate: 13882 case OMPD_taskyield: 13883 case OMPD_barrier: 13884 case OMPD_taskwait: 13885 case OMPD_cancellation_point: 13886 case OMPD_flush: 13887 case OMPD_depobj: 13888 case OMPD_scan: 13889 case OMPD_declare_reduction: 13890 case OMPD_declare_mapper: 13891 case OMPD_declare_simd: 13892 case OMPD_declare_variant: 13893 case OMPD_begin_declare_variant: 13894 case OMPD_end_declare_variant: 13895 case OMPD_declare_target: 13896 case OMPD_end_declare_target: 13897 case OMPD_loop: 13898 case OMPD_simd: 13899 case OMPD_tile: 13900 case OMPD_unroll: 13901 case OMPD_for: 13902 case OMPD_for_simd: 13903 case OMPD_sections: 13904 case OMPD_section: 13905 case OMPD_single: 13906 case OMPD_master: 13907 case OMPD_masked: 13908 case OMPD_critical: 13909 case OMPD_taskgroup: 13910 case OMPD_distribute: 13911 case OMPD_ordered: 13912 case OMPD_atomic: 13913 case OMPD_distribute_simd: 13914 case OMPD_requires: 13915 case OMPD_metadirective: 13916 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 13917 case OMPD_unknown: 13918 default: 13919 llvm_unreachable("Unknown OpenMP directive"); 13920 } 13921 break; 13922 case OMPC_schedule: 13923 switch (DKind) { 13924 case OMPD_parallel_for: 13925 case OMPD_parallel_for_simd: 13926 case OMPD_distribute_parallel_for: 13927 case OMPD_distribute_parallel_for_simd: 13928 case OMPD_teams_distribute_parallel_for: 13929 case OMPD_teams_distribute_parallel_for_simd: 13930 case OMPD_target_parallel_for: 13931 case OMPD_target_parallel_for_simd: 13932 case OMPD_target_teams_distribute_parallel_for: 13933 case OMPD_target_teams_distribute_parallel_for_simd: 13934 CaptureRegion = OMPD_parallel; 13935 break; 13936 case OMPD_for: 13937 case OMPD_for_simd: 13938 // Do not capture schedule-clause expressions. 13939 break; 13940 case OMPD_task: 13941 case OMPD_taskloop: 13942 case OMPD_taskloop_simd: 13943 case OMPD_master_taskloop: 13944 case OMPD_master_taskloop_simd: 13945 case OMPD_parallel_master_taskloop: 13946 case OMPD_parallel_master_taskloop_simd: 13947 case OMPD_target_data: 13948 case OMPD_target_enter_data: 13949 case OMPD_target_exit_data: 13950 case OMPD_target_update: 13951 case OMPD_teams: 13952 case OMPD_teams_distribute: 13953 case OMPD_teams_distribute_simd: 13954 case OMPD_target_teams_distribute: 13955 case OMPD_target_teams_distribute_simd: 13956 case OMPD_target: 13957 case OMPD_target_simd: 13958 case OMPD_target_parallel: 13959 case OMPD_cancel: 13960 case OMPD_parallel: 13961 case OMPD_parallel_master: 13962 case OMPD_parallel_sections: 13963 case OMPD_threadprivate: 13964 case OMPD_allocate: 13965 case OMPD_taskyield: 13966 case OMPD_barrier: 13967 case OMPD_taskwait: 13968 case OMPD_cancellation_point: 13969 case OMPD_flush: 13970 case OMPD_depobj: 13971 case OMPD_scan: 13972 case OMPD_declare_reduction: 13973 case OMPD_declare_mapper: 13974 case OMPD_declare_simd: 13975 case OMPD_declare_variant: 13976 case OMPD_begin_declare_variant: 13977 case OMPD_end_declare_variant: 13978 case OMPD_declare_target: 13979 case OMPD_end_declare_target: 13980 case OMPD_loop: 13981 case OMPD_simd: 13982 case OMPD_tile: 13983 case OMPD_unroll: 13984 case OMPD_sections: 13985 case OMPD_section: 13986 case OMPD_single: 13987 case OMPD_master: 13988 case OMPD_masked: 13989 case OMPD_critical: 13990 case OMPD_taskgroup: 13991 case OMPD_distribute: 13992 case OMPD_ordered: 13993 case OMPD_atomic: 13994 case OMPD_distribute_simd: 13995 case OMPD_target_teams: 13996 case OMPD_requires: 13997 case OMPD_metadirective: 13998 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 13999 case OMPD_unknown: 14000 default: 14001 llvm_unreachable("Unknown OpenMP directive"); 14002 } 14003 break; 14004 case OMPC_dist_schedule: 14005 switch (DKind) { 14006 case OMPD_teams_distribute_parallel_for: 14007 case OMPD_teams_distribute_parallel_for_simd: 14008 case OMPD_teams_distribute: 14009 case OMPD_teams_distribute_simd: 14010 case OMPD_target_teams_distribute_parallel_for: 14011 case OMPD_target_teams_distribute_parallel_for_simd: 14012 case OMPD_target_teams_distribute: 14013 case OMPD_target_teams_distribute_simd: 14014 CaptureRegion = OMPD_teams; 14015 break; 14016 case OMPD_distribute_parallel_for: 14017 case OMPD_distribute_parallel_for_simd: 14018 case OMPD_distribute: 14019 case OMPD_distribute_simd: 14020 // Do not capture dist_schedule-clause expressions. 14021 break; 14022 case OMPD_parallel_for: 14023 case OMPD_parallel_for_simd: 14024 case OMPD_target_parallel_for_simd: 14025 case OMPD_target_parallel_for: 14026 case OMPD_task: 14027 case OMPD_taskloop: 14028 case OMPD_taskloop_simd: 14029 case OMPD_master_taskloop: 14030 case OMPD_master_taskloop_simd: 14031 case OMPD_parallel_master_taskloop: 14032 case OMPD_parallel_master_taskloop_simd: 14033 case OMPD_target_data: 14034 case OMPD_target_enter_data: 14035 case OMPD_target_exit_data: 14036 case OMPD_target_update: 14037 case OMPD_teams: 14038 case OMPD_target: 14039 case OMPD_target_simd: 14040 case OMPD_target_parallel: 14041 case OMPD_cancel: 14042 case OMPD_parallel: 14043 case OMPD_parallel_master: 14044 case OMPD_parallel_sections: 14045 case OMPD_threadprivate: 14046 case OMPD_allocate: 14047 case OMPD_taskyield: 14048 case OMPD_barrier: 14049 case OMPD_taskwait: 14050 case OMPD_cancellation_point: 14051 case OMPD_flush: 14052 case OMPD_depobj: 14053 case OMPD_scan: 14054 case OMPD_declare_reduction: 14055 case OMPD_declare_mapper: 14056 case OMPD_declare_simd: 14057 case OMPD_declare_variant: 14058 case OMPD_begin_declare_variant: 14059 case OMPD_end_declare_variant: 14060 case OMPD_declare_target: 14061 case OMPD_end_declare_target: 14062 case OMPD_loop: 14063 case OMPD_simd: 14064 case OMPD_tile: 14065 case OMPD_unroll: 14066 case OMPD_for: 14067 case OMPD_for_simd: 14068 case OMPD_sections: 14069 case OMPD_section: 14070 case OMPD_single: 14071 case OMPD_master: 14072 case OMPD_masked: 14073 case OMPD_critical: 14074 case OMPD_taskgroup: 14075 case OMPD_ordered: 14076 case OMPD_atomic: 14077 case OMPD_target_teams: 14078 case OMPD_requires: 14079 case OMPD_metadirective: 14080 llvm_unreachable("Unexpected OpenMP directive with dist_schedule clause"); 14081 case OMPD_unknown: 14082 default: 14083 llvm_unreachable("Unknown OpenMP directive"); 14084 } 14085 break; 14086 case OMPC_device: 14087 switch (DKind) { 14088 case OMPD_target_update: 14089 case OMPD_target_enter_data: 14090 case OMPD_target_exit_data: 14091 case OMPD_target: 14092 case OMPD_target_simd: 14093 case OMPD_target_teams: 14094 case OMPD_target_parallel: 14095 case OMPD_target_teams_distribute: 14096 case OMPD_target_teams_distribute_simd: 14097 case OMPD_target_parallel_for: 14098 case OMPD_target_parallel_for_simd: 14099 case OMPD_target_teams_distribute_parallel_for: 14100 case OMPD_target_teams_distribute_parallel_for_simd: 14101 case OMPD_dispatch: 14102 CaptureRegion = OMPD_task; 14103 break; 14104 case OMPD_target_data: 14105 case OMPD_interop: 14106 // Do not capture device-clause expressions. 14107 break; 14108 case OMPD_teams_distribute_parallel_for: 14109 case OMPD_teams_distribute_parallel_for_simd: 14110 case OMPD_teams: 14111 case OMPD_teams_distribute: 14112 case OMPD_teams_distribute_simd: 14113 case OMPD_distribute_parallel_for: 14114 case OMPD_distribute_parallel_for_simd: 14115 case OMPD_task: 14116 case OMPD_taskloop: 14117 case OMPD_taskloop_simd: 14118 case OMPD_master_taskloop: 14119 case OMPD_master_taskloop_simd: 14120 case OMPD_parallel_master_taskloop: 14121 case OMPD_parallel_master_taskloop_simd: 14122 case OMPD_cancel: 14123 case OMPD_parallel: 14124 case OMPD_parallel_master: 14125 case OMPD_parallel_sections: 14126 case OMPD_parallel_for: 14127 case OMPD_parallel_for_simd: 14128 case OMPD_threadprivate: 14129 case OMPD_allocate: 14130 case OMPD_taskyield: 14131 case OMPD_barrier: 14132 case OMPD_taskwait: 14133 case OMPD_cancellation_point: 14134 case OMPD_flush: 14135 case OMPD_depobj: 14136 case OMPD_scan: 14137 case OMPD_declare_reduction: 14138 case OMPD_declare_mapper: 14139 case OMPD_declare_simd: 14140 case OMPD_declare_variant: 14141 case OMPD_begin_declare_variant: 14142 case OMPD_end_declare_variant: 14143 case OMPD_declare_target: 14144 case OMPD_end_declare_target: 14145 case OMPD_loop: 14146 case OMPD_simd: 14147 case OMPD_tile: 14148 case OMPD_unroll: 14149 case OMPD_for: 14150 case OMPD_for_simd: 14151 case OMPD_sections: 14152 case OMPD_section: 14153 case OMPD_single: 14154 case OMPD_master: 14155 case OMPD_masked: 14156 case OMPD_critical: 14157 case OMPD_taskgroup: 14158 case OMPD_distribute: 14159 case OMPD_ordered: 14160 case OMPD_atomic: 14161 case OMPD_distribute_simd: 14162 case OMPD_requires: 14163 case OMPD_metadirective: 14164 llvm_unreachable("Unexpected OpenMP directive with device-clause"); 14165 case OMPD_unknown: 14166 default: 14167 llvm_unreachable("Unknown OpenMP directive"); 14168 } 14169 break; 14170 case OMPC_grainsize: 14171 case OMPC_num_tasks: 14172 case OMPC_final: 14173 case OMPC_priority: 14174 switch (DKind) { 14175 case OMPD_task: 14176 case OMPD_taskloop: 14177 case OMPD_taskloop_simd: 14178 case OMPD_master_taskloop: 14179 case OMPD_master_taskloop_simd: 14180 break; 14181 case OMPD_parallel_master_taskloop: 14182 case OMPD_parallel_master_taskloop_simd: 14183 CaptureRegion = OMPD_parallel; 14184 break; 14185 case OMPD_target_update: 14186 case OMPD_target_enter_data: 14187 case OMPD_target_exit_data: 14188 case OMPD_target: 14189 case OMPD_target_simd: 14190 case OMPD_target_teams: 14191 case OMPD_target_parallel: 14192 case OMPD_target_teams_distribute: 14193 case OMPD_target_teams_distribute_simd: 14194 case OMPD_target_parallel_for: 14195 case OMPD_target_parallel_for_simd: 14196 case OMPD_target_teams_distribute_parallel_for: 14197 case OMPD_target_teams_distribute_parallel_for_simd: 14198 case OMPD_target_data: 14199 case OMPD_teams_distribute_parallel_for: 14200 case OMPD_teams_distribute_parallel_for_simd: 14201 case OMPD_teams: 14202 case OMPD_teams_distribute: 14203 case OMPD_teams_distribute_simd: 14204 case OMPD_distribute_parallel_for: 14205 case OMPD_distribute_parallel_for_simd: 14206 case OMPD_cancel: 14207 case OMPD_parallel: 14208 case OMPD_parallel_master: 14209 case OMPD_parallel_sections: 14210 case OMPD_parallel_for: 14211 case OMPD_parallel_for_simd: 14212 case OMPD_threadprivate: 14213 case OMPD_allocate: 14214 case OMPD_taskyield: 14215 case OMPD_barrier: 14216 case OMPD_taskwait: 14217 case OMPD_cancellation_point: 14218 case OMPD_flush: 14219 case OMPD_depobj: 14220 case OMPD_scan: 14221 case OMPD_declare_reduction: 14222 case OMPD_declare_mapper: 14223 case OMPD_declare_simd: 14224 case OMPD_declare_variant: 14225 case OMPD_begin_declare_variant: 14226 case OMPD_end_declare_variant: 14227 case OMPD_declare_target: 14228 case OMPD_end_declare_target: 14229 case OMPD_loop: 14230 case OMPD_simd: 14231 case OMPD_tile: 14232 case OMPD_unroll: 14233 case OMPD_for: 14234 case OMPD_for_simd: 14235 case OMPD_sections: 14236 case OMPD_section: 14237 case OMPD_single: 14238 case OMPD_master: 14239 case OMPD_masked: 14240 case OMPD_critical: 14241 case OMPD_taskgroup: 14242 case OMPD_distribute: 14243 case OMPD_ordered: 14244 case OMPD_atomic: 14245 case OMPD_distribute_simd: 14246 case OMPD_requires: 14247 case OMPD_metadirective: 14248 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause"); 14249 case OMPD_unknown: 14250 default: 14251 llvm_unreachable("Unknown OpenMP directive"); 14252 } 14253 break; 14254 case OMPC_novariants: 14255 case OMPC_nocontext: 14256 switch (DKind) { 14257 case OMPD_dispatch: 14258 CaptureRegion = OMPD_task; 14259 break; 14260 default: 14261 llvm_unreachable("Unexpected OpenMP directive"); 14262 } 14263 break; 14264 case OMPC_filter: 14265 // Do not capture filter-clause expressions. 14266 break; 14267 case OMPC_when: 14268 if (DKind == OMPD_metadirective) { 14269 CaptureRegion = OMPD_metadirective; 14270 } else if (DKind == OMPD_unknown) { 14271 llvm_unreachable("Unknown OpenMP directive"); 14272 } else { 14273 llvm_unreachable("Unexpected OpenMP directive with when clause"); 14274 } 14275 break; 14276 case OMPC_firstprivate: 14277 case OMPC_lastprivate: 14278 case OMPC_reduction: 14279 case OMPC_task_reduction: 14280 case OMPC_in_reduction: 14281 case OMPC_linear: 14282 case OMPC_default: 14283 case OMPC_proc_bind: 14284 case OMPC_safelen: 14285 case OMPC_simdlen: 14286 case OMPC_sizes: 14287 case OMPC_allocator: 14288 case OMPC_collapse: 14289 case OMPC_private: 14290 case OMPC_shared: 14291 case OMPC_aligned: 14292 case OMPC_copyin: 14293 case OMPC_copyprivate: 14294 case OMPC_ordered: 14295 case OMPC_nowait: 14296 case OMPC_untied: 14297 case OMPC_mergeable: 14298 case OMPC_threadprivate: 14299 case OMPC_allocate: 14300 case OMPC_flush: 14301 case OMPC_depobj: 14302 case OMPC_read: 14303 case OMPC_write: 14304 case OMPC_update: 14305 case OMPC_capture: 14306 case OMPC_seq_cst: 14307 case OMPC_acq_rel: 14308 case OMPC_acquire: 14309 case OMPC_release: 14310 case OMPC_relaxed: 14311 case OMPC_depend: 14312 case OMPC_threads: 14313 case OMPC_simd: 14314 case OMPC_map: 14315 case OMPC_nogroup: 14316 case OMPC_hint: 14317 case OMPC_defaultmap: 14318 case OMPC_unknown: 14319 case OMPC_uniform: 14320 case OMPC_to: 14321 case OMPC_from: 14322 case OMPC_use_device_ptr: 14323 case OMPC_use_device_addr: 14324 case OMPC_is_device_ptr: 14325 case OMPC_unified_address: 14326 case OMPC_unified_shared_memory: 14327 case OMPC_reverse_offload: 14328 case OMPC_dynamic_allocators: 14329 case OMPC_atomic_default_mem_order: 14330 case OMPC_device_type: 14331 case OMPC_match: 14332 case OMPC_nontemporal: 14333 case OMPC_order: 14334 case OMPC_destroy: 14335 case OMPC_detach: 14336 case OMPC_inclusive: 14337 case OMPC_exclusive: 14338 case OMPC_uses_allocators: 14339 case OMPC_affinity: 14340 case OMPC_bind: 14341 default: 14342 llvm_unreachable("Unexpected OpenMP clause."); 14343 } 14344 return CaptureRegion; 14345 } 14346 14347 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 14348 Expr *Condition, SourceLocation StartLoc, 14349 SourceLocation LParenLoc, 14350 SourceLocation NameModifierLoc, 14351 SourceLocation ColonLoc, 14352 SourceLocation EndLoc) { 14353 Expr *ValExpr = Condition; 14354 Stmt *HelperValStmt = nullptr; 14355 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 14356 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 14357 !Condition->isInstantiationDependent() && 14358 !Condition->containsUnexpandedParameterPack()) { 14359 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 14360 if (Val.isInvalid()) 14361 return nullptr; 14362 14363 ValExpr = Val.get(); 14364 14365 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 14366 CaptureRegion = getOpenMPCaptureRegionForClause( 14367 DKind, OMPC_if, LangOpts.OpenMP, NameModifier); 14368 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 14369 ValExpr = MakeFullExpr(ValExpr).get(); 14370 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14371 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 14372 HelperValStmt = buildPreInits(Context, Captures); 14373 } 14374 } 14375 14376 return new (Context) 14377 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 14378 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 14379 } 14380 14381 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 14382 SourceLocation StartLoc, 14383 SourceLocation LParenLoc, 14384 SourceLocation EndLoc) { 14385 Expr *ValExpr = Condition; 14386 Stmt *HelperValStmt = nullptr; 14387 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 14388 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 14389 !Condition->isInstantiationDependent() && 14390 !Condition->containsUnexpandedParameterPack()) { 14391 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 14392 if (Val.isInvalid()) 14393 return nullptr; 14394 14395 ValExpr = MakeFullExpr(Val.get()).get(); 14396 14397 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 14398 CaptureRegion = 14399 getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP); 14400 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 14401 ValExpr = MakeFullExpr(ValExpr).get(); 14402 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14403 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 14404 HelperValStmt = buildPreInits(Context, Captures); 14405 } 14406 } 14407 14408 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion, 14409 StartLoc, LParenLoc, EndLoc); 14410 } 14411 14412 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 14413 Expr *Op) { 14414 if (!Op) 14415 return ExprError(); 14416 14417 class IntConvertDiagnoser : public ICEConvertDiagnoser { 14418 public: 14419 IntConvertDiagnoser() 14420 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 14421 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14422 QualType T) override { 14423 return S.Diag(Loc, diag::err_omp_not_integral) << T; 14424 } 14425 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 14426 QualType T) override { 14427 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 14428 } 14429 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 14430 QualType T, 14431 QualType ConvTy) override { 14432 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 14433 } 14434 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 14435 QualType ConvTy) override { 14436 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 14437 << ConvTy->isEnumeralType() << ConvTy; 14438 } 14439 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 14440 QualType T) override { 14441 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 14442 } 14443 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 14444 QualType ConvTy) override { 14445 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 14446 << ConvTy->isEnumeralType() << ConvTy; 14447 } 14448 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 14449 QualType) override { 14450 llvm_unreachable("conversion functions are permitted"); 14451 } 14452 } ConvertDiagnoser; 14453 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 14454 } 14455 14456 static bool 14457 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind, 14458 bool StrictlyPositive, bool BuildCapture = false, 14459 OpenMPDirectiveKind DKind = OMPD_unknown, 14460 OpenMPDirectiveKind *CaptureRegion = nullptr, 14461 Stmt **HelperValStmt = nullptr) { 14462 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 14463 !ValExpr->isInstantiationDependent()) { 14464 SourceLocation Loc = ValExpr->getExprLoc(); 14465 ExprResult Value = 14466 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 14467 if (Value.isInvalid()) 14468 return false; 14469 14470 ValExpr = Value.get(); 14471 // The expression must evaluate to a non-negative integer value. 14472 if (Optional<llvm::APSInt> Result = 14473 ValExpr->getIntegerConstantExpr(SemaRef.Context)) { 14474 if (Result->isSigned() && 14475 !((!StrictlyPositive && Result->isNonNegative()) || 14476 (StrictlyPositive && Result->isStrictlyPositive()))) { 14477 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 14478 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 14479 << ValExpr->getSourceRange(); 14480 return false; 14481 } 14482 } 14483 if (!BuildCapture) 14484 return true; 14485 *CaptureRegion = 14486 getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP); 14487 if (*CaptureRegion != OMPD_unknown && 14488 !SemaRef.CurContext->isDependentContext()) { 14489 ValExpr = SemaRef.MakeFullExpr(ValExpr).get(); 14490 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14491 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get(); 14492 *HelperValStmt = buildPreInits(SemaRef.Context, Captures); 14493 } 14494 } 14495 return true; 14496 } 14497 14498 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 14499 SourceLocation StartLoc, 14500 SourceLocation LParenLoc, 14501 SourceLocation EndLoc) { 14502 Expr *ValExpr = NumThreads; 14503 Stmt *HelperValStmt = nullptr; 14504 14505 // OpenMP [2.5, Restrictions] 14506 // The num_threads expression must evaluate to a positive integer value. 14507 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 14508 /*StrictlyPositive=*/true)) 14509 return nullptr; 14510 14511 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 14512 OpenMPDirectiveKind CaptureRegion = 14513 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP); 14514 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 14515 ValExpr = MakeFullExpr(ValExpr).get(); 14516 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14517 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 14518 HelperValStmt = buildPreInits(Context, Captures); 14519 } 14520 14521 return new (Context) OMPNumThreadsClause( 14522 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 14523 } 14524 14525 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 14526 OpenMPClauseKind CKind, 14527 bool StrictlyPositive, 14528 bool SuppressExprDiags) { 14529 if (!E) 14530 return ExprError(); 14531 if (E->isValueDependent() || E->isTypeDependent() || 14532 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 14533 return E; 14534 14535 llvm::APSInt Result; 14536 ExprResult ICE; 14537 if (SuppressExprDiags) { 14538 // Use a custom diagnoser that suppresses 'note' diagnostics about the 14539 // expression. 14540 struct SuppressedDiagnoser : public Sema::VerifyICEDiagnoser { 14541 SuppressedDiagnoser() : VerifyICEDiagnoser(/*Suppress=*/true) {} 14542 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 14543 SourceLocation Loc) override { 14544 llvm_unreachable("Diagnostic suppressed"); 14545 } 14546 } Diagnoser; 14547 ICE = VerifyIntegerConstantExpression(E, &Result, Diagnoser, AllowFold); 14548 } else { 14549 ICE = VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold); 14550 } 14551 if (ICE.isInvalid()) 14552 return ExprError(); 14553 14554 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 14555 (!StrictlyPositive && !Result.isNonNegative())) { 14556 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 14557 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 14558 << E->getSourceRange(); 14559 return ExprError(); 14560 } 14561 if ((CKind == OMPC_aligned || CKind == OMPC_align) && !Result.isPowerOf2()) { 14562 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 14563 << E->getSourceRange(); 14564 return ExprError(); 14565 } 14566 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 14567 DSAStack->setAssociatedLoops(Result.getExtValue()); 14568 else if (CKind == OMPC_ordered) 14569 DSAStack->setAssociatedLoops(Result.getExtValue()); 14570 return ICE; 14571 } 14572 14573 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 14574 SourceLocation LParenLoc, 14575 SourceLocation EndLoc) { 14576 // OpenMP [2.8.1, simd construct, Description] 14577 // The parameter of the safelen clause must be a constant 14578 // positive integer expression. 14579 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 14580 if (Safelen.isInvalid()) 14581 return nullptr; 14582 return new (Context) 14583 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 14584 } 14585 14586 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 14587 SourceLocation LParenLoc, 14588 SourceLocation EndLoc) { 14589 // OpenMP [2.8.1, simd construct, Description] 14590 // The parameter of the simdlen clause must be a constant 14591 // positive integer expression. 14592 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 14593 if (Simdlen.isInvalid()) 14594 return nullptr; 14595 return new (Context) 14596 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 14597 } 14598 14599 /// Tries to find omp_allocator_handle_t type. 14600 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc, 14601 DSAStackTy *Stack) { 14602 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT(); 14603 if (!OMPAllocatorHandleT.isNull()) 14604 return true; 14605 // Build the predefined allocator expressions. 14606 bool ErrorFound = false; 14607 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 14608 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 14609 StringRef Allocator = 14610 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind); 14611 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator); 14612 auto *VD = dyn_cast_or_null<ValueDecl>( 14613 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName)); 14614 if (!VD) { 14615 ErrorFound = true; 14616 break; 14617 } 14618 QualType AllocatorType = 14619 VD->getType().getNonLValueExprType(S.getASTContext()); 14620 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc); 14621 if (!Res.isUsable()) { 14622 ErrorFound = true; 14623 break; 14624 } 14625 if (OMPAllocatorHandleT.isNull()) 14626 OMPAllocatorHandleT = AllocatorType; 14627 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) { 14628 ErrorFound = true; 14629 break; 14630 } 14631 Stack->setAllocator(AllocatorKind, Res.get()); 14632 } 14633 if (ErrorFound) { 14634 S.Diag(Loc, diag::err_omp_implied_type_not_found) 14635 << "omp_allocator_handle_t"; 14636 return false; 14637 } 14638 OMPAllocatorHandleT.addConst(); 14639 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT); 14640 return true; 14641 } 14642 14643 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc, 14644 SourceLocation LParenLoc, 14645 SourceLocation EndLoc) { 14646 // OpenMP [2.11.3, allocate Directive, Description] 14647 // allocator is an expression of omp_allocator_handle_t type. 14648 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack)) 14649 return nullptr; 14650 14651 ExprResult Allocator = DefaultLvalueConversion(A); 14652 if (Allocator.isInvalid()) 14653 return nullptr; 14654 Allocator = PerformImplicitConversion(Allocator.get(), 14655 DSAStack->getOMPAllocatorHandleT(), 14656 Sema::AA_Initializing, 14657 /*AllowExplicit=*/true); 14658 if (Allocator.isInvalid()) 14659 return nullptr; 14660 return new (Context) 14661 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc); 14662 } 14663 14664 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 14665 SourceLocation StartLoc, 14666 SourceLocation LParenLoc, 14667 SourceLocation EndLoc) { 14668 // OpenMP [2.7.1, loop construct, Description] 14669 // OpenMP [2.8.1, simd construct, Description] 14670 // OpenMP [2.9.6, distribute construct, Description] 14671 // The parameter of the collapse clause must be a constant 14672 // positive integer expression. 14673 ExprResult NumForLoopsResult = 14674 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 14675 if (NumForLoopsResult.isInvalid()) 14676 return nullptr; 14677 return new (Context) 14678 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 14679 } 14680 14681 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 14682 SourceLocation EndLoc, 14683 SourceLocation LParenLoc, 14684 Expr *NumForLoops) { 14685 // OpenMP [2.7.1, loop construct, Description] 14686 // OpenMP [2.8.1, simd construct, Description] 14687 // OpenMP [2.9.6, distribute construct, Description] 14688 // The parameter of the ordered clause must be a constant 14689 // positive integer expression if any. 14690 if (NumForLoops && LParenLoc.isValid()) { 14691 ExprResult NumForLoopsResult = 14692 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 14693 if (NumForLoopsResult.isInvalid()) 14694 return nullptr; 14695 NumForLoops = NumForLoopsResult.get(); 14696 } else { 14697 NumForLoops = nullptr; 14698 } 14699 auto *Clause = OMPOrderedClause::Create( 14700 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0, 14701 StartLoc, LParenLoc, EndLoc); 14702 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause); 14703 return Clause; 14704 } 14705 14706 OMPClause *Sema::ActOnOpenMPSimpleClause( 14707 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 14708 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 14709 OMPClause *Res = nullptr; 14710 switch (Kind) { 14711 case OMPC_default: 14712 Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument), 14713 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 14714 break; 14715 case OMPC_proc_bind: 14716 Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument), 14717 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 14718 break; 14719 case OMPC_atomic_default_mem_order: 14720 Res = ActOnOpenMPAtomicDefaultMemOrderClause( 14721 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument), 14722 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 14723 break; 14724 case OMPC_order: 14725 Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument), 14726 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 14727 break; 14728 case OMPC_update: 14729 Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument), 14730 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 14731 break; 14732 case OMPC_bind: 14733 Res = ActOnOpenMPBindClause(static_cast<OpenMPBindClauseKind>(Argument), 14734 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 14735 break; 14736 case OMPC_if: 14737 case OMPC_final: 14738 case OMPC_num_threads: 14739 case OMPC_safelen: 14740 case OMPC_simdlen: 14741 case OMPC_sizes: 14742 case OMPC_allocator: 14743 case OMPC_collapse: 14744 case OMPC_schedule: 14745 case OMPC_private: 14746 case OMPC_firstprivate: 14747 case OMPC_lastprivate: 14748 case OMPC_shared: 14749 case OMPC_reduction: 14750 case OMPC_task_reduction: 14751 case OMPC_in_reduction: 14752 case OMPC_linear: 14753 case OMPC_aligned: 14754 case OMPC_copyin: 14755 case OMPC_copyprivate: 14756 case OMPC_ordered: 14757 case OMPC_nowait: 14758 case OMPC_untied: 14759 case OMPC_mergeable: 14760 case OMPC_threadprivate: 14761 case OMPC_allocate: 14762 case OMPC_flush: 14763 case OMPC_depobj: 14764 case OMPC_read: 14765 case OMPC_write: 14766 case OMPC_capture: 14767 case OMPC_seq_cst: 14768 case OMPC_acq_rel: 14769 case OMPC_acquire: 14770 case OMPC_release: 14771 case OMPC_relaxed: 14772 case OMPC_depend: 14773 case OMPC_device: 14774 case OMPC_threads: 14775 case OMPC_simd: 14776 case OMPC_map: 14777 case OMPC_num_teams: 14778 case OMPC_thread_limit: 14779 case OMPC_priority: 14780 case OMPC_grainsize: 14781 case OMPC_nogroup: 14782 case OMPC_num_tasks: 14783 case OMPC_hint: 14784 case OMPC_dist_schedule: 14785 case OMPC_defaultmap: 14786 case OMPC_unknown: 14787 case OMPC_uniform: 14788 case OMPC_to: 14789 case OMPC_from: 14790 case OMPC_use_device_ptr: 14791 case OMPC_use_device_addr: 14792 case OMPC_is_device_ptr: 14793 case OMPC_unified_address: 14794 case OMPC_unified_shared_memory: 14795 case OMPC_reverse_offload: 14796 case OMPC_dynamic_allocators: 14797 case OMPC_device_type: 14798 case OMPC_match: 14799 case OMPC_nontemporal: 14800 case OMPC_destroy: 14801 case OMPC_novariants: 14802 case OMPC_nocontext: 14803 case OMPC_detach: 14804 case OMPC_inclusive: 14805 case OMPC_exclusive: 14806 case OMPC_uses_allocators: 14807 case OMPC_affinity: 14808 case OMPC_when: 14809 default: 14810 llvm_unreachable("Clause is not allowed."); 14811 } 14812 return Res; 14813 } 14814 14815 static std::string 14816 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 14817 ArrayRef<unsigned> Exclude = llvm::None) { 14818 SmallString<256> Buffer; 14819 llvm::raw_svector_ostream Out(Buffer); 14820 unsigned Skipped = Exclude.size(); 14821 auto S = Exclude.begin(), E = Exclude.end(); 14822 for (unsigned I = First; I < Last; ++I) { 14823 if (std::find(S, E, I) != E) { 14824 --Skipped; 14825 continue; 14826 } 14827 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'"; 14828 if (I + Skipped + 2 == Last) 14829 Out << " or "; 14830 else if (I + Skipped + 1 != Last) 14831 Out << ", "; 14832 } 14833 return std::string(Out.str()); 14834 } 14835 14836 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind, 14837 SourceLocation KindKwLoc, 14838 SourceLocation StartLoc, 14839 SourceLocation LParenLoc, 14840 SourceLocation EndLoc) { 14841 if (Kind == OMP_DEFAULT_unknown) { 14842 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 14843 << getListOfPossibleValues(OMPC_default, /*First=*/0, 14844 /*Last=*/unsigned(OMP_DEFAULT_unknown)) 14845 << getOpenMPClauseName(OMPC_default); 14846 return nullptr; 14847 } 14848 14849 switch (Kind) { 14850 case OMP_DEFAULT_none: 14851 DSAStack->setDefaultDSANone(KindKwLoc); 14852 break; 14853 case OMP_DEFAULT_shared: 14854 DSAStack->setDefaultDSAShared(KindKwLoc); 14855 break; 14856 case OMP_DEFAULT_firstprivate: 14857 DSAStack->setDefaultDSAFirstPrivate(KindKwLoc); 14858 break; 14859 default: 14860 llvm_unreachable("DSA unexpected in OpenMP default clause"); 14861 } 14862 14863 return new (Context) 14864 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 14865 } 14866 14867 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind, 14868 SourceLocation KindKwLoc, 14869 SourceLocation StartLoc, 14870 SourceLocation LParenLoc, 14871 SourceLocation EndLoc) { 14872 if (Kind == OMP_PROC_BIND_unknown) { 14873 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 14874 << getListOfPossibleValues(OMPC_proc_bind, 14875 /*First=*/unsigned(OMP_PROC_BIND_master), 14876 /*Last=*/ 14877 unsigned(LangOpts.OpenMP > 50 14878 ? OMP_PROC_BIND_primary 14879 : OMP_PROC_BIND_spread) + 14880 1) 14881 << getOpenMPClauseName(OMPC_proc_bind); 14882 return nullptr; 14883 } 14884 if (Kind == OMP_PROC_BIND_primary && LangOpts.OpenMP < 51) 14885 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 14886 << getListOfPossibleValues(OMPC_proc_bind, 14887 /*First=*/unsigned(OMP_PROC_BIND_master), 14888 /*Last=*/ 14889 unsigned(OMP_PROC_BIND_spread) + 1) 14890 << getOpenMPClauseName(OMPC_proc_bind); 14891 return new (Context) 14892 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 14893 } 14894 14895 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause( 14896 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc, 14897 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 14898 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) { 14899 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 14900 << getListOfPossibleValues( 14901 OMPC_atomic_default_mem_order, /*First=*/0, 14902 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) 14903 << getOpenMPClauseName(OMPC_atomic_default_mem_order); 14904 return nullptr; 14905 } 14906 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc, 14907 LParenLoc, EndLoc); 14908 } 14909 14910 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, 14911 SourceLocation KindKwLoc, 14912 SourceLocation StartLoc, 14913 SourceLocation LParenLoc, 14914 SourceLocation EndLoc) { 14915 if (Kind == OMPC_ORDER_unknown) { 14916 static_assert(OMPC_ORDER_unknown > 0, 14917 "OMPC_ORDER_unknown not greater than 0"); 14918 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 14919 << getListOfPossibleValues(OMPC_order, /*First=*/0, 14920 /*Last=*/OMPC_ORDER_unknown) 14921 << getOpenMPClauseName(OMPC_order); 14922 return nullptr; 14923 } 14924 return new (Context) 14925 OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 14926 } 14927 14928 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, 14929 SourceLocation KindKwLoc, 14930 SourceLocation StartLoc, 14931 SourceLocation LParenLoc, 14932 SourceLocation EndLoc) { 14933 if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source || 14934 Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) { 14935 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink, 14936 OMPC_DEPEND_depobj}; 14937 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 14938 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 14939 /*Last=*/OMPC_DEPEND_unknown, Except) 14940 << getOpenMPClauseName(OMPC_update); 14941 return nullptr; 14942 } 14943 return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind, 14944 EndLoc); 14945 } 14946 14947 OMPClause *Sema::ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs, 14948 SourceLocation StartLoc, 14949 SourceLocation LParenLoc, 14950 SourceLocation EndLoc) { 14951 for (Expr *SizeExpr : SizeExprs) { 14952 ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause( 14953 SizeExpr, OMPC_sizes, /*StrictlyPositive=*/true); 14954 if (!NumForLoopsResult.isUsable()) 14955 return nullptr; 14956 } 14957 14958 DSAStack->setAssociatedLoops(SizeExprs.size()); 14959 return OMPSizesClause::Create(Context, StartLoc, LParenLoc, EndLoc, 14960 SizeExprs); 14961 } 14962 14963 OMPClause *Sema::ActOnOpenMPFullClause(SourceLocation StartLoc, 14964 SourceLocation EndLoc) { 14965 return OMPFullClause::Create(Context, StartLoc, EndLoc); 14966 } 14967 14968 OMPClause *Sema::ActOnOpenMPPartialClause(Expr *FactorExpr, 14969 SourceLocation StartLoc, 14970 SourceLocation LParenLoc, 14971 SourceLocation EndLoc) { 14972 if (FactorExpr) { 14973 // If an argument is specified, it must be a constant (or an unevaluated 14974 // template expression). 14975 ExprResult FactorResult = VerifyPositiveIntegerConstantInClause( 14976 FactorExpr, OMPC_partial, /*StrictlyPositive=*/true); 14977 if (FactorResult.isInvalid()) 14978 return nullptr; 14979 FactorExpr = FactorResult.get(); 14980 } 14981 14982 return OMPPartialClause::Create(Context, StartLoc, LParenLoc, EndLoc, 14983 FactorExpr); 14984 } 14985 14986 OMPClause *Sema::ActOnOpenMPAlignClause(Expr *A, SourceLocation StartLoc, 14987 SourceLocation LParenLoc, 14988 SourceLocation EndLoc) { 14989 ExprResult AlignVal; 14990 AlignVal = VerifyPositiveIntegerConstantInClause(A, OMPC_align); 14991 if (AlignVal.isInvalid()) 14992 return nullptr; 14993 return OMPAlignClause::Create(Context, AlignVal.get(), StartLoc, LParenLoc, 14994 EndLoc); 14995 } 14996 14997 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 14998 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 14999 SourceLocation StartLoc, SourceLocation LParenLoc, 15000 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 15001 SourceLocation EndLoc) { 15002 OMPClause *Res = nullptr; 15003 switch (Kind) { 15004 case OMPC_schedule: 15005 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 15006 assert(Argument.size() == NumberOfElements && 15007 ArgumentLoc.size() == NumberOfElements); 15008 Res = ActOnOpenMPScheduleClause( 15009 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 15010 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 15011 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 15012 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 15013 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 15014 break; 15015 case OMPC_if: 15016 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 15017 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 15018 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 15019 DelimLoc, EndLoc); 15020 break; 15021 case OMPC_dist_schedule: 15022 Res = ActOnOpenMPDistScheduleClause( 15023 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 15024 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 15025 break; 15026 case OMPC_defaultmap: 15027 enum { Modifier, DefaultmapKind }; 15028 Res = ActOnOpenMPDefaultmapClause( 15029 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 15030 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 15031 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 15032 EndLoc); 15033 break; 15034 case OMPC_device: 15035 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 15036 Res = ActOnOpenMPDeviceClause( 15037 static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr, 15038 StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc); 15039 break; 15040 case OMPC_final: 15041 case OMPC_num_threads: 15042 case OMPC_safelen: 15043 case OMPC_simdlen: 15044 case OMPC_sizes: 15045 case OMPC_allocator: 15046 case OMPC_collapse: 15047 case OMPC_default: 15048 case OMPC_proc_bind: 15049 case OMPC_private: 15050 case OMPC_firstprivate: 15051 case OMPC_lastprivate: 15052 case OMPC_shared: 15053 case OMPC_reduction: 15054 case OMPC_task_reduction: 15055 case OMPC_in_reduction: 15056 case OMPC_linear: 15057 case OMPC_aligned: 15058 case OMPC_copyin: 15059 case OMPC_copyprivate: 15060 case OMPC_ordered: 15061 case OMPC_nowait: 15062 case OMPC_untied: 15063 case OMPC_mergeable: 15064 case OMPC_threadprivate: 15065 case OMPC_allocate: 15066 case OMPC_flush: 15067 case OMPC_depobj: 15068 case OMPC_read: 15069 case OMPC_write: 15070 case OMPC_update: 15071 case OMPC_capture: 15072 case OMPC_seq_cst: 15073 case OMPC_acq_rel: 15074 case OMPC_acquire: 15075 case OMPC_release: 15076 case OMPC_relaxed: 15077 case OMPC_depend: 15078 case OMPC_threads: 15079 case OMPC_simd: 15080 case OMPC_map: 15081 case OMPC_num_teams: 15082 case OMPC_thread_limit: 15083 case OMPC_priority: 15084 case OMPC_grainsize: 15085 case OMPC_nogroup: 15086 case OMPC_num_tasks: 15087 case OMPC_hint: 15088 case OMPC_unknown: 15089 case OMPC_uniform: 15090 case OMPC_to: 15091 case OMPC_from: 15092 case OMPC_use_device_ptr: 15093 case OMPC_use_device_addr: 15094 case OMPC_is_device_ptr: 15095 case OMPC_unified_address: 15096 case OMPC_unified_shared_memory: 15097 case OMPC_reverse_offload: 15098 case OMPC_dynamic_allocators: 15099 case OMPC_atomic_default_mem_order: 15100 case OMPC_device_type: 15101 case OMPC_match: 15102 case OMPC_nontemporal: 15103 case OMPC_order: 15104 case OMPC_destroy: 15105 case OMPC_novariants: 15106 case OMPC_nocontext: 15107 case OMPC_detach: 15108 case OMPC_inclusive: 15109 case OMPC_exclusive: 15110 case OMPC_uses_allocators: 15111 case OMPC_affinity: 15112 case OMPC_when: 15113 case OMPC_bind: 15114 default: 15115 llvm_unreachable("Clause is not allowed."); 15116 } 15117 return Res; 15118 } 15119 15120 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 15121 OpenMPScheduleClauseModifier M2, 15122 SourceLocation M1Loc, SourceLocation M2Loc) { 15123 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 15124 SmallVector<unsigned, 2> Excluded; 15125 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 15126 Excluded.push_back(M2); 15127 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 15128 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 15129 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 15130 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 15131 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 15132 << getListOfPossibleValues(OMPC_schedule, 15133 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 15134 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 15135 Excluded) 15136 << getOpenMPClauseName(OMPC_schedule); 15137 return true; 15138 } 15139 return false; 15140 } 15141 15142 OMPClause *Sema::ActOnOpenMPScheduleClause( 15143 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 15144 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 15145 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 15146 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 15147 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 15148 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 15149 return nullptr; 15150 // OpenMP, 2.7.1, Loop Construct, Restrictions 15151 // Either the monotonic modifier or the nonmonotonic modifier can be specified 15152 // but not both. 15153 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 15154 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 15155 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 15156 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 15157 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 15158 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 15159 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 15160 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 15161 return nullptr; 15162 } 15163 if (Kind == OMPC_SCHEDULE_unknown) { 15164 std::string Values; 15165 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 15166 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 15167 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 15168 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 15169 Exclude); 15170 } else { 15171 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 15172 /*Last=*/OMPC_SCHEDULE_unknown); 15173 } 15174 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 15175 << Values << getOpenMPClauseName(OMPC_schedule); 15176 return nullptr; 15177 } 15178 // OpenMP, 2.7.1, Loop Construct, Restrictions 15179 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 15180 // schedule(guided). 15181 // OpenMP 5.0 does not have this restriction. 15182 if (LangOpts.OpenMP < 50 && 15183 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 15184 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 15185 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 15186 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 15187 diag::err_omp_schedule_nonmonotonic_static); 15188 return nullptr; 15189 } 15190 Expr *ValExpr = ChunkSize; 15191 Stmt *HelperValStmt = nullptr; 15192 if (ChunkSize) { 15193 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 15194 !ChunkSize->isInstantiationDependent() && 15195 !ChunkSize->containsUnexpandedParameterPack()) { 15196 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 15197 ExprResult Val = 15198 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 15199 if (Val.isInvalid()) 15200 return nullptr; 15201 15202 ValExpr = Val.get(); 15203 15204 // OpenMP [2.7.1, Restrictions] 15205 // chunk_size must be a loop invariant integer expression with a positive 15206 // value. 15207 if (Optional<llvm::APSInt> Result = 15208 ValExpr->getIntegerConstantExpr(Context)) { 15209 if (Result->isSigned() && !Result->isStrictlyPositive()) { 15210 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 15211 << "schedule" << 1 << ChunkSize->getSourceRange(); 15212 return nullptr; 15213 } 15214 } else if (getOpenMPCaptureRegionForClause( 15215 DSAStack->getCurrentDirective(), OMPC_schedule, 15216 LangOpts.OpenMP) != OMPD_unknown && 15217 !CurContext->isDependentContext()) { 15218 ValExpr = MakeFullExpr(ValExpr).get(); 15219 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 15220 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 15221 HelperValStmt = buildPreInits(Context, Captures); 15222 } 15223 } 15224 } 15225 15226 return new (Context) 15227 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 15228 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 15229 } 15230 15231 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 15232 SourceLocation StartLoc, 15233 SourceLocation EndLoc) { 15234 OMPClause *Res = nullptr; 15235 switch (Kind) { 15236 case OMPC_ordered: 15237 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 15238 break; 15239 case OMPC_nowait: 15240 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 15241 break; 15242 case OMPC_untied: 15243 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 15244 break; 15245 case OMPC_mergeable: 15246 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 15247 break; 15248 case OMPC_read: 15249 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 15250 break; 15251 case OMPC_write: 15252 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 15253 break; 15254 case OMPC_update: 15255 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 15256 break; 15257 case OMPC_capture: 15258 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 15259 break; 15260 case OMPC_seq_cst: 15261 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 15262 break; 15263 case OMPC_acq_rel: 15264 Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc); 15265 break; 15266 case OMPC_acquire: 15267 Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc); 15268 break; 15269 case OMPC_release: 15270 Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc); 15271 break; 15272 case OMPC_relaxed: 15273 Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc); 15274 break; 15275 case OMPC_threads: 15276 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 15277 break; 15278 case OMPC_simd: 15279 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 15280 break; 15281 case OMPC_nogroup: 15282 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 15283 break; 15284 case OMPC_unified_address: 15285 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc); 15286 break; 15287 case OMPC_unified_shared_memory: 15288 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 15289 break; 15290 case OMPC_reverse_offload: 15291 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc); 15292 break; 15293 case OMPC_dynamic_allocators: 15294 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc); 15295 break; 15296 case OMPC_destroy: 15297 Res = ActOnOpenMPDestroyClause(/*InteropVar=*/nullptr, StartLoc, 15298 /*LParenLoc=*/SourceLocation(), 15299 /*VarLoc=*/SourceLocation(), EndLoc); 15300 break; 15301 case OMPC_full: 15302 Res = ActOnOpenMPFullClause(StartLoc, EndLoc); 15303 break; 15304 case OMPC_partial: 15305 Res = ActOnOpenMPPartialClause(nullptr, StartLoc, /*LParenLoc=*/{}, EndLoc); 15306 break; 15307 case OMPC_if: 15308 case OMPC_final: 15309 case OMPC_num_threads: 15310 case OMPC_safelen: 15311 case OMPC_simdlen: 15312 case OMPC_sizes: 15313 case OMPC_allocator: 15314 case OMPC_collapse: 15315 case OMPC_schedule: 15316 case OMPC_private: 15317 case OMPC_firstprivate: 15318 case OMPC_lastprivate: 15319 case OMPC_shared: 15320 case OMPC_reduction: 15321 case OMPC_task_reduction: 15322 case OMPC_in_reduction: 15323 case OMPC_linear: 15324 case OMPC_aligned: 15325 case OMPC_copyin: 15326 case OMPC_copyprivate: 15327 case OMPC_default: 15328 case OMPC_proc_bind: 15329 case OMPC_threadprivate: 15330 case OMPC_allocate: 15331 case OMPC_flush: 15332 case OMPC_depobj: 15333 case OMPC_depend: 15334 case OMPC_device: 15335 case OMPC_map: 15336 case OMPC_num_teams: 15337 case OMPC_thread_limit: 15338 case OMPC_priority: 15339 case OMPC_grainsize: 15340 case OMPC_num_tasks: 15341 case OMPC_hint: 15342 case OMPC_dist_schedule: 15343 case OMPC_defaultmap: 15344 case OMPC_unknown: 15345 case OMPC_uniform: 15346 case OMPC_to: 15347 case OMPC_from: 15348 case OMPC_use_device_ptr: 15349 case OMPC_use_device_addr: 15350 case OMPC_is_device_ptr: 15351 case OMPC_atomic_default_mem_order: 15352 case OMPC_device_type: 15353 case OMPC_match: 15354 case OMPC_nontemporal: 15355 case OMPC_order: 15356 case OMPC_novariants: 15357 case OMPC_nocontext: 15358 case OMPC_detach: 15359 case OMPC_inclusive: 15360 case OMPC_exclusive: 15361 case OMPC_uses_allocators: 15362 case OMPC_affinity: 15363 case OMPC_when: 15364 default: 15365 llvm_unreachable("Clause is not allowed."); 15366 } 15367 return Res; 15368 } 15369 15370 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 15371 SourceLocation EndLoc) { 15372 DSAStack->setNowaitRegion(); 15373 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 15374 } 15375 15376 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 15377 SourceLocation EndLoc) { 15378 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 15379 } 15380 15381 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 15382 SourceLocation EndLoc) { 15383 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 15384 } 15385 15386 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 15387 SourceLocation EndLoc) { 15388 return new (Context) OMPReadClause(StartLoc, EndLoc); 15389 } 15390 15391 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 15392 SourceLocation EndLoc) { 15393 return new (Context) OMPWriteClause(StartLoc, EndLoc); 15394 } 15395 15396 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 15397 SourceLocation EndLoc) { 15398 return OMPUpdateClause::Create(Context, StartLoc, EndLoc); 15399 } 15400 15401 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 15402 SourceLocation EndLoc) { 15403 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 15404 } 15405 15406 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 15407 SourceLocation EndLoc) { 15408 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 15409 } 15410 15411 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc, 15412 SourceLocation EndLoc) { 15413 return new (Context) OMPAcqRelClause(StartLoc, EndLoc); 15414 } 15415 15416 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc, 15417 SourceLocation EndLoc) { 15418 return new (Context) OMPAcquireClause(StartLoc, EndLoc); 15419 } 15420 15421 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc, 15422 SourceLocation EndLoc) { 15423 return new (Context) OMPReleaseClause(StartLoc, EndLoc); 15424 } 15425 15426 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc, 15427 SourceLocation EndLoc) { 15428 return new (Context) OMPRelaxedClause(StartLoc, EndLoc); 15429 } 15430 15431 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 15432 SourceLocation EndLoc) { 15433 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 15434 } 15435 15436 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 15437 SourceLocation EndLoc) { 15438 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 15439 } 15440 15441 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 15442 SourceLocation EndLoc) { 15443 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 15444 } 15445 15446 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, 15447 SourceLocation EndLoc) { 15448 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc); 15449 } 15450 15451 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, 15452 SourceLocation EndLoc) { 15453 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 15454 } 15455 15456 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, 15457 SourceLocation EndLoc) { 15458 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc); 15459 } 15460 15461 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, 15462 SourceLocation EndLoc) { 15463 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc); 15464 } 15465 15466 StmtResult Sema::ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses, 15467 SourceLocation StartLoc, 15468 SourceLocation EndLoc) { 15469 15470 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 15471 // At least one action-clause must appear on a directive. 15472 if (!hasClauses(Clauses, OMPC_init, OMPC_use, OMPC_destroy, OMPC_nowait)) { 15473 StringRef Expected = "'init', 'use', 'destroy', or 'nowait'"; 15474 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 15475 << Expected << getOpenMPDirectiveName(OMPD_interop); 15476 return StmtError(); 15477 } 15478 15479 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 15480 // A depend clause can only appear on the directive if a targetsync 15481 // interop-type is present or the interop-var was initialized with 15482 // the targetsync interop-type. 15483 15484 // If there is any 'init' clause diagnose if there is no 'init' clause with 15485 // interop-type of 'targetsync'. Cases involving other directives cannot be 15486 // diagnosed. 15487 const OMPDependClause *DependClause = nullptr; 15488 bool HasInitClause = false; 15489 bool IsTargetSync = false; 15490 for (const OMPClause *C : Clauses) { 15491 if (IsTargetSync) 15492 break; 15493 if (const auto *InitClause = dyn_cast<OMPInitClause>(C)) { 15494 HasInitClause = true; 15495 if (InitClause->getIsTargetSync()) 15496 IsTargetSync = true; 15497 } else if (const auto *DC = dyn_cast<OMPDependClause>(C)) { 15498 DependClause = DC; 15499 } 15500 } 15501 if (DependClause && HasInitClause && !IsTargetSync) { 15502 Diag(DependClause->getBeginLoc(), diag::err_omp_interop_bad_depend_clause); 15503 return StmtError(); 15504 } 15505 15506 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 15507 // Each interop-var may be specified for at most one action-clause of each 15508 // interop construct. 15509 llvm::SmallPtrSet<const VarDecl *, 4> InteropVars; 15510 for (const OMPClause *C : Clauses) { 15511 OpenMPClauseKind ClauseKind = C->getClauseKind(); 15512 const DeclRefExpr *DRE = nullptr; 15513 SourceLocation VarLoc; 15514 15515 if (ClauseKind == OMPC_init) { 15516 const auto *IC = cast<OMPInitClause>(C); 15517 VarLoc = IC->getVarLoc(); 15518 DRE = dyn_cast_or_null<DeclRefExpr>(IC->getInteropVar()); 15519 } else if (ClauseKind == OMPC_use) { 15520 const auto *UC = cast<OMPUseClause>(C); 15521 VarLoc = UC->getVarLoc(); 15522 DRE = dyn_cast_or_null<DeclRefExpr>(UC->getInteropVar()); 15523 } else if (ClauseKind == OMPC_destroy) { 15524 const auto *DC = cast<OMPDestroyClause>(C); 15525 VarLoc = DC->getVarLoc(); 15526 DRE = dyn_cast_or_null<DeclRefExpr>(DC->getInteropVar()); 15527 } 15528 15529 if (!DRE) 15530 continue; 15531 15532 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 15533 if (!InteropVars.insert(VD->getCanonicalDecl()).second) { 15534 Diag(VarLoc, diag::err_omp_interop_var_multiple_actions) << VD; 15535 return StmtError(); 15536 } 15537 } 15538 } 15539 15540 return OMPInteropDirective::Create(Context, StartLoc, EndLoc, Clauses); 15541 } 15542 15543 static bool isValidInteropVariable(Sema &SemaRef, Expr *InteropVarExpr, 15544 SourceLocation VarLoc, 15545 OpenMPClauseKind Kind) { 15546 if (InteropVarExpr->isValueDependent() || InteropVarExpr->isTypeDependent() || 15547 InteropVarExpr->isInstantiationDependent() || 15548 InteropVarExpr->containsUnexpandedParameterPack()) 15549 return true; 15550 15551 const auto *DRE = dyn_cast<DeclRefExpr>(InteropVarExpr); 15552 if (!DRE || !isa<VarDecl>(DRE->getDecl())) { 15553 SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) << 0; 15554 return false; 15555 } 15556 15557 // Interop variable should be of type omp_interop_t. 15558 bool HasError = false; 15559 QualType InteropType; 15560 LookupResult Result(SemaRef, &SemaRef.Context.Idents.get("omp_interop_t"), 15561 VarLoc, Sema::LookupOrdinaryName); 15562 if (SemaRef.LookupName(Result, SemaRef.getCurScope())) { 15563 NamedDecl *ND = Result.getFoundDecl(); 15564 if (const auto *TD = dyn_cast<TypeDecl>(ND)) { 15565 InteropType = QualType(TD->getTypeForDecl(), 0); 15566 } else { 15567 HasError = true; 15568 } 15569 } else { 15570 HasError = true; 15571 } 15572 15573 if (HasError) { 15574 SemaRef.Diag(VarLoc, diag::err_omp_implied_type_not_found) 15575 << "omp_interop_t"; 15576 return false; 15577 } 15578 15579 QualType VarType = InteropVarExpr->getType().getUnqualifiedType(); 15580 if (!SemaRef.Context.hasSameType(InteropType, VarType)) { 15581 SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_wrong_type); 15582 return false; 15583 } 15584 15585 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 15586 // The interop-var passed to init or destroy must be non-const. 15587 if ((Kind == OMPC_init || Kind == OMPC_destroy) && 15588 isConstNotMutableType(SemaRef, InteropVarExpr->getType())) { 15589 SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) 15590 << /*non-const*/ 1; 15591 return false; 15592 } 15593 return true; 15594 } 15595 15596 OMPClause * 15597 Sema::ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs, 15598 bool IsTarget, bool IsTargetSync, 15599 SourceLocation StartLoc, SourceLocation LParenLoc, 15600 SourceLocation VarLoc, SourceLocation EndLoc) { 15601 15602 if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_init)) 15603 return nullptr; 15604 15605 // Check prefer_type values. These foreign-runtime-id values are either 15606 // string literals or constant integral expressions. 15607 for (const Expr *E : PrefExprs) { 15608 if (E->isValueDependent() || E->isTypeDependent() || 15609 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 15610 continue; 15611 if (E->isIntegerConstantExpr(Context)) 15612 continue; 15613 if (isa<StringLiteral>(E)) 15614 continue; 15615 Diag(E->getExprLoc(), diag::err_omp_interop_prefer_type); 15616 return nullptr; 15617 } 15618 15619 return OMPInitClause::Create(Context, InteropVar, PrefExprs, IsTarget, 15620 IsTargetSync, StartLoc, LParenLoc, VarLoc, 15621 EndLoc); 15622 } 15623 15624 OMPClause *Sema::ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc, 15625 SourceLocation LParenLoc, 15626 SourceLocation VarLoc, 15627 SourceLocation EndLoc) { 15628 15629 if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_use)) 15630 return nullptr; 15631 15632 return new (Context) 15633 OMPUseClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc); 15634 } 15635 15636 OMPClause *Sema::ActOnOpenMPDestroyClause(Expr *InteropVar, 15637 SourceLocation StartLoc, 15638 SourceLocation LParenLoc, 15639 SourceLocation VarLoc, 15640 SourceLocation EndLoc) { 15641 if (InteropVar && 15642 !isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_destroy)) 15643 return nullptr; 15644 15645 return new (Context) 15646 OMPDestroyClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc); 15647 } 15648 15649 OMPClause *Sema::ActOnOpenMPNovariantsClause(Expr *Condition, 15650 SourceLocation StartLoc, 15651 SourceLocation LParenLoc, 15652 SourceLocation EndLoc) { 15653 Expr *ValExpr = Condition; 15654 Stmt *HelperValStmt = nullptr; 15655 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 15656 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 15657 !Condition->isInstantiationDependent() && 15658 !Condition->containsUnexpandedParameterPack()) { 15659 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 15660 if (Val.isInvalid()) 15661 return nullptr; 15662 15663 ValExpr = MakeFullExpr(Val.get()).get(); 15664 15665 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 15666 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_novariants, 15667 LangOpts.OpenMP); 15668 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 15669 ValExpr = MakeFullExpr(ValExpr).get(); 15670 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 15671 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 15672 HelperValStmt = buildPreInits(Context, Captures); 15673 } 15674 } 15675 15676 return new (Context) OMPNovariantsClause( 15677 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 15678 } 15679 15680 OMPClause *Sema::ActOnOpenMPNocontextClause(Expr *Condition, 15681 SourceLocation StartLoc, 15682 SourceLocation LParenLoc, 15683 SourceLocation EndLoc) { 15684 Expr *ValExpr = Condition; 15685 Stmt *HelperValStmt = nullptr; 15686 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 15687 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 15688 !Condition->isInstantiationDependent() && 15689 !Condition->containsUnexpandedParameterPack()) { 15690 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 15691 if (Val.isInvalid()) 15692 return nullptr; 15693 15694 ValExpr = MakeFullExpr(Val.get()).get(); 15695 15696 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 15697 CaptureRegion = 15698 getOpenMPCaptureRegionForClause(DKind, OMPC_nocontext, LangOpts.OpenMP); 15699 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 15700 ValExpr = MakeFullExpr(ValExpr).get(); 15701 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 15702 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 15703 HelperValStmt = buildPreInits(Context, Captures); 15704 } 15705 } 15706 15707 return new (Context) OMPNocontextClause(ValExpr, HelperValStmt, CaptureRegion, 15708 StartLoc, LParenLoc, EndLoc); 15709 } 15710 15711 OMPClause *Sema::ActOnOpenMPFilterClause(Expr *ThreadID, 15712 SourceLocation StartLoc, 15713 SourceLocation LParenLoc, 15714 SourceLocation EndLoc) { 15715 Expr *ValExpr = ThreadID; 15716 Stmt *HelperValStmt = nullptr; 15717 15718 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 15719 OpenMPDirectiveKind CaptureRegion = 15720 getOpenMPCaptureRegionForClause(DKind, OMPC_filter, LangOpts.OpenMP); 15721 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 15722 ValExpr = MakeFullExpr(ValExpr).get(); 15723 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 15724 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 15725 HelperValStmt = buildPreInits(Context, Captures); 15726 } 15727 15728 return new (Context) OMPFilterClause(ValExpr, HelperValStmt, CaptureRegion, 15729 StartLoc, LParenLoc, EndLoc); 15730 } 15731 15732 OMPClause *Sema::ActOnOpenMPVarListClause( 15733 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr, 15734 const OMPVarListLocTy &Locs, SourceLocation ColonLoc, 15735 CXXScopeSpec &ReductionOrMapperIdScopeSpec, 15736 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, 15737 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 15738 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, 15739 SourceLocation ExtraModifierLoc, 15740 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 15741 ArrayRef<SourceLocation> MotionModifiersLoc) { 15742 SourceLocation StartLoc = Locs.StartLoc; 15743 SourceLocation LParenLoc = Locs.LParenLoc; 15744 SourceLocation EndLoc = Locs.EndLoc; 15745 OMPClause *Res = nullptr; 15746 switch (Kind) { 15747 case OMPC_private: 15748 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 15749 break; 15750 case OMPC_firstprivate: 15751 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 15752 break; 15753 case OMPC_lastprivate: 15754 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown && 15755 "Unexpected lastprivate modifier."); 15756 Res = ActOnOpenMPLastprivateClause( 15757 VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier), 15758 ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc); 15759 break; 15760 case OMPC_shared: 15761 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 15762 break; 15763 case OMPC_reduction: 15764 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown && 15765 "Unexpected lastprivate modifier."); 15766 Res = ActOnOpenMPReductionClause( 15767 VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier), 15768 StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc, 15769 ReductionOrMapperIdScopeSpec, ReductionOrMapperId); 15770 break; 15771 case OMPC_task_reduction: 15772 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 15773 EndLoc, ReductionOrMapperIdScopeSpec, 15774 ReductionOrMapperId); 15775 break; 15776 case OMPC_in_reduction: 15777 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 15778 EndLoc, ReductionOrMapperIdScopeSpec, 15779 ReductionOrMapperId); 15780 break; 15781 case OMPC_linear: 15782 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown && 15783 "Unexpected linear modifier."); 15784 Res = ActOnOpenMPLinearClause( 15785 VarList, DepModOrTailExpr, StartLoc, LParenLoc, 15786 static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc, 15787 ColonLoc, EndLoc); 15788 break; 15789 case OMPC_aligned: 15790 Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc, 15791 LParenLoc, ColonLoc, EndLoc); 15792 break; 15793 case OMPC_copyin: 15794 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 15795 break; 15796 case OMPC_copyprivate: 15797 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 15798 break; 15799 case OMPC_flush: 15800 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 15801 break; 15802 case OMPC_depend: 15803 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown && 15804 "Unexpected depend modifier."); 15805 Res = ActOnOpenMPDependClause( 15806 DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier), 15807 ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc); 15808 break; 15809 case OMPC_map: 15810 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown && 15811 "Unexpected map modifier."); 15812 Res = ActOnOpenMPMapClause( 15813 MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec, 15814 ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier), 15815 IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs); 15816 break; 15817 case OMPC_to: 15818 Res = ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc, 15819 ReductionOrMapperIdScopeSpec, ReductionOrMapperId, 15820 ColonLoc, VarList, Locs); 15821 break; 15822 case OMPC_from: 15823 Res = ActOnOpenMPFromClause(MotionModifiers, MotionModifiersLoc, 15824 ReductionOrMapperIdScopeSpec, 15825 ReductionOrMapperId, ColonLoc, VarList, Locs); 15826 break; 15827 case OMPC_use_device_ptr: 15828 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs); 15829 break; 15830 case OMPC_use_device_addr: 15831 Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs); 15832 break; 15833 case OMPC_is_device_ptr: 15834 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs); 15835 break; 15836 case OMPC_allocate: 15837 Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc, 15838 LParenLoc, ColonLoc, EndLoc); 15839 break; 15840 case OMPC_nontemporal: 15841 Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc); 15842 break; 15843 case OMPC_inclusive: 15844 Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc); 15845 break; 15846 case OMPC_exclusive: 15847 Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc); 15848 break; 15849 case OMPC_affinity: 15850 Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc, 15851 DepModOrTailExpr, VarList); 15852 break; 15853 case OMPC_if: 15854 case OMPC_depobj: 15855 case OMPC_final: 15856 case OMPC_num_threads: 15857 case OMPC_safelen: 15858 case OMPC_simdlen: 15859 case OMPC_sizes: 15860 case OMPC_allocator: 15861 case OMPC_collapse: 15862 case OMPC_default: 15863 case OMPC_proc_bind: 15864 case OMPC_schedule: 15865 case OMPC_ordered: 15866 case OMPC_nowait: 15867 case OMPC_untied: 15868 case OMPC_mergeable: 15869 case OMPC_threadprivate: 15870 case OMPC_read: 15871 case OMPC_write: 15872 case OMPC_update: 15873 case OMPC_capture: 15874 case OMPC_seq_cst: 15875 case OMPC_acq_rel: 15876 case OMPC_acquire: 15877 case OMPC_release: 15878 case OMPC_relaxed: 15879 case OMPC_device: 15880 case OMPC_threads: 15881 case OMPC_simd: 15882 case OMPC_num_teams: 15883 case OMPC_thread_limit: 15884 case OMPC_priority: 15885 case OMPC_grainsize: 15886 case OMPC_nogroup: 15887 case OMPC_num_tasks: 15888 case OMPC_hint: 15889 case OMPC_dist_schedule: 15890 case OMPC_defaultmap: 15891 case OMPC_unknown: 15892 case OMPC_uniform: 15893 case OMPC_unified_address: 15894 case OMPC_unified_shared_memory: 15895 case OMPC_reverse_offload: 15896 case OMPC_dynamic_allocators: 15897 case OMPC_atomic_default_mem_order: 15898 case OMPC_device_type: 15899 case OMPC_match: 15900 case OMPC_order: 15901 case OMPC_destroy: 15902 case OMPC_novariants: 15903 case OMPC_nocontext: 15904 case OMPC_detach: 15905 case OMPC_uses_allocators: 15906 case OMPC_when: 15907 case OMPC_bind: 15908 default: 15909 llvm_unreachable("Clause is not allowed."); 15910 } 15911 return Res; 15912 } 15913 15914 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 15915 ExprObjectKind OK, SourceLocation Loc) { 15916 ExprResult Res = BuildDeclRefExpr( 15917 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 15918 if (!Res.isUsable()) 15919 return ExprError(); 15920 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 15921 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 15922 if (!Res.isUsable()) 15923 return ExprError(); 15924 } 15925 if (VK != VK_LValue && Res.get()->isGLValue()) { 15926 Res = DefaultLvalueConversion(Res.get()); 15927 if (!Res.isUsable()) 15928 return ExprError(); 15929 } 15930 return Res; 15931 } 15932 15933 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 15934 SourceLocation StartLoc, 15935 SourceLocation LParenLoc, 15936 SourceLocation EndLoc) { 15937 SmallVector<Expr *, 8> Vars; 15938 SmallVector<Expr *, 8> PrivateCopies; 15939 for (Expr *RefExpr : VarList) { 15940 assert(RefExpr && "NULL expr in OpenMP private clause."); 15941 SourceLocation ELoc; 15942 SourceRange ERange; 15943 Expr *SimpleRefExpr = RefExpr; 15944 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 15945 if (Res.second) { 15946 // It will be analyzed later. 15947 Vars.push_back(RefExpr); 15948 PrivateCopies.push_back(nullptr); 15949 } 15950 ValueDecl *D = Res.first; 15951 if (!D) 15952 continue; 15953 15954 QualType Type = D->getType(); 15955 auto *VD = dyn_cast<VarDecl>(D); 15956 15957 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 15958 // A variable that appears in a private clause must not have an incomplete 15959 // type or a reference type. 15960 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 15961 continue; 15962 Type = Type.getNonReferenceType(); 15963 15964 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 15965 // A variable that is privatized must not have a const-qualified type 15966 // unless it is of class type with a mutable member. This restriction does 15967 // not apply to the firstprivate clause. 15968 // 15969 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions] 15970 // A variable that appears in a private clause must not have a 15971 // const-qualified type unless it is of class type with a mutable member. 15972 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc)) 15973 continue; 15974 15975 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 15976 // in a Construct] 15977 // Variables with the predetermined data-sharing attributes may not be 15978 // listed in data-sharing attributes clauses, except for the cases 15979 // listed below. For these exceptions only, listing a predetermined 15980 // variable in a data-sharing attribute clause is allowed and overrides 15981 // the variable's predetermined data-sharing attributes. 15982 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 15983 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 15984 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 15985 << getOpenMPClauseName(OMPC_private); 15986 reportOriginalDsa(*this, DSAStack, D, DVar); 15987 continue; 15988 } 15989 15990 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 15991 // Variably modified types are not supported for tasks. 15992 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 15993 isOpenMPTaskingDirective(CurrDir)) { 15994 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 15995 << getOpenMPClauseName(OMPC_private) << Type 15996 << getOpenMPDirectiveName(CurrDir); 15997 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 15998 VarDecl::DeclarationOnly; 15999 Diag(D->getLocation(), 16000 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 16001 << D; 16002 continue; 16003 } 16004 16005 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 16006 // A list item cannot appear in both a map clause and a data-sharing 16007 // attribute clause on the same construct 16008 // 16009 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 16010 // A list item cannot appear in both a map clause and a data-sharing 16011 // attribute clause on the same construct unless the construct is a 16012 // combined construct. 16013 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) || 16014 CurrDir == OMPD_target) { 16015 OpenMPClauseKind ConflictKind; 16016 if (DSAStack->checkMappableExprComponentListsForDecl( 16017 VD, /*CurrentRegionOnly=*/true, 16018 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 16019 OpenMPClauseKind WhereFoundClauseKind) -> bool { 16020 ConflictKind = WhereFoundClauseKind; 16021 return true; 16022 })) { 16023 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 16024 << getOpenMPClauseName(OMPC_private) 16025 << getOpenMPClauseName(ConflictKind) 16026 << getOpenMPDirectiveName(CurrDir); 16027 reportOriginalDsa(*this, DSAStack, D, DVar); 16028 continue; 16029 } 16030 } 16031 16032 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 16033 // A variable of class type (or array thereof) that appears in a private 16034 // clause requires an accessible, unambiguous default constructor for the 16035 // class type. 16036 // Generate helper private variable and initialize it with the default 16037 // value. The address of the original variable is replaced by the address of 16038 // the new private variable in CodeGen. This new variable is not added to 16039 // IdResolver, so the code in the OpenMP region uses original variable for 16040 // proper diagnostics. 16041 Type = Type.getUnqualifiedType(); 16042 VarDecl *VDPrivate = 16043 buildVarDecl(*this, ELoc, Type, D->getName(), 16044 D->hasAttrs() ? &D->getAttrs() : nullptr, 16045 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 16046 ActOnUninitializedDecl(VDPrivate); 16047 if (VDPrivate->isInvalidDecl()) 16048 continue; 16049 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 16050 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 16051 16052 DeclRefExpr *Ref = nullptr; 16053 if (!VD && !CurContext->isDependentContext()) 16054 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 16055 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 16056 Vars.push_back((VD || CurContext->isDependentContext()) 16057 ? RefExpr->IgnoreParens() 16058 : Ref); 16059 PrivateCopies.push_back(VDPrivateRefExpr); 16060 } 16061 16062 if (Vars.empty()) 16063 return nullptr; 16064 16065 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 16066 PrivateCopies); 16067 } 16068 16069 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 16070 SourceLocation StartLoc, 16071 SourceLocation LParenLoc, 16072 SourceLocation EndLoc) { 16073 SmallVector<Expr *, 8> Vars; 16074 SmallVector<Expr *, 8> PrivateCopies; 16075 SmallVector<Expr *, 8> Inits; 16076 SmallVector<Decl *, 4> ExprCaptures; 16077 bool IsImplicitClause = 16078 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 16079 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc(); 16080 16081 for (Expr *RefExpr : VarList) { 16082 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 16083 SourceLocation ELoc; 16084 SourceRange ERange; 16085 Expr *SimpleRefExpr = RefExpr; 16086 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 16087 if (Res.second) { 16088 // It will be analyzed later. 16089 Vars.push_back(RefExpr); 16090 PrivateCopies.push_back(nullptr); 16091 Inits.push_back(nullptr); 16092 } 16093 ValueDecl *D = Res.first; 16094 if (!D) 16095 continue; 16096 16097 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 16098 QualType Type = D->getType(); 16099 auto *VD = dyn_cast<VarDecl>(D); 16100 16101 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 16102 // A variable that appears in a private clause must not have an incomplete 16103 // type or a reference type. 16104 if (RequireCompleteType(ELoc, Type, 16105 diag::err_omp_firstprivate_incomplete_type)) 16106 continue; 16107 Type = Type.getNonReferenceType(); 16108 16109 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 16110 // A variable of class type (or array thereof) that appears in a private 16111 // clause requires an accessible, unambiguous copy constructor for the 16112 // class type. 16113 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 16114 16115 // If an implicit firstprivate variable found it was checked already. 16116 DSAStackTy::DSAVarData TopDVar; 16117 if (!IsImplicitClause) { 16118 DSAStackTy::DSAVarData DVar = 16119 DSAStack->getTopDSA(D, /*FromParent=*/false); 16120 TopDVar = DVar; 16121 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 16122 bool IsConstant = ElemType.isConstant(Context); 16123 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 16124 // A list item that specifies a given variable may not appear in more 16125 // than one clause on the same directive, except that a variable may be 16126 // specified in both firstprivate and lastprivate clauses. 16127 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 16128 // A list item may appear in a firstprivate or lastprivate clause but not 16129 // both. 16130 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 16131 (isOpenMPDistributeDirective(CurrDir) || 16132 DVar.CKind != OMPC_lastprivate) && 16133 DVar.RefExpr) { 16134 Diag(ELoc, diag::err_omp_wrong_dsa) 16135 << getOpenMPClauseName(DVar.CKind) 16136 << getOpenMPClauseName(OMPC_firstprivate); 16137 reportOriginalDsa(*this, DSAStack, D, DVar); 16138 continue; 16139 } 16140 16141 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 16142 // in a Construct] 16143 // Variables with the predetermined data-sharing attributes may not be 16144 // listed in data-sharing attributes clauses, except for the cases 16145 // listed below. For these exceptions only, listing a predetermined 16146 // variable in a data-sharing attribute clause is allowed and overrides 16147 // the variable's predetermined data-sharing attributes. 16148 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 16149 // in a Construct, C/C++, p.2] 16150 // Variables with const-qualified type having no mutable member may be 16151 // listed in a firstprivate clause, even if they are static data members. 16152 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 16153 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 16154 Diag(ELoc, diag::err_omp_wrong_dsa) 16155 << getOpenMPClauseName(DVar.CKind) 16156 << getOpenMPClauseName(OMPC_firstprivate); 16157 reportOriginalDsa(*this, DSAStack, D, DVar); 16158 continue; 16159 } 16160 16161 // OpenMP [2.9.3.4, Restrictions, p.2] 16162 // A list item that is private within a parallel region must not appear 16163 // in a firstprivate clause on a worksharing construct if any of the 16164 // worksharing regions arising from the worksharing construct ever bind 16165 // to any of the parallel regions arising from the parallel construct. 16166 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 16167 // A list item that is private within a teams region must not appear in a 16168 // firstprivate clause on a distribute construct if any of the distribute 16169 // regions arising from the distribute construct ever bind to any of the 16170 // teams regions arising from the teams construct. 16171 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 16172 // A list item that appears in a reduction clause of a teams construct 16173 // must not appear in a firstprivate clause on a distribute construct if 16174 // any of the distribute regions arising from the distribute construct 16175 // ever bind to any of the teams regions arising from the teams construct. 16176 if ((isOpenMPWorksharingDirective(CurrDir) || 16177 isOpenMPDistributeDirective(CurrDir)) && 16178 !isOpenMPParallelDirective(CurrDir) && 16179 !isOpenMPTeamsDirective(CurrDir)) { 16180 DVar = DSAStack->getImplicitDSA(D, true); 16181 if (DVar.CKind != OMPC_shared && 16182 (isOpenMPParallelDirective(DVar.DKind) || 16183 isOpenMPTeamsDirective(DVar.DKind) || 16184 DVar.DKind == OMPD_unknown)) { 16185 Diag(ELoc, diag::err_omp_required_access) 16186 << getOpenMPClauseName(OMPC_firstprivate) 16187 << getOpenMPClauseName(OMPC_shared); 16188 reportOriginalDsa(*this, DSAStack, D, DVar); 16189 continue; 16190 } 16191 } 16192 // OpenMP [2.9.3.4, Restrictions, p.3] 16193 // A list item that appears in a reduction clause of a parallel construct 16194 // must not appear in a firstprivate clause on a worksharing or task 16195 // construct if any of the worksharing or task regions arising from the 16196 // worksharing or task construct ever bind to any of the parallel regions 16197 // arising from the parallel construct. 16198 // OpenMP [2.9.3.4, Restrictions, p.4] 16199 // A list item that appears in a reduction clause in worksharing 16200 // construct must not appear in a firstprivate clause in a task construct 16201 // encountered during execution of any of the worksharing regions arising 16202 // from the worksharing construct. 16203 if (isOpenMPTaskingDirective(CurrDir)) { 16204 DVar = DSAStack->hasInnermostDSA( 16205 D, 16206 [](OpenMPClauseKind C, bool AppliedToPointee) { 16207 return C == OMPC_reduction && !AppliedToPointee; 16208 }, 16209 [](OpenMPDirectiveKind K) { 16210 return isOpenMPParallelDirective(K) || 16211 isOpenMPWorksharingDirective(K) || 16212 isOpenMPTeamsDirective(K); 16213 }, 16214 /*FromParent=*/true); 16215 if (DVar.CKind == OMPC_reduction && 16216 (isOpenMPParallelDirective(DVar.DKind) || 16217 isOpenMPWorksharingDirective(DVar.DKind) || 16218 isOpenMPTeamsDirective(DVar.DKind))) { 16219 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 16220 << getOpenMPDirectiveName(DVar.DKind); 16221 reportOriginalDsa(*this, DSAStack, D, DVar); 16222 continue; 16223 } 16224 } 16225 16226 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 16227 // A list item cannot appear in both a map clause and a data-sharing 16228 // attribute clause on the same construct 16229 // 16230 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 16231 // A list item cannot appear in both a map clause and a data-sharing 16232 // attribute clause on the same construct unless the construct is a 16233 // combined construct. 16234 if ((LangOpts.OpenMP <= 45 && 16235 isOpenMPTargetExecutionDirective(CurrDir)) || 16236 CurrDir == OMPD_target) { 16237 OpenMPClauseKind ConflictKind; 16238 if (DSAStack->checkMappableExprComponentListsForDecl( 16239 VD, /*CurrentRegionOnly=*/true, 16240 [&ConflictKind]( 16241 OMPClauseMappableExprCommon::MappableExprComponentListRef, 16242 OpenMPClauseKind WhereFoundClauseKind) { 16243 ConflictKind = WhereFoundClauseKind; 16244 return true; 16245 })) { 16246 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 16247 << getOpenMPClauseName(OMPC_firstprivate) 16248 << getOpenMPClauseName(ConflictKind) 16249 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 16250 reportOriginalDsa(*this, DSAStack, D, DVar); 16251 continue; 16252 } 16253 } 16254 } 16255 16256 // Variably modified types are not supported for tasks. 16257 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 16258 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 16259 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 16260 << getOpenMPClauseName(OMPC_firstprivate) << Type 16261 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 16262 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 16263 VarDecl::DeclarationOnly; 16264 Diag(D->getLocation(), 16265 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 16266 << D; 16267 continue; 16268 } 16269 16270 Type = Type.getUnqualifiedType(); 16271 VarDecl *VDPrivate = 16272 buildVarDecl(*this, ELoc, Type, D->getName(), 16273 D->hasAttrs() ? &D->getAttrs() : nullptr, 16274 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 16275 // Generate helper private variable and initialize it with the value of the 16276 // original variable. The address of the original variable is replaced by 16277 // the address of the new private variable in the CodeGen. This new variable 16278 // is not added to IdResolver, so the code in the OpenMP region uses 16279 // original variable for proper diagnostics and variable capturing. 16280 Expr *VDInitRefExpr = nullptr; 16281 // For arrays generate initializer for single element and replace it by the 16282 // original array element in CodeGen. 16283 if (Type->isArrayType()) { 16284 VarDecl *VDInit = 16285 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 16286 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 16287 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get(); 16288 ElemType = ElemType.getUnqualifiedType(); 16289 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 16290 ".firstprivate.temp"); 16291 InitializedEntity Entity = 16292 InitializedEntity::InitializeVariable(VDInitTemp); 16293 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 16294 16295 InitializationSequence InitSeq(*this, Entity, Kind, Init); 16296 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 16297 if (Result.isInvalid()) 16298 VDPrivate->setInvalidDecl(); 16299 else 16300 VDPrivate->setInit(Result.getAs<Expr>()); 16301 // Remove temp variable declaration. 16302 Context.Deallocate(VDInitTemp); 16303 } else { 16304 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 16305 ".firstprivate.temp"); 16306 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 16307 RefExpr->getExprLoc()); 16308 AddInitializerToDecl(VDPrivate, 16309 DefaultLvalueConversion(VDInitRefExpr).get(), 16310 /*DirectInit=*/false); 16311 } 16312 if (VDPrivate->isInvalidDecl()) { 16313 if (IsImplicitClause) { 16314 Diag(RefExpr->getExprLoc(), 16315 diag::note_omp_task_predetermined_firstprivate_here); 16316 } 16317 continue; 16318 } 16319 CurContext->addDecl(VDPrivate); 16320 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 16321 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 16322 RefExpr->getExprLoc()); 16323 DeclRefExpr *Ref = nullptr; 16324 if (!VD && !CurContext->isDependentContext()) { 16325 if (TopDVar.CKind == OMPC_lastprivate) { 16326 Ref = TopDVar.PrivateCopy; 16327 } else { 16328 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 16329 if (!isOpenMPCapturedDecl(D)) 16330 ExprCaptures.push_back(Ref->getDecl()); 16331 } 16332 } 16333 if (!IsImplicitClause) 16334 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 16335 Vars.push_back((VD || CurContext->isDependentContext()) 16336 ? RefExpr->IgnoreParens() 16337 : Ref); 16338 PrivateCopies.push_back(VDPrivateRefExpr); 16339 Inits.push_back(VDInitRefExpr); 16340 } 16341 16342 if (Vars.empty()) 16343 return nullptr; 16344 16345 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 16346 Vars, PrivateCopies, Inits, 16347 buildPreInits(Context, ExprCaptures)); 16348 } 16349 16350 OMPClause *Sema::ActOnOpenMPLastprivateClause( 16351 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, 16352 SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc, 16353 SourceLocation LParenLoc, SourceLocation EndLoc) { 16354 if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) { 16355 assert(ColonLoc.isValid() && "Colon location must be valid."); 16356 Diag(LPKindLoc, diag::err_omp_unexpected_clause_value) 16357 << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0, 16358 /*Last=*/OMPC_LASTPRIVATE_unknown) 16359 << getOpenMPClauseName(OMPC_lastprivate); 16360 return nullptr; 16361 } 16362 16363 SmallVector<Expr *, 8> Vars; 16364 SmallVector<Expr *, 8> SrcExprs; 16365 SmallVector<Expr *, 8> DstExprs; 16366 SmallVector<Expr *, 8> AssignmentOps; 16367 SmallVector<Decl *, 4> ExprCaptures; 16368 SmallVector<Expr *, 4> ExprPostUpdates; 16369 for (Expr *RefExpr : VarList) { 16370 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 16371 SourceLocation ELoc; 16372 SourceRange ERange; 16373 Expr *SimpleRefExpr = RefExpr; 16374 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 16375 if (Res.second) { 16376 // It will be analyzed later. 16377 Vars.push_back(RefExpr); 16378 SrcExprs.push_back(nullptr); 16379 DstExprs.push_back(nullptr); 16380 AssignmentOps.push_back(nullptr); 16381 } 16382 ValueDecl *D = Res.first; 16383 if (!D) 16384 continue; 16385 16386 QualType Type = D->getType(); 16387 auto *VD = dyn_cast<VarDecl>(D); 16388 16389 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 16390 // A variable that appears in a lastprivate clause must not have an 16391 // incomplete type or a reference type. 16392 if (RequireCompleteType(ELoc, Type, 16393 diag::err_omp_lastprivate_incomplete_type)) 16394 continue; 16395 Type = Type.getNonReferenceType(); 16396 16397 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 16398 // A variable that is privatized must not have a const-qualified type 16399 // unless it is of class type with a mutable member. This restriction does 16400 // not apply to the firstprivate clause. 16401 // 16402 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions] 16403 // A variable that appears in a lastprivate clause must not have a 16404 // const-qualified type unless it is of class type with a mutable member. 16405 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc)) 16406 continue; 16407 16408 // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions] 16409 // A list item that appears in a lastprivate clause with the conditional 16410 // modifier must be a scalar variable. 16411 if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) { 16412 Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar); 16413 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 16414 VarDecl::DeclarationOnly; 16415 Diag(D->getLocation(), 16416 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 16417 << D; 16418 continue; 16419 } 16420 16421 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 16422 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 16423 // in a Construct] 16424 // Variables with the predetermined data-sharing attributes may not be 16425 // listed in data-sharing attributes clauses, except for the cases 16426 // listed below. 16427 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 16428 // A list item may appear in a firstprivate or lastprivate clause but not 16429 // both. 16430 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 16431 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 16432 (isOpenMPDistributeDirective(CurrDir) || 16433 DVar.CKind != OMPC_firstprivate) && 16434 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 16435 Diag(ELoc, diag::err_omp_wrong_dsa) 16436 << getOpenMPClauseName(DVar.CKind) 16437 << getOpenMPClauseName(OMPC_lastprivate); 16438 reportOriginalDsa(*this, DSAStack, D, DVar); 16439 continue; 16440 } 16441 16442 // OpenMP [2.14.3.5, Restrictions, p.2] 16443 // A list item that is private within a parallel region, or that appears in 16444 // the reduction clause of a parallel construct, must not appear in a 16445 // lastprivate clause on a worksharing construct if any of the corresponding 16446 // worksharing regions ever binds to any of the corresponding parallel 16447 // regions. 16448 DSAStackTy::DSAVarData TopDVar = DVar; 16449 if (isOpenMPWorksharingDirective(CurrDir) && 16450 !isOpenMPParallelDirective(CurrDir) && 16451 !isOpenMPTeamsDirective(CurrDir)) { 16452 DVar = DSAStack->getImplicitDSA(D, true); 16453 if (DVar.CKind != OMPC_shared) { 16454 Diag(ELoc, diag::err_omp_required_access) 16455 << getOpenMPClauseName(OMPC_lastprivate) 16456 << getOpenMPClauseName(OMPC_shared); 16457 reportOriginalDsa(*this, DSAStack, D, DVar); 16458 continue; 16459 } 16460 } 16461 16462 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 16463 // A variable of class type (or array thereof) that appears in a 16464 // lastprivate clause requires an accessible, unambiguous default 16465 // constructor for the class type, unless the list item is also specified 16466 // in a firstprivate clause. 16467 // A variable of class type (or array thereof) that appears in a 16468 // lastprivate clause requires an accessible, unambiguous copy assignment 16469 // operator for the class type. 16470 Type = Context.getBaseElementType(Type).getNonReferenceType(); 16471 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(), 16472 Type.getUnqualifiedType(), ".lastprivate.src", 16473 D->hasAttrs() ? &D->getAttrs() : nullptr); 16474 DeclRefExpr *PseudoSrcExpr = 16475 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 16476 VarDecl *DstVD = 16477 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 16478 D->hasAttrs() ? &D->getAttrs() : nullptr); 16479 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 16480 // For arrays generate assignment operation for single element and replace 16481 // it by the original array element in CodeGen. 16482 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 16483 PseudoDstExpr, PseudoSrcExpr); 16484 if (AssignmentOp.isInvalid()) 16485 continue; 16486 AssignmentOp = 16487 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 16488 if (AssignmentOp.isInvalid()) 16489 continue; 16490 16491 DeclRefExpr *Ref = nullptr; 16492 if (!VD && !CurContext->isDependentContext()) { 16493 if (TopDVar.CKind == OMPC_firstprivate) { 16494 Ref = TopDVar.PrivateCopy; 16495 } else { 16496 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 16497 if (!isOpenMPCapturedDecl(D)) 16498 ExprCaptures.push_back(Ref->getDecl()); 16499 } 16500 if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) || 16501 (!isOpenMPCapturedDecl(D) && 16502 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 16503 ExprResult RefRes = DefaultLvalueConversion(Ref); 16504 if (!RefRes.isUsable()) 16505 continue; 16506 ExprResult PostUpdateRes = 16507 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 16508 RefRes.get()); 16509 if (!PostUpdateRes.isUsable()) 16510 continue; 16511 ExprPostUpdates.push_back( 16512 IgnoredValueConversions(PostUpdateRes.get()).get()); 16513 } 16514 } 16515 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 16516 Vars.push_back((VD || CurContext->isDependentContext()) 16517 ? RefExpr->IgnoreParens() 16518 : Ref); 16519 SrcExprs.push_back(PseudoSrcExpr); 16520 DstExprs.push_back(PseudoDstExpr); 16521 AssignmentOps.push_back(AssignmentOp.get()); 16522 } 16523 16524 if (Vars.empty()) 16525 return nullptr; 16526 16527 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 16528 Vars, SrcExprs, DstExprs, AssignmentOps, 16529 LPKind, LPKindLoc, ColonLoc, 16530 buildPreInits(Context, ExprCaptures), 16531 buildPostUpdate(*this, ExprPostUpdates)); 16532 } 16533 16534 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 16535 SourceLocation StartLoc, 16536 SourceLocation LParenLoc, 16537 SourceLocation EndLoc) { 16538 SmallVector<Expr *, 8> Vars; 16539 for (Expr *RefExpr : VarList) { 16540 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 16541 SourceLocation ELoc; 16542 SourceRange ERange; 16543 Expr *SimpleRefExpr = RefExpr; 16544 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 16545 if (Res.second) { 16546 // It will be analyzed later. 16547 Vars.push_back(RefExpr); 16548 } 16549 ValueDecl *D = Res.first; 16550 if (!D) 16551 continue; 16552 16553 auto *VD = dyn_cast<VarDecl>(D); 16554 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 16555 // in a Construct] 16556 // Variables with the predetermined data-sharing attributes may not be 16557 // listed in data-sharing attributes clauses, except for the cases 16558 // listed below. For these exceptions only, listing a predetermined 16559 // variable in a data-sharing attribute clause is allowed and overrides 16560 // the variable's predetermined data-sharing attributes. 16561 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 16562 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 16563 DVar.RefExpr) { 16564 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 16565 << getOpenMPClauseName(OMPC_shared); 16566 reportOriginalDsa(*this, DSAStack, D, DVar); 16567 continue; 16568 } 16569 16570 DeclRefExpr *Ref = nullptr; 16571 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 16572 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 16573 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 16574 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 16575 ? RefExpr->IgnoreParens() 16576 : Ref); 16577 } 16578 16579 if (Vars.empty()) 16580 return nullptr; 16581 16582 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 16583 } 16584 16585 namespace { 16586 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 16587 DSAStackTy *Stack; 16588 16589 public: 16590 bool VisitDeclRefExpr(DeclRefExpr *E) { 16591 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 16592 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 16593 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 16594 return false; 16595 if (DVar.CKind != OMPC_unknown) 16596 return true; 16597 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 16598 VD, 16599 [](OpenMPClauseKind C, bool AppliedToPointee) { 16600 return isOpenMPPrivate(C) && !AppliedToPointee; 16601 }, 16602 [](OpenMPDirectiveKind) { return true; }, 16603 /*FromParent=*/true); 16604 return DVarPrivate.CKind != OMPC_unknown; 16605 } 16606 return false; 16607 } 16608 bool VisitStmt(Stmt *S) { 16609 for (Stmt *Child : S->children()) { 16610 if (Child && Visit(Child)) 16611 return true; 16612 } 16613 return false; 16614 } 16615 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 16616 }; 16617 } // namespace 16618 16619 namespace { 16620 // Transform MemberExpression for specified FieldDecl of current class to 16621 // DeclRefExpr to specified OMPCapturedExprDecl. 16622 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 16623 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 16624 ValueDecl *Field = nullptr; 16625 DeclRefExpr *CapturedExpr = nullptr; 16626 16627 public: 16628 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 16629 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 16630 16631 ExprResult TransformMemberExpr(MemberExpr *E) { 16632 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 16633 E->getMemberDecl() == Field) { 16634 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 16635 return CapturedExpr; 16636 } 16637 return BaseTransform::TransformMemberExpr(E); 16638 } 16639 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 16640 }; 16641 } // namespace 16642 16643 template <typename T, typename U> 16644 static T filterLookupForUDReductionAndMapper( 16645 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) { 16646 for (U &Set : Lookups) { 16647 for (auto *D : Set) { 16648 if (T Res = Gen(cast<ValueDecl>(D))) 16649 return Res; 16650 } 16651 } 16652 return T(); 16653 } 16654 16655 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) { 16656 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case"); 16657 16658 for (auto RD : D->redecls()) { 16659 // Don't bother with extra checks if we already know this one isn't visible. 16660 if (RD == D) 16661 continue; 16662 16663 auto ND = cast<NamedDecl>(RD); 16664 if (LookupResult::isVisible(SemaRef, ND)) 16665 return ND; 16666 } 16667 16668 return nullptr; 16669 } 16670 16671 static void 16672 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id, 16673 SourceLocation Loc, QualType Ty, 16674 SmallVectorImpl<UnresolvedSet<8>> &Lookups) { 16675 // Find all of the associated namespaces and classes based on the 16676 // arguments we have. 16677 Sema::AssociatedNamespaceSet AssociatedNamespaces; 16678 Sema::AssociatedClassSet AssociatedClasses; 16679 OpaqueValueExpr OVE(Loc, Ty, VK_LValue); 16680 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces, 16681 AssociatedClasses); 16682 16683 // C++ [basic.lookup.argdep]p3: 16684 // Let X be the lookup set produced by unqualified lookup (3.4.1) 16685 // and let Y be the lookup set produced by argument dependent 16686 // lookup (defined as follows). If X contains [...] then Y is 16687 // empty. Otherwise Y is the set of declarations found in the 16688 // namespaces associated with the argument types as described 16689 // below. The set of declarations found by the lookup of the name 16690 // is the union of X and Y. 16691 // 16692 // Here, we compute Y and add its members to the overloaded 16693 // candidate set. 16694 for (auto *NS : AssociatedNamespaces) { 16695 // When considering an associated namespace, the lookup is the 16696 // same as the lookup performed when the associated namespace is 16697 // used as a qualifier (3.4.3.2) except that: 16698 // 16699 // -- Any using-directives in the associated namespace are 16700 // ignored. 16701 // 16702 // -- Any namespace-scope friend functions declared in 16703 // associated classes are visible within their respective 16704 // namespaces even if they are not visible during an ordinary 16705 // lookup (11.4). 16706 DeclContext::lookup_result R = NS->lookup(Id.getName()); 16707 for (auto *D : R) { 16708 auto *Underlying = D; 16709 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 16710 Underlying = USD->getTargetDecl(); 16711 16712 if (!isa<OMPDeclareReductionDecl>(Underlying) && 16713 !isa<OMPDeclareMapperDecl>(Underlying)) 16714 continue; 16715 16716 if (!SemaRef.isVisible(D)) { 16717 D = findAcceptableDecl(SemaRef, D); 16718 if (!D) 16719 continue; 16720 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 16721 Underlying = USD->getTargetDecl(); 16722 } 16723 Lookups.emplace_back(); 16724 Lookups.back().addDecl(Underlying); 16725 } 16726 } 16727 } 16728 16729 static ExprResult 16730 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 16731 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 16732 const DeclarationNameInfo &ReductionId, QualType Ty, 16733 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 16734 if (ReductionIdScopeSpec.isInvalid()) 16735 return ExprError(); 16736 SmallVector<UnresolvedSet<8>, 4> Lookups; 16737 if (S) { 16738 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 16739 Lookup.suppressDiagnostics(); 16740 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 16741 NamedDecl *D = Lookup.getRepresentativeDecl(); 16742 do { 16743 S = S->getParent(); 16744 } while (S && !S->isDeclScope(D)); 16745 if (S) 16746 S = S->getParent(); 16747 Lookups.emplace_back(); 16748 Lookups.back().append(Lookup.begin(), Lookup.end()); 16749 Lookup.clear(); 16750 } 16751 } else if (auto *ULE = 16752 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 16753 Lookups.push_back(UnresolvedSet<8>()); 16754 Decl *PrevD = nullptr; 16755 for (NamedDecl *D : ULE->decls()) { 16756 if (D == PrevD) 16757 Lookups.push_back(UnresolvedSet<8>()); 16758 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D)) 16759 Lookups.back().addDecl(DRD); 16760 PrevD = D; 16761 } 16762 } 16763 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || 16764 Ty->isInstantiationDependentType() || 16765 Ty->containsUnexpandedParameterPack() || 16766 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 16767 return !D->isInvalidDecl() && 16768 (D->getType()->isDependentType() || 16769 D->getType()->isInstantiationDependentType() || 16770 D->getType()->containsUnexpandedParameterPack()); 16771 })) { 16772 UnresolvedSet<8> ResSet; 16773 for (const UnresolvedSet<8> &Set : Lookups) { 16774 if (Set.empty()) 16775 continue; 16776 ResSet.append(Set.begin(), Set.end()); 16777 // The last item marks the end of all declarations at the specified scope. 16778 ResSet.addDecl(Set[Set.size() - 1]); 16779 } 16780 return UnresolvedLookupExpr::Create( 16781 SemaRef.Context, /*NamingClass=*/nullptr, 16782 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 16783 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 16784 } 16785 // Lookup inside the classes. 16786 // C++ [over.match.oper]p3: 16787 // For a unary operator @ with an operand of a type whose 16788 // cv-unqualified version is T1, and for a binary operator @ with 16789 // a left operand of a type whose cv-unqualified version is T1 and 16790 // a right operand of a type whose cv-unqualified version is T2, 16791 // three sets of candidate functions, designated member 16792 // candidates, non-member candidates and built-in candidates, are 16793 // constructed as follows: 16794 // -- If T1 is a complete class type or a class currently being 16795 // defined, the set of member candidates is the result of the 16796 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 16797 // the set of member candidates is empty. 16798 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 16799 Lookup.suppressDiagnostics(); 16800 if (const auto *TyRec = Ty->getAs<RecordType>()) { 16801 // Complete the type if it can be completed. 16802 // If the type is neither complete nor being defined, bail out now. 16803 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() || 16804 TyRec->getDecl()->getDefinition()) { 16805 Lookup.clear(); 16806 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl()); 16807 if (Lookup.empty()) { 16808 Lookups.emplace_back(); 16809 Lookups.back().append(Lookup.begin(), Lookup.end()); 16810 } 16811 } 16812 } 16813 // Perform ADL. 16814 if (SemaRef.getLangOpts().CPlusPlus) 16815 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups); 16816 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 16817 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 16818 if (!D->isInvalidDecl() && 16819 SemaRef.Context.hasSameType(D->getType(), Ty)) 16820 return D; 16821 return nullptr; 16822 })) 16823 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), 16824 VK_LValue, Loc); 16825 if (SemaRef.getLangOpts().CPlusPlus) { 16826 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 16827 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 16828 if (!D->isInvalidDecl() && 16829 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 16830 !Ty.isMoreQualifiedThan(D->getType())) 16831 return D; 16832 return nullptr; 16833 })) { 16834 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 16835 /*DetectVirtual=*/false); 16836 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 16837 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 16838 VD->getType().getUnqualifiedType()))) { 16839 if (SemaRef.CheckBaseClassAccess( 16840 Loc, VD->getType(), Ty, Paths.front(), 16841 /*DiagID=*/0) != Sema::AR_inaccessible) { 16842 SemaRef.BuildBasePathArray(Paths, BasePath); 16843 return SemaRef.BuildDeclRefExpr( 16844 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc); 16845 } 16846 } 16847 } 16848 } 16849 } 16850 if (ReductionIdScopeSpec.isSet()) { 16851 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) 16852 << Ty << Range; 16853 return ExprError(); 16854 } 16855 return ExprEmpty(); 16856 } 16857 16858 namespace { 16859 /// Data for the reduction-based clauses. 16860 struct ReductionData { 16861 /// List of original reduction items. 16862 SmallVector<Expr *, 8> Vars; 16863 /// List of private copies of the reduction items. 16864 SmallVector<Expr *, 8> Privates; 16865 /// LHS expressions for the reduction_op expressions. 16866 SmallVector<Expr *, 8> LHSs; 16867 /// RHS expressions for the reduction_op expressions. 16868 SmallVector<Expr *, 8> RHSs; 16869 /// Reduction operation expression. 16870 SmallVector<Expr *, 8> ReductionOps; 16871 /// inscan copy operation expressions. 16872 SmallVector<Expr *, 8> InscanCopyOps; 16873 /// inscan copy temp array expressions for prefix sums. 16874 SmallVector<Expr *, 8> InscanCopyArrayTemps; 16875 /// inscan copy temp array element expressions for prefix sums. 16876 SmallVector<Expr *, 8> InscanCopyArrayElems; 16877 /// Taskgroup descriptors for the corresponding reduction items in 16878 /// in_reduction clauses. 16879 SmallVector<Expr *, 8> TaskgroupDescriptors; 16880 /// List of captures for clause. 16881 SmallVector<Decl *, 4> ExprCaptures; 16882 /// List of postupdate expressions. 16883 SmallVector<Expr *, 4> ExprPostUpdates; 16884 /// Reduction modifier. 16885 unsigned RedModifier = 0; 16886 ReductionData() = delete; 16887 /// Reserves required memory for the reduction data. 16888 ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) { 16889 Vars.reserve(Size); 16890 Privates.reserve(Size); 16891 LHSs.reserve(Size); 16892 RHSs.reserve(Size); 16893 ReductionOps.reserve(Size); 16894 if (RedModifier == OMPC_REDUCTION_inscan) { 16895 InscanCopyOps.reserve(Size); 16896 InscanCopyArrayTemps.reserve(Size); 16897 InscanCopyArrayElems.reserve(Size); 16898 } 16899 TaskgroupDescriptors.reserve(Size); 16900 ExprCaptures.reserve(Size); 16901 ExprPostUpdates.reserve(Size); 16902 } 16903 /// Stores reduction item and reduction operation only (required for dependent 16904 /// reduction item). 16905 void push(Expr *Item, Expr *ReductionOp) { 16906 Vars.emplace_back(Item); 16907 Privates.emplace_back(nullptr); 16908 LHSs.emplace_back(nullptr); 16909 RHSs.emplace_back(nullptr); 16910 ReductionOps.emplace_back(ReductionOp); 16911 TaskgroupDescriptors.emplace_back(nullptr); 16912 if (RedModifier == OMPC_REDUCTION_inscan) { 16913 InscanCopyOps.push_back(nullptr); 16914 InscanCopyArrayTemps.push_back(nullptr); 16915 InscanCopyArrayElems.push_back(nullptr); 16916 } 16917 } 16918 /// Stores reduction data. 16919 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp, 16920 Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp, 16921 Expr *CopyArrayElem) { 16922 Vars.emplace_back(Item); 16923 Privates.emplace_back(Private); 16924 LHSs.emplace_back(LHS); 16925 RHSs.emplace_back(RHS); 16926 ReductionOps.emplace_back(ReductionOp); 16927 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor); 16928 if (RedModifier == OMPC_REDUCTION_inscan) { 16929 InscanCopyOps.push_back(CopyOp); 16930 InscanCopyArrayTemps.push_back(CopyArrayTemp); 16931 InscanCopyArrayElems.push_back(CopyArrayElem); 16932 } else { 16933 assert(CopyOp == nullptr && CopyArrayTemp == nullptr && 16934 CopyArrayElem == nullptr && 16935 "Copy operation must be used for inscan reductions only."); 16936 } 16937 } 16938 }; 16939 } // namespace 16940 16941 static bool checkOMPArraySectionConstantForReduction( 16942 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement, 16943 SmallVectorImpl<llvm::APSInt> &ArraySizes) { 16944 const Expr *Length = OASE->getLength(); 16945 if (Length == nullptr) { 16946 // For array sections of the form [1:] or [:], we would need to analyze 16947 // the lower bound... 16948 if (OASE->getColonLocFirst().isValid()) 16949 return false; 16950 16951 // This is an array subscript which has implicit length 1! 16952 SingleElement = true; 16953 ArraySizes.push_back(llvm::APSInt::get(1)); 16954 } else { 16955 Expr::EvalResult Result; 16956 if (!Length->EvaluateAsInt(Result, Context)) 16957 return false; 16958 16959 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 16960 SingleElement = (ConstantLengthValue.getSExtValue() == 1); 16961 ArraySizes.push_back(ConstantLengthValue); 16962 } 16963 16964 // Get the base of this array section and walk up from there. 16965 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 16966 16967 // We require length = 1 for all array sections except the right-most to 16968 // guarantee that the memory region is contiguous and has no holes in it. 16969 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) { 16970 Length = TempOASE->getLength(); 16971 if (Length == nullptr) { 16972 // For array sections of the form [1:] or [:], we would need to analyze 16973 // the lower bound... 16974 if (OASE->getColonLocFirst().isValid()) 16975 return false; 16976 16977 // This is an array subscript which has implicit length 1! 16978 ArraySizes.push_back(llvm::APSInt::get(1)); 16979 } else { 16980 Expr::EvalResult Result; 16981 if (!Length->EvaluateAsInt(Result, Context)) 16982 return false; 16983 16984 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 16985 if (ConstantLengthValue.getSExtValue() != 1) 16986 return false; 16987 16988 ArraySizes.push_back(ConstantLengthValue); 16989 } 16990 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 16991 } 16992 16993 // If we have a single element, we don't need to add the implicit lengths. 16994 if (!SingleElement) { 16995 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) { 16996 // Has implicit length 1! 16997 ArraySizes.push_back(llvm::APSInt::get(1)); 16998 Base = TempASE->getBase()->IgnoreParenImpCasts(); 16999 } 17000 } 17001 17002 // This array section can be privatized as a single value or as a constant 17003 // sized array. 17004 return true; 17005 } 17006 17007 static BinaryOperatorKind 17008 getRelatedCompoundReductionOp(BinaryOperatorKind BOK) { 17009 if (BOK == BO_Add) 17010 return BO_AddAssign; 17011 if (BOK == BO_Mul) 17012 return BO_MulAssign; 17013 if (BOK == BO_And) 17014 return BO_AndAssign; 17015 if (BOK == BO_Or) 17016 return BO_OrAssign; 17017 if (BOK == BO_Xor) 17018 return BO_XorAssign; 17019 return BOK; 17020 } 17021 17022 static bool actOnOMPReductionKindClause( 17023 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, 17024 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 17025 SourceLocation ColonLoc, SourceLocation EndLoc, 17026 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 17027 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { 17028 DeclarationName DN = ReductionId.getName(); 17029 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator(); 17030 BinaryOperatorKind BOK = BO_Comma; 17031 17032 ASTContext &Context = S.Context; 17033 // OpenMP [2.14.3.6, reduction clause] 17034 // C 17035 // reduction-identifier is either an identifier or one of the following 17036 // operators: +, -, *, &, |, ^, && and || 17037 // C++ 17038 // reduction-identifier is either an id-expression or one of the following 17039 // operators: +, -, *, &, |, ^, && and || 17040 switch (OOK) { 17041 case OO_Plus: 17042 case OO_Minus: 17043 BOK = BO_Add; 17044 break; 17045 case OO_Star: 17046 BOK = BO_Mul; 17047 break; 17048 case OO_Amp: 17049 BOK = BO_And; 17050 break; 17051 case OO_Pipe: 17052 BOK = BO_Or; 17053 break; 17054 case OO_Caret: 17055 BOK = BO_Xor; 17056 break; 17057 case OO_AmpAmp: 17058 BOK = BO_LAnd; 17059 break; 17060 case OO_PipePipe: 17061 BOK = BO_LOr; 17062 break; 17063 case OO_New: 17064 case OO_Delete: 17065 case OO_Array_New: 17066 case OO_Array_Delete: 17067 case OO_Slash: 17068 case OO_Percent: 17069 case OO_Tilde: 17070 case OO_Exclaim: 17071 case OO_Equal: 17072 case OO_Less: 17073 case OO_Greater: 17074 case OO_LessEqual: 17075 case OO_GreaterEqual: 17076 case OO_PlusEqual: 17077 case OO_MinusEqual: 17078 case OO_StarEqual: 17079 case OO_SlashEqual: 17080 case OO_PercentEqual: 17081 case OO_CaretEqual: 17082 case OO_AmpEqual: 17083 case OO_PipeEqual: 17084 case OO_LessLess: 17085 case OO_GreaterGreater: 17086 case OO_LessLessEqual: 17087 case OO_GreaterGreaterEqual: 17088 case OO_EqualEqual: 17089 case OO_ExclaimEqual: 17090 case OO_Spaceship: 17091 case OO_PlusPlus: 17092 case OO_MinusMinus: 17093 case OO_Comma: 17094 case OO_ArrowStar: 17095 case OO_Arrow: 17096 case OO_Call: 17097 case OO_Subscript: 17098 case OO_Conditional: 17099 case OO_Coawait: 17100 case NUM_OVERLOADED_OPERATORS: 17101 llvm_unreachable("Unexpected reduction identifier"); 17102 case OO_None: 17103 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) { 17104 if (II->isStr("max")) 17105 BOK = BO_GT; 17106 else if (II->isStr("min")) 17107 BOK = BO_LT; 17108 } 17109 break; 17110 } 17111 SourceRange ReductionIdRange; 17112 if (ReductionIdScopeSpec.isValid()) 17113 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 17114 else 17115 ReductionIdRange.setBegin(ReductionId.getBeginLoc()); 17116 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 17117 17118 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 17119 bool FirstIter = true; 17120 for (Expr *RefExpr : VarList) { 17121 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 17122 // OpenMP [2.1, C/C++] 17123 // A list item is a variable or array section, subject to the restrictions 17124 // specified in Section 2.4 on page 42 and in each of the sections 17125 // describing clauses and directives for which a list appears. 17126 // OpenMP [2.14.3.3, Restrictions, p.1] 17127 // A variable that is part of another variable (as an array or 17128 // structure element) cannot appear in a private clause. 17129 if (!FirstIter && IR != ER) 17130 ++IR; 17131 FirstIter = false; 17132 SourceLocation ELoc; 17133 SourceRange ERange; 17134 Expr *SimpleRefExpr = RefExpr; 17135 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 17136 /*AllowArraySection=*/true); 17137 if (Res.second) { 17138 // Try to find 'declare reduction' corresponding construct before using 17139 // builtin/overloaded operators. 17140 QualType Type = Context.DependentTy; 17141 CXXCastPath BasePath; 17142 ExprResult DeclareReductionRef = buildDeclareReductionRef( 17143 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 17144 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 17145 Expr *ReductionOp = nullptr; 17146 if (S.CurContext->isDependentContext() && 17147 (DeclareReductionRef.isUnset() || 17148 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 17149 ReductionOp = DeclareReductionRef.get(); 17150 // It will be analyzed later. 17151 RD.push(RefExpr, ReductionOp); 17152 } 17153 ValueDecl *D = Res.first; 17154 if (!D) 17155 continue; 17156 17157 Expr *TaskgroupDescriptor = nullptr; 17158 QualType Type; 17159 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 17160 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 17161 if (ASE) { 17162 Type = ASE->getType().getNonReferenceType(); 17163 } else if (OASE) { 17164 QualType BaseType = 17165 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 17166 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 17167 Type = ATy->getElementType(); 17168 else 17169 Type = BaseType->getPointeeType(); 17170 Type = Type.getNonReferenceType(); 17171 } else { 17172 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 17173 } 17174 auto *VD = dyn_cast<VarDecl>(D); 17175 17176 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 17177 // A variable that appears in a private clause must not have an incomplete 17178 // type or a reference type. 17179 if (S.RequireCompleteType(ELoc, D->getType(), 17180 diag::err_omp_reduction_incomplete_type)) 17181 continue; 17182 // OpenMP [2.14.3.6, reduction clause, Restrictions] 17183 // A list item that appears in a reduction clause must not be 17184 // const-qualified. 17185 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc, 17186 /*AcceptIfMutable*/ false, ASE || OASE)) 17187 continue; 17188 17189 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); 17190 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 17191 // If a list-item is a reference type then it must bind to the same object 17192 // for all threads of the team. 17193 if (!ASE && !OASE) { 17194 if (VD) { 17195 VarDecl *VDDef = VD->getDefinition(); 17196 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 17197 DSARefChecker Check(Stack); 17198 if (Check.Visit(VDDef->getInit())) { 17199 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) 17200 << getOpenMPClauseName(ClauseKind) << ERange; 17201 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 17202 continue; 17203 } 17204 } 17205 } 17206 17207 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 17208 // in a Construct] 17209 // Variables with the predetermined data-sharing attributes may not be 17210 // listed in data-sharing attributes clauses, except for the cases 17211 // listed below. For these exceptions only, listing a predetermined 17212 // variable in a data-sharing attribute clause is allowed and overrides 17213 // the variable's predetermined data-sharing attributes. 17214 // OpenMP [2.14.3.6, Restrictions, p.3] 17215 // Any number of reduction clauses can be specified on the directive, 17216 // but a list item can appear only once in the reduction clauses for that 17217 // directive. 17218 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 17219 if (DVar.CKind == OMPC_reduction) { 17220 S.Diag(ELoc, diag::err_omp_once_referenced) 17221 << getOpenMPClauseName(ClauseKind); 17222 if (DVar.RefExpr) 17223 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 17224 continue; 17225 } 17226 if (DVar.CKind != OMPC_unknown) { 17227 S.Diag(ELoc, diag::err_omp_wrong_dsa) 17228 << getOpenMPClauseName(DVar.CKind) 17229 << getOpenMPClauseName(OMPC_reduction); 17230 reportOriginalDsa(S, Stack, D, DVar); 17231 continue; 17232 } 17233 17234 // OpenMP [2.14.3.6, Restrictions, p.1] 17235 // A list item that appears in a reduction clause of a worksharing 17236 // construct must be shared in the parallel regions to which any of the 17237 // worksharing regions arising from the worksharing construct bind. 17238 if (isOpenMPWorksharingDirective(CurrDir) && 17239 !isOpenMPParallelDirective(CurrDir) && 17240 !isOpenMPTeamsDirective(CurrDir)) { 17241 DVar = Stack->getImplicitDSA(D, true); 17242 if (DVar.CKind != OMPC_shared) { 17243 S.Diag(ELoc, diag::err_omp_required_access) 17244 << getOpenMPClauseName(OMPC_reduction) 17245 << getOpenMPClauseName(OMPC_shared); 17246 reportOriginalDsa(S, Stack, D, DVar); 17247 continue; 17248 } 17249 } 17250 } else { 17251 // Threadprivates cannot be shared between threads, so dignose if the base 17252 // is a threadprivate variable. 17253 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 17254 if (DVar.CKind == OMPC_threadprivate) { 17255 S.Diag(ELoc, diag::err_omp_wrong_dsa) 17256 << getOpenMPClauseName(DVar.CKind) 17257 << getOpenMPClauseName(OMPC_reduction); 17258 reportOriginalDsa(S, Stack, D, DVar); 17259 continue; 17260 } 17261 } 17262 17263 // Try to find 'declare reduction' corresponding construct before using 17264 // builtin/overloaded operators. 17265 CXXCastPath BasePath; 17266 ExprResult DeclareReductionRef = buildDeclareReductionRef( 17267 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 17268 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 17269 if (DeclareReductionRef.isInvalid()) 17270 continue; 17271 if (S.CurContext->isDependentContext() && 17272 (DeclareReductionRef.isUnset() || 17273 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 17274 RD.push(RefExpr, DeclareReductionRef.get()); 17275 continue; 17276 } 17277 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 17278 // Not allowed reduction identifier is found. 17279 S.Diag(ReductionId.getBeginLoc(), 17280 diag::err_omp_unknown_reduction_identifier) 17281 << Type << ReductionIdRange; 17282 continue; 17283 } 17284 17285 // OpenMP [2.14.3.6, reduction clause, Restrictions] 17286 // The type of a list item that appears in a reduction clause must be valid 17287 // for the reduction-identifier. For a max or min reduction in C, the type 17288 // of the list item must be an allowed arithmetic data type: char, int, 17289 // float, double, or _Bool, possibly modified with long, short, signed, or 17290 // unsigned. For a max or min reduction in C++, the type of the list item 17291 // must be an allowed arithmetic data type: char, wchar_t, int, float, 17292 // double, or bool, possibly modified with long, short, signed, or unsigned. 17293 if (DeclareReductionRef.isUnset()) { 17294 if ((BOK == BO_GT || BOK == BO_LT) && 17295 !(Type->isScalarType() || 17296 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 17297 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 17298 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; 17299 if (!ASE && !OASE) { 17300 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 17301 VarDecl::DeclarationOnly; 17302 S.Diag(D->getLocation(), 17303 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17304 << D; 17305 } 17306 continue; 17307 } 17308 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 17309 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { 17310 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) 17311 << getOpenMPClauseName(ClauseKind); 17312 if (!ASE && !OASE) { 17313 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 17314 VarDecl::DeclarationOnly; 17315 S.Diag(D->getLocation(), 17316 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17317 << D; 17318 } 17319 continue; 17320 } 17321 } 17322 17323 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 17324 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", 17325 D->hasAttrs() ? &D->getAttrs() : nullptr); 17326 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), 17327 D->hasAttrs() ? &D->getAttrs() : nullptr); 17328 QualType PrivateTy = Type; 17329 17330 // Try if we can determine constant lengths for all array sections and avoid 17331 // the VLA. 17332 bool ConstantLengthOASE = false; 17333 if (OASE) { 17334 bool SingleElement; 17335 llvm::SmallVector<llvm::APSInt, 4> ArraySizes; 17336 ConstantLengthOASE = checkOMPArraySectionConstantForReduction( 17337 Context, OASE, SingleElement, ArraySizes); 17338 17339 // If we don't have a single element, we must emit a constant array type. 17340 if (ConstantLengthOASE && !SingleElement) { 17341 for (llvm::APSInt &Size : ArraySizes) 17342 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr, 17343 ArrayType::Normal, 17344 /*IndexTypeQuals=*/0); 17345 } 17346 } 17347 17348 if ((OASE && !ConstantLengthOASE) || 17349 (!OASE && !ASE && 17350 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 17351 if (!Context.getTargetInfo().isVLASupported()) { 17352 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) { 17353 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 17354 S.Diag(ELoc, diag::note_vla_unsupported); 17355 continue; 17356 } else { 17357 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 17358 S.targetDiag(ELoc, diag::note_vla_unsupported); 17359 } 17360 } 17361 // For arrays/array sections only: 17362 // Create pseudo array type for private copy. The size for this array will 17363 // be generated during codegen. 17364 // For array subscripts or single variables Private Ty is the same as Type 17365 // (type of the variable or single array element). 17366 PrivateTy = Context.getVariableArrayType( 17367 Type, 17368 new (Context) 17369 OpaqueValueExpr(ELoc, Context.getSizeType(), VK_PRValue), 17370 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 17371 } else if (!ASE && !OASE && 17372 Context.getAsArrayType(D->getType().getNonReferenceType())) { 17373 PrivateTy = D->getType().getNonReferenceType(); 17374 } 17375 // Private copy. 17376 VarDecl *PrivateVD = 17377 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 17378 D->hasAttrs() ? &D->getAttrs() : nullptr, 17379 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 17380 // Add initializer for private variable. 17381 Expr *Init = nullptr; 17382 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); 17383 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); 17384 if (DeclareReductionRef.isUsable()) { 17385 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 17386 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 17387 if (DRD->getInitializer()) { 17388 Init = DRDRef; 17389 RHSVD->setInit(DRDRef); 17390 RHSVD->setInitStyle(VarDecl::CallInit); 17391 } 17392 } else { 17393 switch (BOK) { 17394 case BO_Add: 17395 case BO_Xor: 17396 case BO_Or: 17397 case BO_LOr: 17398 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 17399 if (Type->isScalarType() || Type->isAnyComplexType()) 17400 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 17401 break; 17402 case BO_Mul: 17403 case BO_LAnd: 17404 if (Type->isScalarType() || Type->isAnyComplexType()) { 17405 // '*' and '&&' reduction ops - initializer is '1'. 17406 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 17407 } 17408 break; 17409 case BO_And: { 17410 // '&' reduction op - initializer is '~0'. 17411 QualType OrigType = Type; 17412 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 17413 Type = ComplexTy->getElementType(); 17414 if (Type->isRealFloatingType()) { 17415 llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue( 17416 Context.getFloatTypeSemantics(Type)); 17417 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 17418 Type, ELoc); 17419 } else if (Type->isScalarType()) { 17420 uint64_t Size = Context.getTypeSize(Type); 17421 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 17422 llvm::APInt InitValue = llvm::APInt::getAllOnes(Size); 17423 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 17424 } 17425 if (Init && OrigType->isAnyComplexType()) { 17426 // Init = 0xFFFF + 0xFFFFi; 17427 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 17428 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 17429 } 17430 Type = OrigType; 17431 break; 17432 } 17433 case BO_LT: 17434 case BO_GT: { 17435 // 'min' reduction op - initializer is 'Largest representable number in 17436 // the reduction list item type'. 17437 // 'max' reduction op - initializer is 'Least representable number in 17438 // the reduction list item type'. 17439 if (Type->isIntegerType() || Type->isPointerType()) { 17440 bool IsSigned = Type->hasSignedIntegerRepresentation(); 17441 uint64_t Size = Context.getTypeSize(Type); 17442 QualType IntTy = 17443 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 17444 llvm::APInt InitValue = 17445 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 17446 : llvm::APInt::getMinValue(Size) 17447 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 17448 : llvm::APInt::getMaxValue(Size); 17449 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 17450 if (Type->isPointerType()) { 17451 // Cast to pointer type. 17452 ExprResult CastExpr = S.BuildCStyleCastExpr( 17453 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init); 17454 if (CastExpr.isInvalid()) 17455 continue; 17456 Init = CastExpr.get(); 17457 } 17458 } else if (Type->isRealFloatingType()) { 17459 llvm::APFloat InitValue = llvm::APFloat::getLargest( 17460 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 17461 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 17462 Type, ELoc); 17463 } 17464 break; 17465 } 17466 case BO_PtrMemD: 17467 case BO_PtrMemI: 17468 case BO_MulAssign: 17469 case BO_Div: 17470 case BO_Rem: 17471 case BO_Sub: 17472 case BO_Shl: 17473 case BO_Shr: 17474 case BO_LE: 17475 case BO_GE: 17476 case BO_EQ: 17477 case BO_NE: 17478 case BO_Cmp: 17479 case BO_AndAssign: 17480 case BO_XorAssign: 17481 case BO_OrAssign: 17482 case BO_Assign: 17483 case BO_AddAssign: 17484 case BO_SubAssign: 17485 case BO_DivAssign: 17486 case BO_RemAssign: 17487 case BO_ShlAssign: 17488 case BO_ShrAssign: 17489 case BO_Comma: 17490 llvm_unreachable("Unexpected reduction operation"); 17491 } 17492 } 17493 if (Init && DeclareReductionRef.isUnset()) { 17494 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 17495 // Store initializer for single element in private copy. Will be used 17496 // during codegen. 17497 PrivateVD->setInit(RHSVD->getInit()); 17498 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 17499 } else if (!Init) { 17500 S.ActOnUninitializedDecl(RHSVD); 17501 // Store initializer for single element in private copy. Will be used 17502 // during codegen. 17503 PrivateVD->setInit(RHSVD->getInit()); 17504 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 17505 } 17506 if (RHSVD->isInvalidDecl()) 17507 continue; 17508 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 17509 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) 17510 << Type << ReductionIdRange; 17511 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 17512 VarDecl::DeclarationOnly; 17513 S.Diag(D->getLocation(), 17514 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17515 << D; 17516 continue; 17517 } 17518 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); 17519 ExprResult ReductionOp; 17520 if (DeclareReductionRef.isUsable()) { 17521 QualType RedTy = DeclareReductionRef.get()->getType(); 17522 QualType PtrRedTy = Context.getPointerType(RedTy); 17523 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 17524 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 17525 if (!BasePath.empty()) { 17526 LHS = S.DefaultLvalueConversion(LHS.get()); 17527 RHS = S.DefaultLvalueConversion(RHS.get()); 17528 LHS = ImplicitCastExpr::Create( 17529 Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath, 17530 LHS.get()->getValueKind(), FPOptionsOverride()); 17531 RHS = ImplicitCastExpr::Create( 17532 Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath, 17533 RHS.get()->getValueKind(), FPOptionsOverride()); 17534 } 17535 FunctionProtoType::ExtProtoInfo EPI; 17536 QualType Params[] = {PtrRedTy, PtrRedTy}; 17537 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 17538 auto *OVE = new (Context) OpaqueValueExpr( 17539 ELoc, Context.getPointerType(FnTy), VK_PRValue, OK_Ordinary, 17540 S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); 17541 Expr *Args[] = {LHS.get(), RHS.get()}; 17542 ReductionOp = 17543 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_PRValue, ELoc, 17544 S.CurFPFeatureOverrides()); 17545 } else { 17546 BinaryOperatorKind CombBOK = getRelatedCompoundReductionOp(BOK); 17547 if (Type->isRecordType() && CombBOK != BOK) { 17548 Sema::TentativeAnalysisScope Trap(S); 17549 ReductionOp = 17550 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 17551 CombBOK, LHSDRE, RHSDRE); 17552 } 17553 if (!ReductionOp.isUsable()) { 17554 ReductionOp = 17555 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, 17556 LHSDRE, RHSDRE); 17557 if (ReductionOp.isUsable()) { 17558 if (BOK != BO_LT && BOK != BO_GT) { 17559 ReductionOp = 17560 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 17561 BO_Assign, LHSDRE, ReductionOp.get()); 17562 } else { 17563 auto *ConditionalOp = new (Context) 17564 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, 17565 RHSDRE, Type, VK_LValue, OK_Ordinary); 17566 ReductionOp = 17567 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 17568 BO_Assign, LHSDRE, ConditionalOp); 17569 } 17570 } 17571 } 17572 if (ReductionOp.isUsable()) 17573 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(), 17574 /*DiscardedValue*/ false); 17575 if (!ReductionOp.isUsable()) 17576 continue; 17577 } 17578 17579 // Add copy operations for inscan reductions. 17580 // LHS = RHS; 17581 ExprResult CopyOpRes, TempArrayRes, TempArrayElem; 17582 if (ClauseKind == OMPC_reduction && 17583 RD.RedModifier == OMPC_REDUCTION_inscan) { 17584 ExprResult RHS = S.DefaultLvalueConversion(RHSDRE); 17585 CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE, 17586 RHS.get()); 17587 if (!CopyOpRes.isUsable()) 17588 continue; 17589 CopyOpRes = 17590 S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true); 17591 if (!CopyOpRes.isUsable()) 17592 continue; 17593 // For simd directive and simd-based directives in simd mode no need to 17594 // construct temp array, need just a single temp element. 17595 if (Stack->getCurrentDirective() == OMPD_simd || 17596 (S.getLangOpts().OpenMPSimd && 17597 isOpenMPSimdDirective(Stack->getCurrentDirective()))) { 17598 VarDecl *TempArrayVD = 17599 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 17600 D->hasAttrs() ? &D->getAttrs() : nullptr); 17601 // Add a constructor to the temp decl. 17602 S.ActOnUninitializedDecl(TempArrayVD); 17603 TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc); 17604 } else { 17605 // Build temp array for prefix sum. 17606 auto *Dim = new (S.Context) 17607 OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue); 17608 QualType ArrayTy = 17609 S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal, 17610 /*IndexTypeQuals=*/0, {ELoc, ELoc}); 17611 VarDecl *TempArrayVD = 17612 buildVarDecl(S, ELoc, ArrayTy, D->getName(), 17613 D->hasAttrs() ? &D->getAttrs() : nullptr); 17614 // Add a constructor to the temp decl. 17615 S.ActOnUninitializedDecl(TempArrayVD); 17616 TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc); 17617 TempArrayElem = 17618 S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get()); 17619 auto *Idx = new (S.Context) 17620 OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue); 17621 TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(), 17622 ELoc, Idx, ELoc); 17623 } 17624 } 17625 17626 // OpenMP [2.15.4.6, Restrictions, p.2] 17627 // A list item that appears in an in_reduction clause of a task construct 17628 // must appear in a task_reduction clause of a construct associated with a 17629 // taskgroup region that includes the participating task in its taskgroup 17630 // set. The construct associated with the innermost region that meets this 17631 // condition must specify the same reduction-identifier as the in_reduction 17632 // clause. 17633 if (ClauseKind == OMPC_in_reduction) { 17634 SourceRange ParentSR; 17635 BinaryOperatorKind ParentBOK; 17636 const Expr *ParentReductionOp = nullptr; 17637 Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr; 17638 DSAStackTy::DSAVarData ParentBOKDSA = 17639 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK, 17640 ParentBOKTD); 17641 DSAStackTy::DSAVarData ParentReductionOpDSA = 17642 Stack->getTopMostTaskgroupReductionData( 17643 D, ParentSR, ParentReductionOp, ParentReductionOpTD); 17644 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown; 17645 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown; 17646 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) || 17647 (DeclareReductionRef.isUsable() && IsParentBOK) || 17648 (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) { 17649 bool EmitError = true; 17650 if (IsParentReductionOp && DeclareReductionRef.isUsable()) { 17651 llvm::FoldingSetNodeID RedId, ParentRedId; 17652 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true); 17653 DeclareReductionRef.get()->Profile(RedId, Context, 17654 /*Canonical=*/true); 17655 EmitError = RedId != ParentRedId; 17656 } 17657 if (EmitError) { 17658 S.Diag(ReductionId.getBeginLoc(), 17659 diag::err_omp_reduction_identifier_mismatch) 17660 << ReductionIdRange << RefExpr->getSourceRange(); 17661 S.Diag(ParentSR.getBegin(), 17662 diag::note_omp_previous_reduction_identifier) 17663 << ParentSR 17664 << (IsParentBOK ? ParentBOKDSA.RefExpr 17665 : ParentReductionOpDSA.RefExpr) 17666 ->getSourceRange(); 17667 continue; 17668 } 17669 } 17670 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD; 17671 } 17672 17673 DeclRefExpr *Ref = nullptr; 17674 Expr *VarsExpr = RefExpr->IgnoreParens(); 17675 if (!VD && !S.CurContext->isDependentContext()) { 17676 if (ASE || OASE) { 17677 TransformExprToCaptures RebuildToCapture(S, D); 17678 VarsExpr = 17679 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 17680 Ref = RebuildToCapture.getCapturedExpr(); 17681 } else { 17682 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); 17683 } 17684 if (!S.isOpenMPCapturedDecl(D)) { 17685 RD.ExprCaptures.emplace_back(Ref->getDecl()); 17686 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 17687 ExprResult RefRes = S.DefaultLvalueConversion(Ref); 17688 if (!RefRes.isUsable()) 17689 continue; 17690 ExprResult PostUpdateRes = 17691 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 17692 RefRes.get()); 17693 if (!PostUpdateRes.isUsable()) 17694 continue; 17695 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 17696 Stack->getCurrentDirective() == OMPD_taskgroup) { 17697 S.Diag(RefExpr->getExprLoc(), 17698 diag::err_omp_reduction_non_addressable_expression) 17699 << RefExpr->getSourceRange(); 17700 continue; 17701 } 17702 RD.ExprPostUpdates.emplace_back( 17703 S.IgnoredValueConversions(PostUpdateRes.get()).get()); 17704 } 17705 } 17706 } 17707 // All reduction items are still marked as reduction (to do not increase 17708 // code base size). 17709 unsigned Modifier = RD.RedModifier; 17710 // Consider task_reductions as reductions with task modifier. Required for 17711 // correct analysis of in_reduction clauses. 17712 if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction) 17713 Modifier = OMPC_REDUCTION_task; 17714 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier, 17715 ASE || OASE); 17716 if (Modifier == OMPC_REDUCTION_task && 17717 (CurrDir == OMPD_taskgroup || 17718 ((isOpenMPParallelDirective(CurrDir) || 17719 isOpenMPWorksharingDirective(CurrDir)) && 17720 !isOpenMPSimdDirective(CurrDir)))) { 17721 if (DeclareReductionRef.isUsable()) 17722 Stack->addTaskgroupReductionData(D, ReductionIdRange, 17723 DeclareReductionRef.get()); 17724 else 17725 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK); 17726 } 17727 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(), 17728 TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(), 17729 TempArrayElem.get()); 17730 } 17731 return RD.Vars.empty(); 17732 } 17733 17734 OMPClause *Sema::ActOnOpenMPReductionClause( 17735 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, 17736 SourceLocation StartLoc, SourceLocation LParenLoc, 17737 SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, 17738 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 17739 ArrayRef<Expr *> UnresolvedReductions) { 17740 if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) { 17741 Diag(LParenLoc, diag::err_omp_unexpected_clause_value) 17742 << getListOfPossibleValues(OMPC_reduction, /*First=*/0, 17743 /*Last=*/OMPC_REDUCTION_unknown) 17744 << getOpenMPClauseName(OMPC_reduction); 17745 return nullptr; 17746 } 17747 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions 17748 // A reduction clause with the inscan reduction-modifier may only appear on a 17749 // worksharing-loop construct, a worksharing-loop SIMD construct, a simd 17750 // construct, a parallel worksharing-loop construct or a parallel 17751 // worksharing-loop SIMD construct. 17752 if (Modifier == OMPC_REDUCTION_inscan && 17753 (DSAStack->getCurrentDirective() != OMPD_for && 17754 DSAStack->getCurrentDirective() != OMPD_for_simd && 17755 DSAStack->getCurrentDirective() != OMPD_simd && 17756 DSAStack->getCurrentDirective() != OMPD_parallel_for && 17757 DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) { 17758 Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction); 17759 return nullptr; 17760 } 17761 17762 ReductionData RD(VarList.size(), Modifier); 17763 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, 17764 StartLoc, LParenLoc, ColonLoc, EndLoc, 17765 ReductionIdScopeSpec, ReductionId, 17766 UnresolvedReductions, RD)) 17767 return nullptr; 17768 17769 return OMPReductionClause::Create( 17770 Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier, 17771 RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 17772 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps, 17773 RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems, 17774 buildPreInits(Context, RD.ExprCaptures), 17775 buildPostUpdate(*this, RD.ExprPostUpdates)); 17776 } 17777 17778 OMPClause *Sema::ActOnOpenMPTaskReductionClause( 17779 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 17780 SourceLocation ColonLoc, SourceLocation EndLoc, 17781 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 17782 ArrayRef<Expr *> UnresolvedReductions) { 17783 ReductionData RD(VarList.size()); 17784 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList, 17785 StartLoc, LParenLoc, ColonLoc, EndLoc, 17786 ReductionIdScopeSpec, ReductionId, 17787 UnresolvedReductions, RD)) 17788 return nullptr; 17789 17790 return OMPTaskReductionClause::Create( 17791 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 17792 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 17793 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 17794 buildPreInits(Context, RD.ExprCaptures), 17795 buildPostUpdate(*this, RD.ExprPostUpdates)); 17796 } 17797 17798 OMPClause *Sema::ActOnOpenMPInReductionClause( 17799 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 17800 SourceLocation ColonLoc, SourceLocation EndLoc, 17801 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 17802 ArrayRef<Expr *> UnresolvedReductions) { 17803 ReductionData RD(VarList.size()); 17804 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList, 17805 StartLoc, LParenLoc, ColonLoc, EndLoc, 17806 ReductionIdScopeSpec, ReductionId, 17807 UnresolvedReductions, RD)) 17808 return nullptr; 17809 17810 return OMPInReductionClause::Create( 17811 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 17812 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 17813 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors, 17814 buildPreInits(Context, RD.ExprCaptures), 17815 buildPostUpdate(*this, RD.ExprPostUpdates)); 17816 } 17817 17818 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 17819 SourceLocation LinLoc) { 17820 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 17821 LinKind == OMPC_LINEAR_unknown) { 17822 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 17823 return true; 17824 } 17825 return false; 17826 } 17827 17828 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, 17829 OpenMPLinearClauseKind LinKind, QualType Type, 17830 bool IsDeclareSimd) { 17831 const auto *VD = dyn_cast_or_null<VarDecl>(D); 17832 // A variable must not have an incomplete type or a reference type. 17833 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 17834 return true; 17835 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 17836 !Type->isReferenceType()) { 17837 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 17838 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 17839 return true; 17840 } 17841 Type = Type.getNonReferenceType(); 17842 17843 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 17844 // A variable that is privatized must not have a const-qualified type 17845 // unless it is of class type with a mutable member. This restriction does 17846 // not apply to the firstprivate clause, nor to the linear clause on 17847 // declarative directives (like declare simd). 17848 if (!IsDeclareSimd && 17849 rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc)) 17850 return true; 17851 17852 // A list item must be of integral or pointer type. 17853 Type = Type.getUnqualifiedType().getCanonicalType(); 17854 const auto *Ty = Type.getTypePtrOrNull(); 17855 if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() && 17856 !Ty->isIntegralType(Context) && !Ty->isPointerType())) { 17857 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 17858 if (D) { 17859 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 17860 VarDecl::DeclarationOnly; 17861 Diag(D->getLocation(), 17862 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17863 << D; 17864 } 17865 return true; 17866 } 17867 return false; 17868 } 17869 17870 OMPClause *Sema::ActOnOpenMPLinearClause( 17871 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 17872 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 17873 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 17874 SmallVector<Expr *, 8> Vars; 17875 SmallVector<Expr *, 8> Privates; 17876 SmallVector<Expr *, 8> Inits; 17877 SmallVector<Decl *, 4> ExprCaptures; 17878 SmallVector<Expr *, 4> ExprPostUpdates; 17879 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 17880 LinKind = OMPC_LINEAR_val; 17881 for (Expr *RefExpr : VarList) { 17882 assert(RefExpr && "NULL expr in OpenMP linear clause."); 17883 SourceLocation ELoc; 17884 SourceRange ERange; 17885 Expr *SimpleRefExpr = RefExpr; 17886 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 17887 if (Res.second) { 17888 // It will be analyzed later. 17889 Vars.push_back(RefExpr); 17890 Privates.push_back(nullptr); 17891 Inits.push_back(nullptr); 17892 } 17893 ValueDecl *D = Res.first; 17894 if (!D) 17895 continue; 17896 17897 QualType Type = D->getType(); 17898 auto *VD = dyn_cast<VarDecl>(D); 17899 17900 // OpenMP [2.14.3.7, linear clause] 17901 // A list-item cannot appear in more than one linear clause. 17902 // A list-item that appears in a linear clause cannot appear in any 17903 // other data-sharing attribute clause. 17904 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 17905 if (DVar.RefExpr) { 17906 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 17907 << getOpenMPClauseName(OMPC_linear); 17908 reportOriginalDsa(*this, DSAStack, D, DVar); 17909 continue; 17910 } 17911 17912 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 17913 continue; 17914 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 17915 17916 // Build private copy of original var. 17917 VarDecl *Private = 17918 buildVarDecl(*this, ELoc, Type, D->getName(), 17919 D->hasAttrs() ? &D->getAttrs() : nullptr, 17920 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 17921 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 17922 // Build var to save initial value. 17923 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 17924 Expr *InitExpr; 17925 DeclRefExpr *Ref = nullptr; 17926 if (!VD && !CurContext->isDependentContext()) { 17927 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 17928 if (!isOpenMPCapturedDecl(D)) { 17929 ExprCaptures.push_back(Ref->getDecl()); 17930 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 17931 ExprResult RefRes = DefaultLvalueConversion(Ref); 17932 if (!RefRes.isUsable()) 17933 continue; 17934 ExprResult PostUpdateRes = 17935 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 17936 SimpleRefExpr, RefRes.get()); 17937 if (!PostUpdateRes.isUsable()) 17938 continue; 17939 ExprPostUpdates.push_back( 17940 IgnoredValueConversions(PostUpdateRes.get()).get()); 17941 } 17942 } 17943 } 17944 if (LinKind == OMPC_LINEAR_uval) 17945 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 17946 else 17947 InitExpr = VD ? SimpleRefExpr : Ref; 17948 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 17949 /*DirectInit=*/false); 17950 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 17951 17952 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 17953 Vars.push_back((VD || CurContext->isDependentContext()) 17954 ? RefExpr->IgnoreParens() 17955 : Ref); 17956 Privates.push_back(PrivateRef); 17957 Inits.push_back(InitRef); 17958 } 17959 17960 if (Vars.empty()) 17961 return nullptr; 17962 17963 Expr *StepExpr = Step; 17964 Expr *CalcStepExpr = nullptr; 17965 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 17966 !Step->isInstantiationDependent() && 17967 !Step->containsUnexpandedParameterPack()) { 17968 SourceLocation StepLoc = Step->getBeginLoc(); 17969 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 17970 if (Val.isInvalid()) 17971 return nullptr; 17972 StepExpr = Val.get(); 17973 17974 // Build var to save the step value. 17975 VarDecl *SaveVar = 17976 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 17977 ExprResult SaveRef = 17978 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 17979 ExprResult CalcStep = 17980 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 17981 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false); 17982 17983 // Warn about zero linear step (it would be probably better specified as 17984 // making corresponding variables 'const'). 17985 if (Optional<llvm::APSInt> Result = 17986 StepExpr->getIntegerConstantExpr(Context)) { 17987 if (!Result->isNegative() && !Result->isStrictlyPositive()) 17988 Diag(StepLoc, diag::warn_omp_linear_step_zero) 17989 << Vars[0] << (Vars.size() > 1); 17990 } else if (CalcStep.isUsable()) { 17991 // Calculate the step beforehand instead of doing this on each iteration. 17992 // (This is not used if the number of iterations may be kfold-ed). 17993 CalcStepExpr = CalcStep.get(); 17994 } 17995 } 17996 17997 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 17998 ColonLoc, EndLoc, Vars, Privates, Inits, 17999 StepExpr, CalcStepExpr, 18000 buildPreInits(Context, ExprCaptures), 18001 buildPostUpdate(*this, ExprPostUpdates)); 18002 } 18003 18004 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 18005 Expr *NumIterations, Sema &SemaRef, 18006 Scope *S, DSAStackTy *Stack) { 18007 // Walk the vars and build update/final expressions for the CodeGen. 18008 SmallVector<Expr *, 8> Updates; 18009 SmallVector<Expr *, 8> Finals; 18010 SmallVector<Expr *, 8> UsedExprs; 18011 Expr *Step = Clause.getStep(); 18012 Expr *CalcStep = Clause.getCalcStep(); 18013 // OpenMP [2.14.3.7, linear clause] 18014 // If linear-step is not specified it is assumed to be 1. 18015 if (!Step) 18016 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 18017 else if (CalcStep) 18018 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 18019 bool HasErrors = false; 18020 auto CurInit = Clause.inits().begin(); 18021 auto CurPrivate = Clause.privates().begin(); 18022 OpenMPLinearClauseKind LinKind = Clause.getModifier(); 18023 for (Expr *RefExpr : Clause.varlists()) { 18024 SourceLocation ELoc; 18025 SourceRange ERange; 18026 Expr *SimpleRefExpr = RefExpr; 18027 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange); 18028 ValueDecl *D = Res.first; 18029 if (Res.second || !D) { 18030 Updates.push_back(nullptr); 18031 Finals.push_back(nullptr); 18032 HasErrors = true; 18033 continue; 18034 } 18035 auto &&Info = Stack->isLoopControlVariable(D); 18036 // OpenMP [2.15.11, distribute simd Construct] 18037 // A list item may not appear in a linear clause, unless it is the loop 18038 // iteration variable. 18039 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) && 18040 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) { 18041 SemaRef.Diag(ELoc, 18042 diag::err_omp_linear_distribute_var_non_loop_iteration); 18043 Updates.push_back(nullptr); 18044 Finals.push_back(nullptr); 18045 HasErrors = true; 18046 continue; 18047 } 18048 Expr *InitExpr = *CurInit; 18049 18050 // Build privatized reference to the current linear var. 18051 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 18052 Expr *CapturedRef; 18053 if (LinKind == OMPC_LINEAR_uval) 18054 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 18055 else 18056 CapturedRef = 18057 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 18058 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 18059 /*RefersToCapture=*/true); 18060 18061 // Build update: Var = InitExpr + IV * Step 18062 ExprResult Update; 18063 if (!Info.first) 18064 Update = buildCounterUpdate( 18065 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step, 18066 /*Subtract=*/false, /*IsNonRectangularLB=*/false); 18067 else 18068 Update = *CurPrivate; 18069 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(), 18070 /*DiscardedValue*/ false); 18071 18072 // Build final: Var = PrivCopy; 18073 ExprResult Final; 18074 if (!Info.first) 18075 Final = SemaRef.BuildBinOp( 18076 S, RefExpr->getExprLoc(), BO_Assign, CapturedRef, 18077 SemaRef.DefaultLvalueConversion(*CurPrivate).get()); 18078 else 18079 Final = *CurPrivate; 18080 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(), 18081 /*DiscardedValue*/ false); 18082 18083 if (!Update.isUsable() || !Final.isUsable()) { 18084 Updates.push_back(nullptr); 18085 Finals.push_back(nullptr); 18086 UsedExprs.push_back(nullptr); 18087 HasErrors = true; 18088 } else { 18089 Updates.push_back(Update.get()); 18090 Finals.push_back(Final.get()); 18091 if (!Info.first) 18092 UsedExprs.push_back(SimpleRefExpr); 18093 } 18094 ++CurInit; 18095 ++CurPrivate; 18096 } 18097 if (Expr *S = Clause.getStep()) 18098 UsedExprs.push_back(S); 18099 // Fill the remaining part with the nullptr. 18100 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr); 18101 Clause.setUpdates(Updates); 18102 Clause.setFinals(Finals); 18103 Clause.setUsedExprs(UsedExprs); 18104 return HasErrors; 18105 } 18106 18107 OMPClause *Sema::ActOnOpenMPAlignedClause( 18108 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 18109 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 18110 SmallVector<Expr *, 8> Vars; 18111 for (Expr *RefExpr : VarList) { 18112 assert(RefExpr && "NULL expr in OpenMP linear clause."); 18113 SourceLocation ELoc; 18114 SourceRange ERange; 18115 Expr *SimpleRefExpr = RefExpr; 18116 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 18117 if (Res.second) { 18118 // It will be analyzed later. 18119 Vars.push_back(RefExpr); 18120 } 18121 ValueDecl *D = Res.first; 18122 if (!D) 18123 continue; 18124 18125 QualType QType = D->getType(); 18126 auto *VD = dyn_cast<VarDecl>(D); 18127 18128 // OpenMP [2.8.1, simd construct, Restrictions] 18129 // The type of list items appearing in the aligned clause must be 18130 // array, pointer, reference to array, or reference to pointer. 18131 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 18132 const Type *Ty = QType.getTypePtrOrNull(); 18133 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 18134 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 18135 << QType << getLangOpts().CPlusPlus << ERange; 18136 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 18137 VarDecl::DeclarationOnly; 18138 Diag(D->getLocation(), 18139 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 18140 << D; 18141 continue; 18142 } 18143 18144 // OpenMP [2.8.1, simd construct, Restrictions] 18145 // A list-item cannot appear in more than one aligned clause. 18146 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 18147 Diag(ELoc, diag::err_omp_used_in_clause_twice) 18148 << 0 << getOpenMPClauseName(OMPC_aligned) << ERange; 18149 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 18150 << getOpenMPClauseName(OMPC_aligned); 18151 continue; 18152 } 18153 18154 DeclRefExpr *Ref = nullptr; 18155 if (!VD && isOpenMPCapturedDecl(D)) 18156 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 18157 Vars.push_back(DefaultFunctionArrayConversion( 18158 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 18159 .get()); 18160 } 18161 18162 // OpenMP [2.8.1, simd construct, Description] 18163 // The parameter of the aligned clause, alignment, must be a constant 18164 // positive integer expression. 18165 // If no optional parameter is specified, implementation-defined default 18166 // alignments for SIMD instructions on the target platforms are assumed. 18167 if (Alignment != nullptr) { 18168 ExprResult AlignResult = 18169 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 18170 if (AlignResult.isInvalid()) 18171 return nullptr; 18172 Alignment = AlignResult.get(); 18173 } 18174 if (Vars.empty()) 18175 return nullptr; 18176 18177 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 18178 EndLoc, Vars, Alignment); 18179 } 18180 18181 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 18182 SourceLocation StartLoc, 18183 SourceLocation LParenLoc, 18184 SourceLocation EndLoc) { 18185 SmallVector<Expr *, 8> Vars; 18186 SmallVector<Expr *, 8> SrcExprs; 18187 SmallVector<Expr *, 8> DstExprs; 18188 SmallVector<Expr *, 8> AssignmentOps; 18189 for (Expr *RefExpr : VarList) { 18190 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 18191 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 18192 // It will be analyzed later. 18193 Vars.push_back(RefExpr); 18194 SrcExprs.push_back(nullptr); 18195 DstExprs.push_back(nullptr); 18196 AssignmentOps.push_back(nullptr); 18197 continue; 18198 } 18199 18200 SourceLocation ELoc = RefExpr->getExprLoc(); 18201 // OpenMP [2.1, C/C++] 18202 // A list item is a variable name. 18203 // OpenMP [2.14.4.1, Restrictions, p.1] 18204 // A list item that appears in a copyin clause must be threadprivate. 18205 auto *DE = dyn_cast<DeclRefExpr>(RefExpr); 18206 if (!DE || !isa<VarDecl>(DE->getDecl())) { 18207 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 18208 << 0 << RefExpr->getSourceRange(); 18209 continue; 18210 } 18211 18212 Decl *D = DE->getDecl(); 18213 auto *VD = cast<VarDecl>(D); 18214 18215 QualType Type = VD->getType(); 18216 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 18217 // It will be analyzed later. 18218 Vars.push_back(DE); 18219 SrcExprs.push_back(nullptr); 18220 DstExprs.push_back(nullptr); 18221 AssignmentOps.push_back(nullptr); 18222 continue; 18223 } 18224 18225 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 18226 // A list item that appears in a copyin clause must be threadprivate. 18227 if (!DSAStack->isThreadPrivate(VD)) { 18228 Diag(ELoc, diag::err_omp_required_access) 18229 << getOpenMPClauseName(OMPC_copyin) 18230 << getOpenMPDirectiveName(OMPD_threadprivate); 18231 continue; 18232 } 18233 18234 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 18235 // A variable of class type (or array thereof) that appears in a 18236 // copyin clause requires an accessible, unambiguous copy assignment 18237 // operator for the class type. 18238 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 18239 VarDecl *SrcVD = 18240 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(), 18241 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 18242 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr( 18243 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 18244 VarDecl *DstVD = 18245 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst", 18246 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 18247 DeclRefExpr *PseudoDstExpr = 18248 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 18249 // For arrays generate assignment operation for single element and replace 18250 // it by the original array element in CodeGen. 18251 ExprResult AssignmentOp = 18252 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr, 18253 PseudoSrcExpr); 18254 if (AssignmentOp.isInvalid()) 18255 continue; 18256 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 18257 /*DiscardedValue*/ false); 18258 if (AssignmentOp.isInvalid()) 18259 continue; 18260 18261 DSAStack->addDSA(VD, DE, OMPC_copyin); 18262 Vars.push_back(DE); 18263 SrcExprs.push_back(PseudoSrcExpr); 18264 DstExprs.push_back(PseudoDstExpr); 18265 AssignmentOps.push_back(AssignmentOp.get()); 18266 } 18267 18268 if (Vars.empty()) 18269 return nullptr; 18270 18271 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 18272 SrcExprs, DstExprs, AssignmentOps); 18273 } 18274 18275 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 18276 SourceLocation StartLoc, 18277 SourceLocation LParenLoc, 18278 SourceLocation EndLoc) { 18279 SmallVector<Expr *, 8> Vars; 18280 SmallVector<Expr *, 8> SrcExprs; 18281 SmallVector<Expr *, 8> DstExprs; 18282 SmallVector<Expr *, 8> AssignmentOps; 18283 for (Expr *RefExpr : VarList) { 18284 assert(RefExpr && "NULL expr in OpenMP linear clause."); 18285 SourceLocation ELoc; 18286 SourceRange ERange; 18287 Expr *SimpleRefExpr = RefExpr; 18288 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 18289 if (Res.second) { 18290 // It will be analyzed later. 18291 Vars.push_back(RefExpr); 18292 SrcExprs.push_back(nullptr); 18293 DstExprs.push_back(nullptr); 18294 AssignmentOps.push_back(nullptr); 18295 } 18296 ValueDecl *D = Res.first; 18297 if (!D) 18298 continue; 18299 18300 QualType Type = D->getType(); 18301 auto *VD = dyn_cast<VarDecl>(D); 18302 18303 // OpenMP [2.14.4.2, Restrictions, p.2] 18304 // A list item that appears in a copyprivate clause may not appear in a 18305 // private or firstprivate clause on the single construct. 18306 if (!VD || !DSAStack->isThreadPrivate(VD)) { 18307 DSAStackTy::DSAVarData DVar = 18308 DSAStack->getTopDSA(D, /*FromParent=*/false); 18309 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 18310 DVar.RefExpr) { 18311 Diag(ELoc, diag::err_omp_wrong_dsa) 18312 << getOpenMPClauseName(DVar.CKind) 18313 << getOpenMPClauseName(OMPC_copyprivate); 18314 reportOriginalDsa(*this, DSAStack, D, DVar); 18315 continue; 18316 } 18317 18318 // OpenMP [2.11.4.2, Restrictions, p.1] 18319 // All list items that appear in a copyprivate clause must be either 18320 // threadprivate or private in the enclosing context. 18321 if (DVar.CKind == OMPC_unknown) { 18322 DVar = DSAStack->getImplicitDSA(D, false); 18323 if (DVar.CKind == OMPC_shared) { 18324 Diag(ELoc, diag::err_omp_required_access) 18325 << getOpenMPClauseName(OMPC_copyprivate) 18326 << "threadprivate or private in the enclosing context"; 18327 reportOriginalDsa(*this, DSAStack, D, DVar); 18328 continue; 18329 } 18330 } 18331 } 18332 18333 // Variably modified types are not supported. 18334 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 18335 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 18336 << getOpenMPClauseName(OMPC_copyprivate) << Type 18337 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 18338 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 18339 VarDecl::DeclarationOnly; 18340 Diag(D->getLocation(), 18341 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 18342 << D; 18343 continue; 18344 } 18345 18346 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 18347 // A variable of class type (or array thereof) that appears in a 18348 // copyin clause requires an accessible, unambiguous copy assignment 18349 // operator for the class type. 18350 Type = Context.getBaseElementType(Type.getNonReferenceType()) 18351 .getUnqualifiedType(); 18352 VarDecl *SrcVD = 18353 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src", 18354 D->hasAttrs() ? &D->getAttrs() : nullptr); 18355 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 18356 VarDecl *DstVD = 18357 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst", 18358 D->hasAttrs() ? &D->getAttrs() : nullptr); 18359 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 18360 ExprResult AssignmentOp = BuildBinOp( 18361 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr); 18362 if (AssignmentOp.isInvalid()) 18363 continue; 18364 AssignmentOp = 18365 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 18366 if (AssignmentOp.isInvalid()) 18367 continue; 18368 18369 // No need to mark vars as copyprivate, they are already threadprivate or 18370 // implicitly private. 18371 assert(VD || isOpenMPCapturedDecl(D)); 18372 Vars.push_back( 18373 VD ? RefExpr->IgnoreParens() 18374 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 18375 SrcExprs.push_back(PseudoSrcExpr); 18376 DstExprs.push_back(PseudoDstExpr); 18377 AssignmentOps.push_back(AssignmentOp.get()); 18378 } 18379 18380 if (Vars.empty()) 18381 return nullptr; 18382 18383 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 18384 Vars, SrcExprs, DstExprs, AssignmentOps); 18385 } 18386 18387 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 18388 SourceLocation StartLoc, 18389 SourceLocation LParenLoc, 18390 SourceLocation EndLoc) { 18391 if (VarList.empty()) 18392 return nullptr; 18393 18394 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 18395 } 18396 18397 /// Tries to find omp_depend_t. type. 18398 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack, 18399 bool Diagnose = true) { 18400 QualType OMPDependT = Stack->getOMPDependT(); 18401 if (!OMPDependT.isNull()) 18402 return true; 18403 IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t"); 18404 ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope()); 18405 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 18406 if (Diagnose) 18407 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t"; 18408 return false; 18409 } 18410 Stack->setOMPDependT(PT.get()); 18411 return true; 18412 } 18413 18414 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, 18415 SourceLocation LParenLoc, 18416 SourceLocation EndLoc) { 18417 if (!Depobj) 18418 return nullptr; 18419 18420 bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack); 18421 18422 // OpenMP 5.0, 2.17.10.1 depobj Construct 18423 // depobj is an lvalue expression of type omp_depend_t. 18424 if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() && 18425 !Depobj->isInstantiationDependent() && 18426 !Depobj->containsUnexpandedParameterPack() && 18427 (OMPDependTFound && 18428 !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(), 18429 /*CompareUnqualified=*/true))) { 18430 Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue) 18431 << 0 << Depobj->getType() << Depobj->getSourceRange(); 18432 } 18433 18434 if (!Depobj->isLValue()) { 18435 Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue) 18436 << 1 << Depobj->getSourceRange(); 18437 } 18438 18439 return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj); 18440 } 18441 18442 OMPClause * 18443 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind, 18444 SourceLocation DepLoc, SourceLocation ColonLoc, 18445 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 18446 SourceLocation LParenLoc, SourceLocation EndLoc) { 18447 if (DSAStack->getCurrentDirective() == OMPD_ordered && 18448 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 18449 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 18450 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 18451 return nullptr; 18452 } 18453 if (DSAStack->getCurrentDirective() == OMPD_taskwait && 18454 DepKind == OMPC_DEPEND_mutexinoutset) { 18455 Diag(DepLoc, diag::err_omp_taskwait_depend_mutexinoutset_not_allowed); 18456 return nullptr; 18457 } 18458 if ((DSAStack->getCurrentDirective() != OMPD_ordered || 18459 DSAStack->getCurrentDirective() == OMPD_depobj) && 18460 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 18461 DepKind == OMPC_DEPEND_sink || 18462 ((LangOpts.OpenMP < 50 || 18463 DSAStack->getCurrentDirective() == OMPD_depobj) && 18464 DepKind == OMPC_DEPEND_depobj))) { 18465 SmallVector<unsigned, 3> Except; 18466 Except.push_back(OMPC_DEPEND_source); 18467 Except.push_back(OMPC_DEPEND_sink); 18468 if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj) 18469 Except.push_back(OMPC_DEPEND_depobj); 18470 std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier) 18471 ? "depend modifier(iterator) or " 18472 : ""; 18473 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 18474 << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0, 18475 /*Last=*/OMPC_DEPEND_unknown, 18476 Except) 18477 << getOpenMPClauseName(OMPC_depend); 18478 return nullptr; 18479 } 18480 if (DepModifier && 18481 (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) { 18482 Diag(DepModifier->getExprLoc(), 18483 diag::err_omp_depend_sink_source_with_modifier); 18484 return nullptr; 18485 } 18486 if (DepModifier && 18487 !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator)) 18488 Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator); 18489 18490 SmallVector<Expr *, 8> Vars; 18491 DSAStackTy::OperatorOffsetTy OpsOffs; 18492 llvm::APSInt DepCounter(/*BitWidth=*/32); 18493 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 18494 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) { 18495 if (const Expr *OrderedCountExpr = 18496 DSAStack->getParentOrderedRegionParam().first) { 18497 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 18498 TotalDepCount.setIsUnsigned(/*Val=*/true); 18499 } 18500 } 18501 for (Expr *RefExpr : VarList) { 18502 assert(RefExpr && "NULL expr in OpenMP shared clause."); 18503 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 18504 // It will be analyzed later. 18505 Vars.push_back(RefExpr); 18506 continue; 18507 } 18508 18509 SourceLocation ELoc = RefExpr->getExprLoc(); 18510 Expr *SimpleExpr = RefExpr->IgnoreParenCasts(); 18511 if (DepKind == OMPC_DEPEND_sink) { 18512 if (DSAStack->getParentOrderedRegionParam().first && 18513 DepCounter >= TotalDepCount) { 18514 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 18515 continue; 18516 } 18517 ++DepCounter; 18518 // OpenMP [2.13.9, Summary] 18519 // depend(dependence-type : vec), where dependence-type is: 18520 // 'sink' and where vec is the iteration vector, which has the form: 18521 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 18522 // where n is the value specified by the ordered clause in the loop 18523 // directive, xi denotes the loop iteration variable of the i-th nested 18524 // loop associated with the loop directive, and di is a constant 18525 // non-negative integer. 18526 if (CurContext->isDependentContext()) { 18527 // It will be analyzed later. 18528 Vars.push_back(RefExpr); 18529 continue; 18530 } 18531 SimpleExpr = SimpleExpr->IgnoreImplicit(); 18532 OverloadedOperatorKind OOK = OO_None; 18533 SourceLocation OOLoc; 18534 Expr *LHS = SimpleExpr; 18535 Expr *RHS = nullptr; 18536 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 18537 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 18538 OOLoc = BO->getOperatorLoc(); 18539 LHS = BO->getLHS()->IgnoreParenImpCasts(); 18540 RHS = BO->getRHS()->IgnoreParenImpCasts(); 18541 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 18542 OOK = OCE->getOperator(); 18543 OOLoc = OCE->getOperatorLoc(); 18544 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 18545 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 18546 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 18547 OOK = MCE->getMethodDecl() 18548 ->getNameInfo() 18549 .getName() 18550 .getCXXOverloadedOperator(); 18551 OOLoc = MCE->getCallee()->getExprLoc(); 18552 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 18553 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 18554 } 18555 SourceLocation ELoc; 18556 SourceRange ERange; 18557 auto Res = getPrivateItem(*this, LHS, ELoc, ERange); 18558 if (Res.second) { 18559 // It will be analyzed later. 18560 Vars.push_back(RefExpr); 18561 } 18562 ValueDecl *D = Res.first; 18563 if (!D) 18564 continue; 18565 18566 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 18567 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 18568 continue; 18569 } 18570 if (RHS) { 18571 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 18572 RHS, OMPC_depend, /*StrictlyPositive=*/false); 18573 if (RHSRes.isInvalid()) 18574 continue; 18575 } 18576 if (!CurContext->isDependentContext() && 18577 DSAStack->getParentOrderedRegionParam().first && 18578 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 18579 const ValueDecl *VD = 18580 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue()); 18581 if (VD) 18582 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 18583 << 1 << VD; 18584 else 18585 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; 18586 continue; 18587 } 18588 OpsOffs.emplace_back(RHS, OOK); 18589 } else { 18590 bool OMPDependTFound = LangOpts.OpenMP >= 50; 18591 if (OMPDependTFound) 18592 OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack, 18593 DepKind == OMPC_DEPEND_depobj); 18594 if (DepKind == OMPC_DEPEND_depobj) { 18595 // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++ 18596 // List items used in depend clauses with the depobj dependence type 18597 // must be expressions of the omp_depend_t type. 18598 if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() && 18599 !RefExpr->isInstantiationDependent() && 18600 !RefExpr->containsUnexpandedParameterPack() && 18601 (OMPDependTFound && 18602 !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(), 18603 RefExpr->getType()))) { 18604 Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue) 18605 << 0 << RefExpr->getType() << RefExpr->getSourceRange(); 18606 continue; 18607 } 18608 if (!RefExpr->isLValue()) { 18609 Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue) 18610 << 1 << RefExpr->getType() << RefExpr->getSourceRange(); 18611 continue; 18612 } 18613 } else { 18614 // OpenMP 5.0 [2.17.11, Restrictions] 18615 // List items used in depend clauses cannot be zero-length array 18616 // sections. 18617 QualType ExprTy = RefExpr->getType().getNonReferenceType(); 18618 const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr); 18619 if (OASE) { 18620 QualType BaseType = 18621 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 18622 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 18623 ExprTy = ATy->getElementType(); 18624 else 18625 ExprTy = BaseType->getPointeeType(); 18626 ExprTy = ExprTy.getNonReferenceType(); 18627 const Expr *Length = OASE->getLength(); 18628 Expr::EvalResult Result; 18629 if (Length && !Length->isValueDependent() && 18630 Length->EvaluateAsInt(Result, Context) && 18631 Result.Val.getInt().isZero()) { 18632 Diag(ELoc, 18633 diag::err_omp_depend_zero_length_array_section_not_allowed) 18634 << SimpleExpr->getSourceRange(); 18635 continue; 18636 } 18637 } 18638 18639 // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++ 18640 // List items used in depend clauses with the in, out, inout or 18641 // mutexinoutset dependence types cannot be expressions of the 18642 // omp_depend_t type. 18643 if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() && 18644 !RefExpr->isInstantiationDependent() && 18645 !RefExpr->containsUnexpandedParameterPack() && 18646 (!RefExpr->IgnoreParenImpCasts()->isLValue() || 18647 (OMPDependTFound && 18648 DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr()))) { 18649 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 18650 << (LangOpts.OpenMP >= 50 ? 1 : 0) 18651 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 18652 continue; 18653 } 18654 18655 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 18656 if (ASE && !ASE->getBase()->isTypeDependent() && 18657 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() && 18658 !ASE->getBase()->getType().getNonReferenceType()->isArrayType()) { 18659 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 18660 << (LangOpts.OpenMP >= 50 ? 1 : 0) 18661 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 18662 continue; 18663 } 18664 18665 ExprResult Res; 18666 { 18667 Sema::TentativeAnalysisScope Trap(*this); 18668 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, 18669 RefExpr->IgnoreParenImpCasts()); 18670 } 18671 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) && 18672 !isa<OMPArrayShapingExpr>(SimpleExpr)) { 18673 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 18674 << (LangOpts.OpenMP >= 50 ? 1 : 0) 18675 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 18676 continue; 18677 } 18678 } 18679 } 18680 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 18681 } 18682 18683 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 18684 TotalDepCount > VarList.size() && 18685 DSAStack->getParentOrderedRegionParam().first && 18686 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { 18687 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 18688 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 18689 } 18690 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 18691 Vars.empty()) 18692 return nullptr; 18693 18694 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 18695 DepModifier, DepKind, DepLoc, ColonLoc, 18696 Vars, TotalDepCount.getZExtValue()); 18697 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) && 18698 DSAStack->isParentOrderedRegion()) 18699 DSAStack->addDoacrossDependClause(C, OpsOffs); 18700 return C; 18701 } 18702 18703 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, 18704 Expr *Device, SourceLocation StartLoc, 18705 SourceLocation LParenLoc, 18706 SourceLocation ModifierLoc, 18707 SourceLocation EndLoc) { 18708 assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) && 18709 "Unexpected device modifier in OpenMP < 50."); 18710 18711 bool ErrorFound = false; 18712 if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) { 18713 std::string Values = 18714 getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown); 18715 Diag(ModifierLoc, diag::err_omp_unexpected_clause_value) 18716 << Values << getOpenMPClauseName(OMPC_device); 18717 ErrorFound = true; 18718 } 18719 18720 Expr *ValExpr = Device; 18721 Stmt *HelperValStmt = nullptr; 18722 18723 // OpenMP [2.9.1, Restrictions] 18724 // The device expression must evaluate to a non-negative integer value. 18725 ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 18726 /*StrictlyPositive=*/false) || 18727 ErrorFound; 18728 if (ErrorFound) 18729 return nullptr; 18730 18731 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 18732 OpenMPDirectiveKind CaptureRegion = 18733 getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP); 18734 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 18735 ValExpr = MakeFullExpr(ValExpr).get(); 18736 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 18737 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 18738 HelperValStmt = buildPreInits(Context, Captures); 18739 } 18740 18741 return new (Context) 18742 OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 18743 LParenLoc, ModifierLoc, EndLoc); 18744 } 18745 18746 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 18747 DSAStackTy *Stack, QualType QTy, 18748 bool FullCheck = true) { 18749 if (SemaRef.RequireCompleteType(SL, QTy, diag::err_incomplete_type)) 18750 return false; 18751 if (FullCheck && !SemaRef.CurContext->isDependentContext() && 18752 !QTy.isTriviallyCopyableType(SemaRef.Context)) 18753 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR; 18754 return true; 18755 } 18756 18757 /// Return true if it can be proven that the provided array expression 18758 /// (array section or array subscript) does NOT specify the whole size of the 18759 /// array whose base type is \a BaseQTy. 18760 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 18761 const Expr *E, 18762 QualType BaseQTy) { 18763 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 18764 18765 // If this is an array subscript, it refers to the whole size if the size of 18766 // the dimension is constant and equals 1. Also, an array section assumes the 18767 // format of an array subscript if no colon is used. 18768 if (isa<ArraySubscriptExpr>(E) || 18769 (OASE && OASE->getColonLocFirst().isInvalid())) { 18770 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 18771 return ATy->getSize().getSExtValue() != 1; 18772 // Size can't be evaluated statically. 18773 return false; 18774 } 18775 18776 assert(OASE && "Expecting array section if not an array subscript."); 18777 const Expr *LowerBound = OASE->getLowerBound(); 18778 const Expr *Length = OASE->getLength(); 18779 18780 // If there is a lower bound that does not evaluates to zero, we are not 18781 // covering the whole dimension. 18782 if (LowerBound) { 18783 Expr::EvalResult Result; 18784 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext())) 18785 return false; // Can't get the integer value as a constant. 18786 18787 llvm::APSInt ConstLowerBound = Result.Val.getInt(); 18788 if (ConstLowerBound.getSExtValue()) 18789 return true; 18790 } 18791 18792 // If we don't have a length we covering the whole dimension. 18793 if (!Length) 18794 return false; 18795 18796 // If the base is a pointer, we don't have a way to get the size of the 18797 // pointee. 18798 if (BaseQTy->isPointerType()) 18799 return false; 18800 18801 // We can only check if the length is the same as the size of the dimension 18802 // if we have a constant array. 18803 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 18804 if (!CATy) 18805 return false; 18806 18807 Expr::EvalResult Result; 18808 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 18809 return false; // Can't get the integer value as a constant. 18810 18811 llvm::APSInt ConstLength = Result.Val.getInt(); 18812 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 18813 } 18814 18815 // Return true if it can be proven that the provided array expression (array 18816 // section or array subscript) does NOT specify a single element of the array 18817 // whose base type is \a BaseQTy. 18818 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 18819 const Expr *E, 18820 QualType BaseQTy) { 18821 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 18822 18823 // An array subscript always refer to a single element. Also, an array section 18824 // assumes the format of an array subscript if no colon is used. 18825 if (isa<ArraySubscriptExpr>(E) || 18826 (OASE && OASE->getColonLocFirst().isInvalid())) 18827 return false; 18828 18829 assert(OASE && "Expecting array section if not an array subscript."); 18830 const Expr *Length = OASE->getLength(); 18831 18832 // If we don't have a length we have to check if the array has unitary size 18833 // for this dimension. Also, we should always expect a length if the base type 18834 // is pointer. 18835 if (!Length) { 18836 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 18837 return ATy->getSize().getSExtValue() != 1; 18838 // We cannot assume anything. 18839 return false; 18840 } 18841 18842 // Check if the length evaluates to 1. 18843 Expr::EvalResult Result; 18844 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 18845 return false; // Can't get the integer value as a constant. 18846 18847 llvm::APSInt ConstLength = Result.Val.getInt(); 18848 return ConstLength.getSExtValue() != 1; 18849 } 18850 18851 // The base of elements of list in a map clause have to be either: 18852 // - a reference to variable or field. 18853 // - a member expression. 18854 // - an array expression. 18855 // 18856 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 18857 // reference to 'r'. 18858 // 18859 // If we have: 18860 // 18861 // struct SS { 18862 // Bla S; 18863 // foo() { 18864 // #pragma omp target map (S.Arr[:12]); 18865 // } 18866 // } 18867 // 18868 // We want to retrieve the member expression 'this->S'; 18869 18870 // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2] 18871 // If a list item is an array section, it must specify contiguous storage. 18872 // 18873 // For this restriction it is sufficient that we make sure only references 18874 // to variables or fields and array expressions, and that no array sections 18875 // exist except in the rightmost expression (unless they cover the whole 18876 // dimension of the array). E.g. these would be invalid: 18877 // 18878 // r.ArrS[3:5].Arr[6:7] 18879 // 18880 // r.ArrS[3:5].x 18881 // 18882 // but these would be valid: 18883 // r.ArrS[3].Arr[6:7] 18884 // 18885 // r.ArrS[3].x 18886 namespace { 18887 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> { 18888 Sema &SemaRef; 18889 OpenMPClauseKind CKind = OMPC_unknown; 18890 OpenMPDirectiveKind DKind = OMPD_unknown; 18891 OMPClauseMappableExprCommon::MappableExprComponentList &Components; 18892 bool IsNonContiguous = false; 18893 bool NoDiagnose = false; 18894 const Expr *RelevantExpr = nullptr; 18895 bool AllowUnitySizeArraySection = true; 18896 bool AllowWholeSizeArraySection = true; 18897 bool AllowAnotherPtr = true; 18898 SourceLocation ELoc; 18899 SourceRange ERange; 18900 18901 void emitErrorMsg() { 18902 // If nothing else worked, this is not a valid map clause expression. 18903 if (SemaRef.getLangOpts().OpenMP < 50) { 18904 SemaRef.Diag(ELoc, 18905 diag::err_omp_expected_named_var_member_or_array_expression) 18906 << ERange; 18907 } else { 18908 SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses) 18909 << getOpenMPClauseName(CKind) << ERange; 18910 } 18911 } 18912 18913 public: 18914 bool VisitDeclRefExpr(DeclRefExpr *DRE) { 18915 if (!isa<VarDecl>(DRE->getDecl())) { 18916 emitErrorMsg(); 18917 return false; 18918 } 18919 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 18920 RelevantExpr = DRE; 18921 // Record the component. 18922 Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous); 18923 return true; 18924 } 18925 18926 bool VisitMemberExpr(MemberExpr *ME) { 18927 Expr *E = ME; 18928 Expr *BaseE = ME->getBase()->IgnoreParenCasts(); 18929 18930 if (isa<CXXThisExpr>(BaseE)) { 18931 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 18932 // We found a base expression: this->Val. 18933 RelevantExpr = ME; 18934 } else { 18935 E = BaseE; 18936 } 18937 18938 if (!isa<FieldDecl>(ME->getMemberDecl())) { 18939 if (!NoDiagnose) { 18940 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 18941 << ME->getSourceRange(); 18942 return false; 18943 } 18944 if (RelevantExpr) 18945 return false; 18946 return Visit(E); 18947 } 18948 18949 auto *FD = cast<FieldDecl>(ME->getMemberDecl()); 18950 18951 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 18952 // A bit-field cannot appear in a map clause. 18953 // 18954 if (FD->isBitField()) { 18955 if (!NoDiagnose) { 18956 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 18957 << ME->getSourceRange() << getOpenMPClauseName(CKind); 18958 return false; 18959 } 18960 if (RelevantExpr) 18961 return false; 18962 return Visit(E); 18963 } 18964 18965 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 18966 // If the type of a list item is a reference to a type T then the type 18967 // will be considered to be T for all purposes of this clause. 18968 QualType CurType = BaseE->getType().getNonReferenceType(); 18969 18970 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 18971 // A list item cannot be a variable that is a member of a structure with 18972 // a union type. 18973 // 18974 if (CurType->isUnionType()) { 18975 if (!NoDiagnose) { 18976 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 18977 << ME->getSourceRange(); 18978 return false; 18979 } 18980 return RelevantExpr || Visit(E); 18981 } 18982 18983 // If we got a member expression, we should not expect any array section 18984 // before that: 18985 // 18986 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 18987 // If a list item is an element of a structure, only the rightmost symbol 18988 // of the variable reference can be an array section. 18989 // 18990 AllowUnitySizeArraySection = false; 18991 AllowWholeSizeArraySection = false; 18992 18993 // Record the component. 18994 Components.emplace_back(ME, FD, IsNonContiguous); 18995 return RelevantExpr || Visit(E); 18996 } 18997 18998 bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) { 18999 Expr *E = AE->getBase()->IgnoreParenImpCasts(); 19000 19001 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 19002 if (!NoDiagnose) { 19003 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 19004 << 0 << AE->getSourceRange(); 19005 return false; 19006 } 19007 return RelevantExpr || Visit(E); 19008 } 19009 19010 // If we got an array subscript that express the whole dimension we 19011 // can have any array expressions before. If it only expressing part of 19012 // the dimension, we can only have unitary-size array expressions. 19013 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE, E->getType())) 19014 AllowWholeSizeArraySection = false; 19015 19016 if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) { 19017 Expr::EvalResult Result; 19018 if (!AE->getIdx()->isValueDependent() && 19019 AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) && 19020 !Result.Val.getInt().isZero()) { 19021 SemaRef.Diag(AE->getIdx()->getExprLoc(), 19022 diag::err_omp_invalid_map_this_expr); 19023 SemaRef.Diag(AE->getIdx()->getExprLoc(), 19024 diag::note_omp_invalid_subscript_on_this_ptr_map); 19025 } 19026 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19027 RelevantExpr = TE; 19028 } 19029 19030 // Record the component - we don't have any declaration associated. 19031 Components.emplace_back(AE, nullptr, IsNonContiguous); 19032 19033 return RelevantExpr || Visit(E); 19034 } 19035 19036 bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) { 19037 // After OMP 5.0 Array section in reduction clause will be implicitly 19038 // mapped 19039 assert(!(SemaRef.getLangOpts().OpenMP < 50 && NoDiagnose) && 19040 "Array sections cannot be implicitly mapped."); 19041 Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 19042 QualType CurType = 19043 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 19044 19045 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 19046 // If the type of a list item is a reference to a type T then the type 19047 // will be considered to be T for all purposes of this clause. 19048 if (CurType->isReferenceType()) 19049 CurType = CurType->getPointeeType(); 19050 19051 bool IsPointer = CurType->isAnyPointerType(); 19052 19053 if (!IsPointer && !CurType->isArrayType()) { 19054 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 19055 << 0 << OASE->getSourceRange(); 19056 return false; 19057 } 19058 19059 bool NotWhole = 19060 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType); 19061 bool NotUnity = 19062 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType); 19063 19064 if (AllowWholeSizeArraySection) { 19065 // Any array section is currently allowed. Allowing a whole size array 19066 // section implies allowing a unity array section as well. 19067 // 19068 // If this array section refers to the whole dimension we can still 19069 // accept other array sections before this one, except if the base is a 19070 // pointer. Otherwise, only unitary sections are accepted. 19071 if (NotWhole || IsPointer) 19072 AllowWholeSizeArraySection = false; 19073 } else if (DKind == OMPD_target_update && 19074 SemaRef.getLangOpts().OpenMP >= 50) { 19075 if (IsPointer && !AllowAnotherPtr) 19076 SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined) 19077 << /*array of unknown bound */ 1; 19078 else 19079 IsNonContiguous = true; 19080 } else if (AllowUnitySizeArraySection && NotUnity) { 19081 // A unity or whole array section is not allowed and that is not 19082 // compatible with the properties of the current array section. 19083 if (NoDiagnose) 19084 return false; 19085 SemaRef.Diag(ELoc, 19086 diag::err_array_section_does_not_specify_contiguous_storage) 19087 << OASE->getSourceRange(); 19088 return false; 19089 } 19090 19091 if (IsPointer) 19092 AllowAnotherPtr = false; 19093 19094 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) { 19095 Expr::EvalResult ResultR; 19096 Expr::EvalResult ResultL; 19097 if (!OASE->getLength()->isValueDependent() && 19098 OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) && 19099 !ResultR.Val.getInt().isOne()) { 19100 SemaRef.Diag(OASE->getLength()->getExprLoc(), 19101 diag::err_omp_invalid_map_this_expr); 19102 SemaRef.Diag(OASE->getLength()->getExprLoc(), 19103 diag::note_omp_invalid_length_on_this_ptr_mapping); 19104 } 19105 if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() && 19106 OASE->getLowerBound()->EvaluateAsInt(ResultL, 19107 SemaRef.getASTContext()) && 19108 !ResultL.Val.getInt().isZero()) { 19109 SemaRef.Diag(OASE->getLowerBound()->getExprLoc(), 19110 diag::err_omp_invalid_map_this_expr); 19111 SemaRef.Diag(OASE->getLowerBound()->getExprLoc(), 19112 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping); 19113 } 19114 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19115 RelevantExpr = TE; 19116 } 19117 19118 // Record the component - we don't have any declaration associated. 19119 Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false); 19120 return RelevantExpr || Visit(E); 19121 } 19122 bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) { 19123 Expr *Base = E->getBase(); 19124 19125 // Record the component - we don't have any declaration associated. 19126 Components.emplace_back(E, nullptr, IsNonContiguous); 19127 19128 return Visit(Base->IgnoreParenImpCasts()); 19129 } 19130 19131 bool VisitUnaryOperator(UnaryOperator *UO) { 19132 if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() || 19133 UO->getOpcode() != UO_Deref) { 19134 emitErrorMsg(); 19135 return false; 19136 } 19137 if (!RelevantExpr) { 19138 // Record the component if haven't found base decl. 19139 Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false); 19140 } 19141 return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts()); 19142 } 19143 bool VisitBinaryOperator(BinaryOperator *BO) { 19144 if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) { 19145 emitErrorMsg(); 19146 return false; 19147 } 19148 19149 // Pointer arithmetic is the only thing we expect to happen here so after we 19150 // make sure the binary operator is a pointer type, the we only thing need 19151 // to to is to visit the subtree that has the same type as root (so that we 19152 // know the other subtree is just an offset) 19153 Expr *LE = BO->getLHS()->IgnoreParenImpCasts(); 19154 Expr *RE = BO->getRHS()->IgnoreParenImpCasts(); 19155 Components.emplace_back(BO, nullptr, false); 19156 assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() || 19157 RE->getType().getTypePtr() == BO->getType().getTypePtr()) && 19158 "Either LHS or RHS have base decl inside"); 19159 if (BO->getType().getTypePtr() == LE->getType().getTypePtr()) 19160 return RelevantExpr || Visit(LE); 19161 return RelevantExpr || Visit(RE); 19162 } 19163 bool VisitCXXThisExpr(CXXThisExpr *CTE) { 19164 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19165 RelevantExpr = CTE; 19166 Components.emplace_back(CTE, nullptr, IsNonContiguous); 19167 return true; 19168 } 19169 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) { 19170 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19171 Components.emplace_back(COCE, nullptr, IsNonContiguous); 19172 return true; 19173 } 19174 bool VisitOpaqueValueExpr(OpaqueValueExpr *E) { 19175 Expr *Source = E->getSourceExpr(); 19176 if (!Source) { 19177 emitErrorMsg(); 19178 return false; 19179 } 19180 return Visit(Source); 19181 } 19182 bool VisitStmt(Stmt *) { 19183 emitErrorMsg(); 19184 return false; 19185 } 19186 const Expr *getFoundBase() const { return RelevantExpr; } 19187 explicit MapBaseChecker( 19188 Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, 19189 OMPClauseMappableExprCommon::MappableExprComponentList &Components, 19190 bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange) 19191 : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components), 19192 NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {} 19193 }; 19194 } // namespace 19195 19196 /// Return the expression of the base of the mappable expression or null if it 19197 /// cannot be determined and do all the necessary checks to see if the 19198 /// expression is valid as a standalone mappable expression. In the process, 19199 /// record all the components of the expression. 19200 static const Expr *checkMapClauseExpressionBase( 19201 Sema &SemaRef, Expr *E, 19202 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 19203 OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) { 19204 SourceLocation ELoc = E->getExprLoc(); 19205 SourceRange ERange = E->getSourceRange(); 19206 MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc, 19207 ERange); 19208 if (Checker.Visit(E->IgnoreParens())) { 19209 // Check if the highest dimension array section has length specified 19210 if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() && 19211 (CKind == OMPC_to || CKind == OMPC_from)) { 19212 auto CI = CurComponents.rbegin(); 19213 auto CE = CurComponents.rend(); 19214 for (; CI != CE; ++CI) { 19215 const auto *OASE = 19216 dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression()); 19217 if (!OASE) 19218 continue; 19219 if (OASE && OASE->getLength()) 19220 break; 19221 SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length) 19222 << ERange; 19223 } 19224 } 19225 return Checker.getFoundBase(); 19226 } 19227 return nullptr; 19228 } 19229 19230 // Return true if expression E associated with value VD has conflicts with other 19231 // map information. 19232 static bool checkMapConflicts( 19233 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E, 19234 bool CurrentRegionOnly, 19235 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 19236 OpenMPClauseKind CKind) { 19237 assert(VD && E); 19238 SourceLocation ELoc = E->getExprLoc(); 19239 SourceRange ERange = E->getSourceRange(); 19240 19241 // In order to easily check the conflicts we need to match each component of 19242 // the expression under test with the components of the expressions that are 19243 // already in the stack. 19244 19245 assert(!CurComponents.empty() && "Map clause expression with no components!"); 19246 assert(CurComponents.back().getAssociatedDeclaration() == VD && 19247 "Map clause expression with unexpected base!"); 19248 19249 // Variables to help detecting enclosing problems in data environment nests. 19250 bool IsEnclosedByDataEnvironmentExpr = false; 19251 const Expr *EnclosingExpr = nullptr; 19252 19253 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 19254 VD, CurrentRegionOnly, 19255 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc, 19256 ERange, CKind, &EnclosingExpr, 19257 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef 19258 StackComponents, 19259 OpenMPClauseKind Kind) { 19260 if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50) 19261 return false; 19262 assert(!StackComponents.empty() && 19263 "Map clause expression with no components!"); 19264 assert(StackComponents.back().getAssociatedDeclaration() == VD && 19265 "Map clause expression with unexpected base!"); 19266 (void)VD; 19267 19268 // The whole expression in the stack. 19269 const Expr *RE = StackComponents.front().getAssociatedExpression(); 19270 19271 // Expressions must start from the same base. Here we detect at which 19272 // point both expressions diverge from each other and see if we can 19273 // detect if the memory referred to both expressions is contiguous and 19274 // do not overlap. 19275 auto CI = CurComponents.rbegin(); 19276 auto CE = CurComponents.rend(); 19277 auto SI = StackComponents.rbegin(); 19278 auto SE = StackComponents.rend(); 19279 for (; CI != CE && SI != SE; ++CI, ++SI) { 19280 19281 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 19282 // At most one list item can be an array item derived from a given 19283 // variable in map clauses of the same construct. 19284 if (CurrentRegionOnly && 19285 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 19286 isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) || 19287 isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) && 19288 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 19289 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) || 19290 isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) { 19291 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 19292 diag::err_omp_multiple_array_items_in_map_clause) 19293 << CI->getAssociatedExpression()->getSourceRange(); 19294 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 19295 diag::note_used_here) 19296 << SI->getAssociatedExpression()->getSourceRange(); 19297 return true; 19298 } 19299 19300 // Do both expressions have the same kind? 19301 if (CI->getAssociatedExpression()->getStmtClass() != 19302 SI->getAssociatedExpression()->getStmtClass()) 19303 break; 19304 19305 // Are we dealing with different variables/fields? 19306 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 19307 break; 19308 } 19309 // Check if the extra components of the expressions in the enclosing 19310 // data environment are redundant for the current base declaration. 19311 // If they are, the maps completely overlap, which is legal. 19312 for (; SI != SE; ++SI) { 19313 QualType Type; 19314 if (const auto *ASE = 19315 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 19316 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 19317 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>( 19318 SI->getAssociatedExpression())) { 19319 const Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 19320 Type = 19321 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 19322 } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>( 19323 SI->getAssociatedExpression())) { 19324 Type = OASE->getBase()->getType()->getPointeeType(); 19325 } 19326 if (Type.isNull() || Type->isAnyPointerType() || 19327 checkArrayExpressionDoesNotReferToWholeSize( 19328 SemaRef, SI->getAssociatedExpression(), Type)) 19329 break; 19330 } 19331 19332 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 19333 // List items of map clauses in the same construct must not share 19334 // original storage. 19335 // 19336 // If the expressions are exactly the same or one is a subset of the 19337 // other, it means they are sharing storage. 19338 if (CI == CE && SI == SE) { 19339 if (CurrentRegionOnly) { 19340 if (CKind == OMPC_map) { 19341 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 19342 } else { 19343 assert(CKind == OMPC_to || CKind == OMPC_from); 19344 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 19345 << ERange; 19346 } 19347 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 19348 << RE->getSourceRange(); 19349 return true; 19350 } 19351 // If we find the same expression in the enclosing data environment, 19352 // that is legal. 19353 IsEnclosedByDataEnvironmentExpr = true; 19354 return false; 19355 } 19356 19357 QualType DerivedType = 19358 std::prev(CI)->getAssociatedDeclaration()->getType(); 19359 SourceLocation DerivedLoc = 19360 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 19361 19362 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 19363 // If the type of a list item is a reference to a type T then the type 19364 // will be considered to be T for all purposes of this clause. 19365 DerivedType = DerivedType.getNonReferenceType(); 19366 19367 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 19368 // A variable for which the type is pointer and an array section 19369 // derived from that variable must not appear as list items of map 19370 // clauses of the same construct. 19371 // 19372 // Also, cover one of the cases in: 19373 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 19374 // If any part of the original storage of a list item has corresponding 19375 // storage in the device data environment, all of the original storage 19376 // must have corresponding storage in the device data environment. 19377 // 19378 if (DerivedType->isAnyPointerType()) { 19379 if (CI == CE || SI == SE) { 19380 SemaRef.Diag( 19381 DerivedLoc, 19382 diag::err_omp_pointer_mapped_along_with_derived_section) 19383 << DerivedLoc; 19384 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 19385 << RE->getSourceRange(); 19386 return true; 19387 } 19388 if (CI->getAssociatedExpression()->getStmtClass() != 19389 SI->getAssociatedExpression()->getStmtClass() || 19390 CI->getAssociatedDeclaration()->getCanonicalDecl() == 19391 SI->getAssociatedDeclaration()->getCanonicalDecl()) { 19392 assert(CI != CE && SI != SE); 19393 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced) 19394 << DerivedLoc; 19395 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 19396 << RE->getSourceRange(); 19397 return true; 19398 } 19399 } 19400 19401 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 19402 // List items of map clauses in the same construct must not share 19403 // original storage. 19404 // 19405 // An expression is a subset of the other. 19406 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 19407 if (CKind == OMPC_map) { 19408 if (CI != CE || SI != SE) { 19409 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is 19410 // a pointer. 19411 auto Begin = 19412 CI != CE ? CurComponents.begin() : StackComponents.begin(); 19413 auto End = CI != CE ? CurComponents.end() : StackComponents.end(); 19414 auto It = Begin; 19415 while (It != End && !It->getAssociatedDeclaration()) 19416 std::advance(It, 1); 19417 assert(It != End && 19418 "Expected at least one component with the declaration."); 19419 if (It != Begin && It->getAssociatedDeclaration() 19420 ->getType() 19421 .getCanonicalType() 19422 ->isAnyPointerType()) { 19423 IsEnclosedByDataEnvironmentExpr = false; 19424 EnclosingExpr = nullptr; 19425 return false; 19426 } 19427 } 19428 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 19429 } else { 19430 assert(CKind == OMPC_to || CKind == OMPC_from); 19431 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 19432 << ERange; 19433 } 19434 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 19435 << RE->getSourceRange(); 19436 return true; 19437 } 19438 19439 // The current expression uses the same base as other expression in the 19440 // data environment but does not contain it completely. 19441 if (!CurrentRegionOnly && SI != SE) 19442 EnclosingExpr = RE; 19443 19444 // The current expression is a subset of the expression in the data 19445 // environment. 19446 IsEnclosedByDataEnvironmentExpr |= 19447 (!CurrentRegionOnly && CI != CE && SI == SE); 19448 19449 return false; 19450 }); 19451 19452 if (CurrentRegionOnly) 19453 return FoundError; 19454 19455 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 19456 // If any part of the original storage of a list item has corresponding 19457 // storage in the device data environment, all of the original storage must 19458 // have corresponding storage in the device data environment. 19459 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 19460 // If a list item is an element of a structure, and a different element of 19461 // the structure has a corresponding list item in the device data environment 19462 // prior to a task encountering the construct associated with the map clause, 19463 // then the list item must also have a corresponding list item in the device 19464 // data environment prior to the task encountering the construct. 19465 // 19466 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 19467 SemaRef.Diag(ELoc, 19468 diag::err_omp_original_storage_is_shared_and_does_not_contain) 19469 << ERange; 19470 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 19471 << EnclosingExpr->getSourceRange(); 19472 return true; 19473 } 19474 19475 return FoundError; 19476 } 19477 19478 // Look up the user-defined mapper given the mapper name and mapped type, and 19479 // build a reference to it. 19480 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S, 19481 CXXScopeSpec &MapperIdScopeSpec, 19482 const DeclarationNameInfo &MapperId, 19483 QualType Type, 19484 Expr *UnresolvedMapper) { 19485 if (MapperIdScopeSpec.isInvalid()) 19486 return ExprError(); 19487 // Get the actual type for the array type. 19488 if (Type->isArrayType()) { 19489 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type"); 19490 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType(); 19491 } 19492 // Find all user-defined mappers with the given MapperId. 19493 SmallVector<UnresolvedSet<8>, 4> Lookups; 19494 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName); 19495 Lookup.suppressDiagnostics(); 19496 if (S) { 19497 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) { 19498 NamedDecl *D = Lookup.getRepresentativeDecl(); 19499 while (S && !S->isDeclScope(D)) 19500 S = S->getParent(); 19501 if (S) 19502 S = S->getParent(); 19503 Lookups.emplace_back(); 19504 Lookups.back().append(Lookup.begin(), Lookup.end()); 19505 Lookup.clear(); 19506 } 19507 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) { 19508 // Extract the user-defined mappers with the given MapperId. 19509 Lookups.push_back(UnresolvedSet<8>()); 19510 for (NamedDecl *D : ULE->decls()) { 19511 auto *DMD = cast<OMPDeclareMapperDecl>(D); 19512 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation."); 19513 Lookups.back().addDecl(DMD); 19514 } 19515 } 19516 // Defer the lookup for dependent types. The results will be passed through 19517 // UnresolvedMapper on instantiation. 19518 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() || 19519 Type->isInstantiationDependentType() || 19520 Type->containsUnexpandedParameterPack() || 19521 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 19522 return !D->isInvalidDecl() && 19523 (D->getType()->isDependentType() || 19524 D->getType()->isInstantiationDependentType() || 19525 D->getType()->containsUnexpandedParameterPack()); 19526 })) { 19527 UnresolvedSet<8> URS; 19528 for (const UnresolvedSet<8> &Set : Lookups) { 19529 if (Set.empty()) 19530 continue; 19531 URS.append(Set.begin(), Set.end()); 19532 } 19533 return UnresolvedLookupExpr::Create( 19534 SemaRef.Context, /*NamingClass=*/nullptr, 19535 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId, 19536 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end()); 19537 } 19538 SourceLocation Loc = MapperId.getLoc(); 19539 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 19540 // The type must be of struct, union or class type in C and C++ 19541 if (!Type->isStructureOrClassType() && !Type->isUnionType() && 19542 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) { 19543 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type); 19544 return ExprError(); 19545 } 19546 // Perform argument dependent lookup. 19547 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet()) 19548 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups); 19549 // Return the first user-defined mapper with the desired type. 19550 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 19551 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * { 19552 if (!D->isInvalidDecl() && 19553 SemaRef.Context.hasSameType(D->getType(), Type)) 19554 return D; 19555 return nullptr; 19556 })) 19557 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 19558 // Find the first user-defined mapper with a type derived from the desired 19559 // type. 19560 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 19561 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * { 19562 if (!D->isInvalidDecl() && 19563 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) && 19564 !Type.isMoreQualifiedThan(D->getType())) 19565 return D; 19566 return nullptr; 19567 })) { 19568 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 19569 /*DetectVirtual=*/false); 19570 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) { 19571 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 19572 VD->getType().getUnqualifiedType()))) { 19573 if (SemaRef.CheckBaseClassAccess( 19574 Loc, VD->getType(), Type, Paths.front(), 19575 /*DiagID=*/0) != Sema::AR_inaccessible) { 19576 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 19577 } 19578 } 19579 } 19580 } 19581 // Report error if a mapper is specified, but cannot be found. 19582 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") { 19583 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper) 19584 << Type << MapperId.getName(); 19585 return ExprError(); 19586 } 19587 return ExprEmpty(); 19588 } 19589 19590 namespace { 19591 // Utility struct that gathers all the related lists associated with a mappable 19592 // expression. 19593 struct MappableVarListInfo { 19594 // The list of expressions. 19595 ArrayRef<Expr *> VarList; 19596 // The list of processed expressions. 19597 SmallVector<Expr *, 16> ProcessedVarList; 19598 // The mappble components for each expression. 19599 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 19600 // The base declaration of the variable. 19601 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 19602 // The reference to the user-defined mapper associated with every expression. 19603 SmallVector<Expr *, 16> UDMapperList; 19604 19605 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 19606 // We have a list of components and base declarations for each entry in the 19607 // variable list. 19608 VarComponents.reserve(VarList.size()); 19609 VarBaseDeclarations.reserve(VarList.size()); 19610 } 19611 }; 19612 } // namespace 19613 19614 // Check the validity of the provided variable list for the provided clause kind 19615 // \a CKind. In the check process the valid expressions, mappable expression 19616 // components, variables, and user-defined mappers are extracted and used to 19617 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a 19618 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec, 19619 // and \a MapperId are expected to be valid if the clause kind is 'map'. 19620 static void checkMappableExpressionList( 19621 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind, 19622 MappableVarListInfo &MVLI, SourceLocation StartLoc, 19623 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId, 19624 ArrayRef<Expr *> UnresolvedMappers, 19625 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 19626 ArrayRef<OpenMPMapModifierKind> Modifiers = None, 19627 bool IsMapTypeImplicit = false, bool NoDiagnose = false) { 19628 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 19629 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 19630 "Unexpected clause kind with mappable expressions!"); 19631 19632 // If the identifier of user-defined mapper is not specified, it is "default". 19633 // We do not change the actual name in this clause to distinguish whether a 19634 // mapper is specified explicitly, i.e., it is not explicitly specified when 19635 // MapperId.getName() is empty. 19636 if (!MapperId.getName() || MapperId.getName().isEmpty()) { 19637 auto &DeclNames = SemaRef.getASTContext().DeclarationNames; 19638 MapperId.setName(DeclNames.getIdentifier( 19639 &SemaRef.getASTContext().Idents.get("default"))); 19640 MapperId.setLoc(StartLoc); 19641 } 19642 19643 // Iterators to find the current unresolved mapper expression. 19644 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end(); 19645 bool UpdateUMIt = false; 19646 Expr *UnresolvedMapper = nullptr; 19647 19648 bool HasHoldModifier = 19649 llvm::is_contained(Modifiers, OMPC_MAP_MODIFIER_ompx_hold); 19650 19651 // Keep track of the mappable components and base declarations in this clause. 19652 // Each entry in the list is going to have a list of components associated. We 19653 // record each set of the components so that we can build the clause later on. 19654 // In the end we should have the same amount of declarations and component 19655 // lists. 19656 19657 for (Expr *RE : MVLI.VarList) { 19658 assert(RE && "Null expr in omp to/from/map clause"); 19659 SourceLocation ELoc = RE->getExprLoc(); 19660 19661 // Find the current unresolved mapper expression. 19662 if (UpdateUMIt && UMIt != UMEnd) { 19663 UMIt++; 19664 assert( 19665 UMIt != UMEnd && 19666 "Expect the size of UnresolvedMappers to match with that of VarList"); 19667 } 19668 UpdateUMIt = true; 19669 if (UMIt != UMEnd) 19670 UnresolvedMapper = *UMIt; 19671 19672 const Expr *VE = RE->IgnoreParenLValueCasts(); 19673 19674 if (VE->isValueDependent() || VE->isTypeDependent() || 19675 VE->isInstantiationDependent() || 19676 VE->containsUnexpandedParameterPack()) { 19677 // Try to find the associated user-defined mapper. 19678 ExprResult ER = buildUserDefinedMapperRef( 19679 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 19680 VE->getType().getCanonicalType(), UnresolvedMapper); 19681 if (ER.isInvalid()) 19682 continue; 19683 MVLI.UDMapperList.push_back(ER.get()); 19684 // We can only analyze this information once the missing information is 19685 // resolved. 19686 MVLI.ProcessedVarList.push_back(RE); 19687 continue; 19688 } 19689 19690 Expr *SimpleExpr = RE->IgnoreParenCasts(); 19691 19692 if (!RE->isLValue()) { 19693 if (SemaRef.getLangOpts().OpenMP < 50) { 19694 SemaRef.Diag( 19695 ELoc, diag::err_omp_expected_named_var_member_or_array_expression) 19696 << RE->getSourceRange(); 19697 } else { 19698 SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses) 19699 << getOpenMPClauseName(CKind) << RE->getSourceRange(); 19700 } 19701 continue; 19702 } 19703 19704 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 19705 ValueDecl *CurDeclaration = nullptr; 19706 19707 // Obtain the array or member expression bases if required. Also, fill the 19708 // components array with all the components identified in the process. 19709 const Expr *BE = 19710 checkMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind, 19711 DSAS->getCurrentDirective(), NoDiagnose); 19712 if (!BE) 19713 continue; 19714 19715 assert(!CurComponents.empty() && 19716 "Invalid mappable expression information."); 19717 19718 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) { 19719 // Add store "this" pointer to class in DSAStackTy for future checking 19720 DSAS->addMappedClassesQualTypes(TE->getType()); 19721 // Try to find the associated user-defined mapper. 19722 ExprResult ER = buildUserDefinedMapperRef( 19723 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 19724 VE->getType().getCanonicalType(), UnresolvedMapper); 19725 if (ER.isInvalid()) 19726 continue; 19727 MVLI.UDMapperList.push_back(ER.get()); 19728 // Skip restriction checking for variable or field declarations 19729 MVLI.ProcessedVarList.push_back(RE); 19730 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 19731 MVLI.VarComponents.back().append(CurComponents.begin(), 19732 CurComponents.end()); 19733 MVLI.VarBaseDeclarations.push_back(nullptr); 19734 continue; 19735 } 19736 19737 // For the following checks, we rely on the base declaration which is 19738 // expected to be associated with the last component. The declaration is 19739 // expected to be a variable or a field (if 'this' is being mapped). 19740 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 19741 assert(CurDeclaration && "Null decl on map clause."); 19742 assert( 19743 CurDeclaration->isCanonicalDecl() && 19744 "Expecting components to have associated only canonical declarations."); 19745 19746 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 19747 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 19748 19749 assert((VD || FD) && "Only variables or fields are expected here!"); 19750 (void)FD; 19751 19752 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 19753 // threadprivate variables cannot appear in a map clause. 19754 // OpenMP 4.5 [2.10.5, target update Construct] 19755 // threadprivate variables cannot appear in a from clause. 19756 if (VD && DSAS->isThreadPrivate(VD)) { 19757 if (NoDiagnose) 19758 continue; 19759 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 19760 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 19761 << getOpenMPClauseName(CKind); 19762 reportOriginalDsa(SemaRef, DSAS, VD, DVar); 19763 continue; 19764 } 19765 19766 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 19767 // A list item cannot appear in both a map clause and a data-sharing 19768 // attribute clause on the same construct. 19769 19770 // Check conflicts with other map clause expressions. We check the conflicts 19771 // with the current construct separately from the enclosing data 19772 // environment, because the restrictions are different. We only have to 19773 // check conflicts across regions for the map clauses. 19774 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 19775 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 19776 break; 19777 if (CKind == OMPC_map && 19778 (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) && 19779 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 19780 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 19781 break; 19782 19783 // OpenMP 4.5 [2.10.5, target update Construct] 19784 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 19785 // If the type of a list item is a reference to a type T then the type will 19786 // be considered to be T for all purposes of this clause. 19787 auto I = llvm::find_if( 19788 CurComponents, 19789 [](const OMPClauseMappableExprCommon::MappableComponent &MC) { 19790 return MC.getAssociatedDeclaration(); 19791 }); 19792 assert(I != CurComponents.end() && "Null decl on map clause."); 19793 (void)I; 19794 QualType Type; 19795 auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens()); 19796 auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens()); 19797 auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens()); 19798 if (ASE) { 19799 Type = ASE->getType().getNonReferenceType(); 19800 } else if (OASE) { 19801 QualType BaseType = 19802 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 19803 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 19804 Type = ATy->getElementType(); 19805 else 19806 Type = BaseType->getPointeeType(); 19807 Type = Type.getNonReferenceType(); 19808 } else if (OAShE) { 19809 Type = OAShE->getBase()->getType()->getPointeeType(); 19810 } else { 19811 Type = VE->getType(); 19812 } 19813 19814 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 19815 // A list item in a to or from clause must have a mappable type. 19816 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 19817 // A list item must have a mappable type. 19818 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 19819 DSAS, Type, /*FullCheck=*/true)) 19820 continue; 19821 19822 if (CKind == OMPC_map) { 19823 // target enter data 19824 // OpenMP [2.10.2, Restrictions, p. 99] 19825 // A map-type must be specified in all map clauses and must be either 19826 // to or alloc. 19827 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 19828 if (DKind == OMPD_target_enter_data && 19829 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 19830 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 19831 << (IsMapTypeImplicit ? 1 : 0) 19832 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 19833 << getOpenMPDirectiveName(DKind); 19834 continue; 19835 } 19836 19837 // target exit_data 19838 // OpenMP [2.10.3, Restrictions, p. 102] 19839 // A map-type must be specified in all map clauses and must be either 19840 // from, release, or delete. 19841 if (DKind == OMPD_target_exit_data && 19842 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 19843 MapType == OMPC_MAP_delete)) { 19844 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 19845 << (IsMapTypeImplicit ? 1 : 0) 19846 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 19847 << getOpenMPDirectiveName(DKind); 19848 continue; 19849 } 19850 19851 // The 'ompx_hold' modifier is specifically intended to be used on a 19852 // 'target' or 'target data' directive to prevent data from being unmapped 19853 // during the associated statement. It is not permitted on a 'target 19854 // enter data' or 'target exit data' directive, which have no associated 19855 // statement. 19856 if ((DKind == OMPD_target_enter_data || DKind == OMPD_target_exit_data) && 19857 HasHoldModifier) { 19858 SemaRef.Diag(StartLoc, 19859 diag::err_omp_invalid_map_type_modifier_for_directive) 19860 << getOpenMPSimpleClauseTypeName(OMPC_map, 19861 OMPC_MAP_MODIFIER_ompx_hold) 19862 << getOpenMPDirectiveName(DKind); 19863 continue; 19864 } 19865 19866 // target, target data 19867 // OpenMP 5.0 [2.12.2, Restrictions, p. 163] 19868 // OpenMP 5.0 [2.12.5, Restrictions, p. 174] 19869 // A map-type in a map clause must be to, from, tofrom or alloc 19870 if ((DKind == OMPD_target_data || 19871 isOpenMPTargetExecutionDirective(DKind)) && 19872 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from || 19873 MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) { 19874 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 19875 << (IsMapTypeImplicit ? 1 : 0) 19876 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 19877 << getOpenMPDirectiveName(DKind); 19878 continue; 19879 } 19880 19881 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 19882 // A list item cannot appear in both a map clause and a data-sharing 19883 // attribute clause on the same construct 19884 // 19885 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 19886 // A list item cannot appear in both a map clause and a data-sharing 19887 // attribute clause on the same construct unless the construct is a 19888 // combined construct. 19889 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 && 19890 isOpenMPTargetExecutionDirective(DKind)) || 19891 DKind == OMPD_target)) { 19892 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 19893 if (isOpenMPPrivate(DVar.CKind)) { 19894 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 19895 << getOpenMPClauseName(DVar.CKind) 19896 << getOpenMPClauseName(OMPC_map) 19897 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 19898 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar); 19899 continue; 19900 } 19901 } 19902 } 19903 19904 // Try to find the associated user-defined mapper. 19905 ExprResult ER = buildUserDefinedMapperRef( 19906 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 19907 Type.getCanonicalType(), UnresolvedMapper); 19908 if (ER.isInvalid()) 19909 continue; 19910 MVLI.UDMapperList.push_back(ER.get()); 19911 19912 // Save the current expression. 19913 MVLI.ProcessedVarList.push_back(RE); 19914 19915 // Store the components in the stack so that they can be used to check 19916 // against other clauses later on. 19917 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 19918 /*WhereFoundClauseKind=*/OMPC_map); 19919 19920 // Save the components and declaration to create the clause. For purposes of 19921 // the clause creation, any component list that has has base 'this' uses 19922 // null as base declaration. 19923 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 19924 MVLI.VarComponents.back().append(CurComponents.begin(), 19925 CurComponents.end()); 19926 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 19927 : CurDeclaration); 19928 } 19929 } 19930 19931 OMPClause *Sema::ActOnOpenMPMapClause( 19932 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 19933 ArrayRef<SourceLocation> MapTypeModifiersLoc, 19934 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 19935 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, 19936 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 19937 const OMPVarListLocTy &Locs, bool NoDiagnose, 19938 ArrayRef<Expr *> UnresolvedMappers) { 19939 OpenMPMapModifierKind Modifiers[] = { 19940 OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown, 19941 OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown, 19942 OMPC_MAP_MODIFIER_unknown}; 19943 SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers]; 19944 19945 // Process map-type-modifiers, flag errors for duplicate modifiers. 19946 unsigned Count = 0; 19947 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) { 19948 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown && 19949 llvm::is_contained(Modifiers, MapTypeModifiers[I])) { 19950 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier); 19951 continue; 19952 } 19953 assert(Count < NumberOfOMPMapClauseModifiers && 19954 "Modifiers exceed the allowed number of map type modifiers"); 19955 Modifiers[Count] = MapTypeModifiers[I]; 19956 ModifiersLoc[Count] = MapTypeModifiersLoc[I]; 19957 ++Count; 19958 } 19959 19960 MappableVarListInfo MVLI(VarList); 19961 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc, 19962 MapperIdScopeSpec, MapperId, UnresolvedMappers, 19963 MapType, Modifiers, IsMapTypeImplicit, 19964 NoDiagnose); 19965 19966 // We need to produce a map clause even if we don't have variables so that 19967 // other diagnostics related with non-existing map clauses are accurate. 19968 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList, 19969 MVLI.VarBaseDeclarations, MVLI.VarComponents, 19970 MVLI.UDMapperList, Modifiers, ModifiersLoc, 19971 MapperIdScopeSpec.getWithLocInContext(Context), 19972 MapperId, MapType, IsMapTypeImplicit, MapLoc); 19973 } 19974 19975 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 19976 TypeResult ParsedType) { 19977 assert(ParsedType.isUsable()); 19978 19979 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 19980 if (ReductionType.isNull()) 19981 return QualType(); 19982 19983 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 19984 // A type name in a declare reduction directive cannot be a function type, an 19985 // array type, a reference type, or a type qualified with const, volatile or 19986 // restrict. 19987 if (ReductionType.hasQualifiers()) { 19988 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 19989 return QualType(); 19990 } 19991 19992 if (ReductionType->isFunctionType()) { 19993 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 19994 return QualType(); 19995 } 19996 if (ReductionType->isReferenceType()) { 19997 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 19998 return QualType(); 19999 } 20000 if (ReductionType->isArrayType()) { 20001 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 20002 return QualType(); 20003 } 20004 return ReductionType; 20005 } 20006 20007 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 20008 Scope *S, DeclContext *DC, DeclarationName Name, 20009 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 20010 AccessSpecifier AS, Decl *PrevDeclInScope) { 20011 SmallVector<Decl *, 8> Decls; 20012 Decls.reserve(ReductionTypes.size()); 20013 20014 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 20015 forRedeclarationInCurContext()); 20016 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 20017 // A reduction-identifier may not be re-declared in the current scope for the 20018 // same type or for a type that is compatible according to the base language 20019 // rules. 20020 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 20021 OMPDeclareReductionDecl *PrevDRD = nullptr; 20022 bool InCompoundScope = true; 20023 if (S != nullptr) { 20024 // Find previous declaration with the same name not referenced in other 20025 // declarations. 20026 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 20027 InCompoundScope = 20028 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 20029 LookupName(Lookup, S); 20030 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 20031 /*AllowInlineNamespace=*/false); 20032 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 20033 LookupResult::Filter Filter = Lookup.makeFilter(); 20034 while (Filter.hasNext()) { 20035 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 20036 if (InCompoundScope) { 20037 auto I = UsedAsPrevious.find(PrevDecl); 20038 if (I == UsedAsPrevious.end()) 20039 UsedAsPrevious[PrevDecl] = false; 20040 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope()) 20041 UsedAsPrevious[D] = true; 20042 } 20043 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 20044 PrevDecl->getLocation(); 20045 } 20046 Filter.done(); 20047 if (InCompoundScope) { 20048 for (const auto &PrevData : UsedAsPrevious) { 20049 if (!PrevData.second) { 20050 PrevDRD = PrevData.first; 20051 break; 20052 } 20053 } 20054 } 20055 } else if (PrevDeclInScope != nullptr) { 20056 auto *PrevDRDInScope = PrevDRD = 20057 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 20058 do { 20059 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 20060 PrevDRDInScope->getLocation(); 20061 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 20062 } while (PrevDRDInScope != nullptr); 20063 } 20064 for (const auto &TyData : ReductionTypes) { 20065 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 20066 bool Invalid = false; 20067 if (I != PreviousRedeclTypes.end()) { 20068 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 20069 << TyData.first; 20070 Diag(I->second, diag::note_previous_definition); 20071 Invalid = true; 20072 } 20073 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 20074 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 20075 Name, TyData.first, PrevDRD); 20076 DC->addDecl(DRD); 20077 DRD->setAccess(AS); 20078 Decls.push_back(DRD); 20079 if (Invalid) 20080 DRD->setInvalidDecl(); 20081 else 20082 PrevDRD = DRD; 20083 } 20084 20085 return DeclGroupPtrTy::make( 20086 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 20087 } 20088 20089 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 20090 auto *DRD = cast<OMPDeclareReductionDecl>(D); 20091 20092 // Enter new function scope. 20093 PushFunctionScope(); 20094 setFunctionHasBranchProtectedScope(); 20095 getCurFunction()->setHasOMPDeclareReductionCombiner(); 20096 20097 if (S != nullptr) 20098 PushDeclContext(S, DRD); 20099 else 20100 CurContext = DRD; 20101 20102 PushExpressionEvaluationContext( 20103 ExpressionEvaluationContext::PotentiallyEvaluated); 20104 20105 QualType ReductionType = DRD->getType(); 20106 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 20107 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 20108 // uses semantics of argument handles by value, but it should be passed by 20109 // reference. C lang does not support references, so pass all parameters as 20110 // pointers. 20111 // Create 'T omp_in;' variable. 20112 VarDecl *OmpInParm = 20113 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 20114 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 20115 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 20116 // uses semantics of argument handles by value, but it should be passed by 20117 // reference. C lang does not support references, so pass all parameters as 20118 // pointers. 20119 // Create 'T omp_out;' variable. 20120 VarDecl *OmpOutParm = 20121 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 20122 if (S != nullptr) { 20123 PushOnScopeChains(OmpInParm, S); 20124 PushOnScopeChains(OmpOutParm, S); 20125 } else { 20126 DRD->addDecl(OmpInParm); 20127 DRD->addDecl(OmpOutParm); 20128 } 20129 Expr *InE = 20130 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation()); 20131 Expr *OutE = 20132 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation()); 20133 DRD->setCombinerData(InE, OutE); 20134 } 20135 20136 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 20137 auto *DRD = cast<OMPDeclareReductionDecl>(D); 20138 DiscardCleanupsInEvaluationContext(); 20139 PopExpressionEvaluationContext(); 20140 20141 PopDeclContext(); 20142 PopFunctionScopeInfo(); 20143 20144 if (Combiner != nullptr) 20145 DRD->setCombiner(Combiner); 20146 else 20147 DRD->setInvalidDecl(); 20148 } 20149 20150 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 20151 auto *DRD = cast<OMPDeclareReductionDecl>(D); 20152 20153 // Enter new function scope. 20154 PushFunctionScope(); 20155 setFunctionHasBranchProtectedScope(); 20156 20157 if (S != nullptr) 20158 PushDeclContext(S, DRD); 20159 else 20160 CurContext = DRD; 20161 20162 PushExpressionEvaluationContext( 20163 ExpressionEvaluationContext::PotentiallyEvaluated); 20164 20165 QualType ReductionType = DRD->getType(); 20166 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 20167 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 20168 // uses semantics of argument handles by value, but it should be passed by 20169 // reference. C lang does not support references, so pass all parameters as 20170 // pointers. 20171 // Create 'T omp_priv;' variable. 20172 VarDecl *OmpPrivParm = 20173 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 20174 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 20175 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 20176 // uses semantics of argument handles by value, but it should be passed by 20177 // reference. C lang does not support references, so pass all parameters as 20178 // pointers. 20179 // Create 'T omp_orig;' variable. 20180 VarDecl *OmpOrigParm = 20181 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 20182 if (S != nullptr) { 20183 PushOnScopeChains(OmpPrivParm, S); 20184 PushOnScopeChains(OmpOrigParm, S); 20185 } else { 20186 DRD->addDecl(OmpPrivParm); 20187 DRD->addDecl(OmpOrigParm); 20188 } 20189 Expr *OrigE = 20190 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation()); 20191 Expr *PrivE = 20192 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation()); 20193 DRD->setInitializerData(OrigE, PrivE); 20194 return OmpPrivParm; 20195 } 20196 20197 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 20198 VarDecl *OmpPrivParm) { 20199 auto *DRD = cast<OMPDeclareReductionDecl>(D); 20200 DiscardCleanupsInEvaluationContext(); 20201 PopExpressionEvaluationContext(); 20202 20203 PopDeclContext(); 20204 PopFunctionScopeInfo(); 20205 20206 if (Initializer != nullptr) { 20207 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit); 20208 } else if (OmpPrivParm->hasInit()) { 20209 DRD->setInitializer(OmpPrivParm->getInit(), 20210 OmpPrivParm->isDirectInit() 20211 ? OMPDeclareReductionDecl::DirectInit 20212 : OMPDeclareReductionDecl::CopyInit); 20213 } else { 20214 DRD->setInvalidDecl(); 20215 } 20216 } 20217 20218 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 20219 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 20220 for (Decl *D : DeclReductions.get()) { 20221 if (IsValid) { 20222 if (S) 20223 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S, 20224 /*AddToContext=*/false); 20225 } else { 20226 D->setInvalidDecl(); 20227 } 20228 } 20229 return DeclReductions; 20230 } 20231 20232 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) { 20233 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 20234 QualType T = TInfo->getType(); 20235 if (D.isInvalidType()) 20236 return true; 20237 20238 if (getLangOpts().CPlusPlus) { 20239 // Check that there are no default arguments (C++ only). 20240 CheckExtraCXXDefaultArguments(D); 20241 } 20242 20243 return CreateParsedType(T, TInfo); 20244 } 20245 20246 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, 20247 TypeResult ParsedType) { 20248 assert(ParsedType.isUsable() && "Expect usable parsed mapper type"); 20249 20250 QualType MapperType = GetTypeFromParser(ParsedType.get()); 20251 assert(!MapperType.isNull() && "Expect valid mapper type"); 20252 20253 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 20254 // The type must be of struct, union or class type in C and C++ 20255 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) { 20256 Diag(TyLoc, diag::err_omp_mapper_wrong_type); 20257 return QualType(); 20258 } 20259 return MapperType; 20260 } 20261 20262 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective( 20263 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, 20264 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, 20265 Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) { 20266 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName, 20267 forRedeclarationInCurContext()); 20268 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 20269 // A mapper-identifier may not be redeclared in the current scope for the 20270 // same type or for a type that is compatible according to the base language 20271 // rules. 20272 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 20273 OMPDeclareMapperDecl *PrevDMD = nullptr; 20274 bool InCompoundScope = true; 20275 if (S != nullptr) { 20276 // Find previous declaration with the same name not referenced in other 20277 // declarations. 20278 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 20279 InCompoundScope = 20280 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 20281 LookupName(Lookup, S); 20282 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 20283 /*AllowInlineNamespace=*/false); 20284 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious; 20285 LookupResult::Filter Filter = Lookup.makeFilter(); 20286 while (Filter.hasNext()) { 20287 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next()); 20288 if (InCompoundScope) { 20289 auto I = UsedAsPrevious.find(PrevDecl); 20290 if (I == UsedAsPrevious.end()) 20291 UsedAsPrevious[PrevDecl] = false; 20292 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope()) 20293 UsedAsPrevious[D] = true; 20294 } 20295 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 20296 PrevDecl->getLocation(); 20297 } 20298 Filter.done(); 20299 if (InCompoundScope) { 20300 for (const auto &PrevData : UsedAsPrevious) { 20301 if (!PrevData.second) { 20302 PrevDMD = PrevData.first; 20303 break; 20304 } 20305 } 20306 } 20307 } else if (PrevDeclInScope) { 20308 auto *PrevDMDInScope = PrevDMD = 20309 cast<OMPDeclareMapperDecl>(PrevDeclInScope); 20310 do { 20311 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] = 20312 PrevDMDInScope->getLocation(); 20313 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope(); 20314 } while (PrevDMDInScope != nullptr); 20315 } 20316 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType()); 20317 bool Invalid = false; 20318 if (I != PreviousRedeclTypes.end()) { 20319 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition) 20320 << MapperType << Name; 20321 Diag(I->second, diag::note_previous_definition); 20322 Invalid = true; 20323 } 20324 // Build expressions for implicit maps of data members with 'default' 20325 // mappers. 20326 SmallVector<OMPClause *, 4> ClausesWithImplicit(Clauses.begin(), 20327 Clauses.end()); 20328 if (LangOpts.OpenMP >= 50) 20329 processImplicitMapsWithDefaultMappers(*this, DSAStack, ClausesWithImplicit); 20330 auto *DMD = 20331 OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, MapperType, VN, 20332 ClausesWithImplicit, PrevDMD); 20333 if (S) 20334 PushOnScopeChains(DMD, S); 20335 else 20336 DC->addDecl(DMD); 20337 DMD->setAccess(AS); 20338 if (Invalid) 20339 DMD->setInvalidDecl(); 20340 20341 auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl(); 20342 VD->setDeclContext(DMD); 20343 VD->setLexicalDeclContext(DMD); 20344 DMD->addDecl(VD); 20345 DMD->setMapperVarRef(MapperVarRef); 20346 20347 return DeclGroupPtrTy::make(DeclGroupRef(DMD)); 20348 } 20349 20350 ExprResult 20351 Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType, 20352 SourceLocation StartLoc, 20353 DeclarationName VN) { 20354 TypeSourceInfo *TInfo = 20355 Context.getTrivialTypeSourceInfo(MapperType, StartLoc); 20356 auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(), 20357 StartLoc, StartLoc, VN.getAsIdentifierInfo(), 20358 MapperType, TInfo, SC_None); 20359 if (S) 20360 PushOnScopeChains(VD, S, /*AddToContext=*/false); 20361 Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc); 20362 DSAStack->addDeclareMapperVarRef(E); 20363 return E; 20364 } 20365 20366 bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const { 20367 assert(LangOpts.OpenMP && "Expected OpenMP mode."); 20368 const Expr *Ref = DSAStack->getDeclareMapperVarRef(); 20369 if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref)) { 20370 if (VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl()) 20371 return true; 20372 if (VD->isUsableInConstantExpressions(Context)) 20373 return true; 20374 return false; 20375 } 20376 return true; 20377 } 20378 20379 const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const { 20380 assert(LangOpts.OpenMP && "Expected OpenMP mode."); 20381 return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl(); 20382 } 20383 20384 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 20385 SourceLocation StartLoc, 20386 SourceLocation LParenLoc, 20387 SourceLocation EndLoc) { 20388 Expr *ValExpr = NumTeams; 20389 Stmt *HelperValStmt = nullptr; 20390 20391 // OpenMP [teams Constrcut, Restrictions] 20392 // The num_teams expression must evaluate to a positive integer value. 20393 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 20394 /*StrictlyPositive=*/true)) 20395 return nullptr; 20396 20397 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 20398 OpenMPDirectiveKind CaptureRegion = 20399 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP); 20400 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 20401 ValExpr = MakeFullExpr(ValExpr).get(); 20402 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 20403 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 20404 HelperValStmt = buildPreInits(Context, Captures); 20405 } 20406 20407 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 20408 StartLoc, LParenLoc, EndLoc); 20409 } 20410 20411 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 20412 SourceLocation StartLoc, 20413 SourceLocation LParenLoc, 20414 SourceLocation EndLoc) { 20415 Expr *ValExpr = ThreadLimit; 20416 Stmt *HelperValStmt = nullptr; 20417 20418 // OpenMP [teams Constrcut, Restrictions] 20419 // The thread_limit expression must evaluate to a positive integer value. 20420 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 20421 /*StrictlyPositive=*/true)) 20422 return nullptr; 20423 20424 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 20425 OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause( 20426 DKind, OMPC_thread_limit, LangOpts.OpenMP); 20427 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 20428 ValExpr = MakeFullExpr(ValExpr).get(); 20429 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 20430 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 20431 HelperValStmt = buildPreInits(Context, Captures); 20432 } 20433 20434 return new (Context) OMPThreadLimitClause( 20435 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 20436 } 20437 20438 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 20439 SourceLocation StartLoc, 20440 SourceLocation LParenLoc, 20441 SourceLocation EndLoc) { 20442 Expr *ValExpr = Priority; 20443 Stmt *HelperValStmt = nullptr; 20444 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 20445 20446 // OpenMP [2.9.1, task Constrcut] 20447 // The priority-value is a non-negative numerical scalar expression. 20448 if (!isNonNegativeIntegerValue( 20449 ValExpr, *this, OMPC_priority, 20450 /*StrictlyPositive=*/false, /*BuildCapture=*/true, 20451 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 20452 return nullptr; 20453 20454 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion, 20455 StartLoc, LParenLoc, EndLoc); 20456 } 20457 20458 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 20459 SourceLocation StartLoc, 20460 SourceLocation LParenLoc, 20461 SourceLocation EndLoc) { 20462 Expr *ValExpr = Grainsize; 20463 Stmt *HelperValStmt = nullptr; 20464 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 20465 20466 // OpenMP [2.9.2, taskloop Constrcut] 20467 // The parameter of the grainsize clause must be a positive integer 20468 // expression. 20469 if (!isNonNegativeIntegerValue( 20470 ValExpr, *this, OMPC_grainsize, 20471 /*StrictlyPositive=*/true, /*BuildCapture=*/true, 20472 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 20473 return nullptr; 20474 20475 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion, 20476 StartLoc, LParenLoc, EndLoc); 20477 } 20478 20479 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 20480 SourceLocation StartLoc, 20481 SourceLocation LParenLoc, 20482 SourceLocation EndLoc) { 20483 Expr *ValExpr = NumTasks; 20484 Stmt *HelperValStmt = nullptr; 20485 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 20486 20487 // OpenMP [2.9.2, taskloop Constrcut] 20488 // The parameter of the num_tasks clause must be a positive integer 20489 // expression. 20490 if (!isNonNegativeIntegerValue( 20491 ValExpr, *this, OMPC_num_tasks, 20492 /*StrictlyPositive=*/true, /*BuildCapture=*/true, 20493 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 20494 return nullptr; 20495 20496 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion, 20497 StartLoc, LParenLoc, EndLoc); 20498 } 20499 20500 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 20501 SourceLocation LParenLoc, 20502 SourceLocation EndLoc) { 20503 // OpenMP [2.13.2, critical construct, Description] 20504 // ... where hint-expression is an integer constant expression that evaluates 20505 // to a valid lock hint. 20506 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 20507 if (HintExpr.isInvalid()) 20508 return nullptr; 20509 return new (Context) 20510 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 20511 } 20512 20513 /// Tries to find omp_event_handle_t type. 20514 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc, 20515 DSAStackTy *Stack) { 20516 QualType OMPEventHandleT = Stack->getOMPEventHandleT(); 20517 if (!OMPEventHandleT.isNull()) 20518 return true; 20519 IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t"); 20520 ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope()); 20521 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 20522 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t"; 20523 return false; 20524 } 20525 Stack->setOMPEventHandleT(PT.get()); 20526 return true; 20527 } 20528 20529 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, 20530 SourceLocation LParenLoc, 20531 SourceLocation EndLoc) { 20532 if (!Evt->isValueDependent() && !Evt->isTypeDependent() && 20533 !Evt->isInstantiationDependent() && 20534 !Evt->containsUnexpandedParameterPack()) { 20535 if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack)) 20536 return nullptr; 20537 // OpenMP 5.0, 2.10.1 task Construct. 20538 // event-handle is a variable of the omp_event_handle_t type. 20539 auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts()); 20540 if (!Ref) { 20541 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 20542 << "omp_event_handle_t" << 0 << Evt->getSourceRange(); 20543 return nullptr; 20544 } 20545 auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl()); 20546 if (!VD) { 20547 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 20548 << "omp_event_handle_t" << 0 << Evt->getSourceRange(); 20549 return nullptr; 20550 } 20551 if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(), 20552 VD->getType()) || 20553 VD->getType().isConstant(Context)) { 20554 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 20555 << "omp_event_handle_t" << 1 << VD->getType() 20556 << Evt->getSourceRange(); 20557 return nullptr; 20558 } 20559 // OpenMP 5.0, 2.10.1 task Construct 20560 // [detach clause]... The event-handle will be considered as if it was 20561 // specified on a firstprivate clause. 20562 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false); 20563 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 20564 DVar.RefExpr) { 20565 Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa) 20566 << getOpenMPClauseName(DVar.CKind) 20567 << getOpenMPClauseName(OMPC_firstprivate); 20568 reportOriginalDsa(*this, DSAStack, VD, DVar); 20569 return nullptr; 20570 } 20571 } 20572 20573 return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc); 20574 } 20575 20576 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 20577 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 20578 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 20579 SourceLocation EndLoc) { 20580 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 20581 std::string Values; 20582 Values += "'"; 20583 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 20584 Values += "'"; 20585 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 20586 << Values << getOpenMPClauseName(OMPC_dist_schedule); 20587 return nullptr; 20588 } 20589 Expr *ValExpr = ChunkSize; 20590 Stmt *HelperValStmt = nullptr; 20591 if (ChunkSize) { 20592 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 20593 !ChunkSize->isInstantiationDependent() && 20594 !ChunkSize->containsUnexpandedParameterPack()) { 20595 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 20596 ExprResult Val = 20597 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 20598 if (Val.isInvalid()) 20599 return nullptr; 20600 20601 ValExpr = Val.get(); 20602 20603 // OpenMP [2.7.1, Restrictions] 20604 // chunk_size must be a loop invariant integer expression with a positive 20605 // value. 20606 if (Optional<llvm::APSInt> Result = 20607 ValExpr->getIntegerConstantExpr(Context)) { 20608 if (Result->isSigned() && !Result->isStrictlyPositive()) { 20609 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 20610 << "dist_schedule" << ChunkSize->getSourceRange(); 20611 return nullptr; 20612 } 20613 } else if (getOpenMPCaptureRegionForClause( 20614 DSAStack->getCurrentDirective(), OMPC_dist_schedule, 20615 LangOpts.OpenMP) != OMPD_unknown && 20616 !CurContext->isDependentContext()) { 20617 ValExpr = MakeFullExpr(ValExpr).get(); 20618 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 20619 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 20620 HelperValStmt = buildPreInits(Context, Captures); 20621 } 20622 } 20623 } 20624 20625 return new (Context) 20626 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 20627 Kind, ValExpr, HelperValStmt); 20628 } 20629 20630 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 20631 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 20632 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 20633 SourceLocation KindLoc, SourceLocation EndLoc) { 20634 if (getLangOpts().OpenMP < 50) { 20635 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || 20636 Kind != OMPC_DEFAULTMAP_scalar) { 20637 std::string Value; 20638 SourceLocation Loc; 20639 Value += "'"; 20640 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 20641 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 20642 OMPC_DEFAULTMAP_MODIFIER_tofrom); 20643 Loc = MLoc; 20644 } else { 20645 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 20646 OMPC_DEFAULTMAP_scalar); 20647 Loc = KindLoc; 20648 } 20649 Value += "'"; 20650 Diag(Loc, diag::err_omp_unexpected_clause_value) 20651 << Value << getOpenMPClauseName(OMPC_defaultmap); 20652 return nullptr; 20653 } 20654 } else { 20655 bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown); 20656 bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) || 20657 (LangOpts.OpenMP >= 50 && KindLoc.isInvalid()); 20658 if (!isDefaultmapKind || !isDefaultmapModifier) { 20659 StringRef KindValue = "'scalar', 'aggregate', 'pointer'"; 20660 if (LangOpts.OpenMP == 50) { 20661 StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', " 20662 "'firstprivate', 'none', 'default'"; 20663 if (!isDefaultmapKind && isDefaultmapModifier) { 20664 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 20665 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 20666 } else if (isDefaultmapKind && !isDefaultmapModifier) { 20667 Diag(MLoc, diag::err_omp_unexpected_clause_value) 20668 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 20669 } else { 20670 Diag(MLoc, diag::err_omp_unexpected_clause_value) 20671 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 20672 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 20673 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 20674 } 20675 } else { 20676 StringRef ModifierValue = 20677 "'alloc', 'from', 'to', 'tofrom', " 20678 "'firstprivate', 'none', 'default', 'present'"; 20679 if (!isDefaultmapKind && isDefaultmapModifier) { 20680 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 20681 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 20682 } else if (isDefaultmapKind && !isDefaultmapModifier) { 20683 Diag(MLoc, diag::err_omp_unexpected_clause_value) 20684 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 20685 } else { 20686 Diag(MLoc, diag::err_omp_unexpected_clause_value) 20687 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 20688 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 20689 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 20690 } 20691 } 20692 return nullptr; 20693 } 20694 20695 // OpenMP [5.0, 2.12.5, Restrictions, p. 174] 20696 // At most one defaultmap clause for each category can appear on the 20697 // directive. 20698 if (DSAStack->checkDefaultmapCategory(Kind)) { 20699 Diag(StartLoc, diag::err_omp_one_defaultmap_each_category); 20700 return nullptr; 20701 } 20702 } 20703 if (Kind == OMPC_DEFAULTMAP_unknown) { 20704 // Variable category is not specified - mark all categories. 20705 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc); 20706 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc); 20707 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc); 20708 } else { 20709 DSAStack->setDefaultDMAAttr(M, Kind, StartLoc); 20710 } 20711 20712 return new (Context) 20713 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 20714 } 20715 20716 bool Sema::ActOnStartOpenMPDeclareTargetContext( 20717 DeclareTargetContextInfo &DTCI) { 20718 DeclContext *CurLexicalContext = getCurLexicalContext(); 20719 if (!CurLexicalContext->isFileContext() && 20720 !CurLexicalContext->isExternCContext() && 20721 !CurLexicalContext->isExternCXXContext() && 20722 !isa<CXXRecordDecl>(CurLexicalContext) && 20723 !isa<ClassTemplateDecl>(CurLexicalContext) && 20724 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) && 20725 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) { 20726 Diag(DTCI.Loc, diag::err_omp_region_not_file_context); 20727 return false; 20728 } 20729 DeclareTargetNesting.push_back(DTCI); 20730 return true; 20731 } 20732 20733 const Sema::DeclareTargetContextInfo 20734 Sema::ActOnOpenMPEndDeclareTargetDirective() { 20735 assert(!DeclareTargetNesting.empty() && 20736 "check isInOpenMPDeclareTargetContext() first!"); 20737 return DeclareTargetNesting.pop_back_val(); 20738 } 20739 20740 void Sema::ActOnFinishedOpenMPDeclareTargetContext( 20741 DeclareTargetContextInfo &DTCI) { 20742 for (auto &It : DTCI.ExplicitlyMapped) 20743 ActOnOpenMPDeclareTargetName(It.first, It.second.Loc, It.second.MT, 20744 DTCI.DT); 20745 } 20746 20747 NamedDecl *Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, 20748 CXXScopeSpec &ScopeSpec, 20749 const DeclarationNameInfo &Id) { 20750 LookupResult Lookup(*this, Id, LookupOrdinaryName); 20751 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 20752 20753 if (Lookup.isAmbiguous()) 20754 return nullptr; 20755 Lookup.suppressDiagnostics(); 20756 20757 if (!Lookup.isSingleResult()) { 20758 VarOrFuncDeclFilterCCC CCC(*this); 20759 if (TypoCorrection Corrected = 20760 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC, 20761 CTK_ErrorRecovery)) { 20762 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 20763 << Id.getName()); 20764 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 20765 return nullptr; 20766 } 20767 20768 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 20769 return nullptr; 20770 } 20771 20772 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 20773 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) && 20774 !isa<FunctionTemplateDecl>(ND)) { 20775 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 20776 return nullptr; 20777 } 20778 return ND; 20779 } 20780 20781 void Sema::ActOnOpenMPDeclareTargetName( 20782 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT, 20783 OMPDeclareTargetDeclAttr::DevTypeTy DT) { 20784 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) || 20785 isa<FunctionTemplateDecl>(ND)) && 20786 "Expected variable, function or function template."); 20787 20788 // Diagnose marking after use as it may lead to incorrect diagnosis and 20789 // codegen. 20790 if (LangOpts.OpenMP >= 50 && 20791 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced())) 20792 Diag(Loc, diag::warn_omp_declare_target_after_first_use); 20793 20794 // Explicit declare target lists have precedence. 20795 const unsigned Level = -1; 20796 20797 auto *VD = cast<ValueDecl>(ND); 20798 llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 20799 OMPDeclareTargetDeclAttr::getActiveAttr(VD); 20800 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getDevType() != DT && 20801 ActiveAttr.getValue()->getLevel() == Level) { 20802 Diag(Loc, diag::err_omp_device_type_mismatch) 20803 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT) 20804 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr( 20805 ActiveAttr.getValue()->getDevType()); 20806 return; 20807 } 20808 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getMapType() != MT && 20809 ActiveAttr.getValue()->getLevel() == Level) { 20810 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND; 20811 return; 20812 } 20813 20814 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() == Level) 20815 return; 20816 20817 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT, Level, 20818 SourceRange(Loc, Loc)); 20819 ND->addAttr(A); 20820 if (ASTMutationListener *ML = Context.getASTMutationListener()) 20821 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 20822 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc); 20823 } 20824 20825 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 20826 Sema &SemaRef, Decl *D) { 20827 if (!D || !isa<VarDecl>(D)) 20828 return; 20829 auto *VD = cast<VarDecl>(D); 20830 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy = 20831 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 20832 if (SemaRef.LangOpts.OpenMP >= 50 && 20833 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) || 20834 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) && 20835 VD->hasGlobalStorage()) { 20836 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) { 20837 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions 20838 // If a lambda declaration and definition appears between a 20839 // declare target directive and the matching end declare target 20840 // directive, all variables that are captured by the lambda 20841 // expression must also appear in a to clause. 20842 SemaRef.Diag(VD->getLocation(), 20843 diag::err_omp_lambda_capture_in_declare_target_not_to); 20844 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here) 20845 << VD << 0 << SR; 20846 return; 20847 } 20848 } 20849 if (MapTy.hasValue()) 20850 return; 20851 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context); 20852 SemaRef.Diag(SL, diag::note_used_here) << SR; 20853 } 20854 20855 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 20856 Sema &SemaRef, DSAStackTy *Stack, 20857 ValueDecl *VD) { 20858 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) || 20859 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(), 20860 /*FullCheck=*/false); 20861 } 20862 20863 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 20864 SourceLocation IdLoc) { 20865 if (!D || D->isInvalidDecl()) 20866 return; 20867 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 20868 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation(); 20869 if (auto *VD = dyn_cast<VarDecl>(D)) { 20870 // Only global variables can be marked as declare target. 20871 if (!VD->isFileVarDecl() && !VD->isStaticLocal() && 20872 !VD->isStaticDataMember()) 20873 return; 20874 // 2.10.6: threadprivate variable cannot appear in a declare target 20875 // directive. 20876 if (DSAStack->isThreadPrivate(VD)) { 20877 Diag(SL, diag::err_omp_threadprivate_in_target); 20878 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 20879 return; 20880 } 20881 } 20882 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) 20883 D = FTD->getTemplatedDecl(); 20884 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 20885 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 20886 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD); 20887 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) { 20888 Diag(IdLoc, diag::err_omp_function_in_link_clause); 20889 Diag(FD->getLocation(), diag::note_defined_here) << FD; 20890 return; 20891 } 20892 } 20893 if (auto *VD = dyn_cast<ValueDecl>(D)) { 20894 // Problem if any with var declared with incomplete type will be reported 20895 // as normal, so no need to check it here. 20896 if ((E || !VD->getType()->isIncompleteType()) && 20897 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) 20898 return; 20899 if (!E && isInOpenMPDeclareTargetContext()) { 20900 // Checking declaration inside declare target region. 20901 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) || 20902 isa<FunctionTemplateDecl>(D)) { 20903 llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 20904 OMPDeclareTargetDeclAttr::getActiveAttr(VD); 20905 unsigned Level = DeclareTargetNesting.size(); 20906 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() >= Level) 20907 return; 20908 DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back(); 20909 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit( 20910 Context, OMPDeclareTargetDeclAttr::MT_To, DTCI.DT, Level, 20911 SourceRange(DTCI.Loc, DTCI.Loc)); 20912 D->addAttr(A); 20913 if (ASTMutationListener *ML = Context.getASTMutationListener()) 20914 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 20915 } 20916 return; 20917 } 20918 } 20919 if (!E) 20920 return; 20921 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 20922 } 20923 20924 OMPClause *Sema::ActOnOpenMPToClause( 20925 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 20926 ArrayRef<SourceLocation> MotionModifiersLoc, 20927 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 20928 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 20929 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) { 20930 OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown, 20931 OMPC_MOTION_MODIFIER_unknown}; 20932 SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers]; 20933 20934 // Process motion-modifiers, flag errors for duplicate modifiers. 20935 unsigned Count = 0; 20936 for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) { 20937 if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown && 20938 llvm::is_contained(Modifiers, MotionModifiers[I])) { 20939 Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier); 20940 continue; 20941 } 20942 assert(Count < NumberOfOMPMotionModifiers && 20943 "Modifiers exceed the allowed number of motion modifiers"); 20944 Modifiers[Count] = MotionModifiers[I]; 20945 ModifiersLoc[Count] = MotionModifiersLoc[I]; 20946 ++Count; 20947 } 20948 20949 MappableVarListInfo MVLI(VarList); 20950 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc, 20951 MapperIdScopeSpec, MapperId, UnresolvedMappers); 20952 if (MVLI.ProcessedVarList.empty()) 20953 return nullptr; 20954 20955 return OMPToClause::Create( 20956 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 20957 MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc, 20958 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 20959 } 20960 20961 OMPClause *Sema::ActOnOpenMPFromClause( 20962 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 20963 ArrayRef<SourceLocation> MotionModifiersLoc, 20964 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 20965 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 20966 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) { 20967 OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown, 20968 OMPC_MOTION_MODIFIER_unknown}; 20969 SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers]; 20970 20971 // Process motion-modifiers, flag errors for duplicate modifiers. 20972 unsigned Count = 0; 20973 for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) { 20974 if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown && 20975 llvm::is_contained(Modifiers, MotionModifiers[I])) { 20976 Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier); 20977 continue; 20978 } 20979 assert(Count < NumberOfOMPMotionModifiers && 20980 "Modifiers exceed the allowed number of motion modifiers"); 20981 Modifiers[Count] = MotionModifiers[I]; 20982 ModifiersLoc[Count] = MotionModifiersLoc[I]; 20983 ++Count; 20984 } 20985 20986 MappableVarListInfo MVLI(VarList); 20987 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc, 20988 MapperIdScopeSpec, MapperId, UnresolvedMappers); 20989 if (MVLI.ProcessedVarList.empty()) 20990 return nullptr; 20991 20992 return OMPFromClause::Create( 20993 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 20994 MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc, 20995 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 20996 } 20997 20998 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 20999 const OMPVarListLocTy &Locs) { 21000 MappableVarListInfo MVLI(VarList); 21001 SmallVector<Expr *, 8> PrivateCopies; 21002 SmallVector<Expr *, 8> Inits; 21003 21004 for (Expr *RefExpr : VarList) { 21005 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 21006 SourceLocation ELoc; 21007 SourceRange ERange; 21008 Expr *SimpleRefExpr = RefExpr; 21009 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 21010 if (Res.second) { 21011 // It will be analyzed later. 21012 MVLI.ProcessedVarList.push_back(RefExpr); 21013 PrivateCopies.push_back(nullptr); 21014 Inits.push_back(nullptr); 21015 } 21016 ValueDecl *D = Res.first; 21017 if (!D) 21018 continue; 21019 21020 QualType Type = D->getType(); 21021 Type = Type.getNonReferenceType().getUnqualifiedType(); 21022 21023 auto *VD = dyn_cast<VarDecl>(D); 21024 21025 // Item should be a pointer or reference to pointer. 21026 if (!Type->isPointerType()) { 21027 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 21028 << 0 << RefExpr->getSourceRange(); 21029 continue; 21030 } 21031 21032 // Build the private variable and the expression that refers to it. 21033 auto VDPrivate = 21034 buildVarDecl(*this, ELoc, Type, D->getName(), 21035 D->hasAttrs() ? &D->getAttrs() : nullptr, 21036 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 21037 if (VDPrivate->isInvalidDecl()) 21038 continue; 21039 21040 CurContext->addDecl(VDPrivate); 21041 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 21042 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 21043 21044 // Add temporary variable to initialize the private copy of the pointer. 21045 VarDecl *VDInit = 21046 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 21047 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr( 21048 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc()); 21049 AddInitializerToDecl(VDPrivate, 21050 DefaultLvalueConversion(VDInitRefExpr).get(), 21051 /*DirectInit=*/false); 21052 21053 // If required, build a capture to implement the privatization initialized 21054 // with the current list item value. 21055 DeclRefExpr *Ref = nullptr; 21056 if (!VD) 21057 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 21058 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 21059 PrivateCopies.push_back(VDPrivateRefExpr); 21060 Inits.push_back(VDInitRefExpr); 21061 21062 // We need to add a data sharing attribute for this variable to make sure it 21063 // is correctly captured. A variable that shows up in a use_device_ptr has 21064 // similar properties of a first private variable. 21065 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 21066 21067 // Create a mappable component for the list item. List items in this clause 21068 // only need a component. 21069 MVLI.VarBaseDeclarations.push_back(D); 21070 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 21071 MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D, 21072 /*IsNonContiguous=*/false); 21073 } 21074 21075 if (MVLI.ProcessedVarList.empty()) 21076 return nullptr; 21077 21078 return OMPUseDevicePtrClause::Create( 21079 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits, 21080 MVLI.VarBaseDeclarations, MVLI.VarComponents); 21081 } 21082 21083 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, 21084 const OMPVarListLocTy &Locs) { 21085 MappableVarListInfo MVLI(VarList); 21086 21087 for (Expr *RefExpr : VarList) { 21088 assert(RefExpr && "NULL expr in OpenMP use_device_addr clause."); 21089 SourceLocation ELoc; 21090 SourceRange ERange; 21091 Expr *SimpleRefExpr = RefExpr; 21092 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 21093 /*AllowArraySection=*/true); 21094 if (Res.second) { 21095 // It will be analyzed later. 21096 MVLI.ProcessedVarList.push_back(RefExpr); 21097 } 21098 ValueDecl *D = Res.first; 21099 if (!D) 21100 continue; 21101 auto *VD = dyn_cast<VarDecl>(D); 21102 21103 // If required, build a capture to implement the privatization initialized 21104 // with the current list item value. 21105 DeclRefExpr *Ref = nullptr; 21106 if (!VD) 21107 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 21108 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 21109 21110 // We need to add a data sharing attribute for this variable to make sure it 21111 // is correctly captured. A variable that shows up in a use_device_addr has 21112 // similar properties of a first private variable. 21113 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 21114 21115 // Create a mappable component for the list item. List items in this clause 21116 // only need a component. 21117 MVLI.VarBaseDeclarations.push_back(D); 21118 MVLI.VarComponents.emplace_back(); 21119 Expr *Component = SimpleRefExpr; 21120 if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) || 21121 isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts()))) 21122 Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get(); 21123 MVLI.VarComponents.back().emplace_back(Component, D, 21124 /*IsNonContiguous=*/false); 21125 } 21126 21127 if (MVLI.ProcessedVarList.empty()) 21128 return nullptr; 21129 21130 return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList, 21131 MVLI.VarBaseDeclarations, 21132 MVLI.VarComponents); 21133 } 21134 21135 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 21136 const OMPVarListLocTy &Locs) { 21137 MappableVarListInfo MVLI(VarList); 21138 for (Expr *RefExpr : VarList) { 21139 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 21140 SourceLocation ELoc; 21141 SourceRange ERange; 21142 Expr *SimpleRefExpr = RefExpr; 21143 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 21144 if (Res.second) { 21145 // It will be analyzed later. 21146 MVLI.ProcessedVarList.push_back(RefExpr); 21147 } 21148 ValueDecl *D = Res.first; 21149 if (!D) 21150 continue; 21151 21152 QualType Type = D->getType(); 21153 // item should be a pointer or array or reference to pointer or array 21154 if (!Type.getNonReferenceType()->isPointerType() && 21155 !Type.getNonReferenceType()->isArrayType()) { 21156 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 21157 << 0 << RefExpr->getSourceRange(); 21158 continue; 21159 } 21160 21161 // Check if the declaration in the clause does not show up in any data 21162 // sharing attribute. 21163 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 21164 if (isOpenMPPrivate(DVar.CKind)) { 21165 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 21166 << getOpenMPClauseName(DVar.CKind) 21167 << getOpenMPClauseName(OMPC_is_device_ptr) 21168 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 21169 reportOriginalDsa(*this, DSAStack, D, DVar); 21170 continue; 21171 } 21172 21173 const Expr *ConflictExpr; 21174 if (DSAStack->checkMappableExprComponentListsForDecl( 21175 D, /*CurrentRegionOnly=*/true, 21176 [&ConflictExpr]( 21177 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 21178 OpenMPClauseKind) -> bool { 21179 ConflictExpr = R.front().getAssociatedExpression(); 21180 return true; 21181 })) { 21182 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 21183 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 21184 << ConflictExpr->getSourceRange(); 21185 continue; 21186 } 21187 21188 // Store the components in the stack so that they can be used to check 21189 // against other clauses later on. 21190 OMPClauseMappableExprCommon::MappableComponent MC( 21191 SimpleRefExpr, D, /*IsNonContiguous=*/false); 21192 DSAStack->addMappableExpressionComponents( 21193 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 21194 21195 // Record the expression we've just processed. 21196 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 21197 21198 // Create a mappable component for the list item. List items in this clause 21199 // only need a component. We use a null declaration to signal fields in 21200 // 'this'. 21201 assert((isa<DeclRefExpr>(SimpleRefExpr) || 21202 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 21203 "Unexpected device pointer expression!"); 21204 MVLI.VarBaseDeclarations.push_back( 21205 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 21206 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 21207 MVLI.VarComponents.back().push_back(MC); 21208 } 21209 21210 if (MVLI.ProcessedVarList.empty()) 21211 return nullptr; 21212 21213 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList, 21214 MVLI.VarBaseDeclarations, 21215 MVLI.VarComponents); 21216 } 21217 21218 OMPClause *Sema::ActOnOpenMPAllocateClause( 21219 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, 21220 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 21221 if (Allocator) { 21222 // OpenMP [2.11.4 allocate Clause, Description] 21223 // allocator is an expression of omp_allocator_handle_t type. 21224 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack)) 21225 return nullptr; 21226 21227 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator); 21228 if (AllocatorRes.isInvalid()) 21229 return nullptr; 21230 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(), 21231 DSAStack->getOMPAllocatorHandleT(), 21232 Sema::AA_Initializing, 21233 /*AllowExplicit=*/true); 21234 if (AllocatorRes.isInvalid()) 21235 return nullptr; 21236 Allocator = AllocatorRes.get(); 21237 } else { 21238 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions. 21239 // allocate clauses that appear on a target construct or on constructs in a 21240 // target region must specify an allocator expression unless a requires 21241 // directive with the dynamic_allocators clause is present in the same 21242 // compilation unit. 21243 if (LangOpts.OpenMPIsDevice && 21244 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>()) 21245 targetDiag(StartLoc, diag::err_expected_allocator_expression); 21246 } 21247 // Analyze and build list of variables. 21248 SmallVector<Expr *, 8> Vars; 21249 for (Expr *RefExpr : VarList) { 21250 assert(RefExpr && "NULL expr in OpenMP private clause."); 21251 SourceLocation ELoc; 21252 SourceRange ERange; 21253 Expr *SimpleRefExpr = RefExpr; 21254 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 21255 if (Res.second) { 21256 // It will be analyzed later. 21257 Vars.push_back(RefExpr); 21258 } 21259 ValueDecl *D = Res.first; 21260 if (!D) 21261 continue; 21262 21263 auto *VD = dyn_cast<VarDecl>(D); 21264 DeclRefExpr *Ref = nullptr; 21265 if (!VD && !CurContext->isDependentContext()) 21266 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 21267 Vars.push_back((VD || CurContext->isDependentContext()) 21268 ? RefExpr->IgnoreParens() 21269 : Ref); 21270 } 21271 21272 if (Vars.empty()) 21273 return nullptr; 21274 21275 if (Allocator) 21276 DSAStack->addInnerAllocatorExpr(Allocator); 21277 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator, 21278 ColonLoc, EndLoc, Vars); 21279 } 21280 21281 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, 21282 SourceLocation StartLoc, 21283 SourceLocation LParenLoc, 21284 SourceLocation EndLoc) { 21285 SmallVector<Expr *, 8> Vars; 21286 for (Expr *RefExpr : VarList) { 21287 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 21288 SourceLocation ELoc; 21289 SourceRange ERange; 21290 Expr *SimpleRefExpr = RefExpr; 21291 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 21292 if (Res.second) 21293 // It will be analyzed later. 21294 Vars.push_back(RefExpr); 21295 ValueDecl *D = Res.first; 21296 if (!D) 21297 continue; 21298 21299 // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions. 21300 // A list-item cannot appear in more than one nontemporal clause. 21301 if (const Expr *PrevRef = 21302 DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) { 21303 Diag(ELoc, diag::err_omp_used_in_clause_twice) 21304 << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange; 21305 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 21306 << getOpenMPClauseName(OMPC_nontemporal); 21307 continue; 21308 } 21309 21310 Vars.push_back(RefExpr); 21311 } 21312 21313 if (Vars.empty()) 21314 return nullptr; 21315 21316 return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc, 21317 Vars); 21318 } 21319 21320 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, 21321 SourceLocation StartLoc, 21322 SourceLocation LParenLoc, 21323 SourceLocation EndLoc) { 21324 SmallVector<Expr *, 8> Vars; 21325 for (Expr *RefExpr : VarList) { 21326 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 21327 SourceLocation ELoc; 21328 SourceRange ERange; 21329 Expr *SimpleRefExpr = RefExpr; 21330 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 21331 /*AllowArraySection=*/true); 21332 if (Res.second) 21333 // It will be analyzed later. 21334 Vars.push_back(RefExpr); 21335 ValueDecl *D = Res.first; 21336 if (!D) 21337 continue; 21338 21339 const DSAStackTy::DSAVarData DVar = 21340 DSAStack->getTopDSA(D, /*FromParent=*/true); 21341 // OpenMP 5.0, 2.9.6, scan Directive, Restrictions. 21342 // A list item that appears in the inclusive or exclusive clause must appear 21343 // in a reduction clause with the inscan modifier on the enclosing 21344 // worksharing-loop, worksharing-loop SIMD, or simd construct. 21345 if (DVar.CKind != OMPC_reduction || DVar.Modifier != OMPC_REDUCTION_inscan) 21346 Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction) 21347 << RefExpr->getSourceRange(); 21348 21349 if (DSAStack->getParentDirective() != OMPD_unknown) 21350 DSAStack->markDeclAsUsedInScanDirective(D); 21351 Vars.push_back(RefExpr); 21352 } 21353 21354 if (Vars.empty()) 21355 return nullptr; 21356 21357 return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 21358 } 21359 21360 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, 21361 SourceLocation StartLoc, 21362 SourceLocation LParenLoc, 21363 SourceLocation EndLoc) { 21364 SmallVector<Expr *, 8> Vars; 21365 for (Expr *RefExpr : VarList) { 21366 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 21367 SourceLocation ELoc; 21368 SourceRange ERange; 21369 Expr *SimpleRefExpr = RefExpr; 21370 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 21371 /*AllowArraySection=*/true); 21372 if (Res.second) 21373 // It will be analyzed later. 21374 Vars.push_back(RefExpr); 21375 ValueDecl *D = Res.first; 21376 if (!D) 21377 continue; 21378 21379 OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective(); 21380 DSAStackTy::DSAVarData DVar; 21381 if (ParentDirective != OMPD_unknown) 21382 DVar = DSAStack->getTopDSA(D, /*FromParent=*/true); 21383 // OpenMP 5.0, 2.9.6, scan Directive, Restrictions. 21384 // A list item that appears in the inclusive or exclusive clause must appear 21385 // in a reduction clause with the inscan modifier on the enclosing 21386 // worksharing-loop, worksharing-loop SIMD, or simd construct. 21387 if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction || 21388 DVar.Modifier != OMPC_REDUCTION_inscan) { 21389 Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction) 21390 << RefExpr->getSourceRange(); 21391 } else { 21392 DSAStack->markDeclAsUsedInScanDirective(D); 21393 } 21394 Vars.push_back(RefExpr); 21395 } 21396 21397 if (Vars.empty()) 21398 return nullptr; 21399 21400 return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 21401 } 21402 21403 /// Tries to find omp_alloctrait_t type. 21404 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) { 21405 QualType OMPAlloctraitT = Stack->getOMPAlloctraitT(); 21406 if (!OMPAlloctraitT.isNull()) 21407 return true; 21408 IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t"); 21409 ParsedType PT = S.getTypeName(II, Loc, S.getCurScope()); 21410 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 21411 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t"; 21412 return false; 21413 } 21414 Stack->setOMPAlloctraitT(PT.get()); 21415 return true; 21416 } 21417 21418 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause( 21419 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, 21420 ArrayRef<UsesAllocatorsData> Data) { 21421 // OpenMP [2.12.5, target Construct] 21422 // allocator is an identifier of omp_allocator_handle_t type. 21423 if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack)) 21424 return nullptr; 21425 // OpenMP [2.12.5, target Construct] 21426 // allocator-traits-array is an identifier of const omp_alloctrait_t * type. 21427 if (llvm::any_of( 21428 Data, 21429 [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) && 21430 !findOMPAlloctraitT(*this, StartLoc, DSAStack)) 21431 return nullptr; 21432 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators; 21433 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 21434 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 21435 StringRef Allocator = 21436 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind); 21437 DeclarationName AllocatorName = &Context.Idents.get(Allocator); 21438 PredefinedAllocators.insert(LookupSingleName( 21439 TUScope, AllocatorName, StartLoc, Sema::LookupAnyName)); 21440 } 21441 21442 SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData; 21443 for (const UsesAllocatorsData &D : Data) { 21444 Expr *AllocatorExpr = nullptr; 21445 // Check allocator expression. 21446 if (D.Allocator->isTypeDependent()) { 21447 AllocatorExpr = D.Allocator; 21448 } else { 21449 // Traits were specified - need to assign new allocator to the specified 21450 // allocator, so it must be an lvalue. 21451 AllocatorExpr = D.Allocator->IgnoreParenImpCasts(); 21452 auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr); 21453 bool IsPredefinedAllocator = false; 21454 if (DRE) 21455 IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl()); 21456 if (!DRE || 21457 !(Context.hasSameUnqualifiedType( 21458 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) || 21459 Context.typesAreCompatible(AllocatorExpr->getType(), 21460 DSAStack->getOMPAllocatorHandleT(), 21461 /*CompareUnqualified=*/true)) || 21462 (!IsPredefinedAllocator && 21463 (AllocatorExpr->getType().isConstant(Context) || 21464 !AllocatorExpr->isLValue()))) { 21465 Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected) 21466 << "omp_allocator_handle_t" << (DRE ? 1 : 0) 21467 << AllocatorExpr->getType() << D.Allocator->getSourceRange(); 21468 continue; 21469 } 21470 // OpenMP [2.12.5, target Construct] 21471 // Predefined allocators appearing in a uses_allocators clause cannot have 21472 // traits specified. 21473 if (IsPredefinedAllocator && D.AllocatorTraits) { 21474 Diag(D.AllocatorTraits->getExprLoc(), 21475 diag::err_omp_predefined_allocator_with_traits) 21476 << D.AllocatorTraits->getSourceRange(); 21477 Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator) 21478 << cast<NamedDecl>(DRE->getDecl())->getName() 21479 << D.Allocator->getSourceRange(); 21480 continue; 21481 } 21482 // OpenMP [2.12.5, target Construct] 21483 // Non-predefined allocators appearing in a uses_allocators clause must 21484 // have traits specified. 21485 if (!IsPredefinedAllocator && !D.AllocatorTraits) { 21486 Diag(D.Allocator->getExprLoc(), 21487 diag::err_omp_nonpredefined_allocator_without_traits); 21488 continue; 21489 } 21490 // No allocator traits - just convert it to rvalue. 21491 if (!D.AllocatorTraits) 21492 AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get(); 21493 DSAStack->addUsesAllocatorsDecl( 21494 DRE->getDecl(), 21495 IsPredefinedAllocator 21496 ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator 21497 : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator); 21498 } 21499 Expr *AllocatorTraitsExpr = nullptr; 21500 if (D.AllocatorTraits) { 21501 if (D.AllocatorTraits->isTypeDependent()) { 21502 AllocatorTraitsExpr = D.AllocatorTraits; 21503 } else { 21504 // OpenMP [2.12.5, target Construct] 21505 // Arrays that contain allocator traits that appear in a uses_allocators 21506 // clause must be constant arrays, have constant values and be defined 21507 // in the same scope as the construct in which the clause appears. 21508 AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts(); 21509 // Check that traits expr is a constant array. 21510 QualType TraitTy; 21511 if (const ArrayType *Ty = 21512 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe()) 21513 if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty)) 21514 TraitTy = ConstArrayTy->getElementType(); 21515 if (TraitTy.isNull() || 21516 !(Context.hasSameUnqualifiedType(TraitTy, 21517 DSAStack->getOMPAlloctraitT()) || 21518 Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(), 21519 /*CompareUnqualified=*/true))) { 21520 Diag(D.AllocatorTraits->getExprLoc(), 21521 diag::err_omp_expected_array_alloctraits) 21522 << AllocatorTraitsExpr->getType(); 21523 continue; 21524 } 21525 // Do not map by default allocator traits if it is a standalone 21526 // variable. 21527 if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr)) 21528 DSAStack->addUsesAllocatorsDecl( 21529 DRE->getDecl(), 21530 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait); 21531 } 21532 } 21533 OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back(); 21534 NewD.Allocator = AllocatorExpr; 21535 NewD.AllocatorTraits = AllocatorTraitsExpr; 21536 NewD.LParenLoc = D.LParenLoc; 21537 NewD.RParenLoc = D.RParenLoc; 21538 } 21539 return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc, 21540 NewData); 21541 } 21542 21543 OMPClause *Sema::ActOnOpenMPAffinityClause( 21544 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 21545 SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) { 21546 SmallVector<Expr *, 8> Vars; 21547 for (Expr *RefExpr : Locators) { 21548 assert(RefExpr && "NULL expr in OpenMP shared clause."); 21549 if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) { 21550 // It will be analyzed later. 21551 Vars.push_back(RefExpr); 21552 continue; 21553 } 21554 21555 SourceLocation ELoc = RefExpr->getExprLoc(); 21556 Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts(); 21557 21558 if (!SimpleExpr->isLValue()) { 21559 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 21560 << 1 << 0 << RefExpr->getSourceRange(); 21561 continue; 21562 } 21563 21564 ExprResult Res; 21565 { 21566 Sema::TentativeAnalysisScope Trap(*this); 21567 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr); 21568 } 21569 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) && 21570 !isa<OMPArrayShapingExpr>(SimpleExpr)) { 21571 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 21572 << 1 << 0 << RefExpr->getSourceRange(); 21573 continue; 21574 } 21575 Vars.push_back(SimpleExpr); 21576 } 21577 21578 return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 21579 EndLoc, Modifier, Vars); 21580 } 21581 21582 OMPClause *Sema::ActOnOpenMPBindClause(OpenMPBindClauseKind Kind, 21583 SourceLocation KindLoc, 21584 SourceLocation StartLoc, 21585 SourceLocation LParenLoc, 21586 SourceLocation EndLoc) { 21587 if (Kind == OMPC_BIND_unknown) { 21588 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 21589 << getListOfPossibleValues(OMPC_bind, /*First=*/0, 21590 /*Last=*/unsigned(OMPC_BIND_unknown)) 21591 << getOpenMPClauseName(OMPC_bind); 21592 return nullptr; 21593 } 21594 21595 return OMPBindClause::Create(Context, Kind, KindLoc, StartLoc, LParenLoc, 21596 EndLoc); 21597 } 21598