1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// \file 9 /// This file implements semantic analysis for OpenMP directives and 10 /// clauses. 11 /// 12 //===----------------------------------------------------------------------===// 13 14 #include "TreeTransform.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/AST/DeclCXX.h" 20 #include "clang/AST/DeclOpenMP.h" 21 #include "clang/AST/OpenMPClause.h" 22 #include "clang/AST/StmtCXX.h" 23 #include "clang/AST/StmtOpenMP.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/AST/TypeOrdering.h" 26 #include "clang/Basic/DiagnosticSema.h" 27 #include "clang/Basic/OpenMPKinds.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Sema/Initialization.h" 31 #include "clang/Sema/Lookup.h" 32 #include "clang/Sema/Scope.h" 33 #include "clang/Sema/ScopeInfo.h" 34 #include "clang/Sema/SemaInternal.h" 35 #include "llvm/ADT/IndexedMap.h" 36 #include "llvm/ADT/PointerEmbeddedInt.h" 37 #include "llvm/ADT/STLExtras.h" 38 #include "llvm/ADT/SmallSet.h" 39 #include "llvm/ADT/StringExtras.h" 40 #include "llvm/Frontend/OpenMP/OMPAssume.h" 41 #include "llvm/Frontend/OpenMP/OMPConstants.h" 42 #include <set> 43 44 using namespace clang; 45 using namespace llvm::omp; 46 47 //===----------------------------------------------------------------------===// 48 // Stack of data-sharing attributes for variables 49 //===----------------------------------------------------------------------===// 50 51 static const Expr *checkMapClauseExpressionBase( 52 Sema &SemaRef, Expr *E, 53 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 54 OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose); 55 56 namespace { 57 /// Default data sharing attributes, which can be applied to directive. 58 enum DefaultDataSharingAttributes { 59 DSA_unspecified = 0, /// Data sharing attribute not specified. 60 DSA_none = 1 << 0, /// Default data sharing attribute 'none'. 61 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'. 62 DSA_firstprivate = 1 << 2, /// Default data sharing attribute 'firstprivate'. 63 }; 64 65 /// Stack for tracking declarations used in OpenMP directives and 66 /// clauses and their data-sharing attributes. 67 class DSAStackTy { 68 public: 69 struct DSAVarData { 70 OpenMPDirectiveKind DKind = OMPD_unknown; 71 OpenMPClauseKind CKind = OMPC_unknown; 72 unsigned Modifier = 0; 73 const Expr *RefExpr = nullptr; 74 DeclRefExpr *PrivateCopy = nullptr; 75 SourceLocation ImplicitDSALoc; 76 bool AppliedToPointee = false; 77 DSAVarData() = default; 78 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 79 const Expr *RefExpr, DeclRefExpr *PrivateCopy, 80 SourceLocation ImplicitDSALoc, unsigned Modifier, 81 bool AppliedToPointee) 82 : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr), 83 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc), 84 AppliedToPointee(AppliedToPointee) {} 85 }; 86 using OperatorOffsetTy = 87 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>; 88 using DoacrossDependMapTy = 89 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>; 90 /// Kind of the declaration used in the uses_allocators clauses. 91 enum class UsesAllocatorsDeclKind { 92 /// Predefined allocator 93 PredefinedAllocator, 94 /// User-defined allocator 95 UserDefinedAllocator, 96 /// The declaration that represent allocator trait 97 AllocatorTrait, 98 }; 99 100 private: 101 struct DSAInfo { 102 OpenMPClauseKind Attributes = OMPC_unknown; 103 unsigned Modifier = 0; 104 /// Pointer to a reference expression and a flag which shows that the 105 /// variable is marked as lastprivate(true) or not (false). 106 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr; 107 DeclRefExpr *PrivateCopy = nullptr; 108 /// true if the attribute is applied to the pointee, not the variable 109 /// itself. 110 bool AppliedToPointee = false; 111 }; 112 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>; 113 using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>; 114 using LCDeclInfo = std::pair<unsigned, VarDecl *>; 115 using LoopControlVariablesMapTy = 116 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>; 117 /// Struct that associates a component with the clause kind where they are 118 /// found. 119 struct MappedExprComponentTy { 120 OMPClauseMappableExprCommon::MappableExprComponentLists Components; 121 OpenMPClauseKind Kind = OMPC_unknown; 122 }; 123 using MappedExprComponentsTy = 124 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>; 125 using CriticalsWithHintsTy = 126 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>; 127 struct ReductionData { 128 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>; 129 SourceRange ReductionRange; 130 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp; 131 ReductionData() = default; 132 void set(BinaryOperatorKind BO, SourceRange RR) { 133 ReductionRange = RR; 134 ReductionOp = BO; 135 } 136 void set(const Expr *RefExpr, SourceRange RR) { 137 ReductionRange = RR; 138 ReductionOp = RefExpr; 139 } 140 }; 141 using DeclReductionMapTy = 142 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>; 143 struct DefaultmapInfo { 144 OpenMPDefaultmapClauseModifier ImplicitBehavior = 145 OMPC_DEFAULTMAP_MODIFIER_unknown; 146 SourceLocation SLoc; 147 DefaultmapInfo() = default; 148 DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc) 149 : ImplicitBehavior(M), SLoc(Loc) {} 150 }; 151 152 struct SharingMapTy { 153 DeclSAMapTy SharingMap; 154 DeclReductionMapTy ReductionMap; 155 UsedRefMapTy AlignedMap; 156 UsedRefMapTy NontemporalMap; 157 MappedExprComponentsTy MappedExprComponents; 158 LoopControlVariablesMapTy LCVMap; 159 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 160 SourceLocation DefaultAttrLoc; 161 DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown]; 162 OpenMPDirectiveKind Directive = OMPD_unknown; 163 DeclarationNameInfo DirectiveName; 164 Scope *CurScope = nullptr; 165 DeclContext *Context = nullptr; 166 SourceLocation ConstructLoc; 167 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 168 /// get the data (loop counters etc.) about enclosing loop-based construct. 169 /// This data is required during codegen. 170 DoacrossDependMapTy DoacrossDepends; 171 /// First argument (Expr *) contains optional argument of the 172 /// 'ordered' clause, the second one is true if the regions has 'ordered' 173 /// clause, false otherwise. 174 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion; 175 unsigned AssociatedLoops = 1; 176 bool HasMutipleLoops = false; 177 const Decl *PossiblyLoopCounter = nullptr; 178 bool NowaitRegion = false; 179 bool CancelRegion = false; 180 bool LoopStart = false; 181 bool BodyComplete = false; 182 SourceLocation PrevScanLocation; 183 SourceLocation PrevOrderedLocation; 184 SourceLocation InnerTeamsRegionLoc; 185 /// Reference to the taskgroup task_reduction reference expression. 186 Expr *TaskgroupReductionRef = nullptr; 187 llvm::DenseSet<QualType> MappedClassesQualTypes; 188 SmallVector<Expr *, 4> InnerUsedAllocators; 189 llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates; 190 /// List of globals marked as declare target link in this target region 191 /// (isOpenMPTargetExecutionDirective(Directive) == true). 192 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls; 193 /// List of decls used in inclusive/exclusive clauses of the scan directive. 194 llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective; 195 llvm::DenseMap<CanonicalDeclPtr<const Decl>, UsesAllocatorsDeclKind> 196 UsesAllocatorsDecls; 197 Expr *DeclareMapperVar = nullptr; 198 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 199 Scope *CurScope, SourceLocation Loc) 200 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 201 ConstructLoc(Loc) {} 202 SharingMapTy() = default; 203 }; 204 205 using StackTy = SmallVector<SharingMapTy, 4>; 206 207 /// Stack of used declaration and their data-sharing attributes. 208 DeclSAMapTy Threadprivates; 209 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr; 210 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack; 211 /// true, if check for DSA must be from parent directive, false, if 212 /// from current directive. 213 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 214 Sema &SemaRef; 215 bool ForceCapturing = false; 216 /// true if all the variables in the target executable directives must be 217 /// captured by reference. 218 bool ForceCaptureByReferenceInTargetExecutable = false; 219 CriticalsWithHintsTy Criticals; 220 unsigned IgnoredStackElements = 0; 221 222 /// Iterators over the stack iterate in order from innermost to outermost 223 /// directive. 224 using const_iterator = StackTy::const_reverse_iterator; 225 const_iterator begin() const { 226 return Stack.empty() ? const_iterator() 227 : Stack.back().first.rbegin() + IgnoredStackElements; 228 } 229 const_iterator end() const { 230 return Stack.empty() ? const_iterator() : Stack.back().first.rend(); 231 } 232 using iterator = StackTy::reverse_iterator; 233 iterator begin() { 234 return Stack.empty() ? iterator() 235 : Stack.back().first.rbegin() + IgnoredStackElements; 236 } 237 iterator end() { 238 return Stack.empty() ? iterator() : Stack.back().first.rend(); 239 } 240 241 // Convenience operations to get at the elements of the stack. 242 243 bool isStackEmpty() const { 244 return Stack.empty() || 245 Stack.back().second != CurrentNonCapturingFunctionScope || 246 Stack.back().first.size() <= IgnoredStackElements; 247 } 248 size_t getStackSize() const { 249 return isStackEmpty() ? 0 250 : Stack.back().first.size() - IgnoredStackElements; 251 } 252 253 SharingMapTy *getTopOfStackOrNull() { 254 size_t Size = getStackSize(); 255 if (Size == 0) 256 return nullptr; 257 return &Stack.back().first[Size - 1]; 258 } 259 const SharingMapTy *getTopOfStackOrNull() const { 260 return const_cast<DSAStackTy &>(*this).getTopOfStackOrNull(); 261 } 262 SharingMapTy &getTopOfStack() { 263 assert(!isStackEmpty() && "no current directive"); 264 return *getTopOfStackOrNull(); 265 } 266 const SharingMapTy &getTopOfStack() const { 267 return const_cast<DSAStackTy &>(*this).getTopOfStack(); 268 } 269 270 SharingMapTy *getSecondOnStackOrNull() { 271 size_t Size = getStackSize(); 272 if (Size <= 1) 273 return nullptr; 274 return &Stack.back().first[Size - 2]; 275 } 276 const SharingMapTy *getSecondOnStackOrNull() const { 277 return const_cast<DSAStackTy &>(*this).getSecondOnStackOrNull(); 278 } 279 280 /// Get the stack element at a certain level (previously returned by 281 /// \c getNestingLevel). 282 /// 283 /// Note that nesting levels count from outermost to innermost, and this is 284 /// the reverse of our iteration order where new inner levels are pushed at 285 /// the front of the stack. 286 SharingMapTy &getStackElemAtLevel(unsigned Level) { 287 assert(Level < getStackSize() && "no such stack element"); 288 return Stack.back().first[Level]; 289 } 290 const SharingMapTy &getStackElemAtLevel(unsigned Level) const { 291 return const_cast<DSAStackTy &>(*this).getStackElemAtLevel(Level); 292 } 293 294 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const; 295 296 /// Checks if the variable is a local for OpenMP region. 297 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const; 298 299 /// Vector of previously declared requires directives 300 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls; 301 /// omp_allocator_handle_t type. 302 QualType OMPAllocatorHandleT; 303 /// omp_depend_t type. 304 QualType OMPDependT; 305 /// omp_event_handle_t type. 306 QualType OMPEventHandleT; 307 /// omp_alloctrait_t type. 308 QualType OMPAlloctraitT; 309 /// Expression for the predefined allocators. 310 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = { 311 nullptr}; 312 /// Vector of previously encountered target directives 313 SmallVector<SourceLocation, 2> TargetLocations; 314 SourceLocation AtomicLocation; 315 /// Vector of declare variant construct traits. 316 SmallVector<llvm::omp::TraitProperty, 8> ConstructTraits; 317 318 public: 319 explicit DSAStackTy(Sema &S) : SemaRef(S) {} 320 321 /// Sets omp_allocator_handle_t type. 322 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; } 323 /// Gets omp_allocator_handle_t type. 324 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; } 325 /// Sets omp_alloctrait_t type. 326 void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; } 327 /// Gets omp_alloctrait_t type. 328 QualType getOMPAlloctraitT() const { return OMPAlloctraitT; } 329 /// Sets the given default allocator. 330 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, 331 Expr *Allocator) { 332 OMPPredefinedAllocators[AllocatorKind] = Allocator; 333 } 334 /// Returns the specified default allocator. 335 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const { 336 return OMPPredefinedAllocators[AllocatorKind]; 337 } 338 /// Sets omp_depend_t type. 339 void setOMPDependT(QualType Ty) { OMPDependT = Ty; } 340 /// Gets omp_depend_t type. 341 QualType getOMPDependT() const { return OMPDependT; } 342 343 /// Sets omp_event_handle_t type. 344 void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; } 345 /// Gets omp_event_handle_t type. 346 QualType getOMPEventHandleT() const { return OMPEventHandleT; } 347 348 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 349 OpenMPClauseKind getClauseParsingMode() const { 350 assert(isClauseParsingMode() && "Must be in clause parsing mode."); 351 return ClauseKindMode; 352 } 353 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 354 355 bool isBodyComplete() const { 356 const SharingMapTy *Top = getTopOfStackOrNull(); 357 return Top && Top->BodyComplete; 358 } 359 void setBodyComplete() { getTopOfStack().BodyComplete = true; } 360 361 bool isForceVarCapturing() const { return ForceCapturing; } 362 void setForceVarCapturing(bool V) { ForceCapturing = V; } 363 364 void setForceCaptureByReferenceInTargetExecutable(bool V) { 365 ForceCaptureByReferenceInTargetExecutable = V; 366 } 367 bool isForceCaptureByReferenceInTargetExecutable() const { 368 return ForceCaptureByReferenceInTargetExecutable; 369 } 370 371 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 372 Scope *CurScope, SourceLocation Loc) { 373 assert(!IgnoredStackElements && 374 "cannot change stack while ignoring elements"); 375 if (Stack.empty() || 376 Stack.back().second != CurrentNonCapturingFunctionScope) 377 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope); 378 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc); 379 Stack.back().first.back().DefaultAttrLoc = Loc; 380 } 381 382 void pop() { 383 assert(!IgnoredStackElements && 384 "cannot change stack while ignoring elements"); 385 assert(!Stack.back().first.empty() && 386 "Data-sharing attributes stack is empty!"); 387 Stack.back().first.pop_back(); 388 } 389 390 /// RAII object to temporarily leave the scope of a directive when we want to 391 /// logically operate in its parent. 392 class ParentDirectiveScope { 393 DSAStackTy &Self; 394 bool Active; 395 396 public: 397 ParentDirectiveScope(DSAStackTy &Self, bool Activate) 398 : Self(Self), Active(false) { 399 if (Activate) 400 enable(); 401 } 402 ~ParentDirectiveScope() { disable(); } 403 void disable() { 404 if (Active) { 405 --Self.IgnoredStackElements; 406 Active = false; 407 } 408 } 409 void enable() { 410 if (!Active) { 411 ++Self.IgnoredStackElements; 412 Active = true; 413 } 414 } 415 }; 416 417 /// Marks that we're started loop parsing. 418 void loopInit() { 419 assert(isOpenMPLoopDirective(getCurrentDirective()) && 420 "Expected loop-based directive."); 421 getTopOfStack().LoopStart = true; 422 } 423 /// Start capturing of the variables in the loop context. 424 void loopStart() { 425 assert(isOpenMPLoopDirective(getCurrentDirective()) && 426 "Expected loop-based directive."); 427 getTopOfStack().LoopStart = false; 428 } 429 /// true, if variables are captured, false otherwise. 430 bool isLoopStarted() const { 431 assert(isOpenMPLoopDirective(getCurrentDirective()) && 432 "Expected loop-based directive."); 433 return !getTopOfStack().LoopStart; 434 } 435 /// Marks (or clears) declaration as possibly loop counter. 436 void resetPossibleLoopCounter(const Decl *D = nullptr) { 437 getTopOfStack().PossiblyLoopCounter = D ? D->getCanonicalDecl() : D; 438 } 439 /// Gets the possible loop counter decl. 440 const Decl *getPossiblyLoopCunter() const { 441 return getTopOfStack().PossiblyLoopCounter; 442 } 443 /// Start new OpenMP region stack in new non-capturing function. 444 void pushFunction() { 445 assert(!IgnoredStackElements && 446 "cannot change stack while ignoring elements"); 447 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction(); 448 assert(!isa<CapturingScopeInfo>(CurFnScope)); 449 CurrentNonCapturingFunctionScope = CurFnScope; 450 } 451 /// Pop region stack for non-capturing function. 452 void popFunction(const FunctionScopeInfo *OldFSI) { 453 assert(!IgnoredStackElements && 454 "cannot change stack while ignoring elements"); 455 if (!Stack.empty() && Stack.back().second == OldFSI) { 456 assert(Stack.back().first.empty()); 457 Stack.pop_back(); 458 } 459 CurrentNonCapturingFunctionScope = nullptr; 460 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) { 461 if (!isa<CapturingScopeInfo>(FSI)) { 462 CurrentNonCapturingFunctionScope = FSI; 463 break; 464 } 465 } 466 } 467 468 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) { 469 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint); 470 } 471 const std::pair<const OMPCriticalDirective *, llvm::APSInt> 472 getCriticalWithHint(const DeclarationNameInfo &Name) const { 473 auto I = Criticals.find(Name.getAsString()); 474 if (I != Criticals.end()) 475 return I->second; 476 return std::make_pair(nullptr, llvm::APSInt()); 477 } 478 /// If 'aligned' declaration for given variable \a D was not seen yet, 479 /// add it and return NULL; otherwise return previous occurrence's expression 480 /// for diagnostics. 481 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE); 482 /// If 'nontemporal' declaration for given variable \a D was not seen yet, 483 /// add it and return NULL; otherwise return previous occurrence's expression 484 /// for diagnostics. 485 const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE); 486 487 /// Register specified variable as loop control variable. 488 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture); 489 /// Check if the specified variable is a loop control variable for 490 /// current region. 491 /// \return The index of the loop control variable in the list of associated 492 /// for-loops (from outer to inner). 493 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const; 494 /// Check if the specified variable is a loop control variable for 495 /// parent region. 496 /// \return The index of the loop control variable in the list of associated 497 /// for-loops (from outer to inner). 498 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const; 499 /// Check if the specified variable is a loop control variable for 500 /// current region. 501 /// \return The index of the loop control variable in the list of associated 502 /// for-loops (from outer to inner). 503 const LCDeclInfo isLoopControlVariable(const ValueDecl *D, 504 unsigned Level) const; 505 /// Get the loop control variable for the I-th loop (or nullptr) in 506 /// parent directive. 507 const ValueDecl *getParentLoopControlVariable(unsigned I) const; 508 509 /// Marks the specified decl \p D as used in scan directive. 510 void markDeclAsUsedInScanDirective(ValueDecl *D) { 511 if (SharingMapTy *Stack = getSecondOnStackOrNull()) 512 Stack->UsedInScanDirective.insert(D); 513 } 514 515 /// Checks if the specified declaration was used in the inner scan directive. 516 bool isUsedInScanDirective(ValueDecl *D) const { 517 if (const SharingMapTy *Stack = getTopOfStackOrNull()) 518 return Stack->UsedInScanDirective.contains(D); 519 return false; 520 } 521 522 /// Adds explicit data sharing attribute to the specified declaration. 523 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 524 DeclRefExpr *PrivateCopy = nullptr, unsigned Modifier = 0, 525 bool AppliedToPointee = false); 526 527 /// Adds additional information for the reduction items with the reduction id 528 /// represented as an operator. 529 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 530 BinaryOperatorKind BOK); 531 /// Adds additional information for the reduction items with the reduction id 532 /// represented as reduction identifier. 533 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 534 const Expr *ReductionRef); 535 /// Returns the location and reduction operation from the innermost parent 536 /// region for the given \p D. 537 const DSAVarData 538 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 539 BinaryOperatorKind &BOK, 540 Expr *&TaskgroupDescriptor) const; 541 /// Returns the location and reduction operation from the innermost parent 542 /// region for the given \p D. 543 const DSAVarData 544 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 545 const Expr *&ReductionRef, 546 Expr *&TaskgroupDescriptor) const; 547 /// Return reduction reference expression for the current taskgroup or 548 /// parallel/worksharing directives with task reductions. 549 Expr *getTaskgroupReductionRef() const { 550 assert((getTopOfStack().Directive == OMPD_taskgroup || 551 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 552 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 553 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 554 "taskgroup reference expression requested for non taskgroup or " 555 "parallel/worksharing directive."); 556 return getTopOfStack().TaskgroupReductionRef; 557 } 558 /// Checks if the given \p VD declaration is actually a taskgroup reduction 559 /// descriptor variable at the \p Level of OpenMP regions. 560 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const { 561 return getStackElemAtLevel(Level).TaskgroupReductionRef && 562 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef) 563 ->getDecl() == VD; 564 } 565 566 /// Returns data sharing attributes from top of the stack for the 567 /// specified declaration. 568 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 569 /// Returns data-sharing attributes for the specified declaration. 570 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const; 571 /// Returns data-sharing attributes for the specified declaration. 572 const DSAVarData getImplicitDSA(ValueDecl *D, unsigned Level) const; 573 /// Checks if the specified variables has data-sharing attributes which 574 /// match specified \a CPred predicate in any directive which matches \a DPred 575 /// predicate. 576 const DSAVarData 577 hasDSA(ValueDecl *D, 578 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 579 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 580 bool FromParent) const; 581 /// Checks if the specified variables has data-sharing attributes which 582 /// match specified \a CPred predicate in any innermost directive which 583 /// matches \a DPred predicate. 584 const DSAVarData 585 hasInnermostDSA(ValueDecl *D, 586 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 587 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 588 bool FromParent) const; 589 /// Checks if the specified variables has explicit data-sharing 590 /// attributes which match specified \a CPred predicate at the specified 591 /// OpenMP region. 592 bool 593 hasExplicitDSA(const ValueDecl *D, 594 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 595 unsigned Level, bool NotLastprivate = false) const; 596 597 /// Returns true if the directive at level \Level matches in the 598 /// specified \a DPred predicate. 599 bool hasExplicitDirective( 600 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 601 unsigned Level) const; 602 603 /// Finds a directive which matches specified \a DPred predicate. 604 bool hasDirective( 605 const llvm::function_ref<bool( 606 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)> 607 DPred, 608 bool FromParent) const; 609 610 /// Returns currently analyzed directive. 611 OpenMPDirectiveKind getCurrentDirective() const { 612 const SharingMapTy *Top = getTopOfStackOrNull(); 613 return Top ? Top->Directive : OMPD_unknown; 614 } 615 /// Returns directive kind at specified level. 616 OpenMPDirectiveKind getDirective(unsigned Level) const { 617 assert(!isStackEmpty() && "No directive at specified level."); 618 return getStackElemAtLevel(Level).Directive; 619 } 620 /// Returns the capture region at the specified level. 621 OpenMPDirectiveKind getCaptureRegion(unsigned Level, 622 unsigned OpenMPCaptureLevel) const { 623 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 624 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level)); 625 return CaptureRegions[OpenMPCaptureLevel]; 626 } 627 /// Returns parent directive. 628 OpenMPDirectiveKind getParentDirective() const { 629 const SharingMapTy *Parent = getSecondOnStackOrNull(); 630 return Parent ? Parent->Directive : OMPD_unknown; 631 } 632 633 /// Add requires decl to internal vector 634 void addRequiresDecl(OMPRequiresDecl *RD) { RequiresDecls.push_back(RD); } 635 636 /// Checks if the defined 'requires' directive has specified type of clause. 637 template <typename ClauseType> bool hasRequiresDeclWithClause() const { 638 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) { 639 return llvm::any_of(D->clauselists(), [](const OMPClause *C) { 640 return isa<ClauseType>(C); 641 }); 642 }); 643 } 644 645 /// Checks for a duplicate clause amongst previously declared requires 646 /// directives 647 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const { 648 bool IsDuplicate = false; 649 for (OMPClause *CNew : ClauseList) { 650 for (const OMPRequiresDecl *D : RequiresDecls) { 651 for (const OMPClause *CPrev : D->clauselists()) { 652 if (CNew->getClauseKind() == CPrev->getClauseKind()) { 653 SemaRef.Diag(CNew->getBeginLoc(), 654 diag::err_omp_requires_clause_redeclaration) 655 << getOpenMPClauseName(CNew->getClauseKind()); 656 SemaRef.Diag(CPrev->getBeginLoc(), 657 diag::note_omp_requires_previous_clause) 658 << getOpenMPClauseName(CPrev->getClauseKind()); 659 IsDuplicate = true; 660 } 661 } 662 } 663 } 664 return IsDuplicate; 665 } 666 667 /// Add location of previously encountered target to internal vector 668 void addTargetDirLocation(SourceLocation LocStart) { 669 TargetLocations.push_back(LocStart); 670 } 671 672 /// Add location for the first encountered atomicc directive. 673 void addAtomicDirectiveLoc(SourceLocation Loc) { 674 if (AtomicLocation.isInvalid()) 675 AtomicLocation = Loc; 676 } 677 678 /// Returns the location of the first encountered atomic directive in the 679 /// module. 680 SourceLocation getAtomicDirectiveLoc() const { return AtomicLocation; } 681 682 // Return previously encountered target region locations. 683 ArrayRef<SourceLocation> getEncounteredTargetLocs() const { 684 return TargetLocations; 685 } 686 687 /// Set default data sharing attribute to none. 688 void setDefaultDSANone(SourceLocation Loc) { 689 getTopOfStack().DefaultAttr = DSA_none; 690 getTopOfStack().DefaultAttrLoc = Loc; 691 } 692 /// Set default data sharing attribute to shared. 693 void setDefaultDSAShared(SourceLocation Loc) { 694 getTopOfStack().DefaultAttr = DSA_shared; 695 getTopOfStack().DefaultAttrLoc = Loc; 696 } 697 /// Set default data sharing attribute to firstprivate. 698 void setDefaultDSAFirstPrivate(SourceLocation Loc) { 699 getTopOfStack().DefaultAttr = DSA_firstprivate; 700 getTopOfStack().DefaultAttrLoc = Loc; 701 } 702 /// Set default data mapping attribute to Modifier:Kind 703 void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M, 704 OpenMPDefaultmapClauseKind Kind, SourceLocation Loc) { 705 DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind]; 706 DMI.ImplicitBehavior = M; 707 DMI.SLoc = Loc; 708 } 709 /// Check whether the implicit-behavior has been set in defaultmap 710 bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) { 711 if (VariableCategory == OMPC_DEFAULTMAP_unknown) 712 return getTopOfStack() 713 .DefaultmapMap[OMPC_DEFAULTMAP_aggregate] 714 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown || 715 getTopOfStack() 716 .DefaultmapMap[OMPC_DEFAULTMAP_scalar] 717 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown || 718 getTopOfStack() 719 .DefaultmapMap[OMPC_DEFAULTMAP_pointer] 720 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown; 721 return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior != 722 OMPC_DEFAULTMAP_MODIFIER_unknown; 723 } 724 725 ArrayRef<llvm::omp::TraitProperty> getConstructTraits() { 726 return ConstructTraits; 727 } 728 void handleConstructTrait(ArrayRef<llvm::omp::TraitProperty> Traits, 729 bool ScopeEntry) { 730 if (ScopeEntry) 731 ConstructTraits.append(Traits.begin(), Traits.end()); 732 else 733 for (llvm::omp::TraitProperty Trait : llvm::reverse(Traits)) { 734 llvm::omp::TraitProperty Top = ConstructTraits.pop_back_val(); 735 assert(Top == Trait && "Something left a trait on the stack!"); 736 (void)Trait; 737 (void)Top; 738 } 739 } 740 741 DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const { 742 return getStackSize() <= Level ? DSA_unspecified 743 : getStackElemAtLevel(Level).DefaultAttr; 744 } 745 DefaultDataSharingAttributes getDefaultDSA() const { 746 return isStackEmpty() ? DSA_unspecified : getTopOfStack().DefaultAttr; 747 } 748 SourceLocation getDefaultDSALocation() const { 749 return isStackEmpty() ? SourceLocation() : getTopOfStack().DefaultAttrLoc; 750 } 751 OpenMPDefaultmapClauseModifier 752 getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const { 753 return isStackEmpty() 754 ? OMPC_DEFAULTMAP_MODIFIER_unknown 755 : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior; 756 } 757 OpenMPDefaultmapClauseModifier 758 getDefaultmapModifierAtLevel(unsigned Level, 759 OpenMPDefaultmapClauseKind Kind) const { 760 return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior; 761 } 762 bool isDefaultmapCapturedByRef(unsigned Level, 763 OpenMPDefaultmapClauseKind Kind) const { 764 OpenMPDefaultmapClauseModifier M = 765 getDefaultmapModifierAtLevel(Level, Kind); 766 if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) { 767 return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) || 768 (M == OMPC_DEFAULTMAP_MODIFIER_to) || 769 (M == OMPC_DEFAULTMAP_MODIFIER_from) || 770 (M == OMPC_DEFAULTMAP_MODIFIER_tofrom); 771 } 772 return true; 773 } 774 static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M, 775 OpenMPDefaultmapClauseKind Kind) { 776 switch (Kind) { 777 case OMPC_DEFAULTMAP_scalar: 778 case OMPC_DEFAULTMAP_pointer: 779 return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) || 780 (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) || 781 (M == OMPC_DEFAULTMAP_MODIFIER_default); 782 case OMPC_DEFAULTMAP_aggregate: 783 return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate; 784 default: 785 break; 786 } 787 llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum"); 788 } 789 bool mustBeFirstprivateAtLevel(unsigned Level, 790 OpenMPDefaultmapClauseKind Kind) const { 791 OpenMPDefaultmapClauseModifier M = 792 getDefaultmapModifierAtLevel(Level, Kind); 793 return mustBeFirstprivateBase(M, Kind); 794 } 795 bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const { 796 OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind); 797 return mustBeFirstprivateBase(M, Kind); 798 } 799 800 /// Checks if the specified variable is a threadprivate. 801 bool isThreadPrivate(VarDecl *D) { 802 const DSAVarData DVar = getTopDSA(D, false); 803 return isOpenMPThreadPrivate(DVar.CKind); 804 } 805 806 /// Marks current region as ordered (it has an 'ordered' clause). 807 void setOrderedRegion(bool IsOrdered, const Expr *Param, 808 OMPOrderedClause *Clause) { 809 if (IsOrdered) 810 getTopOfStack().OrderedRegion.emplace(Param, Clause); 811 else 812 getTopOfStack().OrderedRegion.reset(); 813 } 814 /// Returns true, if region is ordered (has associated 'ordered' clause), 815 /// false - otherwise. 816 bool isOrderedRegion() const { 817 if (const SharingMapTy *Top = getTopOfStackOrNull()) 818 return Top->OrderedRegion.hasValue(); 819 return false; 820 } 821 /// Returns optional parameter for the ordered region. 822 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const { 823 if (const SharingMapTy *Top = getTopOfStackOrNull()) 824 if (Top->OrderedRegion.hasValue()) 825 return Top->OrderedRegion.getValue(); 826 return std::make_pair(nullptr, nullptr); 827 } 828 /// Returns true, if parent region is ordered (has associated 829 /// 'ordered' clause), false - otherwise. 830 bool isParentOrderedRegion() const { 831 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 832 return Parent->OrderedRegion.hasValue(); 833 return false; 834 } 835 /// Returns optional parameter for the ordered region. 836 std::pair<const Expr *, OMPOrderedClause *> 837 getParentOrderedRegionParam() const { 838 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 839 if (Parent->OrderedRegion.hasValue()) 840 return Parent->OrderedRegion.getValue(); 841 return std::make_pair(nullptr, nullptr); 842 } 843 /// Marks current region as nowait (it has a 'nowait' clause). 844 void setNowaitRegion(bool IsNowait = true) { 845 getTopOfStack().NowaitRegion = IsNowait; 846 } 847 /// Returns true, if parent region is nowait (has associated 848 /// 'nowait' clause), false - otherwise. 849 bool isParentNowaitRegion() const { 850 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 851 return Parent->NowaitRegion; 852 return false; 853 } 854 /// Marks parent region as cancel region. 855 void setParentCancelRegion(bool Cancel = true) { 856 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 857 Parent->CancelRegion |= Cancel; 858 } 859 /// Return true if current region has inner cancel construct. 860 bool isCancelRegion() const { 861 const SharingMapTy *Top = getTopOfStackOrNull(); 862 return Top ? Top->CancelRegion : false; 863 } 864 865 /// Mark that parent region already has scan directive. 866 void setParentHasScanDirective(SourceLocation Loc) { 867 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 868 Parent->PrevScanLocation = Loc; 869 } 870 /// Return true if current region has inner cancel construct. 871 bool doesParentHasScanDirective() const { 872 const SharingMapTy *Top = getSecondOnStackOrNull(); 873 return Top ? Top->PrevScanLocation.isValid() : false; 874 } 875 /// Return true if current region has inner cancel construct. 876 SourceLocation getParentScanDirectiveLoc() const { 877 const SharingMapTy *Top = getSecondOnStackOrNull(); 878 return Top ? Top->PrevScanLocation : SourceLocation(); 879 } 880 /// Mark that parent region already has ordered directive. 881 void setParentHasOrderedDirective(SourceLocation Loc) { 882 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 883 Parent->PrevOrderedLocation = Loc; 884 } 885 /// Return true if current region has inner ordered construct. 886 bool doesParentHasOrderedDirective() const { 887 const SharingMapTy *Top = getSecondOnStackOrNull(); 888 return Top ? Top->PrevOrderedLocation.isValid() : false; 889 } 890 /// Returns the location of the previously specified ordered directive. 891 SourceLocation getParentOrderedDirectiveLoc() const { 892 const SharingMapTy *Top = getSecondOnStackOrNull(); 893 return Top ? Top->PrevOrderedLocation : SourceLocation(); 894 } 895 896 /// Set collapse value for the region. 897 void setAssociatedLoops(unsigned Val) { 898 getTopOfStack().AssociatedLoops = Val; 899 if (Val > 1) 900 getTopOfStack().HasMutipleLoops = true; 901 } 902 /// Return collapse value for region. 903 unsigned getAssociatedLoops() const { 904 const SharingMapTy *Top = getTopOfStackOrNull(); 905 return Top ? Top->AssociatedLoops : 0; 906 } 907 /// Returns true if the construct is associated with multiple loops. 908 bool hasMutipleLoops() const { 909 const SharingMapTy *Top = getTopOfStackOrNull(); 910 return Top ? Top->HasMutipleLoops : false; 911 } 912 913 /// Marks current target region as one with closely nested teams 914 /// region. 915 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 916 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 917 Parent->InnerTeamsRegionLoc = TeamsRegionLoc; 918 } 919 /// Returns true, if current region has closely nested teams region. 920 bool hasInnerTeamsRegion() const { 921 return getInnerTeamsRegionLoc().isValid(); 922 } 923 /// Returns location of the nested teams region (if any). 924 SourceLocation getInnerTeamsRegionLoc() const { 925 const SharingMapTy *Top = getTopOfStackOrNull(); 926 return Top ? Top->InnerTeamsRegionLoc : SourceLocation(); 927 } 928 929 Scope *getCurScope() const { 930 const SharingMapTy *Top = getTopOfStackOrNull(); 931 return Top ? Top->CurScope : nullptr; 932 } 933 void setContext(DeclContext *DC) { getTopOfStack().Context = DC; } 934 SourceLocation getConstructLoc() const { 935 const SharingMapTy *Top = getTopOfStackOrNull(); 936 return Top ? Top->ConstructLoc : SourceLocation(); 937 } 938 939 /// Do the check specified in \a Check to all component lists and return true 940 /// if any issue is found. 941 bool checkMappableExprComponentListsForDecl( 942 const ValueDecl *VD, bool CurrentRegionOnly, 943 const llvm::function_ref< 944 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 945 OpenMPClauseKind)> 946 Check) const { 947 if (isStackEmpty()) 948 return false; 949 auto SI = begin(); 950 auto SE = end(); 951 952 if (SI == SE) 953 return false; 954 955 if (CurrentRegionOnly) 956 SE = std::next(SI); 957 else 958 std::advance(SI, 1); 959 960 for (; SI != SE; ++SI) { 961 auto MI = SI->MappedExprComponents.find(VD); 962 if (MI != SI->MappedExprComponents.end()) 963 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 964 MI->second.Components) 965 if (Check(L, MI->second.Kind)) 966 return true; 967 } 968 return false; 969 } 970 971 /// Do the check specified in \a Check to all component lists at a given level 972 /// and return true if any issue is found. 973 bool checkMappableExprComponentListsForDeclAtLevel( 974 const ValueDecl *VD, unsigned Level, 975 const llvm::function_ref< 976 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 977 OpenMPClauseKind)> 978 Check) const { 979 if (getStackSize() <= Level) 980 return false; 981 982 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 983 auto MI = StackElem.MappedExprComponents.find(VD); 984 if (MI != StackElem.MappedExprComponents.end()) 985 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 986 MI->second.Components) 987 if (Check(L, MI->second.Kind)) 988 return true; 989 return false; 990 } 991 992 /// Create a new mappable expression component list associated with a given 993 /// declaration and initialize it with the provided list of components. 994 void addMappableExpressionComponents( 995 const ValueDecl *VD, 996 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 997 OpenMPClauseKind WhereFoundClauseKind) { 998 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD]; 999 // Create new entry and append the new components there. 1000 MEC.Components.resize(MEC.Components.size() + 1); 1001 MEC.Components.back().append(Components.begin(), Components.end()); 1002 MEC.Kind = WhereFoundClauseKind; 1003 } 1004 1005 unsigned getNestingLevel() const { 1006 assert(!isStackEmpty()); 1007 return getStackSize() - 1; 1008 } 1009 void addDoacrossDependClause(OMPDependClause *C, 1010 const OperatorOffsetTy &OpsOffs) { 1011 SharingMapTy *Parent = getSecondOnStackOrNull(); 1012 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive)); 1013 Parent->DoacrossDepends.try_emplace(C, OpsOffs); 1014 } 1015 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 1016 getDoacrossDependClauses() const { 1017 const SharingMapTy &StackElem = getTopOfStack(); 1018 if (isOpenMPWorksharingDirective(StackElem.Directive)) { 1019 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends; 1020 return llvm::make_range(Ref.begin(), Ref.end()); 1021 } 1022 return llvm::make_range(StackElem.DoacrossDepends.end(), 1023 StackElem.DoacrossDepends.end()); 1024 } 1025 1026 // Store types of classes which have been explicitly mapped 1027 void addMappedClassesQualTypes(QualType QT) { 1028 SharingMapTy &StackElem = getTopOfStack(); 1029 StackElem.MappedClassesQualTypes.insert(QT); 1030 } 1031 1032 // Return set of mapped classes types 1033 bool isClassPreviouslyMapped(QualType QT) const { 1034 const SharingMapTy &StackElem = getTopOfStack(); 1035 return StackElem.MappedClassesQualTypes.contains(QT); 1036 } 1037 1038 /// Adds global declare target to the parent target region. 1039 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) { 1040 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 1041 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && 1042 "Expected declare target link global."); 1043 for (auto &Elem : *this) { 1044 if (isOpenMPTargetExecutionDirective(Elem.Directive)) { 1045 Elem.DeclareTargetLinkVarDecls.push_back(E); 1046 return; 1047 } 1048 } 1049 } 1050 1051 /// Returns the list of globals with declare target link if current directive 1052 /// is target. 1053 ArrayRef<DeclRefExpr *> getLinkGlobals() const { 1054 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) && 1055 "Expected target executable directive."); 1056 return getTopOfStack().DeclareTargetLinkVarDecls; 1057 } 1058 1059 /// Adds list of allocators expressions. 1060 void addInnerAllocatorExpr(Expr *E) { 1061 getTopOfStack().InnerUsedAllocators.push_back(E); 1062 } 1063 /// Return list of used allocators. 1064 ArrayRef<Expr *> getInnerAllocators() const { 1065 return getTopOfStack().InnerUsedAllocators; 1066 } 1067 /// Marks the declaration as implicitly firstprivate nin the task-based 1068 /// regions. 1069 void addImplicitTaskFirstprivate(unsigned Level, Decl *D) { 1070 getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D); 1071 } 1072 /// Checks if the decl is implicitly firstprivate in the task-based region. 1073 bool isImplicitTaskFirstprivate(Decl *D) const { 1074 return getTopOfStack().ImplicitTaskFirstprivates.contains(D); 1075 } 1076 1077 /// Marks decl as used in uses_allocators clause as the allocator. 1078 void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) { 1079 getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind); 1080 } 1081 /// Checks if specified decl is used in uses allocator clause as the 1082 /// allocator. 1083 Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level, 1084 const Decl *D) const { 1085 const SharingMapTy &StackElem = getTopOfStack(); 1086 auto I = StackElem.UsesAllocatorsDecls.find(D); 1087 if (I == StackElem.UsesAllocatorsDecls.end()) 1088 return None; 1089 return I->getSecond(); 1090 } 1091 Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const { 1092 const SharingMapTy &StackElem = getTopOfStack(); 1093 auto I = StackElem.UsesAllocatorsDecls.find(D); 1094 if (I == StackElem.UsesAllocatorsDecls.end()) 1095 return None; 1096 return I->getSecond(); 1097 } 1098 1099 void addDeclareMapperVarRef(Expr *Ref) { 1100 SharingMapTy &StackElem = getTopOfStack(); 1101 StackElem.DeclareMapperVar = Ref; 1102 } 1103 const Expr *getDeclareMapperVarRef() const { 1104 const SharingMapTy *Top = getTopOfStackOrNull(); 1105 return Top ? Top->DeclareMapperVar : nullptr; 1106 } 1107 }; 1108 1109 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) { 1110 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind); 1111 } 1112 1113 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) { 1114 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || 1115 DKind == OMPD_unknown; 1116 } 1117 1118 } // namespace 1119 1120 static const Expr *getExprAsWritten(const Expr *E) { 1121 if (const auto *FE = dyn_cast<FullExpr>(E)) 1122 E = FE->getSubExpr(); 1123 1124 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 1125 E = MTE->getSubExpr(); 1126 1127 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 1128 E = Binder->getSubExpr(); 1129 1130 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 1131 E = ICE->getSubExprAsWritten(); 1132 return E->IgnoreParens(); 1133 } 1134 1135 static Expr *getExprAsWritten(Expr *E) { 1136 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E))); 1137 } 1138 1139 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) { 1140 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) 1141 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 1142 D = ME->getMemberDecl(); 1143 const auto *VD = dyn_cast<VarDecl>(D); 1144 const auto *FD = dyn_cast<FieldDecl>(D); 1145 if (VD != nullptr) { 1146 VD = VD->getCanonicalDecl(); 1147 D = VD; 1148 } else { 1149 assert(FD); 1150 FD = FD->getCanonicalDecl(); 1151 D = FD; 1152 } 1153 return D; 1154 } 1155 1156 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 1157 return const_cast<ValueDecl *>( 1158 getCanonicalDecl(const_cast<const ValueDecl *>(D))); 1159 } 1160 1161 DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter, 1162 ValueDecl *D) const { 1163 D = getCanonicalDecl(D); 1164 auto *VD = dyn_cast<VarDecl>(D); 1165 const auto *FD = dyn_cast<FieldDecl>(D); 1166 DSAVarData DVar; 1167 if (Iter == end()) { 1168 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1169 // in a region but not in construct] 1170 // File-scope or namespace-scope variables referenced in called routines 1171 // in the region are shared unless they appear in a threadprivate 1172 // directive. 1173 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD)) 1174 DVar.CKind = OMPC_shared; 1175 1176 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 1177 // in a region but not in construct] 1178 // Variables with static storage duration that are declared in called 1179 // routines in the region are shared. 1180 if (VD && VD->hasGlobalStorage()) 1181 DVar.CKind = OMPC_shared; 1182 1183 // Non-static data members are shared by default. 1184 if (FD) 1185 DVar.CKind = OMPC_shared; 1186 1187 return DVar; 1188 } 1189 1190 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1191 // in a Construct, C/C++, predetermined, p.1] 1192 // Variables with automatic storage duration that are declared in a scope 1193 // inside the construct are private. 1194 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 1195 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 1196 DVar.CKind = OMPC_private; 1197 return DVar; 1198 } 1199 1200 DVar.DKind = Iter->Directive; 1201 // Explicitly specified attributes and local variables with predetermined 1202 // attributes. 1203 if (Iter->SharingMap.count(D)) { 1204 const DSAInfo &Data = Iter->SharingMap.lookup(D); 1205 DVar.RefExpr = Data.RefExpr.getPointer(); 1206 DVar.PrivateCopy = Data.PrivateCopy; 1207 DVar.CKind = Data.Attributes; 1208 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1209 DVar.Modifier = Data.Modifier; 1210 DVar.AppliedToPointee = Data.AppliedToPointee; 1211 return DVar; 1212 } 1213 1214 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1215 // in a Construct, C/C++, implicitly determined, p.1] 1216 // In a parallel or task construct, the data-sharing attributes of these 1217 // variables are determined by the default clause, if present. 1218 switch (Iter->DefaultAttr) { 1219 case DSA_shared: 1220 DVar.CKind = OMPC_shared; 1221 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1222 return DVar; 1223 case DSA_none: 1224 return DVar; 1225 case DSA_firstprivate: 1226 if (VD->getStorageDuration() == SD_Static && 1227 VD->getDeclContext()->isFileContext()) { 1228 DVar.CKind = OMPC_unknown; 1229 } else { 1230 DVar.CKind = OMPC_firstprivate; 1231 } 1232 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1233 return DVar; 1234 case DSA_unspecified: 1235 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1236 // in a Construct, implicitly determined, p.2] 1237 // In a parallel construct, if no default clause is present, these 1238 // variables are shared. 1239 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1240 if ((isOpenMPParallelDirective(DVar.DKind) && 1241 !isOpenMPTaskLoopDirective(DVar.DKind)) || 1242 isOpenMPTeamsDirective(DVar.DKind)) { 1243 DVar.CKind = OMPC_shared; 1244 return DVar; 1245 } 1246 1247 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1248 // in a Construct, implicitly determined, p.4] 1249 // In a task construct, if no default clause is present, a variable that in 1250 // the enclosing context is determined to be shared by all implicit tasks 1251 // bound to the current team is shared. 1252 if (isOpenMPTaskingDirective(DVar.DKind)) { 1253 DSAVarData DVarTemp; 1254 const_iterator I = Iter, E = end(); 1255 do { 1256 ++I; 1257 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 1258 // Referenced in a Construct, implicitly determined, p.6] 1259 // In a task construct, if no default clause is present, a variable 1260 // whose data-sharing attribute is not determined by the rules above is 1261 // firstprivate. 1262 DVarTemp = getDSA(I, D); 1263 if (DVarTemp.CKind != OMPC_shared) { 1264 DVar.RefExpr = nullptr; 1265 DVar.CKind = OMPC_firstprivate; 1266 return DVar; 1267 } 1268 } while (I != E && !isImplicitTaskingRegion(I->Directive)); 1269 DVar.CKind = 1270 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 1271 return DVar; 1272 } 1273 } 1274 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1275 // in a Construct, implicitly determined, p.3] 1276 // For constructs other than task, if no default clause is present, these 1277 // variables inherit their data-sharing attributes from the enclosing 1278 // context. 1279 return getDSA(++Iter, D); 1280 } 1281 1282 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D, 1283 const Expr *NewDE) { 1284 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 1285 D = getCanonicalDecl(D); 1286 SharingMapTy &StackElem = getTopOfStack(); 1287 auto It = StackElem.AlignedMap.find(D); 1288 if (It == StackElem.AlignedMap.end()) { 1289 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 1290 StackElem.AlignedMap[D] = NewDE; 1291 return nullptr; 1292 } 1293 assert(It->second && "Unexpected nullptr expr in the aligned map"); 1294 return It->second; 1295 } 1296 1297 const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D, 1298 const Expr *NewDE) { 1299 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 1300 D = getCanonicalDecl(D); 1301 SharingMapTy &StackElem = getTopOfStack(); 1302 auto It = StackElem.NontemporalMap.find(D); 1303 if (It == StackElem.NontemporalMap.end()) { 1304 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 1305 StackElem.NontemporalMap[D] = NewDE; 1306 return nullptr; 1307 } 1308 assert(It->second && "Unexpected nullptr expr in the aligned map"); 1309 return It->second; 1310 } 1311 1312 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) { 1313 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1314 D = getCanonicalDecl(D); 1315 SharingMapTy &StackElem = getTopOfStack(); 1316 StackElem.LCVMap.try_emplace( 1317 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)); 1318 } 1319 1320 const DSAStackTy::LCDeclInfo 1321 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const { 1322 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1323 D = getCanonicalDecl(D); 1324 const SharingMapTy &StackElem = getTopOfStack(); 1325 auto It = StackElem.LCVMap.find(D); 1326 if (It != StackElem.LCVMap.end()) 1327 return It->second; 1328 return {0, nullptr}; 1329 } 1330 1331 const DSAStackTy::LCDeclInfo 1332 DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const { 1333 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1334 D = getCanonicalDecl(D); 1335 for (unsigned I = Level + 1; I > 0; --I) { 1336 const SharingMapTy &StackElem = getStackElemAtLevel(I - 1); 1337 auto It = StackElem.LCVMap.find(D); 1338 if (It != StackElem.LCVMap.end()) 1339 return It->second; 1340 } 1341 return {0, nullptr}; 1342 } 1343 1344 const DSAStackTy::LCDeclInfo 1345 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const { 1346 const SharingMapTy *Parent = getSecondOnStackOrNull(); 1347 assert(Parent && "Data-sharing attributes stack is empty"); 1348 D = getCanonicalDecl(D); 1349 auto It = Parent->LCVMap.find(D); 1350 if (It != Parent->LCVMap.end()) 1351 return It->second; 1352 return {0, nullptr}; 1353 } 1354 1355 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const { 1356 const SharingMapTy *Parent = getSecondOnStackOrNull(); 1357 assert(Parent && "Data-sharing attributes stack is empty"); 1358 if (Parent->LCVMap.size() < I) 1359 return nullptr; 1360 for (const auto &Pair : Parent->LCVMap) 1361 if (Pair.second.first == I) 1362 return Pair.first; 1363 return nullptr; 1364 } 1365 1366 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 1367 DeclRefExpr *PrivateCopy, unsigned Modifier, 1368 bool AppliedToPointee) { 1369 D = getCanonicalDecl(D); 1370 if (A == OMPC_threadprivate) { 1371 DSAInfo &Data = Threadprivates[D]; 1372 Data.Attributes = A; 1373 Data.RefExpr.setPointer(E); 1374 Data.PrivateCopy = nullptr; 1375 Data.Modifier = Modifier; 1376 } else { 1377 DSAInfo &Data = getTopOfStack().SharingMap[D]; 1378 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 1379 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 1380 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 1381 (isLoopControlVariable(D).first && A == OMPC_private)); 1382 Data.Modifier = Modifier; 1383 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 1384 Data.RefExpr.setInt(/*IntVal=*/true); 1385 return; 1386 } 1387 const bool IsLastprivate = 1388 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 1389 Data.Attributes = A; 1390 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 1391 Data.PrivateCopy = PrivateCopy; 1392 Data.AppliedToPointee = AppliedToPointee; 1393 if (PrivateCopy) { 1394 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()]; 1395 Data.Modifier = Modifier; 1396 Data.Attributes = A; 1397 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 1398 Data.PrivateCopy = nullptr; 1399 Data.AppliedToPointee = AppliedToPointee; 1400 } 1401 } 1402 } 1403 1404 /// Build a variable declaration for OpenMP loop iteration variable. 1405 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 1406 StringRef Name, const AttrVec *Attrs = nullptr, 1407 DeclRefExpr *OrigRef = nullptr) { 1408 DeclContext *DC = SemaRef.CurContext; 1409 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 1410 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 1411 auto *Decl = 1412 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 1413 if (Attrs) { 1414 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 1415 I != E; ++I) 1416 Decl->addAttr(*I); 1417 } 1418 Decl->setImplicit(); 1419 if (OrigRef) { 1420 Decl->addAttr( 1421 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef)); 1422 } 1423 return Decl; 1424 } 1425 1426 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 1427 SourceLocation Loc, 1428 bool RefersToCapture = false) { 1429 D->setReferenced(); 1430 D->markUsed(S.Context); 1431 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 1432 SourceLocation(), D, RefersToCapture, Loc, Ty, 1433 VK_LValue); 1434 } 1435 1436 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 1437 BinaryOperatorKind BOK) { 1438 D = getCanonicalDecl(D); 1439 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1440 assert( 1441 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && 1442 "Additional reduction info may be specified only for reduction items."); 1443 ReductionData &ReductionData = getTopOfStack().ReductionMap[D]; 1444 assert(ReductionData.ReductionRange.isInvalid() && 1445 (getTopOfStack().Directive == OMPD_taskgroup || 1446 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 1447 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 1448 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 1449 "Additional reduction info may be specified only once for reduction " 1450 "items."); 1451 ReductionData.set(BOK, SR); 1452 Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef; 1453 if (!TaskgroupReductionRef) { 1454 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1455 SemaRef.Context.VoidPtrTy, ".task_red."); 1456 TaskgroupReductionRef = 1457 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1458 } 1459 } 1460 1461 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 1462 const Expr *ReductionRef) { 1463 D = getCanonicalDecl(D); 1464 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1465 assert( 1466 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && 1467 "Additional reduction info may be specified only for reduction items."); 1468 ReductionData &ReductionData = getTopOfStack().ReductionMap[D]; 1469 assert(ReductionData.ReductionRange.isInvalid() && 1470 (getTopOfStack().Directive == OMPD_taskgroup || 1471 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 1472 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 1473 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 1474 "Additional reduction info may be specified only once for reduction " 1475 "items."); 1476 ReductionData.set(ReductionRef, SR); 1477 Expr *&TaskgroupReductionRef = getTopOfStack().TaskgroupReductionRef; 1478 if (!TaskgroupReductionRef) { 1479 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1480 SemaRef.Context.VoidPtrTy, ".task_red."); 1481 TaskgroupReductionRef = 1482 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1483 } 1484 } 1485 1486 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1487 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK, 1488 Expr *&TaskgroupDescriptor) const { 1489 D = getCanonicalDecl(D); 1490 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1491 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) { 1492 const DSAInfo &Data = I->SharingMap.lookup(D); 1493 if (Data.Attributes != OMPC_reduction || 1494 Data.Modifier != OMPC_REDUCTION_task) 1495 continue; 1496 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1497 if (!ReductionData.ReductionOp || 1498 ReductionData.ReductionOp.is<const Expr *>()) 1499 return DSAVarData(); 1500 SR = ReductionData.ReductionRange; 1501 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>(); 1502 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1503 "expression for the descriptor is not " 1504 "set."); 1505 TaskgroupDescriptor = I->TaskgroupReductionRef; 1506 return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(), 1507 Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task, 1508 /*AppliedToPointee=*/false); 1509 } 1510 return DSAVarData(); 1511 } 1512 1513 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1514 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef, 1515 Expr *&TaskgroupDescriptor) const { 1516 D = getCanonicalDecl(D); 1517 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1518 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) { 1519 const DSAInfo &Data = I->SharingMap.lookup(D); 1520 if (Data.Attributes != OMPC_reduction || 1521 Data.Modifier != OMPC_REDUCTION_task) 1522 continue; 1523 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1524 if (!ReductionData.ReductionOp || 1525 !ReductionData.ReductionOp.is<const Expr *>()) 1526 return DSAVarData(); 1527 SR = ReductionData.ReductionRange; 1528 ReductionRef = ReductionData.ReductionOp.get<const Expr *>(); 1529 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1530 "expression for the descriptor is not " 1531 "set."); 1532 TaskgroupDescriptor = I->TaskgroupReductionRef; 1533 return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(), 1534 Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task, 1535 /*AppliedToPointee=*/false); 1536 } 1537 return DSAVarData(); 1538 } 1539 1540 bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const { 1541 D = D->getCanonicalDecl(); 1542 for (const_iterator E = end(); I != E; ++I) { 1543 if (isImplicitOrExplicitTaskingRegion(I->Directive) || 1544 isOpenMPTargetExecutionDirective(I->Directive)) { 1545 if (I->CurScope) { 1546 Scope *TopScope = I->CurScope->getParent(); 1547 Scope *CurScope = getCurScope(); 1548 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D)) 1549 CurScope = CurScope->getParent(); 1550 return CurScope != TopScope; 1551 } 1552 for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent()) 1553 if (I->Context == DC) 1554 return true; 1555 return false; 1556 } 1557 } 1558 return false; 1559 } 1560 1561 static bool isConstNotMutableType(Sema &SemaRef, QualType Type, 1562 bool AcceptIfMutable = true, 1563 bool *IsClassType = nullptr) { 1564 ASTContext &Context = SemaRef.getASTContext(); 1565 Type = Type.getNonReferenceType().getCanonicalType(); 1566 bool IsConstant = Type.isConstant(Context); 1567 Type = Context.getBaseElementType(Type); 1568 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus 1569 ? Type->getAsCXXRecordDecl() 1570 : nullptr; 1571 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 1572 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate()) 1573 RD = CTD->getTemplatedDecl(); 1574 if (IsClassType) 1575 *IsClassType = RD; 1576 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD && 1577 RD->hasDefinition() && RD->hasMutableFields()); 1578 } 1579 1580 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D, 1581 QualType Type, OpenMPClauseKind CKind, 1582 SourceLocation ELoc, 1583 bool AcceptIfMutable = true, 1584 bool ListItemNotVar = false) { 1585 ASTContext &Context = SemaRef.getASTContext(); 1586 bool IsClassType; 1587 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) { 1588 unsigned Diag = ListItemNotVar ? diag::err_omp_const_list_item 1589 : IsClassType ? diag::err_omp_const_not_mutable_variable 1590 : diag::err_omp_const_variable; 1591 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind); 1592 if (!ListItemNotVar && D) { 1593 const VarDecl *VD = dyn_cast<VarDecl>(D); 1594 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 1595 VarDecl::DeclarationOnly; 1596 SemaRef.Diag(D->getLocation(), 1597 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1598 << D; 1599 } 1600 return true; 1601 } 1602 return false; 1603 } 1604 1605 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, 1606 bool FromParent) { 1607 D = getCanonicalDecl(D); 1608 DSAVarData DVar; 1609 1610 auto *VD = dyn_cast<VarDecl>(D); 1611 auto TI = Threadprivates.find(D); 1612 if (TI != Threadprivates.end()) { 1613 DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); 1614 DVar.CKind = OMPC_threadprivate; 1615 DVar.Modifier = TI->getSecond().Modifier; 1616 return DVar; 1617 } 1618 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 1619 DVar.RefExpr = buildDeclRefExpr( 1620 SemaRef, VD, D->getType().getNonReferenceType(), 1621 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation()); 1622 DVar.CKind = OMPC_threadprivate; 1623 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1624 return DVar; 1625 } 1626 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1627 // in a Construct, C/C++, predetermined, p.1] 1628 // Variables appearing in threadprivate directives are threadprivate. 1629 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 1630 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1631 SemaRef.getLangOpts().OpenMPUseTLS && 1632 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 1633 (VD && VD->getStorageClass() == SC_Register && 1634 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 1635 DVar.RefExpr = buildDeclRefExpr( 1636 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation()); 1637 DVar.CKind = OMPC_threadprivate; 1638 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1639 return DVar; 1640 } 1641 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD && 1642 VD->isLocalVarDeclOrParm() && !isStackEmpty() && 1643 !isLoopControlVariable(D).first) { 1644 const_iterator IterTarget = 1645 std::find_if(begin(), end(), [](const SharingMapTy &Data) { 1646 return isOpenMPTargetExecutionDirective(Data.Directive); 1647 }); 1648 if (IterTarget != end()) { 1649 const_iterator ParentIterTarget = IterTarget + 1; 1650 for (const_iterator Iter = begin(); Iter != ParentIterTarget; ++Iter) { 1651 if (isOpenMPLocal(VD, Iter)) { 1652 DVar.RefExpr = 1653 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1654 D->getLocation()); 1655 DVar.CKind = OMPC_threadprivate; 1656 return DVar; 1657 } 1658 } 1659 if (!isClauseParsingMode() || IterTarget != begin()) { 1660 auto DSAIter = IterTarget->SharingMap.find(D); 1661 if (DSAIter != IterTarget->SharingMap.end() && 1662 isOpenMPPrivate(DSAIter->getSecond().Attributes)) { 1663 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer(); 1664 DVar.CKind = OMPC_threadprivate; 1665 return DVar; 1666 } 1667 const_iterator End = end(); 1668 if (!SemaRef.isOpenMPCapturedByRef(D, 1669 std::distance(ParentIterTarget, End), 1670 /*OpenMPCaptureLevel=*/0)) { 1671 DVar.RefExpr = 1672 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1673 IterTarget->ConstructLoc); 1674 DVar.CKind = OMPC_threadprivate; 1675 return DVar; 1676 } 1677 } 1678 } 1679 } 1680 1681 if (isStackEmpty()) 1682 // Not in OpenMP execution region and top scope was already checked. 1683 return DVar; 1684 1685 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1686 // in a Construct, C/C++, predetermined, p.4] 1687 // Static data members are shared. 1688 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1689 // in a Construct, C/C++, predetermined, p.7] 1690 // Variables with static storage duration that are declared in a scope 1691 // inside the construct are shared. 1692 if (VD && VD->isStaticDataMember()) { 1693 // Check for explicitly specified attributes. 1694 const_iterator I = begin(); 1695 const_iterator EndI = end(); 1696 if (FromParent && I != EndI) 1697 ++I; 1698 if (I != EndI) { 1699 auto It = I->SharingMap.find(D); 1700 if (It != I->SharingMap.end()) { 1701 const DSAInfo &Data = It->getSecond(); 1702 DVar.RefExpr = Data.RefExpr.getPointer(); 1703 DVar.PrivateCopy = Data.PrivateCopy; 1704 DVar.CKind = Data.Attributes; 1705 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1706 DVar.DKind = I->Directive; 1707 DVar.Modifier = Data.Modifier; 1708 DVar.AppliedToPointee = Data.AppliedToPointee; 1709 return DVar; 1710 } 1711 } 1712 1713 DVar.CKind = OMPC_shared; 1714 return DVar; 1715 } 1716 1717 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; }; 1718 // The predetermined shared attribute for const-qualified types having no 1719 // mutable members was removed after OpenMP 3.1. 1720 if (SemaRef.LangOpts.OpenMP <= 31) { 1721 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1722 // in a Construct, C/C++, predetermined, p.6] 1723 // Variables with const qualified type having no mutable member are 1724 // shared. 1725 if (isConstNotMutableType(SemaRef, D->getType())) { 1726 // Variables with const-qualified type having no mutable member may be 1727 // listed in a firstprivate clause, even if they are static data members. 1728 DSAVarData DVarTemp = hasInnermostDSA( 1729 D, 1730 [](OpenMPClauseKind C, bool) { 1731 return C == OMPC_firstprivate || C == OMPC_shared; 1732 }, 1733 MatchesAlways, FromParent); 1734 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 1735 return DVarTemp; 1736 1737 DVar.CKind = OMPC_shared; 1738 return DVar; 1739 } 1740 } 1741 1742 // Explicitly specified attributes and local variables with predetermined 1743 // attributes. 1744 const_iterator I = begin(); 1745 const_iterator EndI = end(); 1746 if (FromParent && I != EndI) 1747 ++I; 1748 if (I == EndI) 1749 return DVar; 1750 auto It = I->SharingMap.find(D); 1751 if (It != I->SharingMap.end()) { 1752 const DSAInfo &Data = It->getSecond(); 1753 DVar.RefExpr = Data.RefExpr.getPointer(); 1754 DVar.PrivateCopy = Data.PrivateCopy; 1755 DVar.CKind = Data.Attributes; 1756 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1757 DVar.DKind = I->Directive; 1758 DVar.Modifier = Data.Modifier; 1759 DVar.AppliedToPointee = Data.AppliedToPointee; 1760 } 1761 1762 return DVar; 1763 } 1764 1765 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1766 bool FromParent) const { 1767 if (isStackEmpty()) { 1768 const_iterator I; 1769 return getDSA(I, D); 1770 } 1771 D = getCanonicalDecl(D); 1772 const_iterator StartI = begin(); 1773 const_iterator EndI = end(); 1774 if (FromParent && StartI != EndI) 1775 ++StartI; 1776 return getDSA(StartI, D); 1777 } 1778 1779 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1780 unsigned Level) const { 1781 if (getStackSize() <= Level) 1782 return DSAVarData(); 1783 D = getCanonicalDecl(D); 1784 const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level); 1785 return getDSA(StartI, D); 1786 } 1787 1788 const DSAStackTy::DSAVarData 1789 DSAStackTy::hasDSA(ValueDecl *D, 1790 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1791 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1792 bool FromParent) const { 1793 if (isStackEmpty()) 1794 return {}; 1795 D = getCanonicalDecl(D); 1796 const_iterator I = begin(); 1797 const_iterator EndI = end(); 1798 if (FromParent && I != EndI) 1799 ++I; 1800 for (; I != EndI; ++I) { 1801 if (!DPred(I->Directive) && 1802 !isImplicitOrExplicitTaskingRegion(I->Directive)) 1803 continue; 1804 const_iterator NewI = I; 1805 DSAVarData DVar = getDSA(NewI, D); 1806 if (I == NewI && CPred(DVar.CKind, DVar.AppliedToPointee)) 1807 return DVar; 1808 } 1809 return {}; 1810 } 1811 1812 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 1813 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1814 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1815 bool FromParent) const { 1816 if (isStackEmpty()) 1817 return {}; 1818 D = getCanonicalDecl(D); 1819 const_iterator StartI = begin(); 1820 const_iterator EndI = end(); 1821 if (FromParent && StartI != EndI) 1822 ++StartI; 1823 if (StartI == EndI || !DPred(StartI->Directive)) 1824 return {}; 1825 const_iterator NewI = StartI; 1826 DSAVarData DVar = getDSA(NewI, D); 1827 return (NewI == StartI && CPred(DVar.CKind, DVar.AppliedToPointee)) 1828 ? DVar 1829 : DSAVarData(); 1830 } 1831 1832 bool DSAStackTy::hasExplicitDSA( 1833 const ValueDecl *D, 1834 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1835 unsigned Level, bool NotLastprivate) const { 1836 if (getStackSize() <= Level) 1837 return false; 1838 D = getCanonicalDecl(D); 1839 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 1840 auto I = StackElem.SharingMap.find(D); 1841 if (I != StackElem.SharingMap.end() && I->getSecond().RefExpr.getPointer() && 1842 CPred(I->getSecond().Attributes, I->getSecond().AppliedToPointee) && 1843 (!NotLastprivate || !I->getSecond().RefExpr.getInt())) 1844 return true; 1845 // Check predetermined rules for the loop control variables. 1846 auto LI = StackElem.LCVMap.find(D); 1847 if (LI != StackElem.LCVMap.end()) 1848 return CPred(OMPC_private, /*AppliedToPointee=*/false); 1849 return false; 1850 } 1851 1852 bool DSAStackTy::hasExplicitDirective( 1853 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1854 unsigned Level) const { 1855 if (getStackSize() <= Level) 1856 return false; 1857 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 1858 return DPred(StackElem.Directive); 1859 } 1860 1861 bool DSAStackTy::hasDirective( 1862 const llvm::function_ref<bool(OpenMPDirectiveKind, 1863 const DeclarationNameInfo &, SourceLocation)> 1864 DPred, 1865 bool FromParent) const { 1866 // We look only in the enclosing region. 1867 size_t Skip = FromParent ? 2 : 1; 1868 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end(); 1869 I != E; ++I) { 1870 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 1871 return true; 1872 } 1873 return false; 1874 } 1875 1876 void Sema::InitDataSharingAttributesStack() { 1877 VarDataSharingAttributesStack = new DSAStackTy(*this); 1878 } 1879 1880 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 1881 1882 void Sema::pushOpenMPFunctionRegion() { DSAStack->pushFunction(); } 1883 1884 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 1885 DSAStack->popFunction(OldFSI); 1886 } 1887 1888 static bool isOpenMPDeviceDelayedContext(Sema &S) { 1889 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && 1890 "Expected OpenMP device compilation."); 1891 return !S.isInOpenMPTargetExecutionDirective(); 1892 } 1893 1894 namespace { 1895 /// Status of the function emission on the host/device. 1896 enum class FunctionEmissionStatus { 1897 Emitted, 1898 Discarded, 1899 Unknown, 1900 }; 1901 } // anonymous namespace 1902 1903 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc, 1904 unsigned DiagID, 1905 FunctionDecl *FD) { 1906 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 1907 "Expected OpenMP device compilation."); 1908 1909 SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop; 1910 if (FD) { 1911 FunctionEmissionStatus FES = getEmissionStatus(FD); 1912 switch (FES) { 1913 case FunctionEmissionStatus::Emitted: 1914 Kind = SemaDiagnosticBuilder::K_Immediate; 1915 break; 1916 case FunctionEmissionStatus::Unknown: 1917 // TODO: We should always delay diagnostics here in case a target 1918 // region is in a function we do not emit. However, as the 1919 // current diagnostics are associated with the function containing 1920 // the target region and we do not emit that one, we would miss out 1921 // on diagnostics for the target region itself. We need to anchor 1922 // the diagnostics with the new generated function *or* ensure we 1923 // emit diagnostics associated with the surrounding function. 1924 Kind = isOpenMPDeviceDelayedContext(*this) 1925 ? SemaDiagnosticBuilder::K_Deferred 1926 : SemaDiagnosticBuilder::K_Immediate; 1927 break; 1928 case FunctionEmissionStatus::TemplateDiscarded: 1929 case FunctionEmissionStatus::OMPDiscarded: 1930 Kind = SemaDiagnosticBuilder::K_Nop; 1931 break; 1932 case FunctionEmissionStatus::CUDADiscarded: 1933 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation"); 1934 break; 1935 } 1936 } 1937 1938 return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this); 1939 } 1940 1941 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc, 1942 unsigned DiagID, 1943 FunctionDecl *FD) { 1944 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice && 1945 "Expected OpenMP host compilation."); 1946 1947 SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop; 1948 if (FD) { 1949 FunctionEmissionStatus FES = getEmissionStatus(FD); 1950 switch (FES) { 1951 case FunctionEmissionStatus::Emitted: 1952 Kind = SemaDiagnosticBuilder::K_Immediate; 1953 break; 1954 case FunctionEmissionStatus::Unknown: 1955 Kind = SemaDiagnosticBuilder::K_Deferred; 1956 break; 1957 case FunctionEmissionStatus::TemplateDiscarded: 1958 case FunctionEmissionStatus::OMPDiscarded: 1959 case FunctionEmissionStatus::CUDADiscarded: 1960 Kind = SemaDiagnosticBuilder::K_Nop; 1961 break; 1962 } 1963 } 1964 1965 return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this); 1966 } 1967 1968 static OpenMPDefaultmapClauseKind 1969 getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) { 1970 if (LO.OpenMP <= 45) { 1971 if (VD->getType().getNonReferenceType()->isScalarType()) 1972 return OMPC_DEFAULTMAP_scalar; 1973 return OMPC_DEFAULTMAP_aggregate; 1974 } 1975 if (VD->getType().getNonReferenceType()->isAnyPointerType()) 1976 return OMPC_DEFAULTMAP_pointer; 1977 if (VD->getType().getNonReferenceType()->isScalarType()) 1978 return OMPC_DEFAULTMAP_scalar; 1979 return OMPC_DEFAULTMAP_aggregate; 1980 } 1981 1982 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, 1983 unsigned OpenMPCaptureLevel) const { 1984 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1985 1986 ASTContext &Ctx = getASTContext(); 1987 bool IsByRef = true; 1988 1989 // Find the directive that is associated with the provided scope. 1990 D = cast<ValueDecl>(D->getCanonicalDecl()); 1991 QualType Ty = D->getType(); 1992 1993 bool IsVariableUsedInMapClause = false; 1994 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 1995 // This table summarizes how a given variable should be passed to the device 1996 // given its type and the clauses where it appears. This table is based on 1997 // the description in OpenMP 4.5 [2.10.4, target Construct] and 1998 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 1999 // 2000 // ========================================================================= 2001 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 2002 // | |(tofrom:scalar)| | pvt | | | | 2003 // ========================================================================= 2004 // | scl | | | | - | | bycopy| 2005 // | scl | | - | x | - | - | bycopy| 2006 // | scl | | x | - | - | - | null | 2007 // | scl | x | | | - | | byref | 2008 // | scl | x | - | x | - | - | bycopy| 2009 // | scl | x | x | - | - | - | null | 2010 // | scl | | - | - | - | x | byref | 2011 // | scl | x | - | - | - | x | byref | 2012 // 2013 // | agg | n.a. | | | - | | byref | 2014 // | agg | n.a. | - | x | - | - | byref | 2015 // | agg | n.a. | x | - | - | - | null | 2016 // | agg | n.a. | - | - | - | x | byref | 2017 // | agg | n.a. | - | - | - | x[] | byref | 2018 // 2019 // | ptr | n.a. | | | - | | bycopy| 2020 // | ptr | n.a. | - | x | - | - | bycopy| 2021 // | ptr | n.a. | x | - | - | - | null | 2022 // | ptr | n.a. | - | - | - | x | byref | 2023 // | ptr | n.a. | - | - | - | x[] | bycopy| 2024 // | ptr | n.a. | - | - | x | | bycopy| 2025 // | ptr | n.a. | - | - | x | x | bycopy| 2026 // | ptr | n.a. | - | - | x | x[] | bycopy| 2027 // ========================================================================= 2028 // Legend: 2029 // scl - scalar 2030 // ptr - pointer 2031 // agg - aggregate 2032 // x - applies 2033 // - - invalid in this combination 2034 // [] - mapped with an array section 2035 // byref - should be mapped by reference 2036 // byval - should be mapped by value 2037 // null - initialize a local variable to null on the device 2038 // 2039 // Observations: 2040 // - All scalar declarations that show up in a map clause have to be passed 2041 // by reference, because they may have been mapped in the enclosing data 2042 // environment. 2043 // - If the scalar value does not fit the size of uintptr, it has to be 2044 // passed by reference, regardless the result in the table above. 2045 // - For pointers mapped by value that have either an implicit map or an 2046 // array section, the runtime library may pass the NULL value to the 2047 // device instead of the value passed to it by the compiler. 2048 2049 if (Ty->isReferenceType()) 2050 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 2051 2052 // Locate map clauses and see if the variable being captured is referred to 2053 // in any of those clauses. Here we only care about variables, not fields, 2054 // because fields are part of aggregates. 2055 bool IsVariableAssociatedWithSection = false; 2056 2057 DSAStack->checkMappableExprComponentListsForDeclAtLevel( 2058 D, Level, 2059 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, 2060 D](OMPClauseMappableExprCommon::MappableExprComponentListRef 2061 MapExprComponents, 2062 OpenMPClauseKind WhereFoundClauseKind) { 2063 // Only the map clause information influences how a variable is 2064 // captured. E.g. is_device_ptr does not require changing the default 2065 // behavior. 2066 if (WhereFoundClauseKind != OMPC_map) 2067 return false; 2068 2069 auto EI = MapExprComponents.rbegin(); 2070 auto EE = MapExprComponents.rend(); 2071 2072 assert(EI != EE && "Invalid map expression!"); 2073 2074 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 2075 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 2076 2077 ++EI; 2078 if (EI == EE) 2079 return false; 2080 2081 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 2082 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 2083 isa<MemberExpr>(EI->getAssociatedExpression()) || 2084 isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) { 2085 IsVariableAssociatedWithSection = true; 2086 // There is nothing more we need to know about this variable. 2087 return true; 2088 } 2089 2090 // Keep looking for more map info. 2091 return false; 2092 }); 2093 2094 if (IsVariableUsedInMapClause) { 2095 // If variable is identified in a map clause it is always captured by 2096 // reference except if it is a pointer that is dereferenced somehow. 2097 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 2098 } else { 2099 // By default, all the data that has a scalar type is mapped by copy 2100 // (except for reduction variables). 2101 // Defaultmap scalar is mutual exclusive to defaultmap pointer 2102 IsByRef = (DSAStack->isForceCaptureByReferenceInTargetExecutable() && 2103 !Ty->isAnyPointerType()) || 2104 !Ty->isScalarType() || 2105 DSAStack->isDefaultmapCapturedByRef( 2106 Level, getVariableCategoryFromDecl(LangOpts, D)) || 2107 DSAStack->hasExplicitDSA( 2108 D, 2109 [](OpenMPClauseKind K, bool AppliedToPointee) { 2110 return K == OMPC_reduction && !AppliedToPointee; 2111 }, 2112 Level); 2113 } 2114 } 2115 2116 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 2117 IsByRef = 2118 ((IsVariableUsedInMapClause && 2119 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) == 2120 OMPD_target) || 2121 !(DSAStack->hasExplicitDSA( 2122 D, 2123 [](OpenMPClauseKind K, bool AppliedToPointee) -> bool { 2124 return K == OMPC_firstprivate || 2125 (K == OMPC_reduction && AppliedToPointee); 2126 }, 2127 Level, /*NotLastprivate=*/true) || 2128 DSAStack->isUsesAllocatorsDecl(Level, D))) && 2129 // If the variable is artificial and must be captured by value - try to 2130 // capture by value. 2131 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() && 2132 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) && 2133 // If the variable is implicitly firstprivate and scalar - capture by 2134 // copy 2135 !(DSAStack->getDefaultDSA() == DSA_firstprivate && 2136 !DSAStack->hasExplicitDSA( 2137 D, [](OpenMPClauseKind K, bool) { return K != OMPC_unknown; }, 2138 Level) && 2139 !DSAStack->isLoopControlVariable(D, Level).first); 2140 } 2141 2142 // When passing data by copy, we need to make sure it fits the uintptr size 2143 // and alignment, because the runtime library only deals with uintptr types. 2144 // If it does not fit the uintptr size, we need to pass the data by reference 2145 // instead. 2146 if (!IsByRef && 2147 (Ctx.getTypeSizeInChars(Ty) > 2148 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 2149 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 2150 IsByRef = true; 2151 } 2152 2153 return IsByRef; 2154 } 2155 2156 unsigned Sema::getOpenMPNestingLevel() const { 2157 assert(getLangOpts().OpenMP); 2158 return DSAStack->getNestingLevel(); 2159 } 2160 2161 bool Sema::isInOpenMPTargetExecutionDirective() const { 2162 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) && 2163 !DSAStack->isClauseParsingMode()) || 2164 DSAStack->hasDirective( 2165 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 2166 SourceLocation) -> bool { 2167 return isOpenMPTargetExecutionDirective(K); 2168 }, 2169 false); 2170 } 2171 2172 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo, 2173 unsigned StopAt) { 2174 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2175 D = getCanonicalDecl(D); 2176 2177 auto *VD = dyn_cast<VarDecl>(D); 2178 // Do not capture constexpr variables. 2179 if (VD && VD->isConstexpr()) 2180 return nullptr; 2181 2182 // If we want to determine whether the variable should be captured from the 2183 // perspective of the current capturing scope, and we've already left all the 2184 // capturing scopes of the top directive on the stack, check from the 2185 // perspective of its parent directive (if any) instead. 2186 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII( 2187 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete()); 2188 2189 // If we are attempting to capture a global variable in a directive with 2190 // 'target' we return true so that this global is also mapped to the device. 2191 // 2192 if (VD && !VD->hasLocalStorage() && 2193 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) { 2194 if (isInOpenMPTargetExecutionDirective()) { 2195 DSAStackTy::DSAVarData DVarTop = 2196 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 2197 if (DVarTop.CKind != OMPC_unknown && DVarTop.RefExpr) 2198 return VD; 2199 // If the declaration is enclosed in a 'declare target' directive, 2200 // then it should not be captured. 2201 // 2202 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 2203 return nullptr; 2204 CapturedRegionScopeInfo *CSI = nullptr; 2205 for (FunctionScopeInfo *FSI : llvm::drop_begin( 2206 llvm::reverse(FunctionScopes), 2207 CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) { 2208 if (!isa<CapturingScopeInfo>(FSI)) 2209 return nullptr; 2210 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI)) 2211 if (RSI->CapRegionKind == CR_OpenMP) { 2212 CSI = RSI; 2213 break; 2214 } 2215 } 2216 assert(CSI && "Failed to find CapturedRegionScopeInfo"); 2217 SmallVector<OpenMPDirectiveKind, 4> Regions; 2218 getOpenMPCaptureRegions(Regions, 2219 DSAStack->getDirective(CSI->OpenMPLevel)); 2220 if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task) 2221 return VD; 2222 } 2223 if (isInOpenMPDeclareTargetContext()) { 2224 // Try to mark variable as declare target if it is used in capturing 2225 // regions. 2226 if (LangOpts.OpenMP <= 45 && 2227 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 2228 checkDeclIsAllowedInOpenMPTarget(nullptr, VD); 2229 return nullptr; 2230 } 2231 } 2232 2233 if (CheckScopeInfo) { 2234 bool OpenMPFound = false; 2235 for (unsigned I = StopAt + 1; I > 0; --I) { 2236 FunctionScopeInfo *FSI = FunctionScopes[I - 1]; 2237 if (!isa<CapturingScopeInfo>(FSI)) 2238 return nullptr; 2239 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI)) 2240 if (RSI->CapRegionKind == CR_OpenMP) { 2241 OpenMPFound = true; 2242 break; 2243 } 2244 } 2245 if (!OpenMPFound) 2246 return nullptr; 2247 } 2248 2249 if (DSAStack->getCurrentDirective() != OMPD_unknown && 2250 (!DSAStack->isClauseParsingMode() || 2251 DSAStack->getParentDirective() != OMPD_unknown)) { 2252 auto &&Info = DSAStack->isLoopControlVariable(D); 2253 if (Info.first || 2254 (VD && VD->hasLocalStorage() && 2255 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) || 2256 (VD && DSAStack->isForceVarCapturing())) 2257 return VD ? VD : Info.second; 2258 DSAStackTy::DSAVarData DVarTop = 2259 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 2260 if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) && 2261 (!VD || VD->hasLocalStorage() || !DVarTop.AppliedToPointee)) 2262 return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl()); 2263 // Threadprivate variables must not be captured. 2264 if (isOpenMPThreadPrivate(DVarTop.CKind)) 2265 return nullptr; 2266 // The variable is not private or it is the variable in the directive with 2267 // default(none) clause and not used in any clause. 2268 DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA( 2269 D, 2270 [](OpenMPClauseKind C, bool AppliedToPointee) { 2271 return isOpenMPPrivate(C) && !AppliedToPointee; 2272 }, 2273 [](OpenMPDirectiveKind) { return true; }, 2274 DSAStack->isClauseParsingMode()); 2275 // Global shared must not be captured. 2276 if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown && 2277 ((DSAStack->getDefaultDSA() != DSA_none && 2278 DSAStack->getDefaultDSA() != DSA_firstprivate) || 2279 DVarTop.CKind == OMPC_shared)) 2280 return nullptr; 2281 if (DVarPrivate.CKind != OMPC_unknown || 2282 (VD && (DSAStack->getDefaultDSA() == DSA_none || 2283 DSAStack->getDefaultDSA() == DSA_firstprivate))) 2284 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 2285 } 2286 return nullptr; 2287 } 2288 2289 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 2290 unsigned Level) const { 2291 FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 2292 } 2293 2294 void Sema::startOpenMPLoop() { 2295 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 2296 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) 2297 DSAStack->loopInit(); 2298 } 2299 2300 void Sema::startOpenMPCXXRangeFor() { 2301 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 2302 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 2303 DSAStack->resetPossibleLoopCounter(); 2304 DSAStack->loopStart(); 2305 } 2306 } 2307 2308 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, 2309 unsigned CapLevel) const { 2310 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2311 if (DSAStack->hasExplicitDirective(isOpenMPTaskingDirective, Level)) { 2312 bool IsTriviallyCopyable = 2313 D->getType().getNonReferenceType().isTriviallyCopyableType(Context) && 2314 !D->getType() 2315 .getNonReferenceType() 2316 .getCanonicalType() 2317 ->getAsCXXRecordDecl(); 2318 OpenMPDirectiveKind DKind = DSAStack->getDirective(Level); 2319 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2320 getOpenMPCaptureRegions(CaptureRegions, DKind); 2321 if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) && 2322 (IsTriviallyCopyable || 2323 !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) { 2324 if (DSAStack->hasExplicitDSA( 2325 D, 2326 [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; }, 2327 Level, /*NotLastprivate=*/true)) 2328 return OMPC_firstprivate; 2329 DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level); 2330 if (DVar.CKind != OMPC_shared && 2331 !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) { 2332 DSAStack->addImplicitTaskFirstprivate(Level, D); 2333 return OMPC_firstprivate; 2334 } 2335 } 2336 } 2337 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 2338 if (DSAStack->getAssociatedLoops() > 0 && !DSAStack->isLoopStarted()) { 2339 DSAStack->resetPossibleLoopCounter(D); 2340 DSAStack->loopStart(); 2341 return OMPC_private; 2342 } 2343 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() || 2344 DSAStack->isLoopControlVariable(D).first) && 2345 !DSAStack->hasExplicitDSA( 2346 D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; }, 2347 Level) && 2348 !isOpenMPSimdDirective(DSAStack->getCurrentDirective())) 2349 return OMPC_private; 2350 } 2351 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2352 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) && 2353 DSAStack->isForceVarCapturing() && 2354 !DSAStack->hasExplicitDSA( 2355 D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; }, 2356 Level)) 2357 return OMPC_private; 2358 } 2359 // User-defined allocators are private since they must be defined in the 2360 // context of target region. 2361 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) && 2362 DSAStack->isUsesAllocatorsDecl(Level, D).getValueOr( 2363 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) == 2364 DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator) 2365 return OMPC_private; 2366 return (DSAStack->hasExplicitDSA( 2367 D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; }, 2368 Level) || 2369 (DSAStack->isClauseParsingMode() && 2370 DSAStack->getClauseParsingMode() == OMPC_private) || 2371 // Consider taskgroup reduction descriptor variable a private 2372 // to avoid possible capture in the region. 2373 (DSAStack->hasExplicitDirective( 2374 [](OpenMPDirectiveKind K) { 2375 return K == OMPD_taskgroup || 2376 ((isOpenMPParallelDirective(K) || 2377 isOpenMPWorksharingDirective(K)) && 2378 !isOpenMPSimdDirective(K)); 2379 }, 2380 Level) && 2381 DSAStack->isTaskgroupReductionRef(D, Level))) 2382 ? OMPC_private 2383 : OMPC_unknown; 2384 } 2385 2386 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, 2387 unsigned Level) { 2388 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2389 D = getCanonicalDecl(D); 2390 OpenMPClauseKind OMPC = OMPC_unknown; 2391 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) { 2392 const unsigned NewLevel = I - 1; 2393 if (DSAStack->hasExplicitDSA( 2394 D, 2395 [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) { 2396 if (isOpenMPPrivate(K) && !AppliedToPointee) { 2397 OMPC = K; 2398 return true; 2399 } 2400 return false; 2401 }, 2402 NewLevel)) 2403 break; 2404 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel( 2405 D, NewLevel, 2406 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 2407 OpenMPClauseKind) { return true; })) { 2408 OMPC = OMPC_map; 2409 break; 2410 } 2411 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 2412 NewLevel)) { 2413 OMPC = OMPC_map; 2414 if (DSAStack->mustBeFirstprivateAtLevel( 2415 NewLevel, getVariableCategoryFromDecl(LangOpts, D))) 2416 OMPC = OMPC_firstprivate; 2417 break; 2418 } 2419 } 2420 if (OMPC != OMPC_unknown) 2421 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC))); 2422 } 2423 2424 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, 2425 unsigned CaptureLevel) const { 2426 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2427 // Return true if the current level is no longer enclosed in a target region. 2428 2429 SmallVector<OpenMPDirectiveKind, 4> Regions; 2430 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level)); 2431 const auto *VD = dyn_cast<VarDecl>(D); 2432 return VD && !VD->hasLocalStorage() && 2433 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 2434 Level) && 2435 Regions[CaptureLevel] != OMPD_task; 2436 } 2437 2438 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, 2439 unsigned CaptureLevel) const { 2440 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2441 // Return true if the current level is no longer enclosed in a target region. 2442 2443 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2444 if (!VD->hasLocalStorage()) { 2445 if (isInOpenMPTargetExecutionDirective()) 2446 return true; 2447 DSAStackTy::DSAVarData TopDVar = 2448 DSAStack->getTopDSA(D, /*FromParent=*/false); 2449 unsigned NumLevels = 2450 getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 2451 if (Level == 0) 2452 return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared; 2453 do { 2454 --Level; 2455 DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level); 2456 if (DVar.CKind != OMPC_shared) 2457 return true; 2458 } while (Level > 0); 2459 } 2460 } 2461 return true; 2462 } 2463 2464 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 2465 2466 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, 2467 OMPTraitInfo &TI) { 2468 OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI)); 2469 } 2470 2471 void Sema::ActOnOpenMPEndDeclareVariant() { 2472 assert(isInOpenMPDeclareVariantScope() && 2473 "Not in OpenMP declare variant scope!"); 2474 2475 OMPDeclareVariantScopes.pop_back(); 2476 } 2477 2478 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, 2479 const FunctionDecl *Callee, 2480 SourceLocation Loc) { 2481 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode."); 2482 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 2483 OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl()); 2484 // Ignore host functions during device analyzis. 2485 if (LangOpts.OpenMPIsDevice && 2486 (!DevTy || *DevTy == OMPDeclareTargetDeclAttr::DT_Host)) 2487 return; 2488 // Ignore nohost functions during host analyzis. 2489 if (!LangOpts.OpenMPIsDevice && DevTy && 2490 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 2491 return; 2492 const FunctionDecl *FD = Callee->getMostRecentDecl(); 2493 DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD); 2494 if (LangOpts.OpenMPIsDevice && DevTy && 2495 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) { 2496 // Diagnose host function called during device codegen. 2497 StringRef HostDevTy = 2498 getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host); 2499 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0; 2500 Diag(*OMPDeclareTargetDeclAttr::getLocation(FD), 2501 diag::note_omp_marked_device_type_here) 2502 << HostDevTy; 2503 return; 2504 } 2505 if (!LangOpts.OpenMPIsDevice && DevTy && 2506 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 2507 // Diagnose nohost function called during host codegen. 2508 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName( 2509 OMPC_device_type, OMPC_DEVICE_TYPE_nohost); 2510 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1; 2511 Diag(*OMPDeclareTargetDeclAttr::getLocation(FD), 2512 diag::note_omp_marked_device_type_here) 2513 << NoHostDevTy; 2514 } 2515 } 2516 2517 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 2518 const DeclarationNameInfo &DirName, 2519 Scope *CurScope, SourceLocation Loc) { 2520 DSAStack->push(DKind, DirName, CurScope, Loc); 2521 PushExpressionEvaluationContext( 2522 ExpressionEvaluationContext::PotentiallyEvaluated); 2523 } 2524 2525 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 2526 DSAStack->setClauseParsingMode(K); 2527 } 2528 2529 void Sema::EndOpenMPClause() { 2530 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 2531 CleanupVarDeclMarking(); 2532 } 2533 2534 static std::pair<ValueDecl *, bool> 2535 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 2536 SourceRange &ERange, bool AllowArraySection = false); 2537 2538 /// Check consistency of the reduction clauses. 2539 static void checkReductionClauses(Sema &S, DSAStackTy *Stack, 2540 ArrayRef<OMPClause *> Clauses) { 2541 bool InscanFound = false; 2542 SourceLocation InscanLoc; 2543 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions. 2544 // A reduction clause without the inscan reduction-modifier may not appear on 2545 // a construct on which a reduction clause with the inscan reduction-modifier 2546 // appears. 2547 for (OMPClause *C : Clauses) { 2548 if (C->getClauseKind() != OMPC_reduction) 2549 continue; 2550 auto *RC = cast<OMPReductionClause>(C); 2551 if (RC->getModifier() == OMPC_REDUCTION_inscan) { 2552 InscanFound = true; 2553 InscanLoc = RC->getModifierLoc(); 2554 continue; 2555 } 2556 if (RC->getModifier() == OMPC_REDUCTION_task) { 2557 // OpenMP 5.0, 2.19.5.4 reduction Clause. 2558 // A reduction clause with the task reduction-modifier may only appear on 2559 // a parallel construct, a worksharing construct or a combined or 2560 // composite construct for which any of the aforementioned constructs is a 2561 // constituent construct and simd or loop are not constituent constructs. 2562 OpenMPDirectiveKind CurDir = Stack->getCurrentDirective(); 2563 if (!(isOpenMPParallelDirective(CurDir) || 2564 isOpenMPWorksharingDirective(CurDir)) || 2565 isOpenMPSimdDirective(CurDir)) 2566 S.Diag(RC->getModifierLoc(), 2567 diag::err_omp_reduction_task_not_parallel_or_worksharing); 2568 continue; 2569 } 2570 } 2571 if (InscanFound) { 2572 for (OMPClause *C : Clauses) { 2573 if (C->getClauseKind() != OMPC_reduction) 2574 continue; 2575 auto *RC = cast<OMPReductionClause>(C); 2576 if (RC->getModifier() != OMPC_REDUCTION_inscan) { 2577 S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown 2578 ? RC->getBeginLoc() 2579 : RC->getModifierLoc(), 2580 diag::err_omp_inscan_reduction_expected); 2581 S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction); 2582 continue; 2583 } 2584 for (Expr *Ref : RC->varlists()) { 2585 assert(Ref && "NULL expr in OpenMP nontemporal clause."); 2586 SourceLocation ELoc; 2587 SourceRange ERange; 2588 Expr *SimpleRefExpr = Ref; 2589 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 2590 /*AllowArraySection=*/true); 2591 ValueDecl *D = Res.first; 2592 if (!D) 2593 continue; 2594 if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) { 2595 S.Diag(Ref->getExprLoc(), 2596 diag::err_omp_reduction_not_inclusive_exclusive) 2597 << Ref->getSourceRange(); 2598 } 2599 } 2600 } 2601 } 2602 } 2603 2604 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack, 2605 ArrayRef<OMPClause *> Clauses); 2606 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 2607 bool WithInit); 2608 2609 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 2610 const ValueDecl *D, 2611 const DSAStackTy::DSAVarData &DVar, 2612 bool IsLoopIterVar = false); 2613 2614 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 2615 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 2616 // A variable of class type (or array thereof) that appears in a lastprivate 2617 // clause requires an accessible, unambiguous default constructor for the 2618 // class type, unless the list item is also specified in a firstprivate 2619 // clause. 2620 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 2621 for (OMPClause *C : D->clauses()) { 2622 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 2623 SmallVector<Expr *, 8> PrivateCopies; 2624 for (Expr *DE : Clause->varlists()) { 2625 if (DE->isValueDependent() || DE->isTypeDependent()) { 2626 PrivateCopies.push_back(nullptr); 2627 continue; 2628 } 2629 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 2630 auto *VD = cast<VarDecl>(DRE->getDecl()); 2631 QualType Type = VD->getType().getNonReferenceType(); 2632 const DSAStackTy::DSAVarData DVar = 2633 DSAStack->getTopDSA(VD, /*FromParent=*/false); 2634 if (DVar.CKind == OMPC_lastprivate) { 2635 // Generate helper private variable and initialize it with the 2636 // default value. The address of the original variable is replaced 2637 // by the address of the new private variable in CodeGen. This new 2638 // variable is not added to IdResolver, so the code in the OpenMP 2639 // region uses original variable for proper diagnostics. 2640 VarDecl *VDPrivate = buildVarDecl( 2641 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 2642 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE); 2643 ActOnUninitializedDecl(VDPrivate); 2644 if (VDPrivate->isInvalidDecl()) { 2645 PrivateCopies.push_back(nullptr); 2646 continue; 2647 } 2648 PrivateCopies.push_back(buildDeclRefExpr( 2649 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 2650 } else { 2651 // The variable is also a firstprivate, so initialization sequence 2652 // for private copy is generated already. 2653 PrivateCopies.push_back(nullptr); 2654 } 2655 } 2656 Clause->setPrivateCopies(PrivateCopies); 2657 continue; 2658 } 2659 // Finalize nontemporal clause by handling private copies, if any. 2660 if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) { 2661 SmallVector<Expr *, 8> PrivateRefs; 2662 for (Expr *RefExpr : Clause->varlists()) { 2663 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 2664 SourceLocation ELoc; 2665 SourceRange ERange; 2666 Expr *SimpleRefExpr = RefExpr; 2667 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 2668 if (Res.second) 2669 // It will be analyzed later. 2670 PrivateRefs.push_back(RefExpr); 2671 ValueDecl *D = Res.first; 2672 if (!D) 2673 continue; 2674 2675 const DSAStackTy::DSAVarData DVar = 2676 DSAStack->getTopDSA(D, /*FromParent=*/false); 2677 PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy 2678 : SimpleRefExpr); 2679 } 2680 Clause->setPrivateRefs(PrivateRefs); 2681 continue; 2682 } 2683 if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) { 2684 for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) { 2685 OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I); 2686 auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts()); 2687 if (!DRE) 2688 continue; 2689 ValueDecl *VD = DRE->getDecl(); 2690 if (!VD || !isa<VarDecl>(VD)) 2691 continue; 2692 DSAStackTy::DSAVarData DVar = 2693 DSAStack->getTopDSA(VD, /*FromParent=*/false); 2694 // OpenMP [2.12.5, target Construct] 2695 // Memory allocators that appear in a uses_allocators clause cannot 2696 // appear in other data-sharing attribute clauses or data-mapping 2697 // attribute clauses in the same construct. 2698 Expr *MapExpr = nullptr; 2699 if (DVar.RefExpr || 2700 DSAStack->checkMappableExprComponentListsForDecl( 2701 VD, /*CurrentRegionOnly=*/true, 2702 [VD, &MapExpr]( 2703 OMPClauseMappableExprCommon::MappableExprComponentListRef 2704 MapExprComponents, 2705 OpenMPClauseKind C) { 2706 auto MI = MapExprComponents.rbegin(); 2707 auto ME = MapExprComponents.rend(); 2708 if (MI != ME && 2709 MI->getAssociatedDeclaration()->getCanonicalDecl() == 2710 VD->getCanonicalDecl()) { 2711 MapExpr = MI->getAssociatedExpression(); 2712 return true; 2713 } 2714 return false; 2715 })) { 2716 Diag(D.Allocator->getExprLoc(), 2717 diag::err_omp_allocator_used_in_clauses) 2718 << D.Allocator->getSourceRange(); 2719 if (DVar.RefExpr) 2720 reportOriginalDsa(*this, DSAStack, VD, DVar); 2721 else 2722 Diag(MapExpr->getExprLoc(), diag::note_used_here) 2723 << MapExpr->getSourceRange(); 2724 } 2725 } 2726 continue; 2727 } 2728 } 2729 // Check allocate clauses. 2730 if (!CurContext->isDependentContext()) 2731 checkAllocateClauses(*this, DSAStack, D->clauses()); 2732 checkReductionClauses(*this, DSAStack, D->clauses()); 2733 } 2734 2735 DSAStack->pop(); 2736 DiscardCleanupsInEvaluationContext(); 2737 PopExpressionEvaluationContext(); 2738 } 2739 2740 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 2741 Expr *NumIterations, Sema &SemaRef, 2742 Scope *S, DSAStackTy *Stack); 2743 2744 namespace { 2745 2746 class VarDeclFilterCCC final : public CorrectionCandidateCallback { 2747 private: 2748 Sema &SemaRef; 2749 2750 public: 2751 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 2752 bool ValidateCandidate(const TypoCorrection &Candidate) override { 2753 NamedDecl *ND = Candidate.getCorrectionDecl(); 2754 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 2755 return VD->hasGlobalStorage() && 2756 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 2757 SemaRef.getCurScope()); 2758 } 2759 return false; 2760 } 2761 2762 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2763 return std::make_unique<VarDeclFilterCCC>(*this); 2764 } 2765 }; 2766 2767 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback { 2768 private: 2769 Sema &SemaRef; 2770 2771 public: 2772 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 2773 bool ValidateCandidate(const TypoCorrection &Candidate) override { 2774 NamedDecl *ND = Candidate.getCorrectionDecl(); 2775 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) || 2776 isa<FunctionDecl>(ND))) { 2777 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 2778 SemaRef.getCurScope()); 2779 } 2780 return false; 2781 } 2782 2783 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2784 return std::make_unique<VarOrFuncDeclFilterCCC>(*this); 2785 } 2786 }; 2787 2788 } // namespace 2789 2790 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 2791 CXXScopeSpec &ScopeSpec, 2792 const DeclarationNameInfo &Id, 2793 OpenMPDirectiveKind Kind) { 2794 LookupResult Lookup(*this, Id, LookupOrdinaryName); 2795 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 2796 2797 if (Lookup.isAmbiguous()) 2798 return ExprError(); 2799 2800 VarDecl *VD; 2801 if (!Lookup.isSingleResult()) { 2802 VarDeclFilterCCC CCC(*this); 2803 if (TypoCorrection Corrected = 2804 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC, 2805 CTK_ErrorRecovery)) { 2806 diagnoseTypo(Corrected, 2807 PDiag(Lookup.empty() 2808 ? diag::err_undeclared_var_use_suggest 2809 : diag::err_omp_expected_var_arg_suggest) 2810 << Id.getName()); 2811 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 2812 } else { 2813 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 2814 : diag::err_omp_expected_var_arg) 2815 << Id.getName(); 2816 return ExprError(); 2817 } 2818 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) { 2819 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 2820 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 2821 return ExprError(); 2822 } 2823 Lookup.suppressDiagnostics(); 2824 2825 // OpenMP [2.9.2, Syntax, C/C++] 2826 // Variables must be file-scope, namespace-scope, or static block-scope. 2827 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) { 2828 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 2829 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal(); 2830 bool IsDecl = 2831 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2832 Diag(VD->getLocation(), 2833 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2834 << VD; 2835 return ExprError(); 2836 } 2837 2838 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 2839 NamedDecl *ND = CanonicalVD; 2840 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 2841 // A threadprivate directive for file-scope variables must appear outside 2842 // any definition or declaration. 2843 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 2844 !getCurLexicalContext()->isTranslationUnit()) { 2845 Diag(Id.getLoc(), diag::err_omp_var_scope) 2846 << getOpenMPDirectiveName(Kind) << VD; 2847 bool IsDecl = 2848 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2849 Diag(VD->getLocation(), 2850 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2851 << VD; 2852 return ExprError(); 2853 } 2854 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 2855 // A threadprivate directive for static class member variables must appear 2856 // in the class definition, in the same scope in which the member 2857 // variables are declared. 2858 if (CanonicalVD->isStaticDataMember() && 2859 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 2860 Diag(Id.getLoc(), diag::err_omp_var_scope) 2861 << getOpenMPDirectiveName(Kind) << VD; 2862 bool IsDecl = 2863 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2864 Diag(VD->getLocation(), 2865 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2866 << VD; 2867 return ExprError(); 2868 } 2869 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 2870 // A threadprivate directive for namespace-scope variables must appear 2871 // outside any definition or declaration other than the namespace 2872 // definition itself. 2873 if (CanonicalVD->getDeclContext()->isNamespace() && 2874 (!getCurLexicalContext()->isFileContext() || 2875 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 2876 Diag(Id.getLoc(), diag::err_omp_var_scope) 2877 << getOpenMPDirectiveName(Kind) << VD; 2878 bool IsDecl = 2879 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2880 Diag(VD->getLocation(), 2881 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2882 << VD; 2883 return ExprError(); 2884 } 2885 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 2886 // A threadprivate directive for static block-scope variables must appear 2887 // in the scope of the variable and not in a nested scope. 2888 if (CanonicalVD->isLocalVarDecl() && CurScope && 2889 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 2890 Diag(Id.getLoc(), diag::err_omp_var_scope) 2891 << getOpenMPDirectiveName(Kind) << VD; 2892 bool IsDecl = 2893 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2894 Diag(VD->getLocation(), 2895 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2896 << VD; 2897 return ExprError(); 2898 } 2899 2900 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 2901 // A threadprivate directive must lexically precede all references to any 2902 // of the variables in its list. 2903 if (Kind == OMPD_threadprivate && VD->isUsed() && 2904 !DSAStack->isThreadPrivate(VD)) { 2905 Diag(Id.getLoc(), diag::err_omp_var_used) 2906 << getOpenMPDirectiveName(Kind) << VD; 2907 return ExprError(); 2908 } 2909 2910 QualType ExprType = VD->getType().getNonReferenceType(); 2911 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 2912 SourceLocation(), VD, 2913 /*RefersToEnclosingVariableOrCapture=*/false, 2914 Id.getLoc(), ExprType, VK_LValue); 2915 } 2916 2917 Sema::DeclGroupPtrTy 2918 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 2919 ArrayRef<Expr *> VarList) { 2920 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 2921 CurContext->addDecl(D); 2922 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2923 } 2924 return nullptr; 2925 } 2926 2927 namespace { 2928 class LocalVarRefChecker final 2929 : public ConstStmtVisitor<LocalVarRefChecker, bool> { 2930 Sema &SemaRef; 2931 2932 public: 2933 bool VisitDeclRefExpr(const DeclRefExpr *E) { 2934 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 2935 if (VD->hasLocalStorage()) { 2936 SemaRef.Diag(E->getBeginLoc(), 2937 diag::err_omp_local_var_in_threadprivate_init) 2938 << E->getSourceRange(); 2939 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 2940 << VD << VD->getSourceRange(); 2941 return true; 2942 } 2943 } 2944 return false; 2945 } 2946 bool VisitStmt(const Stmt *S) { 2947 for (const Stmt *Child : S->children()) { 2948 if (Child && Visit(Child)) 2949 return true; 2950 } 2951 return false; 2952 } 2953 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 2954 }; 2955 } // namespace 2956 2957 OMPThreadPrivateDecl * 2958 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 2959 SmallVector<Expr *, 8> Vars; 2960 for (Expr *RefExpr : VarList) { 2961 auto *DE = cast<DeclRefExpr>(RefExpr); 2962 auto *VD = cast<VarDecl>(DE->getDecl()); 2963 SourceLocation ILoc = DE->getExprLoc(); 2964 2965 // Mark variable as used. 2966 VD->setReferenced(); 2967 VD->markUsed(Context); 2968 2969 QualType QType = VD->getType(); 2970 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 2971 // It will be analyzed later. 2972 Vars.push_back(DE); 2973 continue; 2974 } 2975 2976 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2977 // A threadprivate variable must not have an incomplete type. 2978 if (RequireCompleteType(ILoc, VD->getType(), 2979 diag::err_omp_threadprivate_incomplete_type)) { 2980 continue; 2981 } 2982 2983 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2984 // A threadprivate variable must not have a reference type. 2985 if (VD->getType()->isReferenceType()) { 2986 Diag(ILoc, diag::err_omp_ref_type_arg) 2987 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 2988 bool IsDecl = 2989 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2990 Diag(VD->getLocation(), 2991 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2992 << VD; 2993 continue; 2994 } 2995 2996 // Check if this is a TLS variable. If TLS is not being supported, produce 2997 // the corresponding diagnostic. 2998 if ((VD->getTLSKind() != VarDecl::TLS_None && 2999 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 3000 getLangOpts().OpenMPUseTLS && 3001 getASTContext().getTargetInfo().isTLSSupported())) || 3002 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 3003 !VD->isLocalVarDecl())) { 3004 Diag(ILoc, diag::err_omp_var_thread_local) 3005 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 3006 bool IsDecl = 3007 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 3008 Diag(VD->getLocation(), 3009 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 3010 << VD; 3011 continue; 3012 } 3013 3014 // Check if initial value of threadprivate variable reference variable with 3015 // local storage (it is not supported by runtime). 3016 if (const Expr *Init = VD->getAnyInitializer()) { 3017 LocalVarRefChecker Checker(*this); 3018 if (Checker.Visit(Init)) 3019 continue; 3020 } 3021 3022 Vars.push_back(RefExpr); 3023 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 3024 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 3025 Context, SourceRange(Loc, Loc))); 3026 if (ASTMutationListener *ML = Context.getASTMutationListener()) 3027 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 3028 } 3029 OMPThreadPrivateDecl *D = nullptr; 3030 if (!Vars.empty()) { 3031 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 3032 Vars); 3033 D->setAccess(AS_public); 3034 } 3035 return D; 3036 } 3037 3038 static OMPAllocateDeclAttr::AllocatorTypeTy 3039 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) { 3040 if (!Allocator) 3041 return OMPAllocateDeclAttr::OMPNullMemAlloc; 3042 if (Allocator->isTypeDependent() || Allocator->isValueDependent() || 3043 Allocator->isInstantiationDependent() || 3044 Allocator->containsUnexpandedParameterPack()) 3045 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; 3046 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; 3047 const Expr *AE = Allocator->IgnoreParenImpCasts(); 3048 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 3049 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 3050 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind); 3051 llvm::FoldingSetNodeID AEId, DAEId; 3052 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true); 3053 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true); 3054 if (AEId == DAEId) { 3055 AllocatorKindRes = AllocatorKind; 3056 break; 3057 } 3058 } 3059 return AllocatorKindRes; 3060 } 3061 3062 static bool checkPreviousOMPAllocateAttribute( 3063 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD, 3064 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) { 3065 if (!VD->hasAttr<OMPAllocateDeclAttr>()) 3066 return false; 3067 const auto *A = VD->getAttr<OMPAllocateDeclAttr>(); 3068 Expr *PrevAllocator = A->getAllocator(); 3069 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind = 3070 getAllocatorKind(S, Stack, PrevAllocator); 3071 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind; 3072 if (AllocatorsMatch && 3073 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc && 3074 Allocator && PrevAllocator) { 3075 const Expr *AE = Allocator->IgnoreParenImpCasts(); 3076 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts(); 3077 llvm::FoldingSetNodeID AEId, PAEId; 3078 AE->Profile(AEId, S.Context, /*Canonical=*/true); 3079 PAE->Profile(PAEId, S.Context, /*Canonical=*/true); 3080 AllocatorsMatch = AEId == PAEId; 3081 } 3082 if (!AllocatorsMatch) { 3083 SmallString<256> AllocatorBuffer; 3084 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer); 3085 if (Allocator) 3086 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy()); 3087 SmallString<256> PrevAllocatorBuffer; 3088 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer); 3089 if (PrevAllocator) 3090 PrevAllocator->printPretty(PrevAllocatorStream, nullptr, 3091 S.getPrintingPolicy()); 3092 3093 SourceLocation AllocatorLoc = 3094 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc(); 3095 SourceRange AllocatorRange = 3096 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange(); 3097 SourceLocation PrevAllocatorLoc = 3098 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation(); 3099 SourceRange PrevAllocatorRange = 3100 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange(); 3101 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator) 3102 << (Allocator ? 1 : 0) << AllocatorStream.str() 3103 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str() 3104 << AllocatorRange; 3105 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator) 3106 << PrevAllocatorRange; 3107 return true; 3108 } 3109 return false; 3110 } 3111 3112 static void 3113 applyOMPAllocateAttribute(Sema &S, VarDecl *VD, 3114 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, 3115 Expr *Allocator, Expr *Alignment, SourceRange SR) { 3116 if (VD->hasAttr<OMPAllocateDeclAttr>()) 3117 return; 3118 if (Alignment && 3119 (Alignment->isTypeDependent() || Alignment->isValueDependent() || 3120 Alignment->isInstantiationDependent() || 3121 Alignment->containsUnexpandedParameterPack())) 3122 // Apply later when we have a usable value. 3123 return; 3124 if (Allocator && 3125 (Allocator->isTypeDependent() || Allocator->isValueDependent() || 3126 Allocator->isInstantiationDependent() || 3127 Allocator->containsUnexpandedParameterPack())) 3128 return; 3129 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind, 3130 Allocator, Alignment, SR); 3131 VD->addAttr(A); 3132 if (ASTMutationListener *ML = S.Context.getASTMutationListener()) 3133 ML->DeclarationMarkedOpenMPAllocate(VD, A); 3134 } 3135 3136 Sema::DeclGroupPtrTy 3137 Sema::ActOnOpenMPAllocateDirective(SourceLocation Loc, ArrayRef<Expr *> VarList, 3138 ArrayRef<OMPClause *> Clauses, 3139 DeclContext *Owner) { 3140 assert(Clauses.size() <= 2 && "Expected at most two clauses."); 3141 Expr *Alignment = nullptr; 3142 Expr *Allocator = nullptr; 3143 if (Clauses.empty()) { 3144 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions. 3145 // allocate directives that appear in a target region must specify an 3146 // allocator clause unless a requires directive with the dynamic_allocators 3147 // clause is present in the same compilation unit. 3148 if (LangOpts.OpenMPIsDevice && 3149 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>()) 3150 targetDiag(Loc, diag::err_expected_allocator_clause); 3151 } else { 3152 for (const OMPClause *C : Clauses) 3153 if (const auto *AC = dyn_cast<OMPAllocatorClause>(C)) 3154 Allocator = AC->getAllocator(); 3155 else if (const auto *AC = dyn_cast<OMPAlignClause>(C)) 3156 Alignment = AC->getAlignment(); 3157 else 3158 llvm_unreachable("Unexpected clause on allocate directive"); 3159 } 3160 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind = 3161 getAllocatorKind(*this, DSAStack, Allocator); 3162 SmallVector<Expr *, 8> Vars; 3163 for (Expr *RefExpr : VarList) { 3164 auto *DE = cast<DeclRefExpr>(RefExpr); 3165 auto *VD = cast<VarDecl>(DE->getDecl()); 3166 3167 // Check if this is a TLS variable or global register. 3168 if (VD->getTLSKind() != VarDecl::TLS_None || 3169 VD->hasAttr<OMPThreadPrivateDeclAttr>() || 3170 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 3171 !VD->isLocalVarDecl())) 3172 continue; 3173 3174 // If the used several times in the allocate directive, the same allocator 3175 // must be used. 3176 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD, 3177 AllocatorKind, Allocator)) 3178 continue; 3179 3180 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++ 3181 // If a list item has a static storage type, the allocator expression in the 3182 // allocator clause must be a constant expression that evaluates to one of 3183 // the predefined memory allocator values. 3184 if (Allocator && VD->hasGlobalStorage()) { 3185 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) { 3186 Diag(Allocator->getExprLoc(), 3187 diag::err_omp_expected_predefined_allocator) 3188 << Allocator->getSourceRange(); 3189 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 3190 VarDecl::DeclarationOnly; 3191 Diag(VD->getLocation(), 3192 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 3193 << VD; 3194 continue; 3195 } 3196 } 3197 3198 Vars.push_back(RefExpr); 3199 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator, Alignment, 3200 DE->getSourceRange()); 3201 } 3202 if (Vars.empty()) 3203 return nullptr; 3204 if (!Owner) 3205 Owner = getCurLexicalContext(); 3206 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses); 3207 D->setAccess(AS_public); 3208 Owner->addDecl(D); 3209 return DeclGroupPtrTy::make(DeclGroupRef(D)); 3210 } 3211 3212 Sema::DeclGroupPtrTy 3213 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc, 3214 ArrayRef<OMPClause *> ClauseList) { 3215 OMPRequiresDecl *D = nullptr; 3216 if (!CurContext->isFileContext()) { 3217 Diag(Loc, diag::err_omp_invalid_scope) << "requires"; 3218 } else { 3219 D = CheckOMPRequiresDecl(Loc, ClauseList); 3220 if (D) { 3221 CurContext->addDecl(D); 3222 DSAStack->addRequiresDecl(D); 3223 } 3224 } 3225 return DeclGroupPtrTy::make(DeclGroupRef(D)); 3226 } 3227 3228 void Sema::ActOnOpenMPAssumesDirective(SourceLocation Loc, 3229 OpenMPDirectiveKind DKind, 3230 ArrayRef<std::string> Assumptions, 3231 bool SkippedClauses) { 3232 if (!SkippedClauses && Assumptions.empty()) 3233 Diag(Loc, diag::err_omp_no_clause_for_directive) 3234 << llvm::omp::getAllAssumeClauseOptions() 3235 << llvm::omp::getOpenMPDirectiveName(DKind); 3236 3237 auto *AA = AssumptionAttr::Create(Context, llvm::join(Assumptions, ","), Loc); 3238 if (DKind == llvm::omp::Directive::OMPD_begin_assumes) { 3239 OMPAssumeScoped.push_back(AA); 3240 return; 3241 } 3242 3243 // Global assumes without assumption clauses are ignored. 3244 if (Assumptions.empty()) 3245 return; 3246 3247 assert(DKind == llvm::omp::Directive::OMPD_assumes && 3248 "Unexpected omp assumption directive!"); 3249 OMPAssumeGlobal.push_back(AA); 3250 3251 // The OMPAssumeGlobal scope above will take care of new declarations but 3252 // we also want to apply the assumption to existing ones, e.g., to 3253 // declarations in included headers. To this end, we traverse all existing 3254 // declaration contexts and annotate function declarations here. 3255 SmallVector<DeclContext *, 8> DeclContexts; 3256 auto *Ctx = CurContext; 3257 while (Ctx->getLexicalParent()) 3258 Ctx = Ctx->getLexicalParent(); 3259 DeclContexts.push_back(Ctx); 3260 while (!DeclContexts.empty()) { 3261 DeclContext *DC = DeclContexts.pop_back_val(); 3262 for (auto *SubDC : DC->decls()) { 3263 if (SubDC->isInvalidDecl()) 3264 continue; 3265 if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) { 3266 DeclContexts.push_back(CTD->getTemplatedDecl()); 3267 for (auto *S : CTD->specializations()) 3268 DeclContexts.push_back(S); 3269 continue; 3270 } 3271 if (auto *DC = dyn_cast<DeclContext>(SubDC)) 3272 DeclContexts.push_back(DC); 3273 if (auto *F = dyn_cast<FunctionDecl>(SubDC)) { 3274 F->addAttr(AA); 3275 continue; 3276 } 3277 } 3278 } 3279 } 3280 3281 void Sema::ActOnOpenMPEndAssumesDirective() { 3282 assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!"); 3283 OMPAssumeScoped.pop_back(); 3284 } 3285 3286 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc, 3287 ArrayRef<OMPClause *> ClauseList) { 3288 /// For target specific clauses, the requires directive cannot be 3289 /// specified after the handling of any of the target regions in the 3290 /// current compilation unit. 3291 ArrayRef<SourceLocation> TargetLocations = 3292 DSAStack->getEncounteredTargetLocs(); 3293 SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc(); 3294 if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) { 3295 for (const OMPClause *CNew : ClauseList) { 3296 // Check if any of the requires clauses affect target regions. 3297 if (isa<OMPUnifiedSharedMemoryClause>(CNew) || 3298 isa<OMPUnifiedAddressClause>(CNew) || 3299 isa<OMPReverseOffloadClause>(CNew) || 3300 isa<OMPDynamicAllocatorsClause>(CNew)) { 3301 Diag(Loc, diag::err_omp_directive_before_requires) 3302 << "target" << getOpenMPClauseName(CNew->getClauseKind()); 3303 for (SourceLocation TargetLoc : TargetLocations) { 3304 Diag(TargetLoc, diag::note_omp_requires_encountered_directive) 3305 << "target"; 3306 } 3307 } else if (!AtomicLoc.isInvalid() && 3308 isa<OMPAtomicDefaultMemOrderClause>(CNew)) { 3309 Diag(Loc, diag::err_omp_directive_before_requires) 3310 << "atomic" << getOpenMPClauseName(CNew->getClauseKind()); 3311 Diag(AtomicLoc, diag::note_omp_requires_encountered_directive) 3312 << "atomic"; 3313 } 3314 } 3315 } 3316 3317 if (!DSAStack->hasDuplicateRequiresClause(ClauseList)) 3318 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc, 3319 ClauseList); 3320 return nullptr; 3321 } 3322 3323 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 3324 const ValueDecl *D, 3325 const DSAStackTy::DSAVarData &DVar, 3326 bool IsLoopIterVar) { 3327 if (DVar.RefExpr) { 3328 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 3329 << getOpenMPClauseName(DVar.CKind); 3330 return; 3331 } 3332 enum { 3333 PDSA_StaticMemberShared, 3334 PDSA_StaticLocalVarShared, 3335 PDSA_LoopIterVarPrivate, 3336 PDSA_LoopIterVarLinear, 3337 PDSA_LoopIterVarLastprivate, 3338 PDSA_ConstVarShared, 3339 PDSA_GlobalVarShared, 3340 PDSA_TaskVarFirstprivate, 3341 PDSA_LocalVarPrivate, 3342 PDSA_Implicit 3343 } Reason = PDSA_Implicit; 3344 bool ReportHint = false; 3345 auto ReportLoc = D->getLocation(); 3346 auto *VD = dyn_cast<VarDecl>(D); 3347 if (IsLoopIterVar) { 3348 if (DVar.CKind == OMPC_private) 3349 Reason = PDSA_LoopIterVarPrivate; 3350 else if (DVar.CKind == OMPC_lastprivate) 3351 Reason = PDSA_LoopIterVarLastprivate; 3352 else 3353 Reason = PDSA_LoopIterVarLinear; 3354 } else if (isOpenMPTaskingDirective(DVar.DKind) && 3355 DVar.CKind == OMPC_firstprivate) { 3356 Reason = PDSA_TaskVarFirstprivate; 3357 ReportLoc = DVar.ImplicitDSALoc; 3358 } else if (VD && VD->isStaticLocal()) 3359 Reason = PDSA_StaticLocalVarShared; 3360 else if (VD && VD->isStaticDataMember()) 3361 Reason = PDSA_StaticMemberShared; 3362 else if (VD && VD->isFileVarDecl()) 3363 Reason = PDSA_GlobalVarShared; 3364 else if (D->getType().isConstant(SemaRef.getASTContext())) 3365 Reason = PDSA_ConstVarShared; 3366 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 3367 ReportHint = true; 3368 Reason = PDSA_LocalVarPrivate; 3369 } 3370 if (Reason != PDSA_Implicit) { 3371 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 3372 << Reason << ReportHint 3373 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 3374 } else if (DVar.ImplicitDSALoc.isValid()) { 3375 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 3376 << getOpenMPClauseName(DVar.CKind); 3377 } 3378 } 3379 3380 static OpenMPMapClauseKind 3381 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M, 3382 bool IsAggregateOrDeclareTarget) { 3383 OpenMPMapClauseKind Kind = OMPC_MAP_unknown; 3384 switch (M) { 3385 case OMPC_DEFAULTMAP_MODIFIER_alloc: 3386 Kind = OMPC_MAP_alloc; 3387 break; 3388 case OMPC_DEFAULTMAP_MODIFIER_to: 3389 Kind = OMPC_MAP_to; 3390 break; 3391 case OMPC_DEFAULTMAP_MODIFIER_from: 3392 Kind = OMPC_MAP_from; 3393 break; 3394 case OMPC_DEFAULTMAP_MODIFIER_tofrom: 3395 Kind = OMPC_MAP_tofrom; 3396 break; 3397 case OMPC_DEFAULTMAP_MODIFIER_present: 3398 // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description] 3399 // If implicit-behavior is present, each variable referenced in the 3400 // construct in the category specified by variable-category is treated as if 3401 // it had been listed in a map clause with the map-type of alloc and 3402 // map-type-modifier of present. 3403 Kind = OMPC_MAP_alloc; 3404 break; 3405 case OMPC_DEFAULTMAP_MODIFIER_firstprivate: 3406 case OMPC_DEFAULTMAP_MODIFIER_last: 3407 llvm_unreachable("Unexpected defaultmap implicit behavior"); 3408 case OMPC_DEFAULTMAP_MODIFIER_none: 3409 case OMPC_DEFAULTMAP_MODIFIER_default: 3410 case OMPC_DEFAULTMAP_MODIFIER_unknown: 3411 // IsAggregateOrDeclareTarget could be true if: 3412 // 1. the implicit behavior for aggregate is tofrom 3413 // 2. it's a declare target link 3414 if (IsAggregateOrDeclareTarget) { 3415 Kind = OMPC_MAP_tofrom; 3416 break; 3417 } 3418 llvm_unreachable("Unexpected defaultmap implicit behavior"); 3419 } 3420 assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known"); 3421 return Kind; 3422 } 3423 3424 namespace { 3425 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> { 3426 DSAStackTy *Stack; 3427 Sema &SemaRef; 3428 bool ErrorFound = false; 3429 bool TryCaptureCXXThisMembers = false; 3430 CapturedStmt *CS = nullptr; 3431 const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1; 3432 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate; 3433 llvm::SmallVector<Expr *, 4> ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete]; 3434 llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> 3435 ImplicitMapModifier[DefaultmapKindNum]; 3436 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA; 3437 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations; 3438 3439 void VisitSubCaptures(OMPExecutableDirective *S) { 3440 // Check implicitly captured variables. 3441 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt()) 3442 return; 3443 if (S->getDirectiveKind() == OMPD_atomic || 3444 S->getDirectiveKind() == OMPD_critical || 3445 S->getDirectiveKind() == OMPD_section || 3446 S->getDirectiveKind() == OMPD_master || 3447 S->getDirectiveKind() == OMPD_masked || 3448 isOpenMPLoopTransformationDirective(S->getDirectiveKind())) { 3449 Visit(S->getAssociatedStmt()); 3450 return; 3451 } 3452 visitSubCaptures(S->getInnermostCapturedStmt()); 3453 // Try to capture inner this->member references to generate correct mappings 3454 // and diagnostics. 3455 if (TryCaptureCXXThisMembers || 3456 (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 3457 llvm::any_of(S->getInnermostCapturedStmt()->captures(), 3458 [](const CapturedStmt::Capture &C) { 3459 return C.capturesThis(); 3460 }))) { 3461 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers; 3462 TryCaptureCXXThisMembers = true; 3463 Visit(S->getInnermostCapturedStmt()->getCapturedStmt()); 3464 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers; 3465 } 3466 // In tasks firstprivates are not captured anymore, need to analyze them 3467 // explicitly. 3468 if (isOpenMPTaskingDirective(S->getDirectiveKind()) && 3469 !isOpenMPTaskLoopDirective(S->getDirectiveKind())) { 3470 for (OMPClause *C : S->clauses()) 3471 if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) { 3472 for (Expr *Ref : FC->varlists()) 3473 Visit(Ref); 3474 } 3475 } 3476 } 3477 3478 public: 3479 void VisitDeclRefExpr(DeclRefExpr *E) { 3480 if (TryCaptureCXXThisMembers || E->isTypeDependent() || 3481 E->isValueDependent() || E->containsUnexpandedParameterPack() || 3482 E->isInstantiationDependent()) 3483 return; 3484 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 3485 // Check the datasharing rules for the expressions in the clauses. 3486 if (!CS || (isa<OMPCapturedExprDecl>(VD) && !CS->capturesVariable(VD) && 3487 !Stack->getTopDSA(VD, /*FromParent=*/false).RefExpr)) { 3488 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD)) 3489 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) { 3490 Visit(CED->getInit()); 3491 return; 3492 } 3493 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD)) 3494 // Do not analyze internal variables and do not enclose them into 3495 // implicit clauses. 3496 return; 3497 VD = VD->getCanonicalDecl(); 3498 // Skip internally declared variables. 3499 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) && 3500 !Stack->isImplicitTaskFirstprivate(VD)) 3501 return; 3502 // Skip allocators in uses_allocators clauses. 3503 if (Stack->isUsesAllocatorsDecl(VD).hasValue()) 3504 return; 3505 3506 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 3507 // Check if the variable has explicit DSA set and stop analysis if it so. 3508 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second) 3509 return; 3510 3511 // Skip internally declared static variables. 3512 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 3513 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 3514 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) && 3515 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || 3516 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) && 3517 !Stack->isImplicitTaskFirstprivate(VD)) 3518 return; 3519 3520 SourceLocation ELoc = E->getExprLoc(); 3521 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 3522 // The default(none) clause requires that each variable that is referenced 3523 // in the construct, and does not have a predetermined data-sharing 3524 // attribute, must have its data-sharing attribute explicitly determined 3525 // by being listed in a data-sharing attribute clause. 3526 if (DVar.CKind == OMPC_unknown && 3527 (Stack->getDefaultDSA() == DSA_none || 3528 Stack->getDefaultDSA() == DSA_firstprivate) && 3529 isImplicitOrExplicitTaskingRegion(DKind) && 3530 VarsWithInheritedDSA.count(VD) == 0) { 3531 bool InheritedDSA = Stack->getDefaultDSA() == DSA_none; 3532 if (!InheritedDSA && Stack->getDefaultDSA() == DSA_firstprivate) { 3533 DSAStackTy::DSAVarData DVar = 3534 Stack->getImplicitDSA(VD, /*FromParent=*/false); 3535 InheritedDSA = DVar.CKind == OMPC_unknown; 3536 } 3537 if (InheritedDSA) 3538 VarsWithInheritedDSA[VD] = E; 3539 return; 3540 } 3541 3542 // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description] 3543 // If implicit-behavior is none, each variable referenced in the 3544 // construct that does not have a predetermined data-sharing attribute 3545 // and does not appear in a to or link clause on a declare target 3546 // directive must be listed in a data-mapping attribute clause, a 3547 // data-haring attribute clause (including a data-sharing attribute 3548 // clause on a combined construct where target. is one of the 3549 // constituent constructs), or an is_device_ptr clause. 3550 OpenMPDefaultmapClauseKind ClauseKind = 3551 getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD); 3552 if (SemaRef.getLangOpts().OpenMP >= 50) { 3553 bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) == 3554 OMPC_DEFAULTMAP_MODIFIER_none; 3555 if (DVar.CKind == OMPC_unknown && IsModifierNone && 3556 VarsWithInheritedDSA.count(VD) == 0 && !Res) { 3557 // Only check for data-mapping attribute and is_device_ptr here 3558 // since we have already make sure that the declaration does not 3559 // have a data-sharing attribute above 3560 if (!Stack->checkMappableExprComponentListsForDecl( 3561 VD, /*CurrentRegionOnly=*/true, 3562 [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef 3563 MapExprComponents, 3564 OpenMPClauseKind) { 3565 auto MI = MapExprComponents.rbegin(); 3566 auto ME = MapExprComponents.rend(); 3567 return MI != ME && MI->getAssociatedDeclaration() == VD; 3568 })) { 3569 VarsWithInheritedDSA[VD] = E; 3570 return; 3571 } 3572 } 3573 } 3574 if (SemaRef.getLangOpts().OpenMP > 50) { 3575 bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) == 3576 OMPC_DEFAULTMAP_MODIFIER_present; 3577 if (IsModifierPresent) { 3578 if (llvm::find(ImplicitMapModifier[ClauseKind], 3579 OMPC_MAP_MODIFIER_present) == 3580 std::end(ImplicitMapModifier[ClauseKind])) { 3581 ImplicitMapModifier[ClauseKind].push_back( 3582 OMPC_MAP_MODIFIER_present); 3583 } 3584 } 3585 } 3586 3587 if (isOpenMPTargetExecutionDirective(DKind) && 3588 !Stack->isLoopControlVariable(VD).first) { 3589 if (!Stack->checkMappableExprComponentListsForDecl( 3590 VD, /*CurrentRegionOnly=*/true, 3591 [this](OMPClauseMappableExprCommon::MappableExprComponentListRef 3592 StackComponents, 3593 OpenMPClauseKind) { 3594 if (SemaRef.LangOpts.OpenMP >= 50) 3595 return !StackComponents.empty(); 3596 // Variable is used if it has been marked as an array, array 3597 // section, array shaping or the variable iself. 3598 return StackComponents.size() == 1 || 3599 std::all_of( 3600 std::next(StackComponents.rbegin()), 3601 StackComponents.rend(), 3602 [](const OMPClauseMappableExprCommon:: 3603 MappableComponent &MC) { 3604 return MC.getAssociatedDeclaration() == 3605 nullptr && 3606 (isa<OMPArraySectionExpr>( 3607 MC.getAssociatedExpression()) || 3608 isa<OMPArrayShapingExpr>( 3609 MC.getAssociatedExpression()) || 3610 isa<ArraySubscriptExpr>( 3611 MC.getAssociatedExpression())); 3612 }); 3613 })) { 3614 bool IsFirstprivate = false; 3615 // By default lambdas are captured as firstprivates. 3616 if (const auto *RD = 3617 VD->getType().getNonReferenceType()->getAsCXXRecordDecl()) 3618 IsFirstprivate = RD->isLambda(); 3619 IsFirstprivate = 3620 IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res); 3621 if (IsFirstprivate) { 3622 ImplicitFirstprivate.emplace_back(E); 3623 } else { 3624 OpenMPDefaultmapClauseModifier M = 3625 Stack->getDefaultmapModifier(ClauseKind); 3626 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier( 3627 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res); 3628 ImplicitMap[ClauseKind][Kind].emplace_back(E); 3629 } 3630 return; 3631 } 3632 } 3633 3634 // OpenMP [2.9.3.6, Restrictions, p.2] 3635 // A list item that appears in a reduction clause of the innermost 3636 // enclosing worksharing or parallel construct may not be accessed in an 3637 // explicit task. 3638 DVar = Stack->hasInnermostDSA( 3639 VD, 3640 [](OpenMPClauseKind C, bool AppliedToPointee) { 3641 return C == OMPC_reduction && !AppliedToPointee; 3642 }, 3643 [](OpenMPDirectiveKind K) { 3644 return isOpenMPParallelDirective(K) || 3645 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 3646 }, 3647 /*FromParent=*/true); 3648 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 3649 ErrorFound = true; 3650 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 3651 reportOriginalDsa(SemaRef, Stack, VD, DVar); 3652 return; 3653 } 3654 3655 // Define implicit data-sharing attributes for task. 3656 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false); 3657 if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) || 3658 (Stack->getDefaultDSA() == DSA_firstprivate && 3659 DVar.CKind == OMPC_firstprivate && !DVar.RefExpr)) && 3660 !Stack->isLoopControlVariable(VD).first) { 3661 ImplicitFirstprivate.push_back(E); 3662 return; 3663 } 3664 3665 // Store implicitly used globals with declare target link for parent 3666 // target. 3667 if (!isOpenMPTargetExecutionDirective(DKind) && Res && 3668 *Res == OMPDeclareTargetDeclAttr::MT_Link) { 3669 Stack->addToParentTargetRegionLinkGlobals(E); 3670 return; 3671 } 3672 } 3673 } 3674 void VisitMemberExpr(MemberExpr *E) { 3675 if (E->isTypeDependent() || E->isValueDependent() || 3676 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 3677 return; 3678 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 3679 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 3680 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) { 3681 if (!FD) 3682 return; 3683 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false); 3684 // Check if the variable has explicit DSA set and stop analysis if it 3685 // so. 3686 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second) 3687 return; 3688 3689 if (isOpenMPTargetExecutionDirective(DKind) && 3690 !Stack->isLoopControlVariable(FD).first && 3691 !Stack->checkMappableExprComponentListsForDecl( 3692 FD, /*CurrentRegionOnly=*/true, 3693 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 3694 StackComponents, 3695 OpenMPClauseKind) { 3696 return isa<CXXThisExpr>( 3697 cast<MemberExpr>( 3698 StackComponents.back().getAssociatedExpression()) 3699 ->getBase() 3700 ->IgnoreParens()); 3701 })) { 3702 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 3703 // A bit-field cannot appear in a map clause. 3704 // 3705 if (FD->isBitField()) 3706 return; 3707 3708 // Check to see if the member expression is referencing a class that 3709 // has already been explicitly mapped 3710 if (Stack->isClassPreviouslyMapped(TE->getType())) 3711 return; 3712 3713 OpenMPDefaultmapClauseModifier Modifier = 3714 Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate); 3715 OpenMPDefaultmapClauseKind ClauseKind = 3716 getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD); 3717 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier( 3718 Modifier, /*IsAggregateOrDeclareTarget*/ true); 3719 ImplicitMap[ClauseKind][Kind].emplace_back(E); 3720 return; 3721 } 3722 3723 SourceLocation ELoc = E->getExprLoc(); 3724 // OpenMP [2.9.3.6, Restrictions, p.2] 3725 // A list item that appears in a reduction clause of the innermost 3726 // enclosing worksharing or parallel construct may not be accessed in 3727 // an explicit task. 3728 DVar = Stack->hasInnermostDSA( 3729 FD, 3730 [](OpenMPClauseKind C, bool AppliedToPointee) { 3731 return C == OMPC_reduction && !AppliedToPointee; 3732 }, 3733 [](OpenMPDirectiveKind K) { 3734 return isOpenMPParallelDirective(K) || 3735 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 3736 }, 3737 /*FromParent=*/true); 3738 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 3739 ErrorFound = true; 3740 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 3741 reportOriginalDsa(SemaRef, Stack, FD, DVar); 3742 return; 3743 } 3744 3745 // Define implicit data-sharing attributes for task. 3746 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false); 3747 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 3748 !Stack->isLoopControlVariable(FD).first) { 3749 // Check if there is a captured expression for the current field in the 3750 // region. Do not mark it as firstprivate unless there is no captured 3751 // expression. 3752 // TODO: try to make it firstprivate. 3753 if (DVar.CKind != OMPC_unknown) 3754 ImplicitFirstprivate.push_back(E); 3755 } 3756 return; 3757 } 3758 if (isOpenMPTargetExecutionDirective(DKind)) { 3759 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 3760 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map, 3761 Stack->getCurrentDirective(), 3762 /*NoDiagnose=*/true)) 3763 return; 3764 const auto *VD = cast<ValueDecl>( 3765 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl()); 3766 if (!Stack->checkMappableExprComponentListsForDecl( 3767 VD, /*CurrentRegionOnly=*/true, 3768 [&CurComponents]( 3769 OMPClauseMappableExprCommon::MappableExprComponentListRef 3770 StackComponents, 3771 OpenMPClauseKind) { 3772 auto CCI = CurComponents.rbegin(); 3773 auto CCE = CurComponents.rend(); 3774 for (const auto &SC : llvm::reverse(StackComponents)) { 3775 // Do both expressions have the same kind? 3776 if (CCI->getAssociatedExpression()->getStmtClass() != 3777 SC.getAssociatedExpression()->getStmtClass()) 3778 if (!((isa<OMPArraySectionExpr>( 3779 SC.getAssociatedExpression()) || 3780 isa<OMPArrayShapingExpr>( 3781 SC.getAssociatedExpression())) && 3782 isa<ArraySubscriptExpr>( 3783 CCI->getAssociatedExpression()))) 3784 return false; 3785 3786 const Decl *CCD = CCI->getAssociatedDeclaration(); 3787 const Decl *SCD = SC.getAssociatedDeclaration(); 3788 CCD = CCD ? CCD->getCanonicalDecl() : nullptr; 3789 SCD = SCD ? SCD->getCanonicalDecl() : nullptr; 3790 if (SCD != CCD) 3791 return false; 3792 std::advance(CCI, 1); 3793 if (CCI == CCE) 3794 break; 3795 } 3796 return true; 3797 })) { 3798 Visit(E->getBase()); 3799 } 3800 } else if (!TryCaptureCXXThisMembers) { 3801 Visit(E->getBase()); 3802 } 3803 } 3804 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 3805 for (OMPClause *C : S->clauses()) { 3806 // Skip analysis of arguments of private clauses for task|target 3807 // directives. 3808 if (isa_and_nonnull<OMPPrivateClause>(C)) 3809 continue; 3810 // Skip analysis of arguments of implicitly defined firstprivate clause 3811 // for task|target directives. 3812 // Skip analysis of arguments of implicitly defined map clause for target 3813 // directives. 3814 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) && 3815 C->isImplicit() && 3816 !isOpenMPTaskingDirective(Stack->getCurrentDirective()))) { 3817 for (Stmt *CC : C->children()) { 3818 if (CC) 3819 Visit(CC); 3820 } 3821 } 3822 } 3823 // Check implicitly captured variables. 3824 VisitSubCaptures(S); 3825 } 3826 3827 void VisitOMPLoopTransformationDirective(OMPLoopTransformationDirective *S) { 3828 // Loop transformation directives do not introduce data sharing 3829 VisitStmt(S); 3830 } 3831 3832 void VisitCallExpr(CallExpr *S) { 3833 for (Stmt *C : S->arguments()) { 3834 if (C) { 3835 // Check implicitly captured variables in the task-based directives to 3836 // check if they must be firstprivatized. 3837 Visit(C); 3838 } 3839 } 3840 if (Expr *Callee = S->getCallee()) 3841 if (auto *CE = dyn_cast<MemberExpr>(Callee->IgnoreParenImpCasts())) 3842 Visit(CE->getBase()); 3843 } 3844 void VisitStmt(Stmt *S) { 3845 for (Stmt *C : S->children()) { 3846 if (C) { 3847 // Check implicitly captured variables in the task-based directives to 3848 // check if they must be firstprivatized. 3849 Visit(C); 3850 } 3851 } 3852 } 3853 3854 void visitSubCaptures(CapturedStmt *S) { 3855 for (const CapturedStmt::Capture &Cap : S->captures()) { 3856 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy()) 3857 continue; 3858 VarDecl *VD = Cap.getCapturedVar(); 3859 // Do not try to map the variable if it or its sub-component was mapped 3860 // already. 3861 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 3862 Stack->checkMappableExprComponentListsForDecl( 3863 VD, /*CurrentRegionOnly=*/true, 3864 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 3865 OpenMPClauseKind) { return true; })) 3866 continue; 3867 DeclRefExpr *DRE = buildDeclRefExpr( 3868 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context), 3869 Cap.getLocation(), /*RefersToCapture=*/true); 3870 Visit(DRE); 3871 } 3872 } 3873 bool isErrorFound() const { return ErrorFound; } 3874 ArrayRef<Expr *> getImplicitFirstprivate() const { 3875 return ImplicitFirstprivate; 3876 } 3877 ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind DK, 3878 OpenMPMapClauseKind MK) const { 3879 return ImplicitMap[DK][MK]; 3880 } 3881 ArrayRef<OpenMPMapModifierKind> 3882 getImplicitMapModifier(OpenMPDefaultmapClauseKind Kind) const { 3883 return ImplicitMapModifier[Kind]; 3884 } 3885 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const { 3886 return VarsWithInheritedDSA; 3887 } 3888 3889 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 3890 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) { 3891 // Process declare target link variables for the target directives. 3892 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) { 3893 for (DeclRefExpr *E : Stack->getLinkGlobals()) 3894 Visit(E); 3895 } 3896 } 3897 }; 3898 } // namespace 3899 3900 static void handleDeclareVariantConstructTrait(DSAStackTy *Stack, 3901 OpenMPDirectiveKind DKind, 3902 bool ScopeEntry) { 3903 SmallVector<llvm::omp::TraitProperty, 8> Traits; 3904 if (isOpenMPTargetExecutionDirective(DKind)) 3905 Traits.emplace_back(llvm::omp::TraitProperty::construct_target_target); 3906 if (isOpenMPTeamsDirective(DKind)) 3907 Traits.emplace_back(llvm::omp::TraitProperty::construct_teams_teams); 3908 if (isOpenMPParallelDirective(DKind)) 3909 Traits.emplace_back(llvm::omp::TraitProperty::construct_parallel_parallel); 3910 if (isOpenMPWorksharingDirective(DKind)) 3911 Traits.emplace_back(llvm::omp::TraitProperty::construct_for_for); 3912 if (isOpenMPSimdDirective(DKind)) 3913 Traits.emplace_back(llvm::omp::TraitProperty::construct_simd_simd); 3914 Stack->handleConstructTrait(Traits, ScopeEntry); 3915 } 3916 3917 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 3918 switch (DKind) { 3919 case OMPD_parallel: 3920 case OMPD_parallel_for: 3921 case OMPD_parallel_for_simd: 3922 case OMPD_parallel_sections: 3923 case OMPD_parallel_master: 3924 case OMPD_teams: 3925 case OMPD_teams_distribute: 3926 case OMPD_teams_distribute_simd: { 3927 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3928 QualType KmpInt32PtrTy = 3929 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3930 Sema::CapturedParamNameType Params[] = { 3931 std::make_pair(".global_tid.", KmpInt32PtrTy), 3932 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3933 std::make_pair(StringRef(), QualType()) // __context with shared vars 3934 }; 3935 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3936 Params); 3937 break; 3938 } 3939 case OMPD_target_teams: 3940 case OMPD_target_parallel: 3941 case OMPD_target_parallel_for: 3942 case OMPD_target_parallel_for_simd: 3943 case OMPD_target_teams_distribute: 3944 case OMPD_target_teams_distribute_simd: { 3945 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3946 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3947 QualType KmpInt32PtrTy = 3948 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3949 QualType Args[] = {VoidPtrTy}; 3950 FunctionProtoType::ExtProtoInfo EPI; 3951 EPI.Variadic = true; 3952 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3953 Sema::CapturedParamNameType Params[] = { 3954 std::make_pair(".global_tid.", KmpInt32Ty), 3955 std::make_pair(".part_id.", KmpInt32PtrTy), 3956 std::make_pair(".privates.", VoidPtrTy), 3957 std::make_pair( 3958 ".copy_fn.", 3959 Context.getPointerType(CopyFnType).withConst().withRestrict()), 3960 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 3961 std::make_pair(StringRef(), QualType()) // __context with shared vars 3962 }; 3963 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3964 Params, /*OpenMPCaptureLevel=*/0); 3965 // Mark this captured region as inlined, because we don't use outlined 3966 // function directly. 3967 getCurCapturedRegion()->TheCapturedDecl->addAttr( 3968 AlwaysInlineAttr::CreateImplicit( 3969 Context, {}, AttributeCommonInfo::AS_Keyword, 3970 AlwaysInlineAttr::Keyword_forceinline)); 3971 Sema::CapturedParamNameType ParamsTarget[] = { 3972 std::make_pair(StringRef(), QualType()) // __context with shared vars 3973 }; 3974 // Start a captured region for 'target' with no implicit parameters. 3975 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3976 ParamsTarget, /*OpenMPCaptureLevel=*/1); 3977 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 3978 std::make_pair(".global_tid.", KmpInt32PtrTy), 3979 std::make_pair(".bound_tid.", KmpInt32PtrTy), 3980 std::make_pair(StringRef(), QualType()) // __context with shared vars 3981 }; 3982 // Start a captured region for 'teams' or 'parallel'. Both regions have 3983 // the same implicit parameters. 3984 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 3985 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2); 3986 break; 3987 } 3988 case OMPD_target: 3989 case OMPD_target_simd: { 3990 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 3991 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 3992 QualType KmpInt32PtrTy = 3993 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 3994 QualType Args[] = {VoidPtrTy}; 3995 FunctionProtoType::ExtProtoInfo EPI; 3996 EPI.Variadic = true; 3997 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 3998 Sema::CapturedParamNameType Params[] = { 3999 std::make_pair(".global_tid.", KmpInt32Ty), 4000 std::make_pair(".part_id.", KmpInt32PtrTy), 4001 std::make_pair(".privates.", VoidPtrTy), 4002 std::make_pair( 4003 ".copy_fn.", 4004 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4005 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4006 std::make_pair(StringRef(), QualType()) // __context with shared vars 4007 }; 4008 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4009 Params, /*OpenMPCaptureLevel=*/0); 4010 // Mark this captured region as inlined, because we don't use outlined 4011 // function directly. 4012 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4013 AlwaysInlineAttr::CreateImplicit( 4014 Context, {}, AttributeCommonInfo::AS_Keyword, 4015 AlwaysInlineAttr::Keyword_forceinline)); 4016 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4017 std::make_pair(StringRef(), QualType()), 4018 /*OpenMPCaptureLevel=*/1); 4019 break; 4020 } 4021 case OMPD_atomic: 4022 case OMPD_critical: 4023 case OMPD_section: 4024 case OMPD_master: 4025 case OMPD_masked: 4026 case OMPD_tile: 4027 case OMPD_unroll: 4028 break; 4029 case OMPD_loop: 4030 // TODO: 'loop' may require additional parameters depending on the binding. 4031 // Treat similar to OMPD_simd/OMPD_for for now. 4032 case OMPD_simd: 4033 case OMPD_for: 4034 case OMPD_for_simd: 4035 case OMPD_sections: 4036 case OMPD_single: 4037 case OMPD_taskgroup: 4038 case OMPD_distribute: 4039 case OMPD_distribute_simd: 4040 case OMPD_ordered: 4041 case OMPD_target_data: 4042 case OMPD_dispatch: { 4043 Sema::CapturedParamNameType Params[] = { 4044 std::make_pair(StringRef(), QualType()) // __context with shared vars 4045 }; 4046 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4047 Params); 4048 break; 4049 } 4050 case OMPD_task: { 4051 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4052 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4053 QualType KmpInt32PtrTy = 4054 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4055 QualType Args[] = {VoidPtrTy}; 4056 FunctionProtoType::ExtProtoInfo EPI; 4057 EPI.Variadic = true; 4058 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4059 Sema::CapturedParamNameType Params[] = { 4060 std::make_pair(".global_tid.", KmpInt32Ty), 4061 std::make_pair(".part_id.", KmpInt32PtrTy), 4062 std::make_pair(".privates.", VoidPtrTy), 4063 std::make_pair( 4064 ".copy_fn.", 4065 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4066 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4067 std::make_pair(StringRef(), QualType()) // __context with shared vars 4068 }; 4069 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4070 Params); 4071 // Mark this captured region as inlined, because we don't use outlined 4072 // function directly. 4073 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4074 AlwaysInlineAttr::CreateImplicit( 4075 Context, {}, AttributeCommonInfo::AS_Keyword, 4076 AlwaysInlineAttr::Keyword_forceinline)); 4077 break; 4078 } 4079 case OMPD_taskloop: 4080 case OMPD_taskloop_simd: 4081 case OMPD_master_taskloop: 4082 case OMPD_master_taskloop_simd: { 4083 QualType KmpInt32Ty = 4084 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 4085 .withConst(); 4086 QualType KmpUInt64Ty = 4087 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 4088 .withConst(); 4089 QualType KmpInt64Ty = 4090 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 4091 .withConst(); 4092 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4093 QualType KmpInt32PtrTy = 4094 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4095 QualType Args[] = {VoidPtrTy}; 4096 FunctionProtoType::ExtProtoInfo EPI; 4097 EPI.Variadic = true; 4098 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4099 Sema::CapturedParamNameType Params[] = { 4100 std::make_pair(".global_tid.", KmpInt32Ty), 4101 std::make_pair(".part_id.", KmpInt32PtrTy), 4102 std::make_pair(".privates.", VoidPtrTy), 4103 std::make_pair( 4104 ".copy_fn.", 4105 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4106 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4107 std::make_pair(".lb.", KmpUInt64Ty), 4108 std::make_pair(".ub.", KmpUInt64Ty), 4109 std::make_pair(".st.", KmpInt64Ty), 4110 std::make_pair(".liter.", KmpInt32Ty), 4111 std::make_pair(".reductions.", VoidPtrTy), 4112 std::make_pair(StringRef(), QualType()) // __context with shared vars 4113 }; 4114 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4115 Params); 4116 // Mark this captured region as inlined, because we don't use outlined 4117 // function directly. 4118 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4119 AlwaysInlineAttr::CreateImplicit( 4120 Context, {}, AttributeCommonInfo::AS_Keyword, 4121 AlwaysInlineAttr::Keyword_forceinline)); 4122 break; 4123 } 4124 case OMPD_parallel_master_taskloop: 4125 case OMPD_parallel_master_taskloop_simd: { 4126 QualType KmpInt32Ty = 4127 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 4128 .withConst(); 4129 QualType KmpUInt64Ty = 4130 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 4131 .withConst(); 4132 QualType KmpInt64Ty = 4133 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 4134 .withConst(); 4135 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4136 QualType KmpInt32PtrTy = 4137 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4138 Sema::CapturedParamNameType ParamsParallel[] = { 4139 std::make_pair(".global_tid.", KmpInt32PtrTy), 4140 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4141 std::make_pair(StringRef(), QualType()) // __context with shared vars 4142 }; 4143 // Start a captured region for 'parallel'. 4144 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4145 ParamsParallel, /*OpenMPCaptureLevel=*/0); 4146 QualType Args[] = {VoidPtrTy}; 4147 FunctionProtoType::ExtProtoInfo EPI; 4148 EPI.Variadic = true; 4149 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4150 Sema::CapturedParamNameType Params[] = { 4151 std::make_pair(".global_tid.", KmpInt32Ty), 4152 std::make_pair(".part_id.", KmpInt32PtrTy), 4153 std::make_pair(".privates.", VoidPtrTy), 4154 std::make_pair( 4155 ".copy_fn.", 4156 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4157 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4158 std::make_pair(".lb.", KmpUInt64Ty), 4159 std::make_pair(".ub.", KmpUInt64Ty), 4160 std::make_pair(".st.", KmpInt64Ty), 4161 std::make_pair(".liter.", KmpInt32Ty), 4162 std::make_pair(".reductions.", VoidPtrTy), 4163 std::make_pair(StringRef(), QualType()) // __context with shared vars 4164 }; 4165 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4166 Params, /*OpenMPCaptureLevel=*/1); 4167 // Mark this captured region as inlined, because we don't use outlined 4168 // function directly. 4169 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4170 AlwaysInlineAttr::CreateImplicit( 4171 Context, {}, AttributeCommonInfo::AS_Keyword, 4172 AlwaysInlineAttr::Keyword_forceinline)); 4173 break; 4174 } 4175 case OMPD_distribute_parallel_for_simd: 4176 case OMPD_distribute_parallel_for: { 4177 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4178 QualType KmpInt32PtrTy = 4179 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4180 Sema::CapturedParamNameType Params[] = { 4181 std::make_pair(".global_tid.", KmpInt32PtrTy), 4182 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4183 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 4184 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 4185 std::make_pair(StringRef(), QualType()) // __context with shared vars 4186 }; 4187 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4188 Params); 4189 break; 4190 } 4191 case OMPD_target_teams_distribute_parallel_for: 4192 case OMPD_target_teams_distribute_parallel_for_simd: { 4193 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4194 QualType KmpInt32PtrTy = 4195 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4196 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4197 4198 QualType Args[] = {VoidPtrTy}; 4199 FunctionProtoType::ExtProtoInfo EPI; 4200 EPI.Variadic = true; 4201 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4202 Sema::CapturedParamNameType Params[] = { 4203 std::make_pair(".global_tid.", KmpInt32Ty), 4204 std::make_pair(".part_id.", KmpInt32PtrTy), 4205 std::make_pair(".privates.", VoidPtrTy), 4206 std::make_pair( 4207 ".copy_fn.", 4208 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4209 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4210 std::make_pair(StringRef(), QualType()) // __context with shared vars 4211 }; 4212 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4213 Params, /*OpenMPCaptureLevel=*/0); 4214 // Mark this captured region as inlined, because we don't use outlined 4215 // function directly. 4216 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4217 AlwaysInlineAttr::CreateImplicit( 4218 Context, {}, AttributeCommonInfo::AS_Keyword, 4219 AlwaysInlineAttr::Keyword_forceinline)); 4220 Sema::CapturedParamNameType ParamsTarget[] = { 4221 std::make_pair(StringRef(), QualType()) // __context with shared vars 4222 }; 4223 // Start a captured region for 'target' with no implicit parameters. 4224 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4225 ParamsTarget, /*OpenMPCaptureLevel=*/1); 4226 4227 Sema::CapturedParamNameType ParamsTeams[] = { 4228 std::make_pair(".global_tid.", KmpInt32PtrTy), 4229 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4230 std::make_pair(StringRef(), QualType()) // __context with shared vars 4231 }; 4232 // Start a captured region for 'target' with no implicit parameters. 4233 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4234 ParamsTeams, /*OpenMPCaptureLevel=*/2); 4235 4236 Sema::CapturedParamNameType ParamsParallel[] = { 4237 std::make_pair(".global_tid.", KmpInt32PtrTy), 4238 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4239 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 4240 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 4241 std::make_pair(StringRef(), QualType()) // __context with shared vars 4242 }; 4243 // Start a captured region for 'teams' or 'parallel'. Both regions have 4244 // the same implicit parameters. 4245 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4246 ParamsParallel, /*OpenMPCaptureLevel=*/3); 4247 break; 4248 } 4249 4250 case OMPD_teams_distribute_parallel_for: 4251 case OMPD_teams_distribute_parallel_for_simd: { 4252 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4253 QualType KmpInt32PtrTy = 4254 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4255 4256 Sema::CapturedParamNameType ParamsTeams[] = { 4257 std::make_pair(".global_tid.", KmpInt32PtrTy), 4258 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4259 std::make_pair(StringRef(), QualType()) // __context with shared vars 4260 }; 4261 // Start a captured region for 'target' with no implicit parameters. 4262 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4263 ParamsTeams, /*OpenMPCaptureLevel=*/0); 4264 4265 Sema::CapturedParamNameType ParamsParallel[] = { 4266 std::make_pair(".global_tid.", KmpInt32PtrTy), 4267 std::make_pair(".bound_tid.", KmpInt32PtrTy), 4268 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 4269 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 4270 std::make_pair(StringRef(), QualType()) // __context with shared vars 4271 }; 4272 // Start a captured region for 'teams' or 'parallel'. Both regions have 4273 // the same implicit parameters. 4274 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4275 ParamsParallel, /*OpenMPCaptureLevel=*/1); 4276 break; 4277 } 4278 case OMPD_target_update: 4279 case OMPD_target_enter_data: 4280 case OMPD_target_exit_data: { 4281 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 4282 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 4283 QualType KmpInt32PtrTy = 4284 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 4285 QualType Args[] = {VoidPtrTy}; 4286 FunctionProtoType::ExtProtoInfo EPI; 4287 EPI.Variadic = true; 4288 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 4289 Sema::CapturedParamNameType Params[] = { 4290 std::make_pair(".global_tid.", KmpInt32Ty), 4291 std::make_pair(".part_id.", KmpInt32PtrTy), 4292 std::make_pair(".privates.", VoidPtrTy), 4293 std::make_pair( 4294 ".copy_fn.", 4295 Context.getPointerType(CopyFnType).withConst().withRestrict()), 4296 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 4297 std::make_pair(StringRef(), QualType()) // __context with shared vars 4298 }; 4299 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 4300 Params); 4301 // Mark this captured region as inlined, because we don't use outlined 4302 // function directly. 4303 getCurCapturedRegion()->TheCapturedDecl->addAttr( 4304 AlwaysInlineAttr::CreateImplicit( 4305 Context, {}, AttributeCommonInfo::AS_Keyword, 4306 AlwaysInlineAttr::Keyword_forceinline)); 4307 break; 4308 } 4309 case OMPD_threadprivate: 4310 case OMPD_allocate: 4311 case OMPD_taskyield: 4312 case OMPD_barrier: 4313 case OMPD_taskwait: 4314 case OMPD_cancellation_point: 4315 case OMPD_cancel: 4316 case OMPD_flush: 4317 case OMPD_depobj: 4318 case OMPD_scan: 4319 case OMPD_declare_reduction: 4320 case OMPD_declare_mapper: 4321 case OMPD_declare_simd: 4322 case OMPD_declare_target: 4323 case OMPD_end_declare_target: 4324 case OMPD_requires: 4325 case OMPD_declare_variant: 4326 case OMPD_begin_declare_variant: 4327 case OMPD_end_declare_variant: 4328 case OMPD_metadirective: 4329 llvm_unreachable("OpenMP Directive is not allowed"); 4330 case OMPD_unknown: 4331 default: 4332 llvm_unreachable("Unknown OpenMP directive"); 4333 } 4334 DSAStack->setContext(CurContext); 4335 handleDeclareVariantConstructTrait(DSAStack, DKind, /* ScopeEntry */ true); 4336 } 4337 4338 int Sema::getNumberOfConstructScopes(unsigned Level) const { 4339 return getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 4340 } 4341 4342 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 4343 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 4344 getOpenMPCaptureRegions(CaptureRegions, DKind); 4345 return CaptureRegions.size(); 4346 } 4347 4348 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 4349 Expr *CaptureExpr, bool WithInit, 4350 bool AsExpression) { 4351 assert(CaptureExpr); 4352 ASTContext &C = S.getASTContext(); 4353 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 4354 QualType Ty = Init->getType(); 4355 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 4356 if (S.getLangOpts().CPlusPlus) { 4357 Ty = C.getLValueReferenceType(Ty); 4358 } else { 4359 Ty = C.getPointerType(Ty); 4360 ExprResult Res = 4361 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 4362 if (!Res.isUsable()) 4363 return nullptr; 4364 Init = Res.get(); 4365 } 4366 WithInit = true; 4367 } 4368 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 4369 CaptureExpr->getBeginLoc()); 4370 if (!WithInit) 4371 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C)); 4372 S.CurContext->addHiddenDecl(CED); 4373 Sema::TentativeAnalysisScope Trap(S); 4374 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 4375 return CED; 4376 } 4377 4378 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 4379 bool WithInit) { 4380 OMPCapturedExprDecl *CD; 4381 if (VarDecl *VD = S.isOpenMPCapturedDecl(D)) 4382 CD = cast<OMPCapturedExprDecl>(VD); 4383 else 4384 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 4385 /*AsExpression=*/false); 4386 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 4387 CaptureExpr->getExprLoc()); 4388 } 4389 4390 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 4391 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get(); 4392 if (!Ref) { 4393 OMPCapturedExprDecl *CD = buildCaptureDecl( 4394 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr, 4395 /*WithInit=*/true, /*AsExpression=*/true); 4396 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 4397 CaptureExpr->getExprLoc()); 4398 } 4399 ExprResult Res = Ref; 4400 if (!S.getLangOpts().CPlusPlus && 4401 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 4402 Ref->getType()->isPointerType()) { 4403 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 4404 if (!Res.isUsable()) 4405 return ExprError(); 4406 } 4407 return S.DefaultLvalueConversion(Res.get()); 4408 } 4409 4410 namespace { 4411 // OpenMP directives parsed in this section are represented as a 4412 // CapturedStatement with an associated statement. If a syntax error 4413 // is detected during the parsing of the associated statement, the 4414 // compiler must abort processing and close the CapturedStatement. 4415 // 4416 // Combined directives such as 'target parallel' have more than one 4417 // nested CapturedStatements. This RAII ensures that we unwind out 4418 // of all the nested CapturedStatements when an error is found. 4419 class CaptureRegionUnwinderRAII { 4420 private: 4421 Sema &S; 4422 bool &ErrorFound; 4423 OpenMPDirectiveKind DKind = OMPD_unknown; 4424 4425 public: 4426 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 4427 OpenMPDirectiveKind DKind) 4428 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 4429 ~CaptureRegionUnwinderRAII() { 4430 if (ErrorFound) { 4431 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 4432 while (--ThisCaptureLevel >= 0) 4433 S.ActOnCapturedRegionError(); 4434 } 4435 } 4436 }; 4437 } // namespace 4438 4439 void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) { 4440 // Capture variables captured by reference in lambdas for target-based 4441 // directives. 4442 if (!CurContext->isDependentContext() && 4443 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) || 4444 isOpenMPTargetDataManagementDirective( 4445 DSAStack->getCurrentDirective()))) { 4446 QualType Type = V->getType(); 4447 if (const auto *RD = Type.getCanonicalType() 4448 .getNonReferenceType() 4449 ->getAsCXXRecordDecl()) { 4450 bool SavedForceCaptureByReferenceInTargetExecutable = 4451 DSAStack->isForceCaptureByReferenceInTargetExecutable(); 4452 DSAStack->setForceCaptureByReferenceInTargetExecutable( 4453 /*V=*/true); 4454 if (RD->isLambda()) { 4455 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures; 4456 FieldDecl *ThisCapture; 4457 RD->getCaptureFields(Captures, ThisCapture); 4458 for (const LambdaCapture &LC : RD->captures()) { 4459 if (LC.getCaptureKind() == LCK_ByRef) { 4460 VarDecl *VD = LC.getCapturedVar(); 4461 DeclContext *VDC = VD->getDeclContext(); 4462 if (!VDC->Encloses(CurContext)) 4463 continue; 4464 MarkVariableReferenced(LC.getLocation(), VD); 4465 } else if (LC.getCaptureKind() == LCK_This) { 4466 QualType ThisTy = getCurrentThisType(); 4467 if (!ThisTy.isNull() && 4468 Context.typesAreCompatible(ThisTy, ThisCapture->getType())) 4469 CheckCXXThisCapture(LC.getLocation()); 4470 } 4471 } 4472 } 4473 DSAStack->setForceCaptureByReferenceInTargetExecutable( 4474 SavedForceCaptureByReferenceInTargetExecutable); 4475 } 4476 } 4477 } 4478 4479 static bool checkOrderedOrderSpecified(Sema &S, 4480 const ArrayRef<OMPClause *> Clauses) { 4481 const OMPOrderedClause *Ordered = nullptr; 4482 const OMPOrderClause *Order = nullptr; 4483 4484 for (const OMPClause *Clause : Clauses) { 4485 if (Clause->getClauseKind() == OMPC_ordered) 4486 Ordered = cast<OMPOrderedClause>(Clause); 4487 else if (Clause->getClauseKind() == OMPC_order) { 4488 Order = cast<OMPOrderClause>(Clause); 4489 if (Order->getKind() != OMPC_ORDER_concurrent) 4490 Order = nullptr; 4491 } 4492 if (Ordered && Order) 4493 break; 4494 } 4495 4496 if (Ordered && Order) { 4497 S.Diag(Order->getKindKwLoc(), 4498 diag::err_omp_simple_clause_incompatible_with_ordered) 4499 << getOpenMPClauseName(OMPC_order) 4500 << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent) 4501 << SourceRange(Order->getBeginLoc(), Order->getEndLoc()); 4502 S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param) 4503 << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc()); 4504 return true; 4505 } 4506 return false; 4507 } 4508 4509 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 4510 ArrayRef<OMPClause *> Clauses) { 4511 handleDeclareVariantConstructTrait(DSAStack, DSAStack->getCurrentDirective(), 4512 /* ScopeEntry */ false); 4513 if (DSAStack->getCurrentDirective() == OMPD_atomic || 4514 DSAStack->getCurrentDirective() == OMPD_critical || 4515 DSAStack->getCurrentDirective() == OMPD_section || 4516 DSAStack->getCurrentDirective() == OMPD_master || 4517 DSAStack->getCurrentDirective() == OMPD_masked) 4518 return S; 4519 4520 bool ErrorFound = false; 4521 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 4522 *this, ErrorFound, DSAStack->getCurrentDirective()); 4523 if (!S.isUsable()) { 4524 ErrorFound = true; 4525 return StmtError(); 4526 } 4527 4528 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 4529 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 4530 OMPOrderedClause *OC = nullptr; 4531 OMPScheduleClause *SC = nullptr; 4532 SmallVector<const OMPLinearClause *, 4> LCs; 4533 SmallVector<const OMPClauseWithPreInit *, 4> PICs; 4534 // This is required for proper codegen. 4535 for (OMPClause *Clause : Clauses) { 4536 if (!LangOpts.OpenMPSimd && 4537 isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) && 4538 Clause->getClauseKind() == OMPC_in_reduction) { 4539 // Capture taskgroup task_reduction descriptors inside the tasking regions 4540 // with the corresponding in_reduction items. 4541 auto *IRC = cast<OMPInReductionClause>(Clause); 4542 for (Expr *E : IRC->taskgroup_descriptors()) 4543 if (E) 4544 MarkDeclarationsReferencedInExpr(E); 4545 } 4546 if (isOpenMPPrivate(Clause->getClauseKind()) || 4547 Clause->getClauseKind() == OMPC_copyprivate || 4548 (getLangOpts().OpenMPUseTLS && 4549 getASTContext().getTargetInfo().isTLSSupported() && 4550 Clause->getClauseKind() == OMPC_copyin)) { 4551 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 4552 // Mark all variables in private list clauses as used in inner region. 4553 for (Stmt *VarRef : Clause->children()) { 4554 if (auto *E = cast_or_null<Expr>(VarRef)) { 4555 MarkDeclarationsReferencedInExpr(E); 4556 } 4557 } 4558 DSAStack->setForceVarCapturing(/*V=*/false); 4559 } else if (isOpenMPLoopTransformationDirective( 4560 DSAStack->getCurrentDirective())) { 4561 assert(CaptureRegions.empty() && 4562 "No captured regions in loop transformation directives."); 4563 } else if (CaptureRegions.size() > 1 || 4564 CaptureRegions.back() != OMPD_unknown) { 4565 if (auto *C = OMPClauseWithPreInit::get(Clause)) 4566 PICs.push_back(C); 4567 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 4568 if (Expr *E = C->getPostUpdateExpr()) 4569 MarkDeclarationsReferencedInExpr(E); 4570 } 4571 } 4572 if (Clause->getClauseKind() == OMPC_schedule) 4573 SC = cast<OMPScheduleClause>(Clause); 4574 else if (Clause->getClauseKind() == OMPC_ordered) 4575 OC = cast<OMPOrderedClause>(Clause); 4576 else if (Clause->getClauseKind() == OMPC_linear) 4577 LCs.push_back(cast<OMPLinearClause>(Clause)); 4578 } 4579 // Capture allocator expressions if used. 4580 for (Expr *E : DSAStack->getInnerAllocators()) 4581 MarkDeclarationsReferencedInExpr(E); 4582 // OpenMP, 2.7.1 Loop Construct, Restrictions 4583 // The nonmonotonic modifier cannot be specified if an ordered clause is 4584 // specified. 4585 if (SC && 4586 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 4587 SC->getSecondScheduleModifier() == 4588 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 4589 OC) { 4590 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 4591 ? SC->getFirstScheduleModifierLoc() 4592 : SC->getSecondScheduleModifierLoc(), 4593 diag::err_omp_simple_clause_incompatible_with_ordered) 4594 << getOpenMPClauseName(OMPC_schedule) 4595 << getOpenMPSimpleClauseTypeName(OMPC_schedule, 4596 OMPC_SCHEDULE_MODIFIER_nonmonotonic) 4597 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 4598 ErrorFound = true; 4599 } 4600 // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions. 4601 // If an order(concurrent) clause is present, an ordered clause may not appear 4602 // on the same directive. 4603 if (checkOrderedOrderSpecified(*this, Clauses)) 4604 ErrorFound = true; 4605 if (!LCs.empty() && OC && OC->getNumForLoops()) { 4606 for (const OMPLinearClause *C : LCs) { 4607 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered) 4608 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 4609 } 4610 ErrorFound = true; 4611 } 4612 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 4613 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 4614 OC->getNumForLoops()) { 4615 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd) 4616 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 4617 ErrorFound = true; 4618 } 4619 if (ErrorFound) { 4620 return StmtError(); 4621 } 4622 StmtResult SR = S; 4623 unsigned CompletedRegions = 0; 4624 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 4625 // Mark all variables in private list clauses as used in inner region. 4626 // Required for proper codegen of combined directives. 4627 // TODO: add processing for other clauses. 4628 if (ThisCaptureRegion != OMPD_unknown) { 4629 for (const clang::OMPClauseWithPreInit *C : PICs) { 4630 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 4631 // Find the particular capture region for the clause if the 4632 // directive is a combined one with multiple capture regions. 4633 // If the directive is not a combined one, the capture region 4634 // associated with the clause is OMPD_unknown and is generated 4635 // only once. 4636 if (CaptureRegion == ThisCaptureRegion || 4637 CaptureRegion == OMPD_unknown) { 4638 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 4639 for (Decl *D : DS->decls()) 4640 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 4641 } 4642 } 4643 } 4644 } 4645 if (ThisCaptureRegion == OMPD_target) { 4646 // Capture allocator traits in the target region. They are used implicitly 4647 // and, thus, are not captured by default. 4648 for (OMPClause *C : Clauses) { 4649 if (const auto *UAC = dyn_cast<OMPUsesAllocatorsClause>(C)) { 4650 for (unsigned I = 0, End = UAC->getNumberOfAllocators(); I < End; 4651 ++I) { 4652 OMPUsesAllocatorsClause::Data D = UAC->getAllocatorData(I); 4653 if (Expr *E = D.AllocatorTraits) 4654 MarkDeclarationsReferencedInExpr(E); 4655 } 4656 continue; 4657 } 4658 } 4659 } 4660 if (ThisCaptureRegion == OMPD_parallel) { 4661 // Capture temp arrays for inscan reductions and locals in aligned 4662 // clauses. 4663 for (OMPClause *C : Clauses) { 4664 if (auto *RC = dyn_cast<OMPReductionClause>(C)) { 4665 if (RC->getModifier() != OMPC_REDUCTION_inscan) 4666 continue; 4667 for (Expr *E : RC->copy_array_temps()) 4668 MarkDeclarationsReferencedInExpr(E); 4669 } 4670 if (auto *AC = dyn_cast<OMPAlignedClause>(C)) { 4671 for (Expr *E : AC->varlists()) 4672 MarkDeclarationsReferencedInExpr(E); 4673 } 4674 } 4675 } 4676 if (++CompletedRegions == CaptureRegions.size()) 4677 DSAStack->setBodyComplete(); 4678 SR = ActOnCapturedRegionEnd(SR.get()); 4679 } 4680 return SR; 4681 } 4682 4683 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 4684 OpenMPDirectiveKind CancelRegion, 4685 SourceLocation StartLoc) { 4686 // CancelRegion is only needed for cancel and cancellation_point. 4687 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 4688 return false; 4689 4690 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 4691 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 4692 return false; 4693 4694 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 4695 << getOpenMPDirectiveName(CancelRegion); 4696 return true; 4697 } 4698 4699 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack, 4700 OpenMPDirectiveKind CurrentRegion, 4701 const DeclarationNameInfo &CurrentName, 4702 OpenMPDirectiveKind CancelRegion, 4703 OpenMPBindClauseKind BindKind, 4704 SourceLocation StartLoc) { 4705 if (Stack->getCurScope()) { 4706 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective(); 4707 OpenMPDirectiveKind OffendingRegion = ParentRegion; 4708 bool NestingProhibited = false; 4709 bool CloseNesting = true; 4710 bool OrphanSeen = false; 4711 enum { 4712 NoRecommend, 4713 ShouldBeInParallelRegion, 4714 ShouldBeInOrderedRegion, 4715 ShouldBeInTargetRegion, 4716 ShouldBeInTeamsRegion, 4717 ShouldBeInLoopSimdRegion, 4718 } Recommend = NoRecommend; 4719 if (isOpenMPSimdDirective(ParentRegion) && 4720 ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) || 4721 (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered && 4722 CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic && 4723 CurrentRegion != OMPD_scan))) { 4724 // OpenMP [2.16, Nesting of Regions] 4725 // OpenMP constructs may not be nested inside a simd region. 4726 // OpenMP [2.8.1,simd Construct, Restrictions] 4727 // An ordered construct with the simd clause is the only OpenMP 4728 // construct that can appear in the simd region. 4729 // Allowing a SIMD construct nested in another SIMD construct is an 4730 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 4731 // message. 4732 // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions] 4733 // The only OpenMP constructs that can be encountered during execution of 4734 // a simd region are the atomic construct, the loop construct, the simd 4735 // construct and the ordered construct with the simd clause. 4736 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 4737 ? diag::err_omp_prohibited_region_simd 4738 : diag::warn_omp_nesting_simd) 4739 << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0); 4740 return CurrentRegion != OMPD_simd; 4741 } 4742 if (ParentRegion == OMPD_atomic) { 4743 // OpenMP [2.16, Nesting of Regions] 4744 // OpenMP constructs may not be nested inside an atomic region. 4745 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 4746 return true; 4747 } 4748 if (CurrentRegion == OMPD_section) { 4749 // OpenMP [2.7.2, sections Construct, Restrictions] 4750 // Orphaned section directives are prohibited. That is, the section 4751 // directives must appear within the sections construct and must not be 4752 // encountered elsewhere in the sections region. 4753 if (ParentRegion != OMPD_sections && 4754 ParentRegion != OMPD_parallel_sections) { 4755 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 4756 << (ParentRegion != OMPD_unknown) 4757 << getOpenMPDirectiveName(ParentRegion); 4758 return true; 4759 } 4760 return false; 4761 } 4762 // Allow some constructs (except teams and cancellation constructs) to be 4763 // orphaned (they could be used in functions, called from OpenMP regions 4764 // with the required preconditions). 4765 if (ParentRegion == OMPD_unknown && 4766 !isOpenMPNestingTeamsDirective(CurrentRegion) && 4767 CurrentRegion != OMPD_cancellation_point && 4768 CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_scan) 4769 return false; 4770 if (CurrentRegion == OMPD_cancellation_point || 4771 CurrentRegion == OMPD_cancel) { 4772 // OpenMP [2.16, Nesting of Regions] 4773 // A cancellation point construct for which construct-type-clause is 4774 // taskgroup must be nested inside a task construct. A cancellation 4775 // point construct for which construct-type-clause is not taskgroup must 4776 // be closely nested inside an OpenMP construct that matches the type 4777 // specified in construct-type-clause. 4778 // A cancel construct for which construct-type-clause is taskgroup must be 4779 // nested inside a task construct. A cancel construct for which 4780 // construct-type-clause is not taskgroup must be closely nested inside an 4781 // OpenMP construct that matches the type specified in 4782 // construct-type-clause. 4783 NestingProhibited = 4784 !((CancelRegion == OMPD_parallel && 4785 (ParentRegion == OMPD_parallel || 4786 ParentRegion == OMPD_target_parallel)) || 4787 (CancelRegion == OMPD_for && 4788 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 4789 ParentRegion == OMPD_target_parallel_for || 4790 ParentRegion == OMPD_distribute_parallel_for || 4791 ParentRegion == OMPD_teams_distribute_parallel_for || 4792 ParentRegion == OMPD_target_teams_distribute_parallel_for)) || 4793 (CancelRegion == OMPD_taskgroup && 4794 (ParentRegion == OMPD_task || 4795 (SemaRef.getLangOpts().OpenMP >= 50 && 4796 (ParentRegion == OMPD_taskloop || 4797 ParentRegion == OMPD_master_taskloop || 4798 ParentRegion == OMPD_parallel_master_taskloop)))) || 4799 (CancelRegion == OMPD_sections && 4800 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 4801 ParentRegion == OMPD_parallel_sections))); 4802 OrphanSeen = ParentRegion == OMPD_unknown; 4803 } else if (CurrentRegion == OMPD_master || CurrentRegion == OMPD_masked) { 4804 // OpenMP 5.1 [2.22, Nesting of Regions] 4805 // A masked region may not be closely nested inside a worksharing, loop, 4806 // atomic, task, or taskloop region. 4807 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 4808 isOpenMPGenericLoopDirective(ParentRegion) || 4809 isOpenMPTaskingDirective(ParentRegion); 4810 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 4811 // OpenMP [2.16, Nesting of Regions] 4812 // A critical region may not be nested (closely or otherwise) inside a 4813 // critical region with the same name. Note that this restriction is not 4814 // sufficient to prevent deadlock. 4815 SourceLocation PreviousCriticalLoc; 4816 bool DeadLock = Stack->hasDirective( 4817 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 4818 const DeclarationNameInfo &DNI, 4819 SourceLocation Loc) { 4820 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 4821 PreviousCriticalLoc = Loc; 4822 return true; 4823 } 4824 return false; 4825 }, 4826 false /* skip top directive */); 4827 if (DeadLock) { 4828 SemaRef.Diag(StartLoc, 4829 diag::err_omp_prohibited_region_critical_same_name) 4830 << CurrentName.getName(); 4831 if (PreviousCriticalLoc.isValid()) 4832 SemaRef.Diag(PreviousCriticalLoc, 4833 diag::note_omp_previous_critical_region); 4834 return true; 4835 } 4836 } else if (CurrentRegion == OMPD_barrier) { 4837 // OpenMP 5.1 [2.22, Nesting of Regions] 4838 // A barrier region may not be closely nested inside a worksharing, loop, 4839 // task, taskloop, critical, ordered, atomic, or masked region. 4840 NestingProhibited = 4841 isOpenMPWorksharingDirective(ParentRegion) || 4842 isOpenMPGenericLoopDirective(ParentRegion) || 4843 isOpenMPTaskingDirective(ParentRegion) || 4844 ParentRegion == OMPD_master || ParentRegion == OMPD_masked || 4845 ParentRegion == OMPD_parallel_master || 4846 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered; 4847 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 4848 !isOpenMPParallelDirective(CurrentRegion) && 4849 !isOpenMPTeamsDirective(CurrentRegion)) { 4850 // OpenMP 5.1 [2.22, Nesting of Regions] 4851 // A loop region that binds to a parallel region or a worksharing region 4852 // may not be closely nested inside a worksharing, loop, task, taskloop, 4853 // critical, ordered, atomic, or masked region. 4854 NestingProhibited = 4855 isOpenMPWorksharingDirective(ParentRegion) || 4856 isOpenMPGenericLoopDirective(ParentRegion) || 4857 isOpenMPTaskingDirective(ParentRegion) || 4858 ParentRegion == OMPD_master || ParentRegion == OMPD_masked || 4859 ParentRegion == OMPD_parallel_master || 4860 ParentRegion == OMPD_critical || ParentRegion == OMPD_ordered; 4861 Recommend = ShouldBeInParallelRegion; 4862 } else if (CurrentRegion == OMPD_ordered) { 4863 // OpenMP [2.16, Nesting of Regions] 4864 // An ordered region may not be closely nested inside a critical, 4865 // atomic, or explicit task region. 4866 // An ordered region must be closely nested inside a loop region (or 4867 // parallel loop region) with an ordered clause. 4868 // OpenMP [2.8.1,simd Construct, Restrictions] 4869 // An ordered construct with the simd clause is the only OpenMP construct 4870 // that can appear in the simd region. 4871 NestingProhibited = ParentRegion == OMPD_critical || 4872 isOpenMPTaskingDirective(ParentRegion) || 4873 !(isOpenMPSimdDirective(ParentRegion) || 4874 Stack->isParentOrderedRegion()); 4875 Recommend = ShouldBeInOrderedRegion; 4876 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 4877 // OpenMP [2.16, Nesting of Regions] 4878 // If specified, a teams construct must be contained within a target 4879 // construct. 4880 NestingProhibited = 4881 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) || 4882 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown && 4883 ParentRegion != OMPD_target); 4884 OrphanSeen = ParentRegion == OMPD_unknown; 4885 Recommend = ShouldBeInTargetRegion; 4886 } else if (CurrentRegion == OMPD_scan) { 4887 // OpenMP [2.16, Nesting of Regions] 4888 // If specified, a teams construct must be contained within a target 4889 // construct. 4890 NestingProhibited = 4891 SemaRef.LangOpts.OpenMP < 50 || 4892 (ParentRegion != OMPD_simd && ParentRegion != OMPD_for && 4893 ParentRegion != OMPD_for_simd && ParentRegion != OMPD_parallel_for && 4894 ParentRegion != OMPD_parallel_for_simd); 4895 OrphanSeen = ParentRegion == OMPD_unknown; 4896 Recommend = ShouldBeInLoopSimdRegion; 4897 } 4898 if (!NestingProhibited && 4899 !isOpenMPTargetExecutionDirective(CurrentRegion) && 4900 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 4901 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 4902 // OpenMP [5.1, 2.22, Nesting of Regions] 4903 // distribute, distribute simd, distribute parallel worksharing-loop, 4904 // distribute parallel worksharing-loop SIMD, loop, parallel regions, 4905 // including any parallel regions arising from combined constructs, 4906 // omp_get_num_teams() regions, and omp_get_team_num() regions are the 4907 // only OpenMP regions that may be strictly nested inside the teams 4908 // region. 4909 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 4910 !isOpenMPDistributeDirective(CurrentRegion) && 4911 CurrentRegion != OMPD_loop; 4912 Recommend = ShouldBeInParallelRegion; 4913 } 4914 if (!NestingProhibited && CurrentRegion == OMPD_loop) { 4915 // OpenMP [5.1, 2.11.7, loop Construct, Restrictions] 4916 // If the bind clause is present on the loop construct and binding is 4917 // teams then the corresponding loop region must be strictly nested inside 4918 // a teams region. 4919 NestingProhibited = BindKind == OMPC_BIND_teams && 4920 ParentRegion != OMPD_teams && 4921 ParentRegion != OMPD_target_teams; 4922 Recommend = ShouldBeInTeamsRegion; 4923 } 4924 if (!NestingProhibited && 4925 isOpenMPNestingDistributeDirective(CurrentRegion)) { 4926 // OpenMP 4.5 [2.17 Nesting of Regions] 4927 // The region associated with the distribute construct must be strictly 4928 // nested inside a teams region 4929 NestingProhibited = 4930 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 4931 Recommend = ShouldBeInTeamsRegion; 4932 } 4933 if (!NestingProhibited && 4934 (isOpenMPTargetExecutionDirective(CurrentRegion) || 4935 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 4936 // OpenMP 4.5 [2.17 Nesting of Regions] 4937 // If a target, target update, target data, target enter data, or 4938 // target exit data construct is encountered during execution of a 4939 // target region, the behavior is unspecified. 4940 NestingProhibited = Stack->hasDirective( 4941 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 4942 SourceLocation) { 4943 if (isOpenMPTargetExecutionDirective(K)) { 4944 OffendingRegion = K; 4945 return true; 4946 } 4947 return false; 4948 }, 4949 false /* don't skip top directive */); 4950 CloseNesting = false; 4951 } 4952 if (NestingProhibited) { 4953 if (OrphanSeen) { 4954 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 4955 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 4956 } else { 4957 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 4958 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 4959 << Recommend << getOpenMPDirectiveName(CurrentRegion); 4960 } 4961 return true; 4962 } 4963 } 4964 return false; 4965 } 4966 4967 struct Kind2Unsigned { 4968 using argument_type = OpenMPDirectiveKind; 4969 unsigned operator()(argument_type DK) { return unsigned(DK); } 4970 }; 4971 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 4972 ArrayRef<OMPClause *> Clauses, 4973 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 4974 bool ErrorFound = false; 4975 unsigned NamedModifiersNumber = 0; 4976 llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers; 4977 FoundNameModifiers.resize(llvm::omp::Directive_enumSize + 1); 4978 SmallVector<SourceLocation, 4> NameModifierLoc; 4979 for (const OMPClause *C : Clauses) { 4980 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 4981 // At most one if clause without a directive-name-modifier can appear on 4982 // the directive. 4983 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 4984 if (FoundNameModifiers[CurNM]) { 4985 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 4986 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 4987 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 4988 ErrorFound = true; 4989 } else if (CurNM != OMPD_unknown) { 4990 NameModifierLoc.push_back(IC->getNameModifierLoc()); 4991 ++NamedModifiersNumber; 4992 } 4993 FoundNameModifiers[CurNM] = IC; 4994 if (CurNM == OMPD_unknown) 4995 continue; 4996 // Check if the specified name modifier is allowed for the current 4997 // directive. 4998 // At most one if clause with the particular directive-name-modifier can 4999 // appear on the directive. 5000 if (!llvm::is_contained(AllowedNameModifiers, CurNM)) { 5001 S.Diag(IC->getNameModifierLoc(), 5002 diag::err_omp_wrong_if_directive_name_modifier) 5003 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 5004 ErrorFound = true; 5005 } 5006 } 5007 } 5008 // If any if clause on the directive includes a directive-name-modifier then 5009 // all if clauses on the directive must include a directive-name-modifier. 5010 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 5011 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 5012 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(), 5013 diag::err_omp_no_more_if_clause); 5014 } else { 5015 std::string Values; 5016 std::string Sep(", "); 5017 unsigned AllowedCnt = 0; 5018 unsigned TotalAllowedNum = 5019 AllowedNameModifiers.size() - NamedModifiersNumber; 5020 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 5021 ++Cnt) { 5022 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 5023 if (!FoundNameModifiers[NM]) { 5024 Values += "'"; 5025 Values += getOpenMPDirectiveName(NM); 5026 Values += "'"; 5027 if (AllowedCnt + 2 == TotalAllowedNum) 5028 Values += " or "; 5029 else if (AllowedCnt + 1 != TotalAllowedNum) 5030 Values += Sep; 5031 ++AllowedCnt; 5032 } 5033 } 5034 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(), 5035 diag::err_omp_unnamed_if_clause) 5036 << (TotalAllowedNum > 1) << Values; 5037 } 5038 for (SourceLocation Loc : NameModifierLoc) { 5039 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 5040 } 5041 ErrorFound = true; 5042 } 5043 return ErrorFound; 5044 } 5045 5046 static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr, 5047 SourceLocation &ELoc, 5048 SourceRange &ERange, 5049 bool AllowArraySection) { 5050 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 5051 RefExpr->containsUnexpandedParameterPack()) 5052 return std::make_pair(nullptr, true); 5053 5054 // OpenMP [3.1, C/C++] 5055 // A list item is a variable name. 5056 // OpenMP [2.9.3.3, Restrictions, p.1] 5057 // A variable that is part of another variable (as an array or 5058 // structure element) cannot appear in a private clause. 5059 RefExpr = RefExpr->IgnoreParens(); 5060 enum { 5061 NoArrayExpr = -1, 5062 ArraySubscript = 0, 5063 OMPArraySection = 1 5064 } IsArrayExpr = NoArrayExpr; 5065 if (AllowArraySection) { 5066 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 5067 Expr *Base = ASE->getBase()->IgnoreParenImpCasts(); 5068 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 5069 Base = TempASE->getBase()->IgnoreParenImpCasts(); 5070 RefExpr = Base; 5071 IsArrayExpr = ArraySubscript; 5072 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 5073 Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 5074 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 5075 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 5076 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 5077 Base = TempASE->getBase()->IgnoreParenImpCasts(); 5078 RefExpr = Base; 5079 IsArrayExpr = OMPArraySection; 5080 } 5081 } 5082 ELoc = RefExpr->getExprLoc(); 5083 ERange = RefExpr->getSourceRange(); 5084 RefExpr = RefExpr->IgnoreParenImpCasts(); 5085 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 5086 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 5087 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 5088 (S.getCurrentThisType().isNull() || !ME || 5089 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 5090 !isa<FieldDecl>(ME->getMemberDecl()))) { 5091 if (IsArrayExpr != NoArrayExpr) { 5092 S.Diag(ELoc, diag::err_omp_expected_base_var_name) 5093 << IsArrayExpr << ERange; 5094 } else { 5095 S.Diag(ELoc, 5096 AllowArraySection 5097 ? diag::err_omp_expected_var_name_member_expr_or_array_item 5098 : diag::err_omp_expected_var_name_member_expr) 5099 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 5100 } 5101 return std::make_pair(nullptr, false); 5102 } 5103 return std::make_pair( 5104 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false); 5105 } 5106 5107 namespace { 5108 /// Checks if the allocator is used in uses_allocators clause to be allowed in 5109 /// target regions. 5110 class AllocatorChecker final : public ConstStmtVisitor<AllocatorChecker, bool> { 5111 DSAStackTy *S = nullptr; 5112 5113 public: 5114 bool VisitDeclRefExpr(const DeclRefExpr *E) { 5115 return S->isUsesAllocatorsDecl(E->getDecl()) 5116 .getValueOr( 5117 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) == 5118 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait; 5119 } 5120 bool VisitStmt(const Stmt *S) { 5121 for (const Stmt *Child : S->children()) { 5122 if (Child && Visit(Child)) 5123 return true; 5124 } 5125 return false; 5126 } 5127 explicit AllocatorChecker(DSAStackTy *S) : S(S) {} 5128 }; 5129 } // namespace 5130 5131 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack, 5132 ArrayRef<OMPClause *> Clauses) { 5133 assert(!S.CurContext->isDependentContext() && 5134 "Expected non-dependent context."); 5135 auto AllocateRange = 5136 llvm::make_filter_range(Clauses, OMPAllocateClause::classof); 5137 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>> DeclToCopy; 5138 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) { 5139 return isOpenMPPrivate(C->getClauseKind()); 5140 }); 5141 for (OMPClause *Cl : PrivateRange) { 5142 MutableArrayRef<Expr *>::iterator I, It, Et; 5143 if (Cl->getClauseKind() == OMPC_private) { 5144 auto *PC = cast<OMPPrivateClause>(Cl); 5145 I = PC->private_copies().begin(); 5146 It = PC->varlist_begin(); 5147 Et = PC->varlist_end(); 5148 } else if (Cl->getClauseKind() == OMPC_firstprivate) { 5149 auto *PC = cast<OMPFirstprivateClause>(Cl); 5150 I = PC->private_copies().begin(); 5151 It = PC->varlist_begin(); 5152 Et = PC->varlist_end(); 5153 } else if (Cl->getClauseKind() == OMPC_lastprivate) { 5154 auto *PC = cast<OMPLastprivateClause>(Cl); 5155 I = PC->private_copies().begin(); 5156 It = PC->varlist_begin(); 5157 Et = PC->varlist_end(); 5158 } else if (Cl->getClauseKind() == OMPC_linear) { 5159 auto *PC = cast<OMPLinearClause>(Cl); 5160 I = PC->privates().begin(); 5161 It = PC->varlist_begin(); 5162 Et = PC->varlist_end(); 5163 } else if (Cl->getClauseKind() == OMPC_reduction) { 5164 auto *PC = cast<OMPReductionClause>(Cl); 5165 I = PC->privates().begin(); 5166 It = PC->varlist_begin(); 5167 Et = PC->varlist_end(); 5168 } else if (Cl->getClauseKind() == OMPC_task_reduction) { 5169 auto *PC = cast<OMPTaskReductionClause>(Cl); 5170 I = PC->privates().begin(); 5171 It = PC->varlist_begin(); 5172 Et = PC->varlist_end(); 5173 } else if (Cl->getClauseKind() == OMPC_in_reduction) { 5174 auto *PC = cast<OMPInReductionClause>(Cl); 5175 I = PC->privates().begin(); 5176 It = PC->varlist_begin(); 5177 Et = PC->varlist_end(); 5178 } else { 5179 llvm_unreachable("Expected private clause."); 5180 } 5181 for (Expr *E : llvm::make_range(It, Et)) { 5182 if (!*I) { 5183 ++I; 5184 continue; 5185 } 5186 SourceLocation ELoc; 5187 SourceRange ERange; 5188 Expr *SimpleRefExpr = E; 5189 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 5190 /*AllowArraySection=*/true); 5191 DeclToCopy.try_emplace(Res.first, 5192 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl())); 5193 ++I; 5194 } 5195 } 5196 for (OMPClause *C : AllocateRange) { 5197 auto *AC = cast<OMPAllocateClause>(C); 5198 if (S.getLangOpts().OpenMP >= 50 && 5199 !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() && 5200 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 5201 AC->getAllocator()) { 5202 Expr *Allocator = AC->getAllocator(); 5203 // OpenMP, 2.12.5 target Construct 5204 // Memory allocators that do not appear in a uses_allocators clause cannot 5205 // appear as an allocator in an allocate clause or be used in the target 5206 // region unless a requires directive with the dynamic_allocators clause 5207 // is present in the same compilation unit. 5208 AllocatorChecker Checker(Stack); 5209 if (Checker.Visit(Allocator)) 5210 S.Diag(Allocator->getExprLoc(), 5211 diag::err_omp_allocator_not_in_uses_allocators) 5212 << Allocator->getSourceRange(); 5213 } 5214 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind = 5215 getAllocatorKind(S, Stack, AC->getAllocator()); 5216 // OpenMP, 2.11.4 allocate Clause, Restrictions. 5217 // For task, taskloop or target directives, allocation requests to memory 5218 // allocators with the trait access set to thread result in unspecified 5219 // behavior. 5220 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc && 5221 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 5222 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) { 5223 S.Diag(AC->getAllocator()->getExprLoc(), 5224 diag::warn_omp_allocate_thread_on_task_target_directive) 5225 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 5226 } 5227 for (Expr *E : AC->varlists()) { 5228 SourceLocation ELoc; 5229 SourceRange ERange; 5230 Expr *SimpleRefExpr = E; 5231 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange); 5232 ValueDecl *VD = Res.first; 5233 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false); 5234 if (!isOpenMPPrivate(Data.CKind)) { 5235 S.Diag(E->getExprLoc(), 5236 diag::err_omp_expected_private_copy_for_allocate); 5237 continue; 5238 } 5239 VarDecl *PrivateVD = DeclToCopy[VD]; 5240 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD, 5241 AllocatorKind, AC->getAllocator())) 5242 continue; 5243 // Placeholder until allocate clause supports align modifier. 5244 Expr *Alignment = nullptr; 5245 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(), 5246 Alignment, E->getSourceRange()); 5247 } 5248 } 5249 } 5250 5251 namespace { 5252 /// Rewrite statements and expressions for Sema \p Actions CurContext. 5253 /// 5254 /// Used to wrap already parsed statements/expressions into a new CapturedStmt 5255 /// context. DeclRefExpr used inside the new context are changed to refer to the 5256 /// captured variable instead. 5257 class CaptureVars : public TreeTransform<CaptureVars> { 5258 using BaseTransform = TreeTransform<CaptureVars>; 5259 5260 public: 5261 CaptureVars(Sema &Actions) : BaseTransform(Actions) {} 5262 5263 bool AlwaysRebuild() { return true; } 5264 }; 5265 } // namespace 5266 5267 static VarDecl *precomputeExpr(Sema &Actions, 5268 SmallVectorImpl<Stmt *> &BodyStmts, Expr *E, 5269 StringRef Name) { 5270 Expr *NewE = AssertSuccess(CaptureVars(Actions).TransformExpr(E)); 5271 VarDecl *NewVar = buildVarDecl(Actions, {}, NewE->getType(), Name, nullptr, 5272 dyn_cast<DeclRefExpr>(E->IgnoreImplicit())); 5273 auto *NewDeclStmt = cast<DeclStmt>(AssertSuccess( 5274 Actions.ActOnDeclStmt(Actions.ConvertDeclToDeclGroup(NewVar), {}, {}))); 5275 Actions.AddInitializerToDecl(NewDeclStmt->getSingleDecl(), NewE, false); 5276 BodyStmts.push_back(NewDeclStmt); 5277 return NewVar; 5278 } 5279 5280 /// Create a closure that computes the number of iterations of a loop. 5281 /// 5282 /// \param Actions The Sema object. 5283 /// \param LogicalTy Type for the logical iteration number. 5284 /// \param Rel Comparison operator of the loop condition. 5285 /// \param StartExpr Value of the loop counter at the first iteration. 5286 /// \param StopExpr Expression the loop counter is compared against in the loop 5287 /// condition. \param StepExpr Amount of increment after each iteration. 5288 /// 5289 /// \return Closure (CapturedStmt) of the distance calculation. 5290 static CapturedStmt *buildDistanceFunc(Sema &Actions, QualType LogicalTy, 5291 BinaryOperator::Opcode Rel, 5292 Expr *StartExpr, Expr *StopExpr, 5293 Expr *StepExpr) { 5294 ASTContext &Ctx = Actions.getASTContext(); 5295 TypeSourceInfo *LogicalTSI = Ctx.getTrivialTypeSourceInfo(LogicalTy); 5296 5297 // Captured regions currently don't support return values, we use an 5298 // out-parameter instead. All inputs are implicit captures. 5299 // TODO: Instead of capturing each DeclRefExpr occurring in 5300 // StartExpr/StopExpr/Step, these could also be passed as a value capture. 5301 QualType ResultTy = Ctx.getLValueReferenceType(LogicalTy); 5302 Sema::CapturedParamNameType Params[] = {{"Distance", ResultTy}, 5303 {StringRef(), QualType()}}; 5304 Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params); 5305 5306 Stmt *Body; 5307 { 5308 Sema::CompoundScopeRAII CompoundScope(Actions); 5309 CapturedDecl *CS = cast<CapturedDecl>(Actions.CurContext); 5310 5311 // Get the LValue expression for the result. 5312 ImplicitParamDecl *DistParam = CS->getParam(0); 5313 DeclRefExpr *DistRef = Actions.BuildDeclRefExpr( 5314 DistParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr); 5315 5316 SmallVector<Stmt *, 4> BodyStmts; 5317 5318 // Capture all referenced variable references. 5319 // TODO: Instead of computing NewStart/NewStop/NewStep inside the 5320 // CapturedStmt, we could compute them before and capture the result, to be 5321 // used jointly with the LoopVar function. 5322 VarDecl *NewStart = precomputeExpr(Actions, BodyStmts, StartExpr, ".start"); 5323 VarDecl *NewStop = precomputeExpr(Actions, BodyStmts, StopExpr, ".stop"); 5324 VarDecl *NewStep = precomputeExpr(Actions, BodyStmts, StepExpr, ".step"); 5325 auto BuildVarRef = [&](VarDecl *VD) { 5326 return buildDeclRefExpr(Actions, VD, VD->getType(), {}); 5327 }; 5328 5329 IntegerLiteral *Zero = IntegerLiteral::Create( 5330 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 0), LogicalTy, {}); 5331 IntegerLiteral *One = IntegerLiteral::Create( 5332 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {}); 5333 Expr *Dist; 5334 if (Rel == BO_NE) { 5335 // When using a != comparison, the increment can be +1 or -1. This can be 5336 // dynamic at runtime, so we need to check for the direction. 5337 Expr *IsNegStep = AssertSuccess( 5338 Actions.BuildBinOp(nullptr, {}, BO_LT, BuildVarRef(NewStep), Zero)); 5339 5340 // Positive increment. 5341 Expr *ForwardRange = AssertSuccess(Actions.BuildBinOp( 5342 nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart))); 5343 ForwardRange = AssertSuccess( 5344 Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, ForwardRange)); 5345 Expr *ForwardDist = AssertSuccess(Actions.BuildBinOp( 5346 nullptr, {}, BO_Div, ForwardRange, BuildVarRef(NewStep))); 5347 5348 // Negative increment. 5349 Expr *BackwardRange = AssertSuccess(Actions.BuildBinOp( 5350 nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop))); 5351 BackwardRange = AssertSuccess( 5352 Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, BackwardRange)); 5353 Expr *NegIncAmount = AssertSuccess( 5354 Actions.BuildUnaryOp(nullptr, {}, UO_Minus, BuildVarRef(NewStep))); 5355 Expr *BackwardDist = AssertSuccess( 5356 Actions.BuildBinOp(nullptr, {}, BO_Div, BackwardRange, NegIncAmount)); 5357 5358 // Use the appropriate case. 5359 Dist = AssertSuccess(Actions.ActOnConditionalOp( 5360 {}, {}, IsNegStep, BackwardDist, ForwardDist)); 5361 } else { 5362 assert((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) && 5363 "Expected one of these relational operators"); 5364 5365 // We can derive the direction from any other comparison operator. It is 5366 // non well-formed OpenMP if Step increments/decrements in the other 5367 // directions. Whether at least the first iteration passes the loop 5368 // condition. 5369 Expr *HasAnyIteration = AssertSuccess(Actions.BuildBinOp( 5370 nullptr, {}, Rel, BuildVarRef(NewStart), BuildVarRef(NewStop))); 5371 5372 // Compute the range between first and last counter value. 5373 Expr *Range; 5374 if (Rel == BO_GE || Rel == BO_GT) 5375 Range = AssertSuccess(Actions.BuildBinOp( 5376 nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop))); 5377 else 5378 Range = AssertSuccess(Actions.BuildBinOp( 5379 nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart))); 5380 5381 // Ensure unsigned range space. 5382 Range = 5383 AssertSuccess(Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, Range)); 5384 5385 if (Rel == BO_LE || Rel == BO_GE) { 5386 // Add one to the range if the relational operator is inclusive. 5387 Range = 5388 AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, Range, One)); 5389 } 5390 5391 // Divide by the absolute step amount. If the range is not a multiple of 5392 // the step size, rounding-up the effective upper bound ensures that the 5393 // last iteration is included. 5394 // Note that the rounding-up may cause an overflow in a temporry that 5395 // could be avoided, but would have occurred in a C-style for-loop as well. 5396 Expr *Divisor = BuildVarRef(NewStep); 5397 if (Rel == BO_GE || Rel == BO_GT) 5398 Divisor = 5399 AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Minus, Divisor)); 5400 Expr *DivisorMinusOne = 5401 AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Sub, Divisor, One)); 5402 Expr *RangeRoundUp = AssertSuccess( 5403 Actions.BuildBinOp(nullptr, {}, BO_Add, Range, DivisorMinusOne)); 5404 Dist = AssertSuccess( 5405 Actions.BuildBinOp(nullptr, {}, BO_Div, RangeRoundUp, Divisor)); 5406 5407 // If there is not at least one iteration, the range contains garbage. Fix 5408 // to zero in this case. 5409 Dist = AssertSuccess( 5410 Actions.ActOnConditionalOp({}, {}, HasAnyIteration, Dist, Zero)); 5411 } 5412 5413 // Assign the result to the out-parameter. 5414 Stmt *ResultAssign = AssertSuccess(Actions.BuildBinOp( 5415 Actions.getCurScope(), {}, BO_Assign, DistRef, Dist)); 5416 BodyStmts.push_back(ResultAssign); 5417 5418 Body = AssertSuccess(Actions.ActOnCompoundStmt({}, {}, BodyStmts, false)); 5419 } 5420 5421 return cast<CapturedStmt>( 5422 AssertSuccess(Actions.ActOnCapturedRegionEnd(Body))); 5423 } 5424 5425 /// Create a closure that computes the loop variable from the logical iteration 5426 /// number. 5427 /// 5428 /// \param Actions The Sema object. 5429 /// \param LoopVarTy Type for the loop variable used for result value. 5430 /// \param LogicalTy Type for the logical iteration number. 5431 /// \param StartExpr Value of the loop counter at the first iteration. 5432 /// \param Step Amount of increment after each iteration. 5433 /// \param Deref Whether the loop variable is a dereference of the loop 5434 /// counter variable. 5435 /// 5436 /// \return Closure (CapturedStmt) of the loop value calculation. 5437 static CapturedStmt *buildLoopVarFunc(Sema &Actions, QualType LoopVarTy, 5438 QualType LogicalTy, 5439 DeclRefExpr *StartExpr, Expr *Step, 5440 bool Deref) { 5441 ASTContext &Ctx = Actions.getASTContext(); 5442 5443 // Pass the result as an out-parameter. Passing as return value would require 5444 // the OpenMPIRBuilder to know additional C/C++ semantics, such as how to 5445 // invoke a copy constructor. 5446 QualType TargetParamTy = Ctx.getLValueReferenceType(LoopVarTy); 5447 Sema::CapturedParamNameType Params[] = {{"LoopVar", TargetParamTy}, 5448 {"Logical", LogicalTy}, 5449 {StringRef(), QualType()}}; 5450 Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params); 5451 5452 // Capture the initial iterator which represents the LoopVar value at the 5453 // zero's logical iteration. Since the original ForStmt/CXXForRangeStmt update 5454 // it in every iteration, capture it by value before it is modified. 5455 VarDecl *StartVar = cast<VarDecl>(StartExpr->getDecl()); 5456 bool Invalid = Actions.tryCaptureVariable(StartVar, {}, 5457 Sema::TryCapture_ExplicitByVal, {}); 5458 (void)Invalid; 5459 assert(!Invalid && "Expecting capture-by-value to work."); 5460 5461 Expr *Body; 5462 { 5463 Sema::CompoundScopeRAII CompoundScope(Actions); 5464 auto *CS = cast<CapturedDecl>(Actions.CurContext); 5465 5466 ImplicitParamDecl *TargetParam = CS->getParam(0); 5467 DeclRefExpr *TargetRef = Actions.BuildDeclRefExpr( 5468 TargetParam, LoopVarTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr); 5469 ImplicitParamDecl *IndvarParam = CS->getParam(1); 5470 DeclRefExpr *LogicalRef = Actions.BuildDeclRefExpr( 5471 IndvarParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr); 5472 5473 // Capture the Start expression. 5474 CaptureVars Recap(Actions); 5475 Expr *NewStart = AssertSuccess(Recap.TransformExpr(StartExpr)); 5476 Expr *NewStep = AssertSuccess(Recap.TransformExpr(Step)); 5477 5478 Expr *Skip = AssertSuccess( 5479 Actions.BuildBinOp(nullptr, {}, BO_Mul, NewStep, LogicalRef)); 5480 // TODO: Explicitly cast to the iterator's difference_type instead of 5481 // relying on implicit conversion. 5482 Expr *Advanced = 5483 AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, NewStart, Skip)); 5484 5485 if (Deref) { 5486 // For range-based for-loops convert the loop counter value to a concrete 5487 // loop variable value by dereferencing the iterator. 5488 Advanced = 5489 AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Deref, Advanced)); 5490 } 5491 5492 // Assign the result to the output parameter. 5493 Body = AssertSuccess(Actions.BuildBinOp(Actions.getCurScope(), {}, 5494 BO_Assign, TargetRef, Advanced)); 5495 } 5496 return cast<CapturedStmt>( 5497 AssertSuccess(Actions.ActOnCapturedRegionEnd(Body))); 5498 } 5499 5500 StmtResult Sema::ActOnOpenMPCanonicalLoop(Stmt *AStmt) { 5501 ASTContext &Ctx = getASTContext(); 5502 5503 // Extract the common elements of ForStmt and CXXForRangeStmt: 5504 // Loop variable, repeat condition, increment 5505 Expr *Cond, *Inc; 5506 VarDecl *LIVDecl, *LUVDecl; 5507 if (auto *For = dyn_cast<ForStmt>(AStmt)) { 5508 Stmt *Init = For->getInit(); 5509 if (auto *LCVarDeclStmt = dyn_cast<DeclStmt>(Init)) { 5510 // For statement declares loop variable. 5511 LIVDecl = cast<VarDecl>(LCVarDeclStmt->getSingleDecl()); 5512 } else if (auto *LCAssign = dyn_cast<BinaryOperator>(Init)) { 5513 // For statement reuses variable. 5514 assert(LCAssign->getOpcode() == BO_Assign && 5515 "init part must be a loop variable assignment"); 5516 auto *CounterRef = cast<DeclRefExpr>(LCAssign->getLHS()); 5517 LIVDecl = cast<VarDecl>(CounterRef->getDecl()); 5518 } else 5519 llvm_unreachable("Cannot determine loop variable"); 5520 LUVDecl = LIVDecl; 5521 5522 Cond = For->getCond(); 5523 Inc = For->getInc(); 5524 } else if (auto *RangeFor = dyn_cast<CXXForRangeStmt>(AStmt)) { 5525 DeclStmt *BeginStmt = RangeFor->getBeginStmt(); 5526 LIVDecl = cast<VarDecl>(BeginStmt->getSingleDecl()); 5527 LUVDecl = RangeFor->getLoopVariable(); 5528 5529 Cond = RangeFor->getCond(); 5530 Inc = RangeFor->getInc(); 5531 } else 5532 llvm_unreachable("unhandled kind of loop"); 5533 5534 QualType CounterTy = LIVDecl->getType(); 5535 QualType LVTy = LUVDecl->getType(); 5536 5537 // Analyze the loop condition. 5538 Expr *LHS, *RHS; 5539 BinaryOperator::Opcode CondRel; 5540 Cond = Cond->IgnoreImplicit(); 5541 if (auto *CondBinExpr = dyn_cast<BinaryOperator>(Cond)) { 5542 LHS = CondBinExpr->getLHS(); 5543 RHS = CondBinExpr->getRHS(); 5544 CondRel = CondBinExpr->getOpcode(); 5545 } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Cond)) { 5546 assert(CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands"); 5547 LHS = CondCXXOp->getArg(0); 5548 RHS = CondCXXOp->getArg(1); 5549 switch (CondCXXOp->getOperator()) { 5550 case OO_ExclaimEqual: 5551 CondRel = BO_NE; 5552 break; 5553 case OO_Less: 5554 CondRel = BO_LT; 5555 break; 5556 case OO_LessEqual: 5557 CondRel = BO_LE; 5558 break; 5559 case OO_Greater: 5560 CondRel = BO_GT; 5561 break; 5562 case OO_GreaterEqual: 5563 CondRel = BO_GE; 5564 break; 5565 default: 5566 llvm_unreachable("unexpected iterator operator"); 5567 } 5568 } else 5569 llvm_unreachable("unexpected loop condition"); 5570 5571 // Normalize such that the loop counter is on the LHS. 5572 if (!isa<DeclRefExpr>(LHS->IgnoreImplicit()) || 5573 cast<DeclRefExpr>(LHS->IgnoreImplicit())->getDecl() != LIVDecl) { 5574 std::swap(LHS, RHS); 5575 CondRel = BinaryOperator::reverseComparisonOp(CondRel); 5576 } 5577 auto *CounterRef = cast<DeclRefExpr>(LHS->IgnoreImplicit()); 5578 5579 // Decide the bit width for the logical iteration counter. By default use the 5580 // unsigned ptrdiff_t integer size (for iterators and pointers). 5581 // TODO: For iterators, use iterator::difference_type, 5582 // std::iterator_traits<>::difference_type or decltype(it - end). 5583 QualType LogicalTy = Ctx.getUnsignedPointerDiffType(); 5584 if (CounterTy->isIntegerType()) { 5585 unsigned BitWidth = Ctx.getIntWidth(CounterTy); 5586 LogicalTy = Ctx.getIntTypeForBitwidth(BitWidth, false); 5587 } 5588 5589 // Analyze the loop increment. 5590 Expr *Step; 5591 if (auto *IncUn = dyn_cast<UnaryOperator>(Inc)) { 5592 int Direction; 5593 switch (IncUn->getOpcode()) { 5594 case UO_PreInc: 5595 case UO_PostInc: 5596 Direction = 1; 5597 break; 5598 case UO_PreDec: 5599 case UO_PostDec: 5600 Direction = -1; 5601 break; 5602 default: 5603 llvm_unreachable("unhandled unary increment operator"); 5604 } 5605 Step = IntegerLiteral::Create( 5606 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), Direction), LogicalTy, {}); 5607 } else if (auto *IncBin = dyn_cast<BinaryOperator>(Inc)) { 5608 if (IncBin->getOpcode() == BO_AddAssign) { 5609 Step = IncBin->getRHS(); 5610 } else if (IncBin->getOpcode() == BO_SubAssign) { 5611 Step = 5612 AssertSuccess(BuildUnaryOp(nullptr, {}, UO_Minus, IncBin->getRHS())); 5613 } else 5614 llvm_unreachable("unhandled binary increment operator"); 5615 } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Inc)) { 5616 switch (CondCXXOp->getOperator()) { 5617 case OO_PlusPlus: 5618 Step = IntegerLiteral::Create( 5619 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {}); 5620 break; 5621 case OO_MinusMinus: 5622 Step = IntegerLiteral::Create( 5623 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), -1), LogicalTy, {}); 5624 break; 5625 case OO_PlusEqual: 5626 Step = CondCXXOp->getArg(1); 5627 break; 5628 case OO_MinusEqual: 5629 Step = AssertSuccess( 5630 BuildUnaryOp(nullptr, {}, UO_Minus, CondCXXOp->getArg(1))); 5631 break; 5632 default: 5633 llvm_unreachable("unhandled overloaded increment operator"); 5634 } 5635 } else 5636 llvm_unreachable("unknown increment expression"); 5637 5638 CapturedStmt *DistanceFunc = 5639 buildDistanceFunc(*this, LogicalTy, CondRel, LHS, RHS, Step); 5640 CapturedStmt *LoopVarFunc = buildLoopVarFunc( 5641 *this, LVTy, LogicalTy, CounterRef, Step, isa<CXXForRangeStmt>(AStmt)); 5642 DeclRefExpr *LVRef = BuildDeclRefExpr(LUVDecl, LUVDecl->getType(), VK_LValue, 5643 {}, nullptr, nullptr, {}, nullptr); 5644 return OMPCanonicalLoop::create(getASTContext(), AStmt, DistanceFunc, 5645 LoopVarFunc, LVRef); 5646 } 5647 5648 StmtResult Sema::ActOnOpenMPLoopnest(Stmt *AStmt) { 5649 // Handle a literal loop. 5650 if (isa<ForStmt>(AStmt) || isa<CXXForRangeStmt>(AStmt)) 5651 return ActOnOpenMPCanonicalLoop(AStmt); 5652 5653 // If not a literal loop, it must be the result of a loop transformation. 5654 OMPExecutableDirective *LoopTransform = cast<OMPExecutableDirective>(AStmt); 5655 assert( 5656 isOpenMPLoopTransformationDirective(LoopTransform->getDirectiveKind()) && 5657 "Loop transformation directive expected"); 5658 return LoopTransform; 5659 } 5660 5661 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S, 5662 CXXScopeSpec &MapperIdScopeSpec, 5663 const DeclarationNameInfo &MapperId, 5664 QualType Type, 5665 Expr *UnresolvedMapper); 5666 5667 /// Perform DFS through the structure/class data members trying to find 5668 /// member(s) with user-defined 'default' mapper and generate implicit map 5669 /// clauses for such members with the found 'default' mapper. 5670 static void 5671 processImplicitMapsWithDefaultMappers(Sema &S, DSAStackTy *Stack, 5672 SmallVectorImpl<OMPClause *> &Clauses) { 5673 // Check for the deault mapper for data members. 5674 if (S.getLangOpts().OpenMP < 50) 5675 return; 5676 SmallVector<OMPClause *, 4> ImplicitMaps; 5677 for (int Cnt = 0, EndCnt = Clauses.size(); Cnt < EndCnt; ++Cnt) { 5678 auto *C = dyn_cast<OMPMapClause>(Clauses[Cnt]); 5679 if (!C) 5680 continue; 5681 SmallVector<Expr *, 4> SubExprs; 5682 auto *MI = C->mapperlist_begin(); 5683 for (auto I = C->varlist_begin(), End = C->varlist_end(); I != End; 5684 ++I, ++MI) { 5685 // Expression is mapped using mapper - skip it. 5686 if (*MI) 5687 continue; 5688 Expr *E = *I; 5689 // Expression is dependent - skip it, build the mapper when it gets 5690 // instantiated. 5691 if (E->isTypeDependent() || E->isValueDependent() || 5692 E->containsUnexpandedParameterPack()) 5693 continue; 5694 // Array section - need to check for the mapping of the array section 5695 // element. 5696 QualType CanonType = E->getType().getCanonicalType(); 5697 if (CanonType->isSpecificBuiltinType(BuiltinType::OMPArraySection)) { 5698 const auto *OASE = cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts()); 5699 QualType BaseType = 5700 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 5701 QualType ElemType; 5702 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 5703 ElemType = ATy->getElementType(); 5704 else 5705 ElemType = BaseType->getPointeeType(); 5706 CanonType = ElemType; 5707 } 5708 5709 // DFS over data members in structures/classes. 5710 SmallVector<std::pair<QualType, FieldDecl *>, 4> Types( 5711 1, {CanonType, nullptr}); 5712 llvm::DenseMap<const Type *, Expr *> Visited; 5713 SmallVector<std::pair<FieldDecl *, unsigned>, 4> ParentChain( 5714 1, {nullptr, 1}); 5715 while (!Types.empty()) { 5716 QualType BaseType; 5717 FieldDecl *CurFD; 5718 std::tie(BaseType, CurFD) = Types.pop_back_val(); 5719 while (ParentChain.back().second == 0) 5720 ParentChain.pop_back(); 5721 --ParentChain.back().second; 5722 if (BaseType.isNull()) 5723 continue; 5724 // Only structs/classes are allowed to have mappers. 5725 const RecordDecl *RD = BaseType.getCanonicalType()->getAsRecordDecl(); 5726 if (!RD) 5727 continue; 5728 auto It = Visited.find(BaseType.getTypePtr()); 5729 if (It == Visited.end()) { 5730 // Try to find the associated user-defined mapper. 5731 CXXScopeSpec MapperIdScopeSpec; 5732 DeclarationNameInfo DefaultMapperId; 5733 DefaultMapperId.setName(S.Context.DeclarationNames.getIdentifier( 5734 &S.Context.Idents.get("default"))); 5735 DefaultMapperId.setLoc(E->getExprLoc()); 5736 ExprResult ER = buildUserDefinedMapperRef( 5737 S, Stack->getCurScope(), MapperIdScopeSpec, DefaultMapperId, 5738 BaseType, /*UnresolvedMapper=*/nullptr); 5739 if (ER.isInvalid()) 5740 continue; 5741 It = Visited.try_emplace(BaseType.getTypePtr(), ER.get()).first; 5742 } 5743 // Found default mapper. 5744 if (It->second) { 5745 auto *OE = new (S.Context) OpaqueValueExpr(E->getExprLoc(), CanonType, 5746 VK_LValue, OK_Ordinary, E); 5747 OE->setIsUnique(/*V=*/true); 5748 Expr *BaseExpr = OE; 5749 for (const auto &P : ParentChain) { 5750 if (P.first) { 5751 BaseExpr = S.BuildMemberExpr( 5752 BaseExpr, /*IsArrow=*/false, E->getExprLoc(), 5753 NestedNameSpecifierLoc(), SourceLocation(), P.first, 5754 DeclAccessPair::make(P.first, P.first->getAccess()), 5755 /*HadMultipleCandidates=*/false, DeclarationNameInfo(), 5756 P.first->getType(), VK_LValue, OK_Ordinary); 5757 BaseExpr = S.DefaultLvalueConversion(BaseExpr).get(); 5758 } 5759 } 5760 if (CurFD) 5761 BaseExpr = S.BuildMemberExpr( 5762 BaseExpr, /*IsArrow=*/false, E->getExprLoc(), 5763 NestedNameSpecifierLoc(), SourceLocation(), CurFD, 5764 DeclAccessPair::make(CurFD, CurFD->getAccess()), 5765 /*HadMultipleCandidates=*/false, DeclarationNameInfo(), 5766 CurFD->getType(), VK_LValue, OK_Ordinary); 5767 SubExprs.push_back(BaseExpr); 5768 continue; 5769 } 5770 // Check for the "default" mapper for data members. 5771 bool FirstIter = true; 5772 for (FieldDecl *FD : RD->fields()) { 5773 if (!FD) 5774 continue; 5775 QualType FieldTy = FD->getType(); 5776 if (FieldTy.isNull() || 5777 !(FieldTy->isStructureOrClassType() || FieldTy->isUnionType())) 5778 continue; 5779 if (FirstIter) { 5780 FirstIter = false; 5781 ParentChain.emplace_back(CurFD, 1); 5782 } else { 5783 ++ParentChain.back().second; 5784 } 5785 Types.emplace_back(FieldTy, FD); 5786 } 5787 } 5788 } 5789 if (SubExprs.empty()) 5790 continue; 5791 CXXScopeSpec MapperIdScopeSpec; 5792 DeclarationNameInfo MapperId; 5793 if (OMPClause *NewClause = S.ActOnOpenMPMapClause( 5794 C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), 5795 MapperIdScopeSpec, MapperId, C->getMapType(), 5796 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(), 5797 SubExprs, OMPVarListLocTy())) 5798 Clauses.push_back(NewClause); 5799 } 5800 } 5801 5802 StmtResult Sema::ActOnOpenMPExecutableDirective( 5803 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 5804 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 5805 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 5806 StmtResult Res = StmtError(); 5807 OpenMPBindClauseKind BindKind = OMPC_BIND_unknown; 5808 if (const OMPBindClause *BC = 5809 OMPExecutableDirective::getSingleClause<OMPBindClause>(Clauses)) 5810 BindKind = BC->getBindKind(); 5811 // First check CancelRegion which is then used in checkNestingOfRegions. 5812 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 5813 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 5814 BindKind, StartLoc)) 5815 return StmtError(); 5816 5817 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 5818 VarsWithInheritedDSAType VarsWithInheritedDSA; 5819 bool ErrorFound = false; 5820 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 5821 if (AStmt && !CurContext->isDependentContext() && Kind != OMPD_atomic && 5822 Kind != OMPD_critical && Kind != OMPD_section && Kind != OMPD_master && 5823 Kind != OMPD_masked && !isOpenMPLoopTransformationDirective(Kind)) { 5824 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5825 5826 // Check default data sharing attributes for referenced variables. 5827 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 5828 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 5829 Stmt *S = AStmt; 5830 while (--ThisCaptureLevel >= 0) 5831 S = cast<CapturedStmt>(S)->getCapturedStmt(); 5832 DSAChecker.Visit(S); 5833 if (!isOpenMPTargetDataManagementDirective(Kind) && 5834 !isOpenMPTaskingDirective(Kind)) { 5835 // Visit subcaptures to generate implicit clauses for captured vars. 5836 auto *CS = cast<CapturedStmt>(AStmt); 5837 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 5838 getOpenMPCaptureRegions(CaptureRegions, Kind); 5839 // Ignore outer tasking regions for target directives. 5840 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task) 5841 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 5842 DSAChecker.visitSubCaptures(CS); 5843 } 5844 if (DSAChecker.isErrorFound()) 5845 return StmtError(); 5846 // Generate list of implicitly defined firstprivate variables. 5847 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 5848 5849 SmallVector<Expr *, 4> ImplicitFirstprivates( 5850 DSAChecker.getImplicitFirstprivate().begin(), 5851 DSAChecker.getImplicitFirstprivate().end()); 5852 const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1; 5853 SmallVector<Expr *, 4> ImplicitMaps[DefaultmapKindNum][OMPC_MAP_delete]; 5854 SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> 5855 ImplicitMapModifiers[DefaultmapKindNum]; 5856 SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers> 5857 ImplicitMapModifiersLoc[DefaultmapKindNum]; 5858 // Get the original location of present modifier from Defaultmap clause. 5859 SourceLocation PresentModifierLocs[DefaultmapKindNum]; 5860 for (OMPClause *C : Clauses) { 5861 if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C)) 5862 if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present) 5863 PresentModifierLocs[DMC->getDefaultmapKind()] = 5864 DMC->getDefaultmapModifierLoc(); 5865 } 5866 for (unsigned VC = 0; VC < DefaultmapKindNum; ++VC) { 5867 auto Kind = static_cast<OpenMPDefaultmapClauseKind>(VC); 5868 for (unsigned I = 0; I < OMPC_MAP_delete; ++I) { 5869 ArrayRef<Expr *> ImplicitMap = DSAChecker.getImplicitMap( 5870 Kind, static_cast<OpenMPMapClauseKind>(I)); 5871 ImplicitMaps[VC][I].append(ImplicitMap.begin(), ImplicitMap.end()); 5872 } 5873 ArrayRef<OpenMPMapModifierKind> ImplicitModifier = 5874 DSAChecker.getImplicitMapModifier(Kind); 5875 ImplicitMapModifiers[VC].append(ImplicitModifier.begin(), 5876 ImplicitModifier.end()); 5877 std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[VC]), 5878 ImplicitModifier.size(), PresentModifierLocs[VC]); 5879 } 5880 // Mark taskgroup task_reduction descriptors as implicitly firstprivate. 5881 for (OMPClause *C : Clauses) { 5882 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) { 5883 for (Expr *E : IRC->taskgroup_descriptors()) 5884 if (E) 5885 ImplicitFirstprivates.emplace_back(E); 5886 } 5887 // OpenMP 5.0, 2.10.1 task Construct 5888 // [detach clause]... The event-handle will be considered as if it was 5889 // specified on a firstprivate clause. 5890 if (auto *DC = dyn_cast<OMPDetachClause>(C)) 5891 ImplicitFirstprivates.push_back(DC->getEventHandler()); 5892 } 5893 if (!ImplicitFirstprivates.empty()) { 5894 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 5895 ImplicitFirstprivates, SourceLocation(), SourceLocation(), 5896 SourceLocation())) { 5897 ClausesWithImplicit.push_back(Implicit); 5898 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 5899 ImplicitFirstprivates.size(); 5900 } else { 5901 ErrorFound = true; 5902 } 5903 } 5904 // OpenMP 5.0 [2.19.7] 5905 // If a list item appears in a reduction, lastprivate or linear 5906 // clause on a combined target construct then it is treated as 5907 // if it also appears in a map clause with a map-type of tofrom 5908 if (getLangOpts().OpenMP >= 50 && Kind != OMPD_target && 5909 isOpenMPTargetExecutionDirective(Kind)) { 5910 SmallVector<Expr *, 4> ImplicitExprs; 5911 for (OMPClause *C : Clauses) { 5912 if (auto *RC = dyn_cast<OMPReductionClause>(C)) 5913 for (Expr *E : RC->varlists()) 5914 if (!isa<DeclRefExpr>(E->IgnoreParenImpCasts())) 5915 ImplicitExprs.emplace_back(E); 5916 } 5917 if (!ImplicitExprs.empty()) { 5918 ArrayRef<Expr *> Exprs = ImplicitExprs; 5919 CXXScopeSpec MapperIdScopeSpec; 5920 DeclarationNameInfo MapperId; 5921 if (OMPClause *Implicit = ActOnOpenMPMapClause( 5922 OMPC_MAP_MODIFIER_unknown, SourceLocation(), MapperIdScopeSpec, 5923 MapperId, OMPC_MAP_tofrom, 5924 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(), 5925 Exprs, OMPVarListLocTy(), /*NoDiagnose=*/true)) 5926 ClausesWithImplicit.emplace_back(Implicit); 5927 } 5928 } 5929 for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) { 5930 int ClauseKindCnt = -1; 5931 for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) { 5932 ++ClauseKindCnt; 5933 if (ImplicitMap.empty()) 5934 continue; 5935 CXXScopeSpec MapperIdScopeSpec; 5936 DeclarationNameInfo MapperId; 5937 auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt); 5938 if (OMPClause *Implicit = ActOnOpenMPMapClause( 5939 ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I], 5940 MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true, 5941 SourceLocation(), SourceLocation(), ImplicitMap, 5942 OMPVarListLocTy())) { 5943 ClausesWithImplicit.emplace_back(Implicit); 5944 ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() != 5945 ImplicitMap.size(); 5946 } else { 5947 ErrorFound = true; 5948 } 5949 } 5950 } 5951 // Build expressions for implicit maps of data members with 'default' 5952 // mappers. 5953 if (LangOpts.OpenMP >= 50) 5954 processImplicitMapsWithDefaultMappers(*this, DSAStack, 5955 ClausesWithImplicit); 5956 } 5957 5958 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 5959 switch (Kind) { 5960 case OMPD_parallel: 5961 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 5962 EndLoc); 5963 AllowedNameModifiers.push_back(OMPD_parallel); 5964 break; 5965 case OMPD_simd: 5966 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 5967 VarsWithInheritedDSA); 5968 if (LangOpts.OpenMP >= 50) 5969 AllowedNameModifiers.push_back(OMPD_simd); 5970 break; 5971 case OMPD_tile: 5972 Res = 5973 ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 5974 break; 5975 case OMPD_unroll: 5976 Res = ActOnOpenMPUnrollDirective(ClausesWithImplicit, AStmt, StartLoc, 5977 EndLoc); 5978 break; 5979 case OMPD_for: 5980 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 5981 VarsWithInheritedDSA); 5982 break; 5983 case OMPD_for_simd: 5984 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 5985 EndLoc, VarsWithInheritedDSA); 5986 if (LangOpts.OpenMP >= 50) 5987 AllowedNameModifiers.push_back(OMPD_simd); 5988 break; 5989 case OMPD_sections: 5990 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 5991 EndLoc); 5992 break; 5993 case OMPD_section: 5994 assert(ClausesWithImplicit.empty() && 5995 "No clauses are allowed for 'omp section' directive"); 5996 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 5997 break; 5998 case OMPD_single: 5999 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 6000 EndLoc); 6001 break; 6002 case OMPD_master: 6003 assert(ClausesWithImplicit.empty() && 6004 "No clauses are allowed for 'omp master' directive"); 6005 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 6006 break; 6007 case OMPD_masked: 6008 Res = ActOnOpenMPMaskedDirective(ClausesWithImplicit, AStmt, StartLoc, 6009 EndLoc); 6010 break; 6011 case OMPD_critical: 6012 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 6013 StartLoc, EndLoc); 6014 break; 6015 case OMPD_parallel_for: 6016 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 6017 EndLoc, VarsWithInheritedDSA); 6018 AllowedNameModifiers.push_back(OMPD_parallel); 6019 break; 6020 case OMPD_parallel_for_simd: 6021 Res = ActOnOpenMPParallelForSimdDirective( 6022 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6023 AllowedNameModifiers.push_back(OMPD_parallel); 6024 if (LangOpts.OpenMP >= 50) 6025 AllowedNameModifiers.push_back(OMPD_simd); 6026 break; 6027 case OMPD_parallel_master: 6028 Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt, 6029 StartLoc, EndLoc); 6030 AllowedNameModifiers.push_back(OMPD_parallel); 6031 break; 6032 case OMPD_parallel_sections: 6033 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 6034 StartLoc, EndLoc); 6035 AllowedNameModifiers.push_back(OMPD_parallel); 6036 break; 6037 case OMPD_task: 6038 Res = 6039 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 6040 AllowedNameModifiers.push_back(OMPD_task); 6041 break; 6042 case OMPD_taskyield: 6043 assert(ClausesWithImplicit.empty() && 6044 "No clauses are allowed for 'omp taskyield' directive"); 6045 assert(AStmt == nullptr && 6046 "No associated statement allowed for 'omp taskyield' directive"); 6047 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 6048 break; 6049 case OMPD_barrier: 6050 assert(ClausesWithImplicit.empty() && 6051 "No clauses are allowed for 'omp barrier' directive"); 6052 assert(AStmt == nullptr && 6053 "No associated statement allowed for 'omp barrier' directive"); 6054 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 6055 break; 6056 case OMPD_taskwait: 6057 assert(AStmt == nullptr && 6058 "No associated statement allowed for 'omp taskwait' directive"); 6059 Res = ActOnOpenMPTaskwaitDirective(ClausesWithImplicit, StartLoc, EndLoc); 6060 break; 6061 case OMPD_taskgroup: 6062 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, 6063 EndLoc); 6064 break; 6065 case OMPD_flush: 6066 assert(AStmt == nullptr && 6067 "No associated statement allowed for 'omp flush' directive"); 6068 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 6069 break; 6070 case OMPD_depobj: 6071 assert(AStmt == nullptr && 6072 "No associated statement allowed for 'omp depobj' directive"); 6073 Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc); 6074 break; 6075 case OMPD_scan: 6076 assert(AStmt == nullptr && 6077 "No associated statement allowed for 'omp scan' directive"); 6078 Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc); 6079 break; 6080 case OMPD_ordered: 6081 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 6082 EndLoc); 6083 break; 6084 case OMPD_atomic: 6085 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 6086 EndLoc); 6087 break; 6088 case OMPD_teams: 6089 Res = 6090 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 6091 break; 6092 case OMPD_target: 6093 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 6094 EndLoc); 6095 AllowedNameModifiers.push_back(OMPD_target); 6096 break; 6097 case OMPD_target_parallel: 6098 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 6099 StartLoc, EndLoc); 6100 AllowedNameModifiers.push_back(OMPD_target); 6101 AllowedNameModifiers.push_back(OMPD_parallel); 6102 break; 6103 case OMPD_target_parallel_for: 6104 Res = ActOnOpenMPTargetParallelForDirective( 6105 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6106 AllowedNameModifiers.push_back(OMPD_target); 6107 AllowedNameModifiers.push_back(OMPD_parallel); 6108 break; 6109 case OMPD_cancellation_point: 6110 assert(ClausesWithImplicit.empty() && 6111 "No clauses are allowed for 'omp cancellation point' directive"); 6112 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 6113 "cancellation point' directive"); 6114 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 6115 break; 6116 case OMPD_cancel: 6117 assert(AStmt == nullptr && 6118 "No associated statement allowed for 'omp cancel' directive"); 6119 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 6120 CancelRegion); 6121 AllowedNameModifiers.push_back(OMPD_cancel); 6122 break; 6123 case OMPD_target_data: 6124 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 6125 EndLoc); 6126 AllowedNameModifiers.push_back(OMPD_target_data); 6127 break; 6128 case OMPD_target_enter_data: 6129 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 6130 EndLoc, AStmt); 6131 AllowedNameModifiers.push_back(OMPD_target_enter_data); 6132 break; 6133 case OMPD_target_exit_data: 6134 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 6135 EndLoc, AStmt); 6136 AllowedNameModifiers.push_back(OMPD_target_exit_data); 6137 break; 6138 case OMPD_taskloop: 6139 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 6140 EndLoc, VarsWithInheritedDSA); 6141 AllowedNameModifiers.push_back(OMPD_taskloop); 6142 break; 6143 case OMPD_taskloop_simd: 6144 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 6145 EndLoc, VarsWithInheritedDSA); 6146 AllowedNameModifiers.push_back(OMPD_taskloop); 6147 if (LangOpts.OpenMP >= 50) 6148 AllowedNameModifiers.push_back(OMPD_simd); 6149 break; 6150 case OMPD_master_taskloop: 6151 Res = ActOnOpenMPMasterTaskLoopDirective( 6152 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6153 AllowedNameModifiers.push_back(OMPD_taskloop); 6154 break; 6155 case OMPD_master_taskloop_simd: 6156 Res = ActOnOpenMPMasterTaskLoopSimdDirective( 6157 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6158 AllowedNameModifiers.push_back(OMPD_taskloop); 6159 if (LangOpts.OpenMP >= 50) 6160 AllowedNameModifiers.push_back(OMPD_simd); 6161 break; 6162 case OMPD_parallel_master_taskloop: 6163 Res = ActOnOpenMPParallelMasterTaskLoopDirective( 6164 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6165 AllowedNameModifiers.push_back(OMPD_taskloop); 6166 AllowedNameModifiers.push_back(OMPD_parallel); 6167 break; 6168 case OMPD_parallel_master_taskloop_simd: 6169 Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective( 6170 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6171 AllowedNameModifiers.push_back(OMPD_taskloop); 6172 AllowedNameModifiers.push_back(OMPD_parallel); 6173 if (LangOpts.OpenMP >= 50) 6174 AllowedNameModifiers.push_back(OMPD_simd); 6175 break; 6176 case OMPD_distribute: 6177 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 6178 EndLoc, VarsWithInheritedDSA); 6179 break; 6180 case OMPD_target_update: 6181 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, 6182 EndLoc, AStmt); 6183 AllowedNameModifiers.push_back(OMPD_target_update); 6184 break; 6185 case OMPD_distribute_parallel_for: 6186 Res = ActOnOpenMPDistributeParallelForDirective( 6187 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6188 AllowedNameModifiers.push_back(OMPD_parallel); 6189 break; 6190 case OMPD_distribute_parallel_for_simd: 6191 Res = ActOnOpenMPDistributeParallelForSimdDirective( 6192 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6193 AllowedNameModifiers.push_back(OMPD_parallel); 6194 if (LangOpts.OpenMP >= 50) 6195 AllowedNameModifiers.push_back(OMPD_simd); 6196 break; 6197 case OMPD_distribute_simd: 6198 Res = ActOnOpenMPDistributeSimdDirective( 6199 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6200 if (LangOpts.OpenMP >= 50) 6201 AllowedNameModifiers.push_back(OMPD_simd); 6202 break; 6203 case OMPD_target_parallel_for_simd: 6204 Res = ActOnOpenMPTargetParallelForSimdDirective( 6205 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6206 AllowedNameModifiers.push_back(OMPD_target); 6207 AllowedNameModifiers.push_back(OMPD_parallel); 6208 if (LangOpts.OpenMP >= 50) 6209 AllowedNameModifiers.push_back(OMPD_simd); 6210 break; 6211 case OMPD_target_simd: 6212 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 6213 EndLoc, VarsWithInheritedDSA); 6214 AllowedNameModifiers.push_back(OMPD_target); 6215 if (LangOpts.OpenMP >= 50) 6216 AllowedNameModifiers.push_back(OMPD_simd); 6217 break; 6218 case OMPD_teams_distribute: 6219 Res = ActOnOpenMPTeamsDistributeDirective( 6220 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6221 break; 6222 case OMPD_teams_distribute_simd: 6223 Res = ActOnOpenMPTeamsDistributeSimdDirective( 6224 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6225 if (LangOpts.OpenMP >= 50) 6226 AllowedNameModifiers.push_back(OMPD_simd); 6227 break; 6228 case OMPD_teams_distribute_parallel_for_simd: 6229 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 6230 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6231 AllowedNameModifiers.push_back(OMPD_parallel); 6232 if (LangOpts.OpenMP >= 50) 6233 AllowedNameModifiers.push_back(OMPD_simd); 6234 break; 6235 case OMPD_teams_distribute_parallel_for: 6236 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 6237 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6238 AllowedNameModifiers.push_back(OMPD_parallel); 6239 break; 6240 case OMPD_target_teams: 6241 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 6242 EndLoc); 6243 AllowedNameModifiers.push_back(OMPD_target); 6244 break; 6245 case OMPD_target_teams_distribute: 6246 Res = ActOnOpenMPTargetTeamsDistributeDirective( 6247 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6248 AllowedNameModifiers.push_back(OMPD_target); 6249 break; 6250 case OMPD_target_teams_distribute_parallel_for: 6251 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 6252 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6253 AllowedNameModifiers.push_back(OMPD_target); 6254 AllowedNameModifiers.push_back(OMPD_parallel); 6255 break; 6256 case OMPD_target_teams_distribute_parallel_for_simd: 6257 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 6258 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6259 AllowedNameModifiers.push_back(OMPD_target); 6260 AllowedNameModifiers.push_back(OMPD_parallel); 6261 if (LangOpts.OpenMP >= 50) 6262 AllowedNameModifiers.push_back(OMPD_simd); 6263 break; 6264 case OMPD_target_teams_distribute_simd: 6265 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 6266 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6267 AllowedNameModifiers.push_back(OMPD_target); 6268 if (LangOpts.OpenMP >= 50) 6269 AllowedNameModifiers.push_back(OMPD_simd); 6270 break; 6271 case OMPD_interop: 6272 assert(AStmt == nullptr && 6273 "No associated statement allowed for 'omp interop' directive"); 6274 Res = ActOnOpenMPInteropDirective(ClausesWithImplicit, StartLoc, EndLoc); 6275 break; 6276 case OMPD_dispatch: 6277 Res = ActOnOpenMPDispatchDirective(ClausesWithImplicit, AStmt, StartLoc, 6278 EndLoc); 6279 break; 6280 case OMPD_loop: 6281 Res = ActOnOpenMPGenericLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 6282 EndLoc, VarsWithInheritedDSA); 6283 break; 6284 case OMPD_declare_target: 6285 case OMPD_end_declare_target: 6286 case OMPD_threadprivate: 6287 case OMPD_allocate: 6288 case OMPD_declare_reduction: 6289 case OMPD_declare_mapper: 6290 case OMPD_declare_simd: 6291 case OMPD_requires: 6292 case OMPD_declare_variant: 6293 case OMPD_begin_declare_variant: 6294 case OMPD_end_declare_variant: 6295 llvm_unreachable("OpenMP Directive is not allowed"); 6296 case OMPD_unknown: 6297 default: 6298 llvm_unreachable("Unknown OpenMP directive"); 6299 } 6300 6301 ErrorFound = Res.isInvalid() || ErrorFound; 6302 6303 // Check variables in the clauses if default(none) or 6304 // default(firstprivate) was specified. 6305 if (DSAStack->getDefaultDSA() == DSA_none || 6306 DSAStack->getDefaultDSA() == DSA_firstprivate) { 6307 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr); 6308 for (OMPClause *C : Clauses) { 6309 switch (C->getClauseKind()) { 6310 case OMPC_num_threads: 6311 case OMPC_dist_schedule: 6312 // Do not analyse if no parent teams directive. 6313 if (isOpenMPTeamsDirective(Kind)) 6314 break; 6315 continue; 6316 case OMPC_if: 6317 if (isOpenMPTeamsDirective(Kind) && 6318 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target) 6319 break; 6320 if (isOpenMPParallelDirective(Kind) && 6321 isOpenMPTaskLoopDirective(Kind) && 6322 cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel) 6323 break; 6324 continue; 6325 case OMPC_schedule: 6326 case OMPC_detach: 6327 break; 6328 case OMPC_grainsize: 6329 case OMPC_num_tasks: 6330 case OMPC_final: 6331 case OMPC_priority: 6332 case OMPC_novariants: 6333 case OMPC_nocontext: 6334 // Do not analyze if no parent parallel directive. 6335 if (isOpenMPParallelDirective(Kind)) 6336 break; 6337 continue; 6338 case OMPC_ordered: 6339 case OMPC_device: 6340 case OMPC_num_teams: 6341 case OMPC_thread_limit: 6342 case OMPC_hint: 6343 case OMPC_collapse: 6344 case OMPC_safelen: 6345 case OMPC_simdlen: 6346 case OMPC_sizes: 6347 case OMPC_default: 6348 case OMPC_proc_bind: 6349 case OMPC_private: 6350 case OMPC_firstprivate: 6351 case OMPC_lastprivate: 6352 case OMPC_shared: 6353 case OMPC_reduction: 6354 case OMPC_task_reduction: 6355 case OMPC_in_reduction: 6356 case OMPC_linear: 6357 case OMPC_aligned: 6358 case OMPC_copyin: 6359 case OMPC_copyprivate: 6360 case OMPC_nowait: 6361 case OMPC_untied: 6362 case OMPC_mergeable: 6363 case OMPC_allocate: 6364 case OMPC_read: 6365 case OMPC_write: 6366 case OMPC_update: 6367 case OMPC_capture: 6368 case OMPC_compare: 6369 case OMPC_seq_cst: 6370 case OMPC_acq_rel: 6371 case OMPC_acquire: 6372 case OMPC_release: 6373 case OMPC_relaxed: 6374 case OMPC_depend: 6375 case OMPC_threads: 6376 case OMPC_simd: 6377 case OMPC_map: 6378 case OMPC_nogroup: 6379 case OMPC_defaultmap: 6380 case OMPC_to: 6381 case OMPC_from: 6382 case OMPC_use_device_ptr: 6383 case OMPC_use_device_addr: 6384 case OMPC_is_device_ptr: 6385 case OMPC_nontemporal: 6386 case OMPC_order: 6387 case OMPC_destroy: 6388 case OMPC_inclusive: 6389 case OMPC_exclusive: 6390 case OMPC_uses_allocators: 6391 case OMPC_affinity: 6392 case OMPC_bind: 6393 continue; 6394 case OMPC_allocator: 6395 case OMPC_flush: 6396 case OMPC_depobj: 6397 case OMPC_threadprivate: 6398 case OMPC_uniform: 6399 case OMPC_unknown: 6400 case OMPC_unified_address: 6401 case OMPC_unified_shared_memory: 6402 case OMPC_reverse_offload: 6403 case OMPC_dynamic_allocators: 6404 case OMPC_atomic_default_mem_order: 6405 case OMPC_device_type: 6406 case OMPC_match: 6407 case OMPC_when: 6408 default: 6409 llvm_unreachable("Unexpected clause"); 6410 } 6411 for (Stmt *CC : C->children()) { 6412 if (CC) 6413 DSAChecker.Visit(CC); 6414 } 6415 } 6416 for (const auto &P : DSAChecker.getVarsWithInheritedDSA()) 6417 VarsWithInheritedDSA[P.getFirst()] = P.getSecond(); 6418 } 6419 for (const auto &P : VarsWithInheritedDSA) { 6420 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst())) 6421 continue; 6422 ErrorFound = true; 6423 if (DSAStack->getDefaultDSA() == DSA_none || 6424 DSAStack->getDefaultDSA() == DSA_firstprivate) { 6425 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 6426 << P.first << P.second->getSourceRange(); 6427 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none); 6428 } else if (getLangOpts().OpenMP >= 50) { 6429 Diag(P.second->getExprLoc(), 6430 diag::err_omp_defaultmap_no_attr_for_variable) 6431 << P.first << P.second->getSourceRange(); 6432 Diag(DSAStack->getDefaultDSALocation(), 6433 diag::note_omp_defaultmap_attr_none); 6434 } 6435 } 6436 6437 if (!AllowedNameModifiers.empty()) 6438 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 6439 ErrorFound; 6440 6441 if (ErrorFound) 6442 return StmtError(); 6443 6444 if (!CurContext->isDependentContext() && 6445 isOpenMPTargetExecutionDirective(Kind) && 6446 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || 6447 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() || 6448 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() || 6449 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) { 6450 // Register target to DSA Stack. 6451 DSAStack->addTargetDirLocation(StartLoc); 6452 } 6453 6454 return Res; 6455 } 6456 6457 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 6458 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 6459 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 6460 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 6461 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 6462 assert(Aligneds.size() == Alignments.size()); 6463 assert(Linears.size() == LinModifiers.size()); 6464 assert(Linears.size() == Steps.size()); 6465 if (!DG || DG.get().isNull()) 6466 return DeclGroupPtrTy(); 6467 6468 const int SimdId = 0; 6469 if (!DG.get().isSingleDecl()) { 6470 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant) 6471 << SimdId; 6472 return DG; 6473 } 6474 Decl *ADecl = DG.get().getSingleDecl(); 6475 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 6476 ADecl = FTD->getTemplatedDecl(); 6477 6478 auto *FD = dyn_cast<FunctionDecl>(ADecl); 6479 if (!FD) { 6480 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId; 6481 return DeclGroupPtrTy(); 6482 } 6483 6484 // OpenMP [2.8.2, declare simd construct, Description] 6485 // The parameter of the simdlen clause must be a constant positive integer 6486 // expression. 6487 ExprResult SL; 6488 if (Simdlen) 6489 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 6490 // OpenMP [2.8.2, declare simd construct, Description] 6491 // The special this pointer can be used as if was one of the arguments to the 6492 // function in any of the linear, aligned, or uniform clauses. 6493 // The uniform clause declares one or more arguments to have an invariant 6494 // value for all concurrent invocations of the function in the execution of a 6495 // single SIMD loop. 6496 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs; 6497 const Expr *UniformedLinearThis = nullptr; 6498 for (const Expr *E : Uniforms) { 6499 E = E->IgnoreParenImpCasts(); 6500 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 6501 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 6502 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 6503 FD->getParamDecl(PVD->getFunctionScopeIndex()) 6504 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 6505 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E); 6506 continue; 6507 } 6508 if (isa<CXXThisExpr>(E)) { 6509 UniformedLinearThis = E; 6510 continue; 6511 } 6512 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 6513 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 6514 } 6515 // OpenMP [2.8.2, declare simd construct, Description] 6516 // The aligned clause declares that the object to which each list item points 6517 // is aligned to the number of bytes expressed in the optional parameter of 6518 // the aligned clause. 6519 // The special this pointer can be used as if was one of the arguments to the 6520 // function in any of the linear, aligned, or uniform clauses. 6521 // The type of list items appearing in the aligned clause must be array, 6522 // pointer, reference to array, or reference to pointer. 6523 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs; 6524 const Expr *AlignedThis = nullptr; 6525 for (const Expr *E : Aligneds) { 6526 E = E->IgnoreParenImpCasts(); 6527 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 6528 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 6529 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 6530 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 6531 FD->getParamDecl(PVD->getFunctionScopeIndex()) 6532 ->getCanonicalDecl() == CanonPVD) { 6533 // OpenMP [2.8.1, simd construct, Restrictions] 6534 // A list-item cannot appear in more than one aligned clause. 6535 if (AlignedArgs.count(CanonPVD) > 0) { 6536 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice) 6537 << 1 << getOpenMPClauseName(OMPC_aligned) 6538 << E->getSourceRange(); 6539 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 6540 diag::note_omp_explicit_dsa) 6541 << getOpenMPClauseName(OMPC_aligned); 6542 continue; 6543 } 6544 AlignedArgs[CanonPVD] = E; 6545 QualType QTy = PVD->getType() 6546 .getNonReferenceType() 6547 .getUnqualifiedType() 6548 .getCanonicalType(); 6549 const Type *Ty = QTy.getTypePtrOrNull(); 6550 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 6551 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 6552 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 6553 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 6554 } 6555 continue; 6556 } 6557 } 6558 if (isa<CXXThisExpr>(E)) { 6559 if (AlignedThis) { 6560 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice) 6561 << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange(); 6562 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 6563 << getOpenMPClauseName(OMPC_aligned); 6564 } 6565 AlignedThis = E; 6566 continue; 6567 } 6568 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 6569 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 6570 } 6571 // The optional parameter of the aligned clause, alignment, must be a constant 6572 // positive integer expression. If no optional parameter is specified, 6573 // implementation-defined default alignments for SIMD instructions on the 6574 // target platforms are assumed. 6575 SmallVector<const Expr *, 4> NewAligns; 6576 for (Expr *E : Alignments) { 6577 ExprResult Align; 6578 if (E) 6579 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 6580 NewAligns.push_back(Align.get()); 6581 } 6582 // OpenMP [2.8.2, declare simd construct, Description] 6583 // The linear clause declares one or more list items to be private to a SIMD 6584 // lane and to have a linear relationship with respect to the iteration space 6585 // of a loop. 6586 // The special this pointer can be used as if was one of the arguments to the 6587 // function in any of the linear, aligned, or uniform clauses. 6588 // When a linear-step expression is specified in a linear clause it must be 6589 // either a constant integer expression or an integer-typed parameter that is 6590 // specified in a uniform clause on the directive. 6591 llvm::DenseMap<const Decl *, const Expr *> LinearArgs; 6592 const bool IsUniformedThis = UniformedLinearThis != nullptr; 6593 auto MI = LinModifiers.begin(); 6594 for (const Expr *E : Linears) { 6595 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 6596 ++MI; 6597 E = E->IgnoreParenImpCasts(); 6598 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 6599 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 6600 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 6601 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 6602 FD->getParamDecl(PVD->getFunctionScopeIndex()) 6603 ->getCanonicalDecl() == CanonPVD) { 6604 // OpenMP [2.15.3.7, linear Clause, Restrictions] 6605 // A list-item cannot appear in more than one linear clause. 6606 if (LinearArgs.count(CanonPVD) > 0) { 6607 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 6608 << getOpenMPClauseName(OMPC_linear) 6609 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 6610 Diag(LinearArgs[CanonPVD]->getExprLoc(), 6611 diag::note_omp_explicit_dsa) 6612 << getOpenMPClauseName(OMPC_linear); 6613 continue; 6614 } 6615 // Each argument can appear in at most one uniform or linear clause. 6616 if (UniformedArgs.count(CanonPVD) > 0) { 6617 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 6618 << getOpenMPClauseName(OMPC_linear) 6619 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 6620 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 6621 diag::note_omp_explicit_dsa) 6622 << getOpenMPClauseName(OMPC_uniform); 6623 continue; 6624 } 6625 LinearArgs[CanonPVD] = E; 6626 if (E->isValueDependent() || E->isTypeDependent() || 6627 E->isInstantiationDependent() || 6628 E->containsUnexpandedParameterPack()) 6629 continue; 6630 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 6631 PVD->getOriginalType(), 6632 /*IsDeclareSimd=*/true); 6633 continue; 6634 } 6635 } 6636 if (isa<CXXThisExpr>(E)) { 6637 if (UniformedLinearThis) { 6638 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 6639 << getOpenMPClauseName(OMPC_linear) 6640 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 6641 << E->getSourceRange(); 6642 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 6643 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 6644 : OMPC_linear); 6645 continue; 6646 } 6647 UniformedLinearThis = E; 6648 if (E->isValueDependent() || E->isTypeDependent() || 6649 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 6650 continue; 6651 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 6652 E->getType(), /*IsDeclareSimd=*/true); 6653 continue; 6654 } 6655 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 6656 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 6657 } 6658 Expr *Step = nullptr; 6659 Expr *NewStep = nullptr; 6660 SmallVector<Expr *, 4> NewSteps; 6661 for (Expr *E : Steps) { 6662 // Skip the same step expression, it was checked already. 6663 if (Step == E || !E) { 6664 NewSteps.push_back(E ? NewStep : nullptr); 6665 continue; 6666 } 6667 Step = E; 6668 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step)) 6669 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 6670 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 6671 if (UniformedArgs.count(CanonPVD) == 0) { 6672 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 6673 << Step->getSourceRange(); 6674 } else if (E->isValueDependent() || E->isTypeDependent() || 6675 E->isInstantiationDependent() || 6676 E->containsUnexpandedParameterPack() || 6677 CanonPVD->getType()->hasIntegerRepresentation()) { 6678 NewSteps.push_back(Step); 6679 } else { 6680 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 6681 << Step->getSourceRange(); 6682 } 6683 continue; 6684 } 6685 NewStep = Step; 6686 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 6687 !Step->isInstantiationDependent() && 6688 !Step->containsUnexpandedParameterPack()) { 6689 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 6690 .get(); 6691 if (NewStep) 6692 NewStep = 6693 VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get(); 6694 } 6695 NewSteps.push_back(NewStep); 6696 } 6697 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 6698 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 6699 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 6700 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 6701 const_cast<Expr **>(Linears.data()), Linears.size(), 6702 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 6703 NewSteps.data(), NewSteps.size(), SR); 6704 ADecl->addAttr(NewAttr); 6705 return DG; 6706 } 6707 6708 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto, 6709 QualType NewType) { 6710 assert(NewType->isFunctionProtoType() && 6711 "Expected function type with prototype."); 6712 assert(FD->getType()->isFunctionNoProtoType() && 6713 "Expected function with type with no prototype."); 6714 assert(FDWithProto->getType()->isFunctionProtoType() && 6715 "Expected function with prototype."); 6716 // Synthesize parameters with the same types. 6717 FD->setType(NewType); 6718 SmallVector<ParmVarDecl *, 16> Params; 6719 for (const ParmVarDecl *P : FDWithProto->parameters()) { 6720 auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(), 6721 SourceLocation(), nullptr, P->getType(), 6722 /*TInfo=*/nullptr, SC_None, nullptr); 6723 Param->setScopeInfo(0, Params.size()); 6724 Param->setImplicit(); 6725 Params.push_back(Param); 6726 } 6727 6728 FD->setParams(Params); 6729 } 6730 6731 void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) { 6732 if (D->isInvalidDecl()) 6733 return; 6734 FunctionDecl *FD = nullptr; 6735 if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D)) 6736 FD = UTemplDecl->getTemplatedDecl(); 6737 else 6738 FD = cast<FunctionDecl>(D); 6739 assert(FD && "Expected a function declaration!"); 6740 6741 // If we are instantiating templates we do *not* apply scoped assumptions but 6742 // only global ones. We apply scoped assumption to the template definition 6743 // though. 6744 if (!inTemplateInstantiation()) { 6745 for (AssumptionAttr *AA : OMPAssumeScoped) 6746 FD->addAttr(AA); 6747 } 6748 for (AssumptionAttr *AA : OMPAssumeGlobal) 6749 FD->addAttr(AA); 6750 } 6751 6752 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI) 6753 : TI(&TI), NameSuffix(TI.getMangledName()) {} 6754 6755 void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 6756 Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, 6757 SmallVectorImpl<FunctionDecl *> &Bases) { 6758 if (!D.getIdentifier()) 6759 return; 6760 6761 OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back(); 6762 6763 // Template specialization is an extension, check if we do it. 6764 bool IsTemplated = !TemplateParamLists.empty(); 6765 if (IsTemplated & 6766 !DVScope.TI->isExtensionActive( 6767 llvm::omp::TraitProperty::implementation_extension_allow_templates)) 6768 return; 6769 6770 IdentifierInfo *BaseII = D.getIdentifier(); 6771 LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(), 6772 LookupOrdinaryName); 6773 LookupParsedName(Lookup, S, &D.getCXXScopeSpec()); 6774 6775 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6776 QualType FType = TInfo->getType(); 6777 6778 bool IsConstexpr = 6779 D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr; 6780 bool IsConsteval = 6781 D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval; 6782 6783 for (auto *Candidate : Lookup) { 6784 auto *CandidateDecl = Candidate->getUnderlyingDecl(); 6785 FunctionDecl *UDecl = nullptr; 6786 if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl)) { 6787 auto *FTD = cast<FunctionTemplateDecl>(CandidateDecl); 6788 if (FTD->getTemplateParameters()->size() == TemplateParamLists.size()) 6789 UDecl = FTD->getTemplatedDecl(); 6790 } else if (!IsTemplated) 6791 UDecl = dyn_cast<FunctionDecl>(CandidateDecl); 6792 if (!UDecl) 6793 continue; 6794 6795 // Don't specialize constexpr/consteval functions with 6796 // non-constexpr/consteval functions. 6797 if (UDecl->isConstexpr() && !IsConstexpr) 6798 continue; 6799 if (UDecl->isConsteval() && !IsConsteval) 6800 continue; 6801 6802 QualType UDeclTy = UDecl->getType(); 6803 if (!UDeclTy->isDependentType()) { 6804 QualType NewType = Context.mergeFunctionTypes( 6805 FType, UDeclTy, /* OfBlockPointer */ false, 6806 /* Unqualified */ false, /* AllowCXX */ true); 6807 if (NewType.isNull()) 6808 continue; 6809 } 6810 6811 // Found a base! 6812 Bases.push_back(UDecl); 6813 } 6814 6815 bool UseImplicitBase = !DVScope.TI->isExtensionActive( 6816 llvm::omp::TraitProperty::implementation_extension_disable_implicit_base); 6817 // If no base was found we create a declaration that we use as base. 6818 if (Bases.empty() && UseImplicitBase) { 6819 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 6820 Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists); 6821 BaseD->setImplicit(true); 6822 if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD)) 6823 Bases.push_back(BaseTemplD->getTemplatedDecl()); 6824 else 6825 Bases.push_back(cast<FunctionDecl>(BaseD)); 6826 } 6827 6828 std::string MangledName; 6829 MangledName += D.getIdentifier()->getName(); 6830 MangledName += getOpenMPVariantManglingSeparatorStr(); 6831 MangledName += DVScope.NameSuffix; 6832 IdentifierInfo &VariantII = Context.Idents.get(MangledName); 6833 6834 VariantII.setMangledOpenMPVariantName(true); 6835 D.SetIdentifier(&VariantII, D.getBeginLoc()); 6836 } 6837 6838 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 6839 Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) { 6840 // Do not mark function as is used to prevent its emission if this is the 6841 // only place where it is used. 6842 EnterExpressionEvaluationContext Unevaluated( 6843 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6844 6845 FunctionDecl *FD = nullptr; 6846 if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D)) 6847 FD = UTemplDecl->getTemplatedDecl(); 6848 else 6849 FD = cast<FunctionDecl>(D); 6850 auto *VariantFuncRef = DeclRefExpr::Create( 6851 Context, NestedNameSpecifierLoc(), SourceLocation(), FD, 6852 /* RefersToEnclosingVariableOrCapture */ false, 6853 /* NameLoc */ FD->getLocation(), FD->getType(), 6854 ExprValueKind::VK_PRValue); 6855 6856 OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back(); 6857 auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit( 6858 Context, VariantFuncRef, DVScope.TI, 6859 /*NothingArgs=*/nullptr, /*NothingArgsSize=*/0, 6860 /*NeedDevicePtrArgs=*/nullptr, /*NeedDevicePtrArgsSize=*/0, 6861 /*AppendArgs=*/nullptr, /*AppendArgsSize=*/0); 6862 for (FunctionDecl *BaseFD : Bases) 6863 BaseFD->addAttr(OMPDeclareVariantA); 6864 } 6865 6866 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope, 6867 SourceLocation LParenLoc, 6868 MultiExprArg ArgExprs, 6869 SourceLocation RParenLoc, Expr *ExecConfig) { 6870 // The common case is a regular call we do not want to specialize at all. Try 6871 // to make that case fast by bailing early. 6872 CallExpr *CE = dyn_cast<CallExpr>(Call.get()); 6873 if (!CE) 6874 return Call; 6875 6876 FunctionDecl *CalleeFnDecl = CE->getDirectCallee(); 6877 if (!CalleeFnDecl) 6878 return Call; 6879 6880 if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>()) 6881 return Call; 6882 6883 ASTContext &Context = getASTContext(); 6884 std::function<void(StringRef)> DiagUnknownTrait = [this, 6885 CE](StringRef ISATrait) { 6886 // TODO Track the selector locations in a way that is accessible here to 6887 // improve the diagnostic location. 6888 Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait) 6889 << ISATrait; 6890 }; 6891 TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait), 6892 getCurFunctionDecl(), DSAStack->getConstructTraits()); 6893 6894 QualType CalleeFnType = CalleeFnDecl->getType(); 6895 6896 SmallVector<Expr *, 4> Exprs; 6897 SmallVector<VariantMatchInfo, 4> VMIs; 6898 while (CalleeFnDecl) { 6899 for (OMPDeclareVariantAttr *A : 6900 CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) { 6901 Expr *VariantRef = A->getVariantFuncRef(); 6902 6903 VariantMatchInfo VMI; 6904 OMPTraitInfo &TI = A->getTraitInfo(); 6905 TI.getAsVariantMatchInfo(Context, VMI); 6906 if (!isVariantApplicableInContext(VMI, OMPCtx, 6907 /* DeviceSetOnly */ false)) 6908 continue; 6909 6910 VMIs.push_back(VMI); 6911 Exprs.push_back(VariantRef); 6912 } 6913 6914 CalleeFnDecl = CalleeFnDecl->getPreviousDecl(); 6915 } 6916 6917 ExprResult NewCall; 6918 do { 6919 int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx); 6920 if (BestIdx < 0) 6921 return Call; 6922 Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]); 6923 Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl(); 6924 6925 { 6926 // Try to build a (member) call expression for the current best applicable 6927 // variant expression. We allow this to fail in which case we continue 6928 // with the next best variant expression. The fail case is part of the 6929 // implementation defined behavior in the OpenMP standard when it talks 6930 // about what differences in the function prototypes: "Any differences 6931 // that the specific OpenMP context requires in the prototype of the 6932 // variant from the base function prototype are implementation defined." 6933 // This wording is there to allow the specialized variant to have a 6934 // different type than the base function. This is intended and OK but if 6935 // we cannot create a call the difference is not in the "implementation 6936 // defined range" we allow. 6937 Sema::TentativeAnalysisScope Trap(*this); 6938 6939 if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) { 6940 auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE); 6941 BestExpr = MemberExpr::CreateImplicit( 6942 Context, MemberCall->getImplicitObjectArgument(), 6943 /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy, 6944 MemberCall->getValueKind(), MemberCall->getObjectKind()); 6945 } 6946 NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc, 6947 ExecConfig); 6948 if (NewCall.isUsable()) { 6949 if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) { 6950 FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee(); 6951 QualType NewType = Context.mergeFunctionTypes( 6952 CalleeFnType, NewCalleeFnDecl->getType(), 6953 /* OfBlockPointer */ false, 6954 /* Unqualified */ false, /* AllowCXX */ true); 6955 if (!NewType.isNull()) 6956 break; 6957 // Don't use the call if the function type was not compatible. 6958 NewCall = nullptr; 6959 } 6960 } 6961 } 6962 6963 VMIs.erase(VMIs.begin() + BestIdx); 6964 Exprs.erase(Exprs.begin() + BestIdx); 6965 } while (!VMIs.empty()); 6966 6967 if (!NewCall.isUsable()) 6968 return Call; 6969 return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0); 6970 } 6971 6972 Optional<std::pair<FunctionDecl *, Expr *>> 6973 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG, 6974 Expr *VariantRef, OMPTraitInfo &TI, 6975 unsigned NumAppendArgs, 6976 SourceRange SR) { 6977 if (!DG || DG.get().isNull()) 6978 return None; 6979 6980 const int VariantId = 1; 6981 // Must be applied only to single decl. 6982 if (!DG.get().isSingleDecl()) { 6983 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant) 6984 << VariantId << SR; 6985 return None; 6986 } 6987 Decl *ADecl = DG.get().getSingleDecl(); 6988 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 6989 ADecl = FTD->getTemplatedDecl(); 6990 6991 // Decl must be a function. 6992 auto *FD = dyn_cast<FunctionDecl>(ADecl); 6993 if (!FD) { 6994 Diag(ADecl->getLocation(), diag::err_omp_function_expected) 6995 << VariantId << SR; 6996 return None; 6997 } 6998 6999 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) { 7000 return FD->hasAttrs() && 7001 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() || 7002 FD->hasAttr<TargetAttr>()); 7003 }; 7004 // OpenMP is not compatible with CPU-specific attributes. 7005 if (HasMultiVersionAttributes(FD)) { 7006 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes) 7007 << SR; 7008 return None; 7009 } 7010 7011 // Allow #pragma omp declare variant only if the function is not used. 7012 if (FD->isUsed(false)) 7013 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used) 7014 << FD->getLocation(); 7015 7016 // Check if the function was emitted already. 7017 const FunctionDecl *Definition; 7018 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) && 7019 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition))) 7020 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted) 7021 << FD->getLocation(); 7022 7023 // The VariantRef must point to function. 7024 if (!VariantRef) { 7025 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId; 7026 return None; 7027 } 7028 7029 auto ShouldDelayChecks = [](Expr *&E, bool) { 7030 return E && (E->isTypeDependent() || E->isValueDependent() || 7031 E->containsUnexpandedParameterPack() || 7032 E->isInstantiationDependent()); 7033 }; 7034 // Do not check templates, wait until instantiation. 7035 if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) || 7036 TI.anyScoreOrCondition(ShouldDelayChecks)) 7037 return std::make_pair(FD, VariantRef); 7038 7039 // Deal with non-constant score and user condition expressions. 7040 auto HandleNonConstantScoresAndConditions = [this](Expr *&E, 7041 bool IsScore) -> bool { 7042 if (!E || E->isIntegerConstantExpr(Context)) 7043 return false; 7044 7045 if (IsScore) { 7046 // We warn on non-constant scores and pretend they were not present. 7047 Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant) 7048 << E; 7049 E = nullptr; 7050 } else { 7051 // We could replace a non-constant user condition with "false" but we 7052 // will soon need to handle these anyway for the dynamic version of 7053 // OpenMP context selectors. 7054 Diag(E->getExprLoc(), 7055 diag::err_omp_declare_variant_user_condition_not_constant) 7056 << E; 7057 } 7058 return true; 7059 }; 7060 if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions)) 7061 return None; 7062 7063 QualType AdjustedFnType = FD->getType(); 7064 if (NumAppendArgs) { 7065 const auto *PTy = AdjustedFnType->getAsAdjusted<FunctionProtoType>(); 7066 if (!PTy) { 7067 Diag(FD->getLocation(), diag::err_omp_declare_variant_prototype_required) 7068 << SR; 7069 return None; 7070 } 7071 // Adjust the function type to account for an extra omp_interop_t for each 7072 // specified in the append_args clause. 7073 const TypeDecl *TD = nullptr; 7074 LookupResult Result(*this, &Context.Idents.get("omp_interop_t"), 7075 SR.getBegin(), Sema::LookupOrdinaryName); 7076 if (LookupName(Result, getCurScope())) { 7077 NamedDecl *ND = Result.getFoundDecl(); 7078 TD = dyn_cast_or_null<TypeDecl>(ND); 7079 } 7080 if (!TD) { 7081 Diag(SR.getBegin(), diag::err_omp_interop_type_not_found) << SR; 7082 return None; 7083 } 7084 QualType InteropType = Context.getTypeDeclType(TD); 7085 if (PTy->isVariadic()) { 7086 Diag(FD->getLocation(), diag::err_omp_append_args_with_varargs) << SR; 7087 return None; 7088 } 7089 llvm::SmallVector<QualType, 8> Params; 7090 Params.append(PTy->param_type_begin(), PTy->param_type_end()); 7091 Params.insert(Params.end(), NumAppendArgs, InteropType); 7092 AdjustedFnType = Context.getFunctionType(PTy->getReturnType(), Params, 7093 PTy->getExtProtoInfo()); 7094 } 7095 7096 // Convert VariantRef expression to the type of the original function to 7097 // resolve possible conflicts. 7098 ExprResult VariantRefCast = VariantRef; 7099 if (LangOpts.CPlusPlus) { 7100 QualType FnPtrType; 7101 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7102 if (Method && !Method->isStatic()) { 7103 const Type *ClassType = 7104 Context.getTypeDeclType(Method->getParent()).getTypePtr(); 7105 FnPtrType = Context.getMemberPointerType(AdjustedFnType, ClassType); 7106 ExprResult ER; 7107 { 7108 // Build adrr_of unary op to correctly handle type checks for member 7109 // functions. 7110 Sema::TentativeAnalysisScope Trap(*this); 7111 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf, 7112 VariantRef); 7113 } 7114 if (!ER.isUsable()) { 7115 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7116 << VariantId << VariantRef->getSourceRange(); 7117 return None; 7118 } 7119 VariantRef = ER.get(); 7120 } else { 7121 FnPtrType = Context.getPointerType(AdjustedFnType); 7122 } 7123 QualType VarianPtrType = Context.getPointerType(VariantRef->getType()); 7124 if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) { 7125 ImplicitConversionSequence ICS = TryImplicitConversion( 7126 VariantRef, FnPtrType.getUnqualifiedType(), 7127 /*SuppressUserConversions=*/false, AllowedExplicit::None, 7128 /*InOverloadResolution=*/false, 7129 /*CStyle=*/false, 7130 /*AllowObjCWritebackConversion=*/false); 7131 if (ICS.isFailure()) { 7132 Diag(VariantRef->getExprLoc(), 7133 diag::err_omp_declare_variant_incompat_types) 7134 << VariantRef->getType() 7135 << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType()) 7136 << (NumAppendArgs ? 1 : 0) << VariantRef->getSourceRange(); 7137 return None; 7138 } 7139 VariantRefCast = PerformImplicitConversion( 7140 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting); 7141 if (!VariantRefCast.isUsable()) 7142 return None; 7143 } 7144 // Drop previously built artificial addr_of unary op for member functions. 7145 if (Method && !Method->isStatic()) { 7146 Expr *PossibleAddrOfVariantRef = VariantRefCast.get(); 7147 if (auto *UO = dyn_cast<UnaryOperator>( 7148 PossibleAddrOfVariantRef->IgnoreImplicit())) 7149 VariantRefCast = UO->getSubExpr(); 7150 } 7151 } 7152 7153 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get()); 7154 if (!ER.isUsable() || 7155 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) { 7156 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7157 << VariantId << VariantRef->getSourceRange(); 7158 return None; 7159 } 7160 7161 // The VariantRef must point to function. 7162 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts()); 7163 if (!DRE) { 7164 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7165 << VariantId << VariantRef->getSourceRange(); 7166 return None; 7167 } 7168 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl()); 7169 if (!NewFD) { 7170 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7171 << VariantId << VariantRef->getSourceRange(); 7172 return None; 7173 } 7174 7175 if (FD->getCanonicalDecl() == NewFD->getCanonicalDecl()) { 7176 Diag(VariantRef->getExprLoc(), 7177 diag::err_omp_declare_variant_same_base_function) 7178 << VariantRef->getSourceRange(); 7179 return None; 7180 } 7181 7182 // Check if function types are compatible in C. 7183 if (!LangOpts.CPlusPlus) { 7184 QualType NewType = 7185 Context.mergeFunctionTypes(AdjustedFnType, NewFD->getType()); 7186 if (NewType.isNull()) { 7187 Diag(VariantRef->getExprLoc(), 7188 diag::err_omp_declare_variant_incompat_types) 7189 << NewFD->getType() << FD->getType() << (NumAppendArgs ? 1 : 0) 7190 << VariantRef->getSourceRange(); 7191 return None; 7192 } 7193 if (NewType->isFunctionProtoType()) { 7194 if (FD->getType()->isFunctionNoProtoType()) 7195 setPrototype(*this, FD, NewFD, NewType); 7196 else if (NewFD->getType()->isFunctionNoProtoType()) 7197 setPrototype(*this, NewFD, FD, NewType); 7198 } 7199 } 7200 7201 // Check if variant function is not marked with declare variant directive. 7202 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) { 7203 Diag(VariantRef->getExprLoc(), 7204 diag::warn_omp_declare_variant_marked_as_declare_variant) 7205 << VariantRef->getSourceRange(); 7206 SourceRange SR = 7207 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange(); 7208 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR; 7209 return None; 7210 } 7211 7212 enum DoesntSupport { 7213 VirtFuncs = 1, 7214 Constructors = 3, 7215 Destructors = 4, 7216 DeletedFuncs = 5, 7217 DefaultedFuncs = 6, 7218 ConstexprFuncs = 7, 7219 ConstevalFuncs = 8, 7220 }; 7221 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) { 7222 if (CXXFD->isVirtual()) { 7223 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7224 << VirtFuncs; 7225 return None; 7226 } 7227 7228 if (isa<CXXConstructorDecl>(FD)) { 7229 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7230 << Constructors; 7231 return None; 7232 } 7233 7234 if (isa<CXXDestructorDecl>(FD)) { 7235 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7236 << Destructors; 7237 return None; 7238 } 7239 } 7240 7241 if (FD->isDeleted()) { 7242 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7243 << DeletedFuncs; 7244 return None; 7245 } 7246 7247 if (FD->isDefaulted()) { 7248 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7249 << DefaultedFuncs; 7250 return None; 7251 } 7252 7253 if (FD->isConstexpr()) { 7254 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7255 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 7256 return None; 7257 } 7258 7259 // Check general compatibility. 7260 if (areMultiversionVariantFunctionsCompatible( 7261 FD, NewFD, PartialDiagnostic::NullDiagnostic(), 7262 PartialDiagnosticAt(SourceLocation(), 7263 PartialDiagnostic::NullDiagnostic()), 7264 PartialDiagnosticAt( 7265 VariantRef->getExprLoc(), 7266 PDiag(diag::err_omp_declare_variant_doesnt_support)), 7267 PartialDiagnosticAt(VariantRef->getExprLoc(), 7268 PDiag(diag::err_omp_declare_variant_diff) 7269 << FD->getLocation()), 7270 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false, 7271 /*CLinkageMayDiffer=*/true)) 7272 return None; 7273 return std::make_pair(FD, cast<Expr>(DRE)); 7274 } 7275 7276 void Sema::ActOnOpenMPDeclareVariantDirective( 7277 FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, 7278 ArrayRef<Expr *> AdjustArgsNothing, 7279 ArrayRef<Expr *> AdjustArgsNeedDevicePtr, 7280 ArrayRef<OMPDeclareVariantAttr::InteropType> AppendArgs, 7281 SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc, 7282 SourceRange SR) { 7283 7284 // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions] 7285 // An adjust_args clause or append_args clause can only be specified if the 7286 // dispatch selector of the construct selector set appears in the match 7287 // clause. 7288 7289 SmallVector<Expr *, 8> AllAdjustArgs; 7290 llvm::append_range(AllAdjustArgs, AdjustArgsNothing); 7291 llvm::append_range(AllAdjustArgs, AdjustArgsNeedDevicePtr); 7292 7293 if (!AllAdjustArgs.empty() || !AppendArgs.empty()) { 7294 VariantMatchInfo VMI; 7295 TI.getAsVariantMatchInfo(Context, VMI); 7296 if (!llvm::is_contained( 7297 VMI.ConstructTraits, 7298 llvm::omp::TraitProperty::construct_dispatch_dispatch)) { 7299 if (!AllAdjustArgs.empty()) 7300 Diag(AdjustArgsLoc, diag::err_omp_clause_requires_dispatch_construct) 7301 << getOpenMPClauseName(OMPC_adjust_args); 7302 if (!AppendArgs.empty()) 7303 Diag(AppendArgsLoc, diag::err_omp_clause_requires_dispatch_construct) 7304 << getOpenMPClauseName(OMPC_append_args); 7305 return; 7306 } 7307 } 7308 7309 // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions] 7310 // Each argument can only appear in a single adjust_args clause for each 7311 // declare variant directive. 7312 llvm::SmallPtrSet<const VarDecl *, 4> AdjustVars; 7313 7314 for (Expr *E : AllAdjustArgs) { 7315 E = E->IgnoreParenImpCasts(); 7316 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) { 7317 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 7318 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 7319 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 7320 FD->getParamDecl(PVD->getFunctionScopeIndex()) 7321 ->getCanonicalDecl() == CanonPVD) { 7322 // It's a parameter of the function, check duplicates. 7323 if (!AdjustVars.insert(CanonPVD).second) { 7324 Diag(DRE->getLocation(), diag::err_omp_adjust_arg_multiple_clauses) 7325 << PVD; 7326 return; 7327 } 7328 continue; 7329 } 7330 } 7331 } 7332 // Anything that is not a function parameter is an error. 7333 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) << FD << 0; 7334 return; 7335 } 7336 7337 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit( 7338 Context, VariantRef, &TI, const_cast<Expr **>(AdjustArgsNothing.data()), 7339 AdjustArgsNothing.size(), 7340 const_cast<Expr **>(AdjustArgsNeedDevicePtr.data()), 7341 AdjustArgsNeedDevicePtr.size(), 7342 const_cast<OMPDeclareVariantAttr::InteropType *>(AppendArgs.data()), 7343 AppendArgs.size(), SR); 7344 FD->addAttr(NewAttr); 7345 } 7346 7347 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 7348 Stmt *AStmt, 7349 SourceLocation StartLoc, 7350 SourceLocation EndLoc) { 7351 if (!AStmt) 7352 return StmtError(); 7353 7354 auto *CS = cast<CapturedStmt>(AStmt); 7355 // 1.2.2 OpenMP Language Terminology 7356 // Structured block - An executable statement with a single entry at the 7357 // top and a single exit at the bottom. 7358 // The point of exit cannot be a branch out of the structured block. 7359 // longjmp() and throw() must not violate the entry/exit criteria. 7360 CS->getCapturedDecl()->setNothrow(); 7361 7362 setFunctionHasBranchProtectedScope(); 7363 7364 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 7365 DSAStack->getTaskgroupReductionRef(), 7366 DSAStack->isCancelRegion()); 7367 } 7368 7369 namespace { 7370 /// Iteration space of a single for loop. 7371 struct LoopIterationSpace final { 7372 /// True if the condition operator is the strict compare operator (<, > or 7373 /// !=). 7374 bool IsStrictCompare = false; 7375 /// Condition of the loop. 7376 Expr *PreCond = nullptr; 7377 /// This expression calculates the number of iterations in the loop. 7378 /// It is always possible to calculate it before starting the loop. 7379 Expr *NumIterations = nullptr; 7380 /// The loop counter variable. 7381 Expr *CounterVar = nullptr; 7382 /// Private loop counter variable. 7383 Expr *PrivateCounterVar = nullptr; 7384 /// This is initializer for the initial value of #CounterVar. 7385 Expr *CounterInit = nullptr; 7386 /// This is step for the #CounterVar used to generate its update: 7387 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 7388 Expr *CounterStep = nullptr; 7389 /// Should step be subtracted? 7390 bool Subtract = false; 7391 /// Source range of the loop init. 7392 SourceRange InitSrcRange; 7393 /// Source range of the loop condition. 7394 SourceRange CondSrcRange; 7395 /// Source range of the loop increment. 7396 SourceRange IncSrcRange; 7397 /// Minimum value that can have the loop control variable. Used to support 7398 /// non-rectangular loops. Applied only for LCV with the non-iterator types, 7399 /// since only such variables can be used in non-loop invariant expressions. 7400 Expr *MinValue = nullptr; 7401 /// Maximum value that can have the loop control variable. Used to support 7402 /// non-rectangular loops. Applied only for LCV with the non-iterator type, 7403 /// since only such variables can be used in non-loop invariant expressions. 7404 Expr *MaxValue = nullptr; 7405 /// true, if the lower bound depends on the outer loop control var. 7406 bool IsNonRectangularLB = false; 7407 /// true, if the upper bound depends on the outer loop control var. 7408 bool IsNonRectangularUB = false; 7409 /// Index of the loop this loop depends on and forms non-rectangular loop 7410 /// nest. 7411 unsigned LoopDependentIdx = 0; 7412 /// Final condition for the non-rectangular loop nest support. It is used to 7413 /// check that the number of iterations for this particular counter must be 7414 /// finished. 7415 Expr *FinalCondition = nullptr; 7416 }; 7417 7418 /// Helper class for checking canonical form of the OpenMP loops and 7419 /// extracting iteration space of each loop in the loop nest, that will be used 7420 /// for IR generation. 7421 class OpenMPIterationSpaceChecker { 7422 /// Reference to Sema. 7423 Sema &SemaRef; 7424 /// Does the loop associated directive support non-rectangular loops? 7425 bool SupportsNonRectangular; 7426 /// Data-sharing stack. 7427 DSAStackTy &Stack; 7428 /// A location for diagnostics (when there is no some better location). 7429 SourceLocation DefaultLoc; 7430 /// A location for diagnostics (when increment is not compatible). 7431 SourceLocation ConditionLoc; 7432 /// A source location for referring to loop init later. 7433 SourceRange InitSrcRange; 7434 /// A source location for referring to condition later. 7435 SourceRange ConditionSrcRange; 7436 /// A source location for referring to increment later. 7437 SourceRange IncrementSrcRange; 7438 /// Loop variable. 7439 ValueDecl *LCDecl = nullptr; 7440 /// Reference to loop variable. 7441 Expr *LCRef = nullptr; 7442 /// Lower bound (initializer for the var). 7443 Expr *LB = nullptr; 7444 /// Upper bound. 7445 Expr *UB = nullptr; 7446 /// Loop step (increment). 7447 Expr *Step = nullptr; 7448 /// This flag is true when condition is one of: 7449 /// Var < UB 7450 /// Var <= UB 7451 /// UB > Var 7452 /// UB >= Var 7453 /// This will have no value when the condition is != 7454 llvm::Optional<bool> TestIsLessOp; 7455 /// This flag is true when condition is strict ( < or > ). 7456 bool TestIsStrictOp = false; 7457 /// This flag is true when step is subtracted on each iteration. 7458 bool SubtractStep = false; 7459 /// The outer loop counter this loop depends on (if any). 7460 const ValueDecl *DepDecl = nullptr; 7461 /// Contains number of loop (starts from 1) on which loop counter init 7462 /// expression of this loop depends on. 7463 Optional<unsigned> InitDependOnLC; 7464 /// Contains number of loop (starts from 1) on which loop counter condition 7465 /// expression of this loop depends on. 7466 Optional<unsigned> CondDependOnLC; 7467 /// Checks if the provide statement depends on the loop counter. 7468 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer); 7469 /// Original condition required for checking of the exit condition for 7470 /// non-rectangular loop. 7471 Expr *Condition = nullptr; 7472 7473 public: 7474 OpenMPIterationSpaceChecker(Sema &SemaRef, bool SupportsNonRectangular, 7475 DSAStackTy &Stack, SourceLocation DefaultLoc) 7476 : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular), 7477 Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 7478 /// Check init-expr for canonical loop form and save loop counter 7479 /// variable - #Var and its initialization value - #LB. 7480 bool checkAndSetInit(Stmt *S, bool EmitDiags = true); 7481 /// Check test-expr for canonical form, save upper-bound (#UB), flags 7482 /// for less/greater and for strict/non-strict comparison. 7483 bool checkAndSetCond(Expr *S); 7484 /// Check incr-expr for canonical loop form and return true if it 7485 /// does not conform, otherwise save loop step (#Step). 7486 bool checkAndSetInc(Expr *S); 7487 /// Return the loop counter variable. 7488 ValueDecl *getLoopDecl() const { return LCDecl; } 7489 /// Return the reference expression to loop counter variable. 7490 Expr *getLoopDeclRefExpr() const { return LCRef; } 7491 /// Source range of the loop init. 7492 SourceRange getInitSrcRange() const { return InitSrcRange; } 7493 /// Source range of the loop condition. 7494 SourceRange getConditionSrcRange() const { return ConditionSrcRange; } 7495 /// Source range of the loop increment. 7496 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; } 7497 /// True if the step should be subtracted. 7498 bool shouldSubtractStep() const { return SubtractStep; } 7499 /// True, if the compare operator is strict (<, > or !=). 7500 bool isStrictTestOp() const { return TestIsStrictOp; } 7501 /// Build the expression to calculate the number of iterations. 7502 Expr *buildNumIterations( 7503 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType, 7504 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 7505 /// Build the precondition expression for the loops. 7506 Expr * 7507 buildPreCond(Scope *S, Expr *Cond, 7508 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 7509 /// Build reference expression to the counter be used for codegen. 7510 DeclRefExpr * 7511 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 7512 DSAStackTy &DSA) const; 7513 /// Build reference expression to the private counter be used for 7514 /// codegen. 7515 Expr *buildPrivateCounterVar() const; 7516 /// Build initialization of the counter be used for codegen. 7517 Expr *buildCounterInit() const; 7518 /// Build step of the counter be used for codegen. 7519 Expr *buildCounterStep() const; 7520 /// Build loop data with counter value for depend clauses in ordered 7521 /// directives. 7522 Expr * 7523 buildOrderedLoopData(Scope *S, Expr *Counter, 7524 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 7525 SourceLocation Loc, Expr *Inc = nullptr, 7526 OverloadedOperatorKind OOK = OO_Amp); 7527 /// Builds the minimum value for the loop counter. 7528 std::pair<Expr *, Expr *> buildMinMaxValues( 7529 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 7530 /// Builds final condition for the non-rectangular loops. 7531 Expr *buildFinalCondition(Scope *S) const; 7532 /// Return true if any expression is dependent. 7533 bool dependent() const; 7534 /// Returns true if the initializer forms non-rectangular loop. 7535 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); } 7536 /// Returns true if the condition forms non-rectangular loop. 7537 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); } 7538 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise. 7539 unsigned getLoopDependentIdx() const { 7540 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0)); 7541 } 7542 7543 private: 7544 /// Check the right-hand side of an assignment in the increment 7545 /// expression. 7546 bool checkAndSetIncRHS(Expr *RHS); 7547 /// Helper to set loop counter variable and its initializer. 7548 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB, 7549 bool EmitDiags); 7550 /// Helper to set upper bound. 7551 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp, 7552 SourceRange SR, SourceLocation SL); 7553 /// Helper to set loop increment. 7554 bool setStep(Expr *NewStep, bool Subtract); 7555 }; 7556 7557 bool OpenMPIterationSpaceChecker::dependent() const { 7558 if (!LCDecl) { 7559 assert(!LB && !UB && !Step); 7560 return false; 7561 } 7562 return LCDecl->getType()->isDependentType() || 7563 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 7564 (Step && Step->isValueDependent()); 7565 } 7566 7567 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl, 7568 Expr *NewLCRefExpr, 7569 Expr *NewLB, bool EmitDiags) { 7570 // State consistency checking to ensure correct usage. 7571 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 7572 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 7573 if (!NewLCDecl || !NewLB || NewLB->containsErrors()) 7574 return true; 7575 LCDecl = getCanonicalDecl(NewLCDecl); 7576 LCRef = NewLCRefExpr; 7577 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 7578 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 7579 if ((Ctor->isCopyOrMoveConstructor() || 7580 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 7581 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 7582 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 7583 LB = NewLB; 7584 if (EmitDiags) 7585 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true); 7586 return false; 7587 } 7588 7589 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, 7590 llvm::Optional<bool> LessOp, 7591 bool StrictOp, SourceRange SR, 7592 SourceLocation SL) { 7593 // State consistency checking to ensure correct usage. 7594 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 7595 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 7596 if (!NewUB || NewUB->containsErrors()) 7597 return true; 7598 UB = NewUB; 7599 if (LessOp) 7600 TestIsLessOp = LessOp; 7601 TestIsStrictOp = StrictOp; 7602 ConditionSrcRange = SR; 7603 ConditionLoc = SL; 7604 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false); 7605 return false; 7606 } 7607 7608 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) { 7609 // State consistency checking to ensure correct usage. 7610 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 7611 if (!NewStep || NewStep->containsErrors()) 7612 return true; 7613 if (!NewStep->isValueDependent()) { 7614 // Check that the step is integer expression. 7615 SourceLocation StepLoc = NewStep->getBeginLoc(); 7616 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( 7617 StepLoc, getExprAsWritten(NewStep)); 7618 if (Val.isInvalid()) 7619 return true; 7620 NewStep = Val.get(); 7621 7622 // OpenMP [2.6, Canonical Loop Form, Restrictions] 7623 // If test-expr is of form var relational-op b and relational-op is < or 7624 // <= then incr-expr must cause var to increase on each iteration of the 7625 // loop. If test-expr is of form var relational-op b and relational-op is 7626 // > or >= then incr-expr must cause var to decrease on each iteration of 7627 // the loop. 7628 // If test-expr is of form b relational-op var and relational-op is < or 7629 // <= then incr-expr must cause var to decrease on each iteration of the 7630 // loop. If test-expr is of form b relational-op var and relational-op is 7631 // > or >= then incr-expr must cause var to increase on each iteration of 7632 // the loop. 7633 Optional<llvm::APSInt> Result = 7634 NewStep->getIntegerConstantExpr(SemaRef.Context); 7635 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 7636 bool IsConstNeg = 7637 Result && Result->isSigned() && (Subtract != Result->isNegative()); 7638 bool IsConstPos = 7639 Result && Result->isSigned() && (Subtract == Result->isNegative()); 7640 bool IsConstZero = Result && !Result->getBoolValue(); 7641 7642 // != with increment is treated as <; != with decrement is treated as > 7643 if (!TestIsLessOp.hasValue()) 7644 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract); 7645 if (UB && 7646 (IsConstZero || (TestIsLessOp.getValue() 7647 ? (IsConstNeg || (IsUnsigned && Subtract)) 7648 : (IsConstPos || (IsUnsigned && !Subtract))))) { 7649 SemaRef.Diag(NewStep->getExprLoc(), 7650 diag::err_omp_loop_incr_not_compatible) 7651 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange(); 7652 SemaRef.Diag(ConditionLoc, 7653 diag::note_omp_loop_cond_requres_compatible_incr) 7654 << TestIsLessOp.getValue() << ConditionSrcRange; 7655 return true; 7656 } 7657 if (TestIsLessOp.getValue() == Subtract) { 7658 NewStep = 7659 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 7660 .get(); 7661 Subtract = !Subtract; 7662 } 7663 } 7664 7665 Step = NewStep; 7666 SubtractStep = Subtract; 7667 return false; 7668 } 7669 7670 namespace { 7671 /// Checker for the non-rectangular loops. Checks if the initializer or 7672 /// condition expression references loop counter variable. 7673 class LoopCounterRefChecker final 7674 : public ConstStmtVisitor<LoopCounterRefChecker, bool> { 7675 Sema &SemaRef; 7676 DSAStackTy &Stack; 7677 const ValueDecl *CurLCDecl = nullptr; 7678 const ValueDecl *DepDecl = nullptr; 7679 const ValueDecl *PrevDepDecl = nullptr; 7680 bool IsInitializer = true; 7681 bool SupportsNonRectangular; 7682 unsigned BaseLoopId = 0; 7683 bool checkDecl(const Expr *E, const ValueDecl *VD) { 7684 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) { 7685 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter) 7686 << (IsInitializer ? 0 : 1); 7687 return false; 7688 } 7689 const auto &&Data = Stack.isLoopControlVariable(VD); 7690 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions. 7691 // The type of the loop iterator on which we depend may not have a random 7692 // access iterator type. 7693 if (Data.first && VD->getType()->isRecordType()) { 7694 SmallString<128> Name; 7695 llvm::raw_svector_ostream OS(Name); 7696 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(), 7697 /*Qualified=*/true); 7698 SemaRef.Diag(E->getExprLoc(), 7699 diag::err_omp_wrong_dependency_iterator_type) 7700 << OS.str(); 7701 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD; 7702 return false; 7703 } 7704 if (Data.first && !SupportsNonRectangular) { 7705 SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency); 7706 return false; 7707 } 7708 if (Data.first && 7709 (DepDecl || (PrevDepDecl && 7710 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) { 7711 if (!DepDecl && PrevDepDecl) 7712 DepDecl = PrevDepDecl; 7713 SmallString<128> Name; 7714 llvm::raw_svector_ostream OS(Name); 7715 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(), 7716 /*Qualified=*/true); 7717 SemaRef.Diag(E->getExprLoc(), 7718 diag::err_omp_invariant_or_linear_dependency) 7719 << OS.str(); 7720 return false; 7721 } 7722 if (Data.first) { 7723 DepDecl = VD; 7724 BaseLoopId = Data.first; 7725 } 7726 return Data.first; 7727 } 7728 7729 public: 7730 bool VisitDeclRefExpr(const DeclRefExpr *E) { 7731 const ValueDecl *VD = E->getDecl(); 7732 if (isa<VarDecl>(VD)) 7733 return checkDecl(E, VD); 7734 return false; 7735 } 7736 bool VisitMemberExpr(const MemberExpr *E) { 7737 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 7738 const ValueDecl *VD = E->getMemberDecl(); 7739 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD)) 7740 return checkDecl(E, VD); 7741 } 7742 return false; 7743 } 7744 bool VisitStmt(const Stmt *S) { 7745 bool Res = false; 7746 for (const Stmt *Child : S->children()) 7747 Res = (Child && Visit(Child)) || Res; 7748 return Res; 7749 } 7750 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack, 7751 const ValueDecl *CurLCDecl, bool IsInitializer, 7752 const ValueDecl *PrevDepDecl = nullptr, 7753 bool SupportsNonRectangular = true) 7754 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl), 7755 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer), 7756 SupportsNonRectangular(SupportsNonRectangular) {} 7757 unsigned getBaseLoopId() const { 7758 assert(CurLCDecl && "Expected loop dependency."); 7759 return BaseLoopId; 7760 } 7761 const ValueDecl *getDepDecl() const { 7762 assert(CurLCDecl && "Expected loop dependency."); 7763 return DepDecl; 7764 } 7765 }; 7766 } // namespace 7767 7768 Optional<unsigned> 7769 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S, 7770 bool IsInitializer) { 7771 // Check for the non-rectangular loops. 7772 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer, 7773 DepDecl, SupportsNonRectangular); 7774 if (LoopStmtChecker.Visit(S)) { 7775 DepDecl = LoopStmtChecker.getDepDecl(); 7776 return LoopStmtChecker.getBaseLoopId(); 7777 } 7778 return llvm::None; 7779 } 7780 7781 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) { 7782 // Check init-expr for canonical loop form and save loop counter 7783 // variable - #Var and its initialization value - #LB. 7784 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 7785 // var = lb 7786 // integer-type var = lb 7787 // random-access-iterator-type var = lb 7788 // pointer-type var = lb 7789 // 7790 if (!S) { 7791 if (EmitDiags) { 7792 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 7793 } 7794 return true; 7795 } 7796 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 7797 if (!ExprTemp->cleanupsHaveSideEffects()) 7798 S = ExprTemp->getSubExpr(); 7799 7800 InitSrcRange = S->getSourceRange(); 7801 if (Expr *E = dyn_cast<Expr>(S)) 7802 S = E->IgnoreParens(); 7803 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 7804 if (BO->getOpcode() == BO_Assign) { 7805 Expr *LHS = BO->getLHS()->IgnoreParens(); 7806 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 7807 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 7808 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 7809 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7810 EmitDiags); 7811 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags); 7812 } 7813 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 7814 if (ME->isArrow() && 7815 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7816 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7817 EmitDiags); 7818 } 7819 } 7820 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 7821 if (DS->isSingleDecl()) { 7822 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 7823 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 7824 // Accept non-canonical init form here but emit ext. warning. 7825 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 7826 SemaRef.Diag(S->getBeginLoc(), 7827 diag::ext_omp_loop_not_canonical_init) 7828 << S->getSourceRange(); 7829 return setLCDeclAndLB( 7830 Var, 7831 buildDeclRefExpr(SemaRef, Var, 7832 Var->getType().getNonReferenceType(), 7833 DS->getBeginLoc()), 7834 Var->getInit(), EmitDiags); 7835 } 7836 } 7837 } 7838 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 7839 if (CE->getOperator() == OO_Equal) { 7840 Expr *LHS = CE->getArg(0); 7841 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 7842 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 7843 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 7844 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7845 EmitDiags); 7846 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags); 7847 } 7848 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 7849 if (ME->isArrow() && 7850 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7851 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7852 EmitDiags); 7853 } 7854 } 7855 } 7856 7857 if (dependent() || SemaRef.CurContext->isDependentContext()) 7858 return false; 7859 if (EmitDiags) { 7860 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init) 7861 << S->getSourceRange(); 7862 } 7863 return true; 7864 } 7865 7866 /// Ignore parenthesizes, implicit casts, copy constructor and return the 7867 /// variable (which may be the loop variable) if possible. 7868 static const ValueDecl *getInitLCDecl(const Expr *E) { 7869 if (!E) 7870 return nullptr; 7871 E = getExprAsWritten(E); 7872 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 7873 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 7874 if ((Ctor->isCopyOrMoveConstructor() || 7875 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 7876 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 7877 E = CE->getArg(0)->IgnoreParenImpCasts(); 7878 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 7879 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 7880 return getCanonicalDecl(VD); 7881 } 7882 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E)) 7883 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7884 return getCanonicalDecl(ME->getMemberDecl()); 7885 return nullptr; 7886 } 7887 7888 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) { 7889 // Check test-expr for canonical form, save upper-bound UB, flags for 7890 // less/greater and for strict/non-strict comparison. 7891 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following: 7892 // var relational-op b 7893 // b relational-op var 7894 // 7895 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50; 7896 if (!S) { 7897 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) 7898 << (IneqCondIsCanonical ? 1 : 0) << LCDecl; 7899 return true; 7900 } 7901 Condition = S; 7902 S = getExprAsWritten(S); 7903 SourceLocation CondLoc = S->getBeginLoc(); 7904 auto &&CheckAndSetCond = [this, IneqCondIsCanonical]( 7905 BinaryOperatorKind Opcode, const Expr *LHS, 7906 const Expr *RHS, SourceRange SR, 7907 SourceLocation OpLoc) -> llvm::Optional<bool> { 7908 if (BinaryOperator::isRelationalOp(Opcode)) { 7909 if (getInitLCDecl(LHS) == LCDecl) 7910 return setUB(const_cast<Expr *>(RHS), 7911 (Opcode == BO_LT || Opcode == BO_LE), 7912 (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc); 7913 if (getInitLCDecl(RHS) == LCDecl) 7914 return setUB(const_cast<Expr *>(LHS), 7915 (Opcode == BO_GT || Opcode == BO_GE), 7916 (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc); 7917 } else if (IneqCondIsCanonical && Opcode == BO_NE) { 7918 return setUB(const_cast<Expr *>(getInitLCDecl(LHS) == LCDecl ? RHS : LHS), 7919 /*LessOp=*/llvm::None, 7920 /*StrictOp=*/true, SR, OpLoc); 7921 } 7922 return llvm::None; 7923 }; 7924 llvm::Optional<bool> Res; 7925 if (auto *RBO = dyn_cast<CXXRewrittenBinaryOperator>(S)) { 7926 CXXRewrittenBinaryOperator::DecomposedForm DF = RBO->getDecomposedForm(); 7927 Res = CheckAndSetCond(DF.Opcode, DF.LHS, DF.RHS, RBO->getSourceRange(), 7928 RBO->getOperatorLoc()); 7929 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 7930 Res = CheckAndSetCond(BO->getOpcode(), BO->getLHS(), BO->getRHS(), 7931 BO->getSourceRange(), BO->getOperatorLoc()); 7932 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 7933 if (CE->getNumArgs() == 2) { 7934 Res = CheckAndSetCond( 7935 BinaryOperator::getOverloadedOpcode(CE->getOperator()), CE->getArg(0), 7936 CE->getArg(1), CE->getSourceRange(), CE->getOperatorLoc()); 7937 } 7938 } 7939 if (Res.hasValue()) 7940 return *Res; 7941 if (dependent() || SemaRef.CurContext->isDependentContext()) 7942 return false; 7943 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 7944 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl; 7945 return true; 7946 } 7947 7948 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) { 7949 // RHS of canonical loop form increment can be: 7950 // var + incr 7951 // incr + var 7952 // var - incr 7953 // 7954 RHS = RHS->IgnoreParenImpCasts(); 7955 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 7956 if (BO->isAdditiveOp()) { 7957 bool IsAdd = BO->getOpcode() == BO_Add; 7958 if (getInitLCDecl(BO->getLHS()) == LCDecl) 7959 return setStep(BO->getRHS(), !IsAdd); 7960 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl) 7961 return setStep(BO->getLHS(), /*Subtract=*/false); 7962 } 7963 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 7964 bool IsAdd = CE->getOperator() == OO_Plus; 7965 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 7966 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 7967 return setStep(CE->getArg(1), !IsAdd); 7968 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl) 7969 return setStep(CE->getArg(0), /*Subtract=*/false); 7970 } 7971 } 7972 if (dependent() || SemaRef.CurContext->isDependentContext()) 7973 return false; 7974 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 7975 << RHS->getSourceRange() << LCDecl; 7976 return true; 7977 } 7978 7979 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) { 7980 // Check incr-expr for canonical loop form and return true if it 7981 // does not conform. 7982 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 7983 // ++var 7984 // var++ 7985 // --var 7986 // var-- 7987 // var += incr 7988 // var -= incr 7989 // var = var + incr 7990 // var = incr + var 7991 // var = var - incr 7992 // 7993 if (!S) { 7994 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 7995 return true; 7996 } 7997 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 7998 if (!ExprTemp->cleanupsHaveSideEffects()) 7999 S = ExprTemp->getSubExpr(); 8000 8001 IncrementSrcRange = S->getSourceRange(); 8002 S = S->IgnoreParens(); 8003 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 8004 if (UO->isIncrementDecrementOp() && 8005 getInitLCDecl(UO->getSubExpr()) == LCDecl) 8006 return setStep(SemaRef 8007 .ActOnIntegerConstant(UO->getBeginLoc(), 8008 (UO->isDecrementOp() ? -1 : 1)) 8009 .get(), 8010 /*Subtract=*/false); 8011 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 8012 switch (BO->getOpcode()) { 8013 case BO_AddAssign: 8014 case BO_SubAssign: 8015 if (getInitLCDecl(BO->getLHS()) == LCDecl) 8016 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 8017 break; 8018 case BO_Assign: 8019 if (getInitLCDecl(BO->getLHS()) == LCDecl) 8020 return checkAndSetIncRHS(BO->getRHS()); 8021 break; 8022 default: 8023 break; 8024 } 8025 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 8026 switch (CE->getOperator()) { 8027 case OO_PlusPlus: 8028 case OO_MinusMinus: 8029 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 8030 return setStep(SemaRef 8031 .ActOnIntegerConstant( 8032 CE->getBeginLoc(), 8033 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 8034 .get(), 8035 /*Subtract=*/false); 8036 break; 8037 case OO_PlusEqual: 8038 case OO_MinusEqual: 8039 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 8040 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 8041 break; 8042 case OO_Equal: 8043 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 8044 return checkAndSetIncRHS(CE->getArg(1)); 8045 break; 8046 default: 8047 break; 8048 } 8049 } 8050 if (dependent() || SemaRef.CurContext->isDependentContext()) 8051 return false; 8052 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 8053 << S->getSourceRange() << LCDecl; 8054 return true; 8055 } 8056 8057 static ExprResult 8058 tryBuildCapture(Sema &SemaRef, Expr *Capture, 8059 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8060 if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors()) 8061 return Capture; 8062 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 8063 return SemaRef.PerformImplicitConversion( 8064 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 8065 /*AllowExplicit=*/true); 8066 auto I = Captures.find(Capture); 8067 if (I != Captures.end()) 8068 return buildCapture(SemaRef, Capture, I->second); 8069 DeclRefExpr *Ref = nullptr; 8070 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 8071 Captures[Capture] = Ref; 8072 return Res; 8073 } 8074 8075 /// Calculate number of iterations, transforming to unsigned, if number of 8076 /// iterations may be larger than the original type. 8077 static Expr * 8078 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc, 8079 Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy, 8080 bool TestIsStrictOp, bool RoundToStep, 8081 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8082 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 8083 if (!NewStep.isUsable()) 8084 return nullptr; 8085 llvm::APSInt LRes, SRes; 8086 bool IsLowerConst = false, IsStepConst = false; 8087 if (Optional<llvm::APSInt> Res = 8088 Lower->getIntegerConstantExpr(SemaRef.Context)) { 8089 LRes = *Res; 8090 IsLowerConst = true; 8091 } 8092 if (Optional<llvm::APSInt> Res = 8093 Step->getIntegerConstantExpr(SemaRef.Context)) { 8094 SRes = *Res; 8095 IsStepConst = true; 8096 } 8097 bool NoNeedToConvert = IsLowerConst && !RoundToStep && 8098 ((!TestIsStrictOp && LRes.isNonNegative()) || 8099 (TestIsStrictOp && LRes.isStrictlyPositive())); 8100 bool NeedToReorganize = false; 8101 // Check if any subexpressions in Lower -Step [+ 1] lead to overflow. 8102 if (!NoNeedToConvert && IsLowerConst && 8103 (TestIsStrictOp || (RoundToStep && IsStepConst))) { 8104 NoNeedToConvert = true; 8105 if (RoundToStep) { 8106 unsigned BW = LRes.getBitWidth() > SRes.getBitWidth() 8107 ? LRes.getBitWidth() 8108 : SRes.getBitWidth(); 8109 LRes = LRes.extend(BW + 1); 8110 LRes.setIsSigned(true); 8111 SRes = SRes.extend(BW + 1); 8112 SRes.setIsSigned(true); 8113 LRes -= SRes; 8114 NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes; 8115 LRes = LRes.trunc(BW); 8116 } 8117 if (TestIsStrictOp) { 8118 unsigned BW = LRes.getBitWidth(); 8119 LRes = LRes.extend(BW + 1); 8120 LRes.setIsSigned(true); 8121 ++LRes; 8122 NoNeedToConvert = 8123 NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes; 8124 // truncate to the original bitwidth. 8125 LRes = LRes.trunc(BW); 8126 } 8127 NeedToReorganize = NoNeedToConvert; 8128 } 8129 llvm::APSInt URes; 8130 bool IsUpperConst = false; 8131 if (Optional<llvm::APSInt> Res = 8132 Upper->getIntegerConstantExpr(SemaRef.Context)) { 8133 URes = *Res; 8134 IsUpperConst = true; 8135 } 8136 if (NoNeedToConvert && IsLowerConst && IsUpperConst && 8137 (!RoundToStep || IsStepConst)) { 8138 unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth() 8139 : URes.getBitWidth(); 8140 LRes = LRes.extend(BW + 1); 8141 LRes.setIsSigned(true); 8142 URes = URes.extend(BW + 1); 8143 URes.setIsSigned(true); 8144 URes -= LRes; 8145 NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes; 8146 NeedToReorganize = NoNeedToConvert; 8147 } 8148 // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant 8149 // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to 8150 // unsigned. 8151 if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) && 8152 !LCTy->isDependentType() && LCTy->isIntegerType()) { 8153 QualType LowerTy = Lower->getType(); 8154 QualType UpperTy = Upper->getType(); 8155 uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy); 8156 uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy); 8157 if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) || 8158 (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) { 8159 QualType CastType = SemaRef.Context.getIntTypeForBitwidth( 8160 LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0); 8161 Upper = 8162 SemaRef 8163 .PerformImplicitConversion( 8164 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(), 8165 CastType, Sema::AA_Converting) 8166 .get(); 8167 Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(); 8168 NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get()); 8169 } 8170 } 8171 if (!Lower || !Upper || NewStep.isInvalid()) 8172 return nullptr; 8173 8174 ExprResult Diff; 8175 // If need to reorganize, then calculate the form as Upper - (Lower - Step [+ 8176 // 1]). 8177 if (NeedToReorganize) { 8178 Diff = Lower; 8179 8180 if (RoundToStep) { 8181 // Lower - Step 8182 Diff = 8183 SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get()); 8184 if (!Diff.isUsable()) 8185 return nullptr; 8186 } 8187 8188 // Lower - Step [+ 1] 8189 if (TestIsStrictOp) 8190 Diff = SemaRef.BuildBinOp( 8191 S, DefaultLoc, BO_Add, Diff.get(), 8192 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 8193 if (!Diff.isUsable()) 8194 return nullptr; 8195 8196 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8197 if (!Diff.isUsable()) 8198 return nullptr; 8199 8200 // Upper - (Lower - Step [+ 1]). 8201 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get()); 8202 if (!Diff.isUsable()) 8203 return nullptr; 8204 } else { 8205 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 8206 8207 if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) { 8208 // BuildBinOp already emitted error, this one is to point user to upper 8209 // and lower bound, and to tell what is passed to 'operator-'. 8210 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx) 8211 << Upper->getSourceRange() << Lower->getSourceRange(); 8212 return nullptr; 8213 } 8214 8215 if (!Diff.isUsable()) 8216 return nullptr; 8217 8218 // Upper - Lower [- 1] 8219 if (TestIsStrictOp) 8220 Diff = SemaRef.BuildBinOp( 8221 S, DefaultLoc, BO_Sub, Diff.get(), 8222 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 8223 if (!Diff.isUsable()) 8224 return nullptr; 8225 8226 if (RoundToStep) { 8227 // Upper - Lower [- 1] + Step 8228 Diff = 8229 SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 8230 if (!Diff.isUsable()) 8231 return nullptr; 8232 } 8233 } 8234 8235 // Parentheses (for dumping/debugging purposes only). 8236 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8237 if (!Diff.isUsable()) 8238 return nullptr; 8239 8240 // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step 8241 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 8242 if (!Diff.isUsable()) 8243 return nullptr; 8244 8245 return Diff.get(); 8246 } 8247 8248 /// Build the expression to calculate the number of iterations. 8249 Expr *OpenMPIterationSpaceChecker::buildNumIterations( 8250 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType, 8251 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 8252 QualType VarType = LCDecl->getType().getNonReferenceType(); 8253 if (!VarType->isIntegerType() && !VarType->isPointerType() && 8254 !SemaRef.getLangOpts().CPlusPlus) 8255 return nullptr; 8256 Expr *LBVal = LB; 8257 Expr *UBVal = UB; 8258 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) : 8259 // max(LB(MinVal), LB(MaxVal)) 8260 if (InitDependOnLC) { 8261 const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1]; 8262 if (!IS.MinValue || !IS.MaxValue) 8263 return nullptr; 8264 // OuterVar = Min 8265 ExprResult MinValue = 8266 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue); 8267 if (!MinValue.isUsable()) 8268 return nullptr; 8269 8270 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8271 IS.CounterVar, MinValue.get()); 8272 if (!LBMinVal.isUsable()) 8273 return nullptr; 8274 // OuterVar = Min, LBVal 8275 LBMinVal = 8276 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal); 8277 if (!LBMinVal.isUsable()) 8278 return nullptr; 8279 // (OuterVar = Min, LBVal) 8280 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get()); 8281 if (!LBMinVal.isUsable()) 8282 return nullptr; 8283 8284 // OuterVar = Max 8285 ExprResult MaxValue = 8286 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue); 8287 if (!MaxValue.isUsable()) 8288 return nullptr; 8289 8290 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8291 IS.CounterVar, MaxValue.get()); 8292 if (!LBMaxVal.isUsable()) 8293 return nullptr; 8294 // OuterVar = Max, LBVal 8295 LBMaxVal = 8296 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal); 8297 if (!LBMaxVal.isUsable()) 8298 return nullptr; 8299 // (OuterVar = Max, LBVal) 8300 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get()); 8301 if (!LBMaxVal.isUsable()) 8302 return nullptr; 8303 8304 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get(); 8305 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get(); 8306 if (!LBMin || !LBMax) 8307 return nullptr; 8308 // LB(MinVal) < LB(MaxVal) 8309 ExprResult MinLessMaxRes = 8310 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax); 8311 if (!MinLessMaxRes.isUsable()) 8312 return nullptr; 8313 Expr *MinLessMax = 8314 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get(); 8315 if (!MinLessMax) 8316 return nullptr; 8317 if (TestIsLessOp.getValue()) { 8318 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal), 8319 // LB(MaxVal)) 8320 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc, 8321 MinLessMax, LBMin, LBMax); 8322 if (!MinLB.isUsable()) 8323 return nullptr; 8324 LBVal = MinLB.get(); 8325 } else { 8326 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal), 8327 // LB(MaxVal)) 8328 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc, 8329 MinLessMax, LBMax, LBMin); 8330 if (!MaxLB.isUsable()) 8331 return nullptr; 8332 LBVal = MaxLB.get(); 8333 } 8334 } 8335 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) : 8336 // min(UB(MinVal), UB(MaxVal)) 8337 if (CondDependOnLC) { 8338 const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1]; 8339 if (!IS.MinValue || !IS.MaxValue) 8340 return nullptr; 8341 // OuterVar = Min 8342 ExprResult MinValue = 8343 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue); 8344 if (!MinValue.isUsable()) 8345 return nullptr; 8346 8347 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8348 IS.CounterVar, MinValue.get()); 8349 if (!UBMinVal.isUsable()) 8350 return nullptr; 8351 // OuterVar = Min, UBVal 8352 UBMinVal = 8353 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal); 8354 if (!UBMinVal.isUsable()) 8355 return nullptr; 8356 // (OuterVar = Min, UBVal) 8357 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get()); 8358 if (!UBMinVal.isUsable()) 8359 return nullptr; 8360 8361 // OuterVar = Max 8362 ExprResult MaxValue = 8363 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue); 8364 if (!MaxValue.isUsable()) 8365 return nullptr; 8366 8367 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8368 IS.CounterVar, MaxValue.get()); 8369 if (!UBMaxVal.isUsable()) 8370 return nullptr; 8371 // OuterVar = Max, UBVal 8372 UBMaxVal = 8373 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal); 8374 if (!UBMaxVal.isUsable()) 8375 return nullptr; 8376 // (OuterVar = Max, UBVal) 8377 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get()); 8378 if (!UBMaxVal.isUsable()) 8379 return nullptr; 8380 8381 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get(); 8382 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get(); 8383 if (!UBMin || !UBMax) 8384 return nullptr; 8385 // UB(MinVal) > UB(MaxVal) 8386 ExprResult MinGreaterMaxRes = 8387 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax); 8388 if (!MinGreaterMaxRes.isUsable()) 8389 return nullptr; 8390 Expr *MinGreaterMax = 8391 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get(); 8392 if (!MinGreaterMax) 8393 return nullptr; 8394 if (TestIsLessOp.getValue()) { 8395 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal), 8396 // UB(MaxVal)) 8397 ExprResult MaxUB = SemaRef.ActOnConditionalOp( 8398 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax); 8399 if (!MaxUB.isUsable()) 8400 return nullptr; 8401 UBVal = MaxUB.get(); 8402 } else { 8403 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal), 8404 // UB(MaxVal)) 8405 ExprResult MinUB = SemaRef.ActOnConditionalOp( 8406 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin); 8407 if (!MinUB.isUsable()) 8408 return nullptr; 8409 UBVal = MinUB.get(); 8410 } 8411 } 8412 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal; 8413 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal; 8414 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 8415 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 8416 if (!Upper || !Lower) 8417 return nullptr; 8418 8419 ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, 8420 Step, VarType, TestIsStrictOp, 8421 /*RoundToStep=*/true, Captures); 8422 if (!Diff.isUsable()) 8423 return nullptr; 8424 8425 // OpenMP runtime requires 32-bit or 64-bit loop variables. 8426 QualType Type = Diff.get()->getType(); 8427 ASTContext &C = SemaRef.Context; 8428 bool UseVarType = VarType->hasIntegerRepresentation() && 8429 C.getTypeSize(Type) > C.getTypeSize(VarType); 8430 if (!Type->isIntegerType() || UseVarType) { 8431 unsigned NewSize = 8432 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 8433 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 8434 : Type->hasSignedIntegerRepresentation(); 8435 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 8436 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 8437 Diff = SemaRef.PerformImplicitConversion( 8438 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 8439 if (!Diff.isUsable()) 8440 return nullptr; 8441 } 8442 } 8443 if (LimitedType) { 8444 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 8445 if (NewSize != C.getTypeSize(Type)) { 8446 if (NewSize < C.getTypeSize(Type)) { 8447 assert(NewSize == 64 && "incorrect loop var size"); 8448 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 8449 << InitSrcRange << ConditionSrcRange; 8450 } 8451 QualType NewType = C.getIntTypeForBitwidth( 8452 NewSize, Type->hasSignedIntegerRepresentation() || 8453 C.getTypeSize(Type) < NewSize); 8454 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 8455 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 8456 Sema::AA_Converting, true); 8457 if (!Diff.isUsable()) 8458 return nullptr; 8459 } 8460 } 8461 } 8462 8463 return Diff.get(); 8464 } 8465 8466 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues( 8467 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 8468 // Do not build for iterators, they cannot be used in non-rectangular loop 8469 // nests. 8470 if (LCDecl->getType()->isRecordType()) 8471 return std::make_pair(nullptr, nullptr); 8472 // If we subtract, the min is in the condition, otherwise the min is in the 8473 // init value. 8474 Expr *MinExpr = nullptr; 8475 Expr *MaxExpr = nullptr; 8476 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB; 8477 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB; 8478 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue() 8479 : CondDependOnLC.hasValue(); 8480 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue() 8481 : InitDependOnLC.hasValue(); 8482 Expr *Lower = 8483 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get(); 8484 Expr *Upper = 8485 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get(); 8486 if (!Upper || !Lower) 8487 return std::make_pair(nullptr, nullptr); 8488 8489 if (TestIsLessOp.getValue()) 8490 MinExpr = Lower; 8491 else 8492 MaxExpr = Upper; 8493 8494 // Build minimum/maximum value based on number of iterations. 8495 QualType VarType = LCDecl->getType().getNonReferenceType(); 8496 8497 ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, 8498 Step, VarType, TestIsStrictOp, 8499 /*RoundToStep=*/false, Captures); 8500 if (!Diff.isUsable()) 8501 return std::make_pair(nullptr, nullptr); 8502 8503 // ((Upper - Lower [- 1]) / Step) * Step 8504 // Parentheses (for dumping/debugging purposes only). 8505 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8506 if (!Diff.isUsable()) 8507 return std::make_pair(nullptr, nullptr); 8508 8509 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 8510 if (!NewStep.isUsable()) 8511 return std::make_pair(nullptr, nullptr); 8512 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get()); 8513 if (!Diff.isUsable()) 8514 return std::make_pair(nullptr, nullptr); 8515 8516 // Parentheses (for dumping/debugging purposes only). 8517 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8518 if (!Diff.isUsable()) 8519 return std::make_pair(nullptr, nullptr); 8520 8521 // Convert to the ptrdiff_t, if original type is pointer. 8522 if (VarType->isAnyPointerType() && 8523 !SemaRef.Context.hasSameType( 8524 Diff.get()->getType(), 8525 SemaRef.Context.getUnsignedPointerDiffType())) { 8526 Diff = SemaRef.PerformImplicitConversion( 8527 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(), 8528 Sema::AA_Converting, /*AllowExplicit=*/true); 8529 } 8530 if (!Diff.isUsable()) 8531 return std::make_pair(nullptr, nullptr); 8532 8533 if (TestIsLessOp.getValue()) { 8534 // MinExpr = Lower; 8535 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step) 8536 Diff = SemaRef.BuildBinOp( 8537 S, DefaultLoc, BO_Add, 8538 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(), 8539 Diff.get()); 8540 if (!Diff.isUsable()) 8541 return std::make_pair(nullptr, nullptr); 8542 } else { 8543 // MaxExpr = Upper; 8544 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step) 8545 Diff = SemaRef.BuildBinOp( 8546 S, DefaultLoc, BO_Sub, 8547 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(), 8548 Diff.get()); 8549 if (!Diff.isUsable()) 8550 return std::make_pair(nullptr, nullptr); 8551 } 8552 8553 // Convert to the original type. 8554 if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) 8555 Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType, 8556 Sema::AA_Converting, 8557 /*AllowExplicit=*/true); 8558 if (!Diff.isUsable()) 8559 return std::make_pair(nullptr, nullptr); 8560 8561 Sema::TentativeAnalysisScope Trap(SemaRef); 8562 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false); 8563 if (!Diff.isUsable()) 8564 return std::make_pair(nullptr, nullptr); 8565 8566 if (TestIsLessOp.getValue()) 8567 MaxExpr = Diff.get(); 8568 else 8569 MinExpr = Diff.get(); 8570 8571 return std::make_pair(MinExpr, MaxExpr); 8572 } 8573 8574 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const { 8575 if (InitDependOnLC || CondDependOnLC) 8576 return Condition; 8577 return nullptr; 8578 } 8579 8580 Expr *OpenMPIterationSpaceChecker::buildPreCond( 8581 Scope *S, Expr *Cond, 8582 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 8583 // Do not build a precondition when the condition/initialization is dependent 8584 // to prevent pessimistic early loop exit. 8585 // TODO: this can be improved by calculating min/max values but not sure that 8586 // it will be very effective. 8587 if (CondDependOnLC || InitDependOnLC) 8588 return SemaRef 8589 .PerformImplicitConversion( 8590 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(), 8591 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 8592 /*AllowExplicit=*/true) 8593 .get(); 8594 8595 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 8596 Sema::TentativeAnalysisScope Trap(SemaRef); 8597 8598 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures); 8599 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures); 8600 if (!NewLB.isUsable() || !NewUB.isUsable()) 8601 return nullptr; 8602 8603 ExprResult CondExpr = SemaRef.BuildBinOp( 8604 S, DefaultLoc, 8605 TestIsLessOp.getValue() ? (TestIsStrictOp ? BO_LT : BO_LE) 8606 : (TestIsStrictOp ? BO_GT : BO_GE), 8607 NewLB.get(), NewUB.get()); 8608 if (CondExpr.isUsable()) { 8609 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 8610 SemaRef.Context.BoolTy)) 8611 CondExpr = SemaRef.PerformImplicitConversion( 8612 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 8613 /*AllowExplicit=*/true); 8614 } 8615 8616 // Otherwise use original loop condition and evaluate it in runtime. 8617 return CondExpr.isUsable() ? CondExpr.get() : Cond; 8618 } 8619 8620 /// Build reference expression to the counter be used for codegen. 8621 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar( 8622 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 8623 DSAStackTy &DSA) const { 8624 auto *VD = dyn_cast<VarDecl>(LCDecl); 8625 if (!VD) { 8626 VD = SemaRef.isOpenMPCapturedDecl(LCDecl); 8627 DeclRefExpr *Ref = buildDeclRefExpr( 8628 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 8629 const DSAStackTy::DSAVarData Data = 8630 DSA.getTopDSA(LCDecl, /*FromParent=*/false); 8631 // If the loop control decl is explicitly marked as private, do not mark it 8632 // as captured again. 8633 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 8634 Captures.insert(std::make_pair(LCRef, Ref)); 8635 return Ref; 8636 } 8637 return cast<DeclRefExpr>(LCRef); 8638 } 8639 8640 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const { 8641 if (LCDecl && !LCDecl->isInvalidDecl()) { 8642 QualType Type = LCDecl->getType().getNonReferenceType(); 8643 VarDecl *PrivateVar = buildVarDecl( 8644 SemaRef, DefaultLoc, Type, LCDecl->getName(), 8645 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr, 8646 isa<VarDecl>(LCDecl) 8647 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc) 8648 : nullptr); 8649 if (PrivateVar->isInvalidDecl()) 8650 return nullptr; 8651 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 8652 } 8653 return nullptr; 8654 } 8655 8656 /// Build initialization of the counter to be used for codegen. 8657 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; } 8658 8659 /// Build step of the counter be used for codegen. 8660 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; } 8661 8662 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData( 8663 Scope *S, Expr *Counter, 8664 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc, 8665 Expr *Inc, OverloadedOperatorKind OOK) { 8666 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get(); 8667 if (!Cnt) 8668 return nullptr; 8669 if (Inc) { 8670 assert((OOK == OO_Plus || OOK == OO_Minus) && 8671 "Expected only + or - operations for depend clauses."); 8672 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub; 8673 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get(); 8674 if (!Cnt) 8675 return nullptr; 8676 } 8677 QualType VarType = LCDecl->getType().getNonReferenceType(); 8678 if (!VarType->isIntegerType() && !VarType->isPointerType() && 8679 !SemaRef.getLangOpts().CPlusPlus) 8680 return nullptr; 8681 // Upper - Lower 8682 Expr *Upper = TestIsLessOp.getValue() 8683 ? Cnt 8684 : tryBuildCapture(SemaRef, LB, Captures).get(); 8685 Expr *Lower = TestIsLessOp.getValue() 8686 ? tryBuildCapture(SemaRef, LB, Captures).get() 8687 : Cnt; 8688 if (!Upper || !Lower) 8689 return nullptr; 8690 8691 ExprResult Diff = calculateNumIters( 8692 SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType, 8693 /*TestIsStrictOp=*/false, /*RoundToStep=*/false, Captures); 8694 if (!Diff.isUsable()) 8695 return nullptr; 8696 8697 return Diff.get(); 8698 } 8699 } // namespace 8700 8701 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 8702 assert(getLangOpts().OpenMP && "OpenMP is not active."); 8703 assert(Init && "Expected loop in canonical form."); 8704 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 8705 if (AssociatedLoops > 0 && 8706 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 8707 DSAStack->loopStart(); 8708 OpenMPIterationSpaceChecker ISC(*this, /*SupportsNonRectangular=*/true, 8709 *DSAStack, ForLoc); 8710 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) { 8711 if (ValueDecl *D = ISC.getLoopDecl()) { 8712 auto *VD = dyn_cast<VarDecl>(D); 8713 DeclRefExpr *PrivateRef = nullptr; 8714 if (!VD) { 8715 if (VarDecl *Private = isOpenMPCapturedDecl(D)) { 8716 VD = Private; 8717 } else { 8718 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(), 8719 /*WithInit=*/false); 8720 VD = cast<VarDecl>(PrivateRef->getDecl()); 8721 } 8722 } 8723 DSAStack->addLoopControlVariable(D, VD); 8724 const Decl *LD = DSAStack->getPossiblyLoopCunter(); 8725 if (LD != D->getCanonicalDecl()) { 8726 DSAStack->resetPossibleLoopCounter(); 8727 if (auto *Var = dyn_cast_or_null<VarDecl>(LD)) 8728 MarkDeclarationsReferencedInExpr( 8729 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var), 8730 Var->getType().getNonLValueExprType(Context), 8731 ForLoc, /*RefersToCapture=*/true)); 8732 } 8733 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 8734 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables 8735 // Referenced in a Construct, C/C++]. The loop iteration variable in the 8736 // associated for-loop of a simd construct with just one associated 8737 // for-loop may be listed in a linear clause with a constant-linear-step 8738 // that is the increment of the associated for-loop. The loop iteration 8739 // variable(s) in the associated for-loop(s) of a for or parallel for 8740 // construct may be listed in a private or lastprivate clause. 8741 DSAStackTy::DSAVarData DVar = 8742 DSAStack->getTopDSA(D, /*FromParent=*/false); 8743 // If LoopVarRefExpr is nullptr it means the corresponding loop variable 8744 // is declared in the loop and it is predetermined as a private. 8745 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr(); 8746 OpenMPClauseKind PredeterminedCKind = 8747 isOpenMPSimdDirective(DKind) 8748 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear) 8749 : OMPC_private; 8750 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 8751 DVar.CKind != PredeterminedCKind && DVar.RefExpr && 8752 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate && 8753 DVar.CKind != OMPC_private))) || 8754 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 8755 DKind == OMPD_master_taskloop || 8756 DKind == OMPD_parallel_master_taskloop || 8757 isOpenMPDistributeDirective(DKind)) && 8758 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 8759 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 8760 (DVar.CKind != OMPC_private || DVar.RefExpr)) { 8761 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa) 8762 << getOpenMPClauseName(DVar.CKind) 8763 << getOpenMPDirectiveName(DKind) 8764 << getOpenMPClauseName(PredeterminedCKind); 8765 if (DVar.RefExpr == nullptr) 8766 DVar.CKind = PredeterminedCKind; 8767 reportOriginalDsa(*this, DSAStack, D, DVar, 8768 /*IsLoopIterVar=*/true); 8769 } else if (LoopDeclRefExpr) { 8770 // Make the loop iteration variable private (for worksharing 8771 // constructs), linear (for simd directives with the only one 8772 // associated loop) or lastprivate (for simd directives with several 8773 // collapsed or ordered loops). 8774 if (DVar.CKind == OMPC_unknown) 8775 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind, 8776 PrivateRef); 8777 } 8778 } 8779 } 8780 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 8781 } 8782 } 8783 8784 /// Called on a for stmt to check and extract its iteration space 8785 /// for further processing (such as collapsing). 8786 static bool checkOpenMPIterationSpace( 8787 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 8788 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 8789 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr, 8790 Expr *OrderedLoopCountExpr, 8791 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 8792 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces, 8793 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8794 bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind); 8795 // OpenMP [2.9.1, Canonical Loop Form] 8796 // for (init-expr; test-expr; incr-expr) structured-block 8797 // for (range-decl: range-expr) structured-block 8798 if (auto *CanonLoop = dyn_cast_or_null<OMPCanonicalLoop>(S)) 8799 S = CanonLoop->getLoopStmt(); 8800 auto *For = dyn_cast_or_null<ForStmt>(S); 8801 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S); 8802 // Ranged for is supported only in OpenMP 5.0. 8803 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) { 8804 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for) 8805 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 8806 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount 8807 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 8808 if (TotalNestedLoopCount > 1) { 8809 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 8810 SemaRef.Diag(DSA.getConstructLoc(), 8811 diag::note_omp_collapse_ordered_expr) 8812 << 2 << CollapseLoopCountExpr->getSourceRange() 8813 << OrderedLoopCountExpr->getSourceRange(); 8814 else if (CollapseLoopCountExpr) 8815 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 8816 diag::note_omp_collapse_ordered_expr) 8817 << 0 << CollapseLoopCountExpr->getSourceRange(); 8818 else 8819 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 8820 diag::note_omp_collapse_ordered_expr) 8821 << 1 << OrderedLoopCountExpr->getSourceRange(); 8822 } 8823 return true; 8824 } 8825 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) && 8826 "No loop body."); 8827 // Postpone analysis in dependent contexts for ranged for loops. 8828 if (CXXFor && SemaRef.CurContext->isDependentContext()) 8829 return false; 8830 8831 OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA, 8832 For ? For->getForLoc() : CXXFor->getForLoc()); 8833 8834 // Check init. 8835 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt(); 8836 if (ISC.checkAndSetInit(Init)) 8837 return true; 8838 8839 bool HasErrors = false; 8840 8841 // Check loop variable's type. 8842 if (ValueDecl *LCDecl = ISC.getLoopDecl()) { 8843 // OpenMP [2.6, Canonical Loop Form] 8844 // Var is one of the following: 8845 // A variable of signed or unsigned integer type. 8846 // For C++, a variable of a random access iterator type. 8847 // For C, a variable of a pointer type. 8848 QualType VarType = LCDecl->getType().getNonReferenceType(); 8849 if (!VarType->isDependentType() && !VarType->isIntegerType() && 8850 !VarType->isPointerType() && 8851 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 8852 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type) 8853 << SemaRef.getLangOpts().CPlusPlus; 8854 HasErrors = true; 8855 } 8856 8857 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 8858 // a Construct 8859 // The loop iteration variable(s) in the associated for-loop(s) of a for or 8860 // parallel for construct is (are) private. 8861 // The loop iteration variable in the associated for-loop of a simd 8862 // construct with just one associated for-loop is linear with a 8863 // constant-linear-step that is the increment of the associated for-loop. 8864 // Exclude loop var from the list of variables with implicitly defined data 8865 // sharing attributes. 8866 VarsWithImplicitDSA.erase(LCDecl); 8867 8868 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 8869 8870 // Check test-expr. 8871 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond()); 8872 8873 // Check incr-expr. 8874 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc()); 8875 } 8876 8877 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 8878 return HasErrors; 8879 8880 // Build the loop's iteration space representation. 8881 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond( 8882 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures); 8883 ResultIterSpaces[CurrentNestedLoopCount].NumIterations = 8884 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces, 8885 (isOpenMPWorksharingDirective(DKind) || 8886 isOpenMPGenericLoopDirective(DKind) || 8887 isOpenMPTaskLoopDirective(DKind) || 8888 isOpenMPDistributeDirective(DKind) || 8889 isOpenMPLoopTransformationDirective(DKind)), 8890 Captures); 8891 ResultIterSpaces[CurrentNestedLoopCount].CounterVar = 8892 ISC.buildCounterVar(Captures, DSA); 8893 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar = 8894 ISC.buildPrivateCounterVar(); 8895 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit(); 8896 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep(); 8897 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange(); 8898 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange = 8899 ISC.getConditionSrcRange(); 8900 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange = 8901 ISC.getIncrementSrcRange(); 8902 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep(); 8903 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare = 8904 ISC.isStrictTestOp(); 8905 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue, 8906 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) = 8907 ISC.buildMinMaxValues(DSA.getCurScope(), Captures); 8908 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition = 8909 ISC.buildFinalCondition(DSA.getCurScope()); 8910 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB = 8911 ISC.doesInitDependOnLC(); 8912 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB = 8913 ISC.doesCondDependOnLC(); 8914 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx = 8915 ISC.getLoopDependentIdx(); 8916 8917 HasErrors |= 8918 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr || 8919 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr || 8920 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr || 8921 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr || 8922 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr || 8923 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr); 8924 if (!HasErrors && DSA.isOrderedRegion()) { 8925 if (DSA.getOrderedRegionParam().second->getNumForLoops()) { 8926 if (CurrentNestedLoopCount < 8927 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) { 8928 DSA.getOrderedRegionParam().second->setLoopNumIterations( 8929 CurrentNestedLoopCount, 8930 ResultIterSpaces[CurrentNestedLoopCount].NumIterations); 8931 DSA.getOrderedRegionParam().second->setLoopCounter( 8932 CurrentNestedLoopCount, 8933 ResultIterSpaces[CurrentNestedLoopCount].CounterVar); 8934 } 8935 } 8936 for (auto &Pair : DSA.getDoacrossDependClauses()) { 8937 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) { 8938 // Erroneous case - clause has some problems. 8939 continue; 8940 } 8941 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink && 8942 Pair.second.size() <= CurrentNestedLoopCount) { 8943 // Erroneous case - clause has some problems. 8944 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr); 8945 continue; 8946 } 8947 Expr *CntValue; 8948 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 8949 CntValue = ISC.buildOrderedLoopData( 8950 DSA.getCurScope(), 8951 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures, 8952 Pair.first->getDependencyLoc()); 8953 else 8954 CntValue = ISC.buildOrderedLoopData( 8955 DSA.getCurScope(), 8956 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures, 8957 Pair.first->getDependencyLoc(), 8958 Pair.second[CurrentNestedLoopCount].first, 8959 Pair.second[CurrentNestedLoopCount].second); 8960 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue); 8961 } 8962 } 8963 8964 return HasErrors; 8965 } 8966 8967 /// Build 'VarRef = Start. 8968 static ExprResult 8969 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 8970 ExprResult Start, bool IsNonRectangularLB, 8971 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8972 // Build 'VarRef = Start. 8973 ExprResult NewStart = IsNonRectangularLB 8974 ? Start.get() 8975 : tryBuildCapture(SemaRef, Start.get(), Captures); 8976 if (!NewStart.isUsable()) 8977 return ExprError(); 8978 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 8979 VarRef.get()->getType())) { 8980 NewStart = SemaRef.PerformImplicitConversion( 8981 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 8982 /*AllowExplicit=*/true); 8983 if (!NewStart.isUsable()) 8984 return ExprError(); 8985 } 8986 8987 ExprResult Init = 8988 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 8989 return Init; 8990 } 8991 8992 /// Build 'VarRef = Start + Iter * Step'. 8993 static ExprResult buildCounterUpdate( 8994 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 8995 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract, 8996 bool IsNonRectangularLB, 8997 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) { 8998 // Add parentheses (for debugging purposes only). 8999 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 9000 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 9001 !Step.isUsable()) 9002 return ExprError(); 9003 9004 ExprResult NewStep = Step; 9005 if (Captures) 9006 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 9007 if (NewStep.isInvalid()) 9008 return ExprError(); 9009 ExprResult Update = 9010 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 9011 if (!Update.isUsable()) 9012 return ExprError(); 9013 9014 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 9015 // 'VarRef = Start (+|-) Iter * Step'. 9016 if (!Start.isUsable()) 9017 return ExprError(); 9018 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get()); 9019 if (!NewStart.isUsable()) 9020 return ExprError(); 9021 if (Captures && !IsNonRectangularLB) 9022 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 9023 if (NewStart.isInvalid()) 9024 return ExprError(); 9025 9026 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 9027 ExprResult SavedUpdate = Update; 9028 ExprResult UpdateVal; 9029 if (VarRef.get()->getType()->isOverloadableType() || 9030 NewStart.get()->getType()->isOverloadableType() || 9031 Update.get()->getType()->isOverloadableType()) { 9032 Sema::TentativeAnalysisScope Trap(SemaRef); 9033 9034 Update = 9035 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 9036 if (Update.isUsable()) { 9037 UpdateVal = 9038 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 9039 VarRef.get(), SavedUpdate.get()); 9040 if (UpdateVal.isUsable()) { 9041 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 9042 UpdateVal.get()); 9043 } 9044 } 9045 } 9046 9047 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 9048 if (!Update.isUsable() || !UpdateVal.isUsable()) { 9049 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 9050 NewStart.get(), SavedUpdate.get()); 9051 if (!Update.isUsable()) 9052 return ExprError(); 9053 9054 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 9055 VarRef.get()->getType())) { 9056 Update = SemaRef.PerformImplicitConversion( 9057 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 9058 if (!Update.isUsable()) 9059 return ExprError(); 9060 } 9061 9062 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 9063 } 9064 return Update; 9065 } 9066 9067 /// Convert integer expression \a E to make it have at least \a Bits 9068 /// bits. 9069 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 9070 if (E == nullptr) 9071 return ExprError(); 9072 ASTContext &C = SemaRef.Context; 9073 QualType OldType = E->getType(); 9074 unsigned HasBits = C.getTypeSize(OldType); 9075 if (HasBits >= Bits) 9076 return ExprResult(E); 9077 // OK to convert to signed, because new type has more bits than old. 9078 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 9079 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 9080 true); 9081 } 9082 9083 /// Check if the given expression \a E is a constant integer that fits 9084 /// into \a Bits bits. 9085 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) { 9086 if (E == nullptr) 9087 return false; 9088 if (Optional<llvm::APSInt> Result = 9089 E->getIntegerConstantExpr(SemaRef.Context)) 9090 return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits); 9091 return false; 9092 } 9093 9094 /// Build preinits statement for the given declarations. 9095 static Stmt *buildPreInits(ASTContext &Context, 9096 MutableArrayRef<Decl *> PreInits) { 9097 if (!PreInits.empty()) { 9098 return new (Context) DeclStmt( 9099 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 9100 SourceLocation(), SourceLocation()); 9101 } 9102 return nullptr; 9103 } 9104 9105 /// Build preinits statement for the given declarations. 9106 static Stmt * 9107 buildPreInits(ASTContext &Context, 9108 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 9109 if (!Captures.empty()) { 9110 SmallVector<Decl *, 16> PreInits; 9111 for (const auto &Pair : Captures) 9112 PreInits.push_back(Pair.second->getDecl()); 9113 return buildPreInits(Context, PreInits); 9114 } 9115 return nullptr; 9116 } 9117 9118 /// Build postupdate expression for the given list of postupdates expressions. 9119 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 9120 Expr *PostUpdate = nullptr; 9121 if (!PostUpdates.empty()) { 9122 for (Expr *E : PostUpdates) { 9123 Expr *ConvE = S.BuildCStyleCastExpr( 9124 E->getExprLoc(), 9125 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 9126 E->getExprLoc(), E) 9127 .get(); 9128 PostUpdate = PostUpdate 9129 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 9130 PostUpdate, ConvE) 9131 .get() 9132 : ConvE; 9133 } 9134 } 9135 return PostUpdate; 9136 } 9137 9138 /// Called on a for stmt to check itself and nested loops (if any). 9139 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 9140 /// number of collapsed loops otherwise. 9141 static unsigned 9142 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 9143 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 9144 DSAStackTy &DSA, 9145 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 9146 OMPLoopBasedDirective::HelperExprs &Built) { 9147 unsigned NestedLoopCount = 1; 9148 bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) && 9149 !isOpenMPLoopTransformationDirective(DKind); 9150 9151 if (CollapseLoopCountExpr) { 9152 // Found 'collapse' clause - calculate collapse number. 9153 Expr::EvalResult Result; 9154 if (!CollapseLoopCountExpr->isValueDependent() && 9155 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 9156 NestedLoopCount = Result.Val.getInt().getLimitedValue(); 9157 } else { 9158 Built.clear(/*Size=*/1); 9159 return 1; 9160 } 9161 } 9162 unsigned OrderedLoopCount = 1; 9163 if (OrderedLoopCountExpr) { 9164 // Found 'ordered' clause - calculate collapse number. 9165 Expr::EvalResult EVResult; 9166 if (!OrderedLoopCountExpr->isValueDependent() && 9167 OrderedLoopCountExpr->EvaluateAsInt(EVResult, 9168 SemaRef.getASTContext())) { 9169 llvm::APSInt Result = EVResult.Val.getInt(); 9170 if (Result.getLimitedValue() < NestedLoopCount) { 9171 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 9172 diag::err_omp_wrong_ordered_loop_count) 9173 << OrderedLoopCountExpr->getSourceRange(); 9174 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 9175 diag::note_collapse_loop_count) 9176 << CollapseLoopCountExpr->getSourceRange(); 9177 } 9178 OrderedLoopCount = Result.getLimitedValue(); 9179 } else { 9180 Built.clear(/*Size=*/1); 9181 return 1; 9182 } 9183 } 9184 // This is helper routine for loop directives (e.g., 'for', 'simd', 9185 // 'for simd', etc.). 9186 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 9187 unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount); 9188 SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops); 9189 if (!OMPLoopBasedDirective::doForAllLoops( 9190 AStmt->IgnoreContainers(!isOpenMPLoopTransformationDirective(DKind)), 9191 SupportsNonPerfectlyNested, NumLoops, 9192 [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount, 9193 CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA, 9194 &IterSpaces, &Captures](unsigned Cnt, Stmt *CurStmt) { 9195 if (checkOpenMPIterationSpace( 9196 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 9197 NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr, 9198 VarsWithImplicitDSA, IterSpaces, Captures)) 9199 return true; 9200 if (Cnt > 0 && Cnt >= NestedLoopCount && 9201 IterSpaces[Cnt].CounterVar) { 9202 // Handle initialization of captured loop iterator variables. 9203 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar); 9204 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) { 9205 Captures[DRE] = DRE; 9206 } 9207 } 9208 return false; 9209 }, 9210 [&SemaRef, &Captures](OMPLoopTransformationDirective *Transform) { 9211 Stmt *DependentPreInits = Transform->getPreInits(); 9212 if (!DependentPreInits) 9213 return; 9214 for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) { 9215 auto *D = cast<VarDecl>(C); 9216 DeclRefExpr *Ref = buildDeclRefExpr(SemaRef, D, D->getType(), 9217 Transform->getBeginLoc()); 9218 Captures[Ref] = Ref; 9219 } 9220 })) 9221 return 0; 9222 9223 Built.clear(/* size */ NestedLoopCount); 9224 9225 if (SemaRef.CurContext->isDependentContext()) 9226 return NestedLoopCount; 9227 9228 // An example of what is generated for the following code: 9229 // 9230 // #pragma omp simd collapse(2) ordered(2) 9231 // for (i = 0; i < NI; ++i) 9232 // for (k = 0; k < NK; ++k) 9233 // for (j = J0; j < NJ; j+=2) { 9234 // <loop body> 9235 // } 9236 // 9237 // We generate the code below. 9238 // Note: the loop body may be outlined in CodeGen. 9239 // Note: some counters may be C++ classes, operator- is used to find number of 9240 // iterations and operator+= to calculate counter value. 9241 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 9242 // or i64 is currently supported). 9243 // 9244 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 9245 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 9246 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 9247 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 9248 // // similar updates for vars in clauses (e.g. 'linear') 9249 // <loop body (using local i and j)> 9250 // } 9251 // i = NI; // assign final values of counters 9252 // j = NJ; 9253 // 9254 9255 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 9256 // the iteration counts of the collapsed for loops. 9257 // Precondition tests if there is at least one iteration (all conditions are 9258 // true). 9259 auto PreCond = ExprResult(IterSpaces[0].PreCond); 9260 Expr *N0 = IterSpaces[0].NumIterations; 9261 ExprResult LastIteration32 = 9262 widenIterationCount(/*Bits=*/32, 9263 SemaRef 9264 .PerformImplicitConversion( 9265 N0->IgnoreImpCasts(), N0->getType(), 9266 Sema::AA_Converting, /*AllowExplicit=*/true) 9267 .get(), 9268 SemaRef); 9269 ExprResult LastIteration64 = widenIterationCount( 9270 /*Bits=*/64, 9271 SemaRef 9272 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(), 9273 Sema::AA_Converting, 9274 /*AllowExplicit=*/true) 9275 .get(), 9276 SemaRef); 9277 9278 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 9279 return NestedLoopCount; 9280 9281 ASTContext &C = SemaRef.Context; 9282 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 9283 9284 Scope *CurScope = DSA.getCurScope(); 9285 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 9286 if (PreCond.isUsable()) { 9287 PreCond = 9288 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 9289 PreCond.get(), IterSpaces[Cnt].PreCond); 9290 } 9291 Expr *N = IterSpaces[Cnt].NumIterations; 9292 SourceLocation Loc = N->getExprLoc(); 9293 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 9294 if (LastIteration32.isUsable()) 9295 LastIteration32 = SemaRef.BuildBinOp( 9296 CurScope, Loc, BO_Mul, LastIteration32.get(), 9297 SemaRef 9298 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 9299 Sema::AA_Converting, 9300 /*AllowExplicit=*/true) 9301 .get()); 9302 if (LastIteration64.isUsable()) 9303 LastIteration64 = SemaRef.BuildBinOp( 9304 CurScope, Loc, BO_Mul, LastIteration64.get(), 9305 SemaRef 9306 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 9307 Sema::AA_Converting, 9308 /*AllowExplicit=*/true) 9309 .get()); 9310 } 9311 9312 // Choose either the 32-bit or 64-bit version. 9313 ExprResult LastIteration = LastIteration64; 9314 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse || 9315 (LastIteration32.isUsable() && 9316 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 9317 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 9318 fitsInto( 9319 /*Bits=*/32, 9320 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 9321 LastIteration64.get(), SemaRef)))) 9322 LastIteration = LastIteration32; 9323 QualType VType = LastIteration.get()->getType(); 9324 QualType RealVType = VType; 9325 QualType StrideVType = VType; 9326 if (isOpenMPTaskLoopDirective(DKind)) { 9327 VType = 9328 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 9329 StrideVType = 9330 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 9331 } 9332 9333 if (!LastIteration.isUsable()) 9334 return 0; 9335 9336 // Save the number of iterations. 9337 ExprResult NumIterations = LastIteration; 9338 { 9339 LastIteration = SemaRef.BuildBinOp( 9340 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 9341 LastIteration.get(), 9342 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 9343 if (!LastIteration.isUsable()) 9344 return 0; 9345 } 9346 9347 // Calculate the last iteration number beforehand instead of doing this on 9348 // each iteration. Do not do this if the number of iterations may be kfold-ed. 9349 bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context); 9350 ExprResult CalcLastIteration; 9351 if (!IsConstant) { 9352 ExprResult SaveRef = 9353 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 9354 LastIteration = SaveRef; 9355 9356 // Prepare SaveRef + 1. 9357 NumIterations = SemaRef.BuildBinOp( 9358 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 9359 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 9360 if (!NumIterations.isUsable()) 9361 return 0; 9362 } 9363 9364 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 9365 9366 // Build variables passed into runtime, necessary for worksharing directives. 9367 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 9368 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 9369 isOpenMPDistributeDirective(DKind) || 9370 isOpenMPGenericLoopDirective(DKind) || 9371 isOpenMPLoopTransformationDirective(DKind)) { 9372 // Lower bound variable, initialized with zero. 9373 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 9374 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 9375 SemaRef.AddInitializerToDecl(LBDecl, 9376 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 9377 /*DirectInit*/ false); 9378 9379 // Upper bound variable, initialized with last iteration number. 9380 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 9381 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 9382 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 9383 /*DirectInit*/ false); 9384 9385 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 9386 // This will be used to implement clause 'lastprivate'. 9387 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 9388 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 9389 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 9390 SemaRef.AddInitializerToDecl(ILDecl, 9391 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 9392 /*DirectInit*/ false); 9393 9394 // Stride variable returned by runtime (we initialize it to 1 by default). 9395 VarDecl *STDecl = 9396 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 9397 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 9398 SemaRef.AddInitializerToDecl(STDecl, 9399 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 9400 /*DirectInit*/ false); 9401 9402 // Build expression: UB = min(UB, LastIteration) 9403 // It is necessary for CodeGen of directives with static scheduling. 9404 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 9405 UB.get(), LastIteration.get()); 9406 ExprResult CondOp = SemaRef.ActOnConditionalOp( 9407 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(), 9408 LastIteration.get(), UB.get()); 9409 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 9410 CondOp.get()); 9411 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false); 9412 9413 // If we have a combined directive that combines 'distribute', 'for' or 9414 // 'simd' we need to be able to access the bounds of the schedule of the 9415 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 9416 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 9417 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9418 // Lower bound variable, initialized with zero. 9419 VarDecl *CombLBDecl = 9420 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 9421 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 9422 SemaRef.AddInitializerToDecl( 9423 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 9424 /*DirectInit*/ false); 9425 9426 // Upper bound variable, initialized with last iteration number. 9427 VarDecl *CombUBDecl = 9428 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 9429 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 9430 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 9431 /*DirectInit*/ false); 9432 9433 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 9434 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 9435 ExprResult CombCondOp = 9436 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 9437 LastIteration.get(), CombUB.get()); 9438 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 9439 CombCondOp.get()); 9440 CombEUB = 9441 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false); 9442 9443 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 9444 // We expect to have at least 2 more parameters than the 'parallel' 9445 // directive does - the lower and upper bounds of the previous schedule. 9446 assert(CD->getNumParams() >= 4 && 9447 "Unexpected number of parameters in loop combined directive"); 9448 9449 // Set the proper type for the bounds given what we learned from the 9450 // enclosed loops. 9451 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 9452 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 9453 9454 // Previous lower and upper bounds are obtained from the region 9455 // parameters. 9456 PrevLB = 9457 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 9458 PrevUB = 9459 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 9460 } 9461 } 9462 9463 // Build the iteration variable and its initialization before loop. 9464 ExprResult IV; 9465 ExprResult Init, CombInit; 9466 { 9467 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 9468 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 9469 Expr *RHS = (isOpenMPWorksharingDirective(DKind) || 9470 isOpenMPGenericLoopDirective(DKind) || 9471 isOpenMPTaskLoopDirective(DKind) || 9472 isOpenMPDistributeDirective(DKind) || 9473 isOpenMPLoopTransformationDirective(DKind)) 9474 ? LB.get() 9475 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 9476 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 9477 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false); 9478 9479 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9480 Expr *CombRHS = 9481 (isOpenMPWorksharingDirective(DKind) || 9482 isOpenMPGenericLoopDirective(DKind) || 9483 isOpenMPTaskLoopDirective(DKind) || 9484 isOpenMPDistributeDirective(DKind)) 9485 ? CombLB.get() 9486 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 9487 CombInit = 9488 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 9489 CombInit = 9490 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false); 9491 } 9492 } 9493 9494 bool UseStrictCompare = 9495 RealVType->hasUnsignedIntegerRepresentation() && 9496 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) { 9497 return LIS.IsStrictCompare; 9498 }); 9499 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for 9500 // unsigned IV)) for worksharing loops. 9501 SourceLocation CondLoc = AStmt->getBeginLoc(); 9502 Expr *BoundUB = UB.get(); 9503 if (UseStrictCompare) { 9504 BoundUB = 9505 SemaRef 9506 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB, 9507 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 9508 .get(); 9509 BoundUB = 9510 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get(); 9511 } 9512 ExprResult Cond = 9513 (isOpenMPWorksharingDirective(DKind) || 9514 isOpenMPGenericLoopDirective(DKind) || 9515 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind) || 9516 isOpenMPLoopTransformationDirective(DKind)) 9517 ? SemaRef.BuildBinOp(CurScope, CondLoc, 9518 UseStrictCompare ? BO_LT : BO_LE, IV.get(), 9519 BoundUB) 9520 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 9521 NumIterations.get()); 9522 ExprResult CombDistCond; 9523 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9524 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 9525 NumIterations.get()); 9526 } 9527 9528 ExprResult CombCond; 9529 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9530 Expr *BoundCombUB = CombUB.get(); 9531 if (UseStrictCompare) { 9532 BoundCombUB = 9533 SemaRef 9534 .BuildBinOp( 9535 CurScope, CondLoc, BO_Add, BoundCombUB, 9536 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 9537 .get(); 9538 BoundCombUB = 9539 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false) 9540 .get(); 9541 } 9542 CombCond = 9543 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 9544 IV.get(), BoundCombUB); 9545 } 9546 // Loop increment (IV = IV + 1) 9547 SourceLocation IncLoc = AStmt->getBeginLoc(); 9548 ExprResult Inc = 9549 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 9550 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 9551 if (!Inc.isUsable()) 9552 return 0; 9553 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 9554 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false); 9555 if (!Inc.isUsable()) 9556 return 0; 9557 9558 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 9559 // Used for directives with static scheduling. 9560 // In combined construct, add combined version that use CombLB and CombUB 9561 // base variables for the update 9562 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 9563 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 9564 isOpenMPGenericLoopDirective(DKind) || 9565 isOpenMPDistributeDirective(DKind) || 9566 isOpenMPLoopTransformationDirective(DKind)) { 9567 // LB + ST 9568 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 9569 if (!NextLB.isUsable()) 9570 return 0; 9571 // LB = LB + ST 9572 NextLB = 9573 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 9574 NextLB = 9575 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false); 9576 if (!NextLB.isUsable()) 9577 return 0; 9578 // UB + ST 9579 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 9580 if (!NextUB.isUsable()) 9581 return 0; 9582 // UB = UB + ST 9583 NextUB = 9584 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 9585 NextUB = 9586 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false); 9587 if (!NextUB.isUsable()) 9588 return 0; 9589 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9590 CombNextLB = 9591 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 9592 if (!NextLB.isUsable()) 9593 return 0; 9594 // LB = LB + ST 9595 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 9596 CombNextLB.get()); 9597 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(), 9598 /*DiscardedValue*/ false); 9599 if (!CombNextLB.isUsable()) 9600 return 0; 9601 // UB + ST 9602 CombNextUB = 9603 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 9604 if (!CombNextUB.isUsable()) 9605 return 0; 9606 // UB = UB + ST 9607 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 9608 CombNextUB.get()); 9609 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(), 9610 /*DiscardedValue*/ false); 9611 if (!CombNextUB.isUsable()) 9612 return 0; 9613 } 9614 } 9615 9616 // Create increment expression for distribute loop when combined in a same 9617 // directive with for as IV = IV + ST; ensure upper bound expression based 9618 // on PrevUB instead of NumIterations - used to implement 'for' when found 9619 // in combination with 'distribute', like in 'distribute parallel for' 9620 SourceLocation DistIncLoc = AStmt->getBeginLoc(); 9621 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond; 9622 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9623 DistCond = SemaRef.BuildBinOp( 9624 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB); 9625 assert(DistCond.isUsable() && "distribute cond expr was not built"); 9626 9627 DistInc = 9628 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 9629 assert(DistInc.isUsable() && "distribute inc expr was not built"); 9630 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 9631 DistInc.get()); 9632 DistInc = 9633 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false); 9634 assert(DistInc.isUsable() && "distribute inc expr was not built"); 9635 9636 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 9637 // construct 9638 ExprResult NewPrevUB = PrevUB; 9639 SourceLocation DistEUBLoc = AStmt->getBeginLoc(); 9640 if (!SemaRef.Context.hasSameType(UB.get()->getType(), 9641 PrevUB.get()->getType())) { 9642 NewPrevUB = SemaRef.BuildCStyleCastExpr( 9643 DistEUBLoc, 9644 SemaRef.Context.getTrivialTypeSourceInfo(UB.get()->getType()), 9645 DistEUBLoc, NewPrevUB.get()); 9646 if (!NewPrevUB.isUsable()) 9647 return 0; 9648 } 9649 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, 9650 UB.get(), NewPrevUB.get()); 9651 ExprResult CondOp = SemaRef.ActOnConditionalOp( 9652 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), NewPrevUB.get(), UB.get()); 9653 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 9654 CondOp.get()); 9655 PrevEUB = 9656 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false); 9657 9658 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in 9659 // parallel for is in combination with a distribute directive with 9660 // schedule(static, 1) 9661 Expr *BoundPrevUB = PrevUB.get(); 9662 if (UseStrictCompare) { 9663 BoundPrevUB = 9664 SemaRef 9665 .BuildBinOp( 9666 CurScope, CondLoc, BO_Add, BoundPrevUB, 9667 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 9668 .get(); 9669 BoundPrevUB = 9670 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false) 9671 .get(); 9672 } 9673 ParForInDistCond = 9674 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 9675 IV.get(), BoundPrevUB); 9676 } 9677 9678 // Build updates and final values of the loop counters. 9679 bool HasErrors = false; 9680 Built.Counters.resize(NestedLoopCount); 9681 Built.Inits.resize(NestedLoopCount); 9682 Built.Updates.resize(NestedLoopCount); 9683 Built.Finals.resize(NestedLoopCount); 9684 Built.DependentCounters.resize(NestedLoopCount); 9685 Built.DependentInits.resize(NestedLoopCount); 9686 Built.FinalsConditions.resize(NestedLoopCount); 9687 { 9688 // We implement the following algorithm for obtaining the 9689 // original loop iteration variable values based on the 9690 // value of the collapsed loop iteration variable IV. 9691 // 9692 // Let n+1 be the number of collapsed loops in the nest. 9693 // Iteration variables (I0, I1, .... In) 9694 // Iteration counts (N0, N1, ... Nn) 9695 // 9696 // Acc = IV; 9697 // 9698 // To compute Ik for loop k, 0 <= k <= n, generate: 9699 // Prod = N(k+1) * N(k+2) * ... * Nn; 9700 // Ik = Acc / Prod; 9701 // Acc -= Ik * Prod; 9702 // 9703 ExprResult Acc = IV; 9704 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 9705 LoopIterationSpace &IS = IterSpaces[Cnt]; 9706 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 9707 ExprResult Iter; 9708 9709 // Compute prod 9710 ExprResult Prod = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 9711 for (unsigned int K = Cnt + 1; K < NestedLoopCount; ++K) 9712 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(), 9713 IterSpaces[K].NumIterations); 9714 9715 // Iter = Acc / Prod 9716 // If there is at least one more inner loop to avoid 9717 // multiplication by 1. 9718 if (Cnt + 1 < NestedLoopCount) 9719 Iter = 9720 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, Acc.get(), Prod.get()); 9721 else 9722 Iter = Acc; 9723 if (!Iter.isUsable()) { 9724 HasErrors = true; 9725 break; 9726 } 9727 9728 // Update Acc: 9729 // Acc -= Iter * Prod 9730 // Check if there is at least one more inner loop to avoid 9731 // multiplication by 1. 9732 if (Cnt + 1 < NestedLoopCount) 9733 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Iter.get(), 9734 Prod.get()); 9735 else 9736 Prod = Iter; 9737 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, Acc.get(), Prod.get()); 9738 9739 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 9740 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 9741 DeclRefExpr *CounterVar = buildDeclRefExpr( 9742 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(), 9743 /*RefersToCapture=*/true); 9744 ExprResult Init = 9745 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 9746 IS.CounterInit, IS.IsNonRectangularLB, Captures); 9747 if (!Init.isUsable()) { 9748 HasErrors = true; 9749 break; 9750 } 9751 ExprResult Update = buildCounterUpdate( 9752 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 9753 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures); 9754 if (!Update.isUsable()) { 9755 HasErrors = true; 9756 break; 9757 } 9758 9759 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 9760 ExprResult Final = 9761 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar, 9762 IS.CounterInit, IS.NumIterations, IS.CounterStep, 9763 IS.Subtract, IS.IsNonRectangularLB, &Captures); 9764 if (!Final.isUsable()) { 9765 HasErrors = true; 9766 break; 9767 } 9768 9769 if (!Update.isUsable() || !Final.isUsable()) { 9770 HasErrors = true; 9771 break; 9772 } 9773 // Save results 9774 Built.Counters[Cnt] = IS.CounterVar; 9775 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 9776 Built.Inits[Cnt] = Init.get(); 9777 Built.Updates[Cnt] = Update.get(); 9778 Built.Finals[Cnt] = Final.get(); 9779 Built.DependentCounters[Cnt] = nullptr; 9780 Built.DependentInits[Cnt] = nullptr; 9781 Built.FinalsConditions[Cnt] = nullptr; 9782 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) { 9783 Built.DependentCounters[Cnt] = 9784 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx]; 9785 Built.DependentInits[Cnt] = 9786 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx]; 9787 Built.FinalsConditions[Cnt] = IS.FinalCondition; 9788 } 9789 } 9790 } 9791 9792 if (HasErrors) 9793 return 0; 9794 9795 // Save results 9796 Built.IterationVarRef = IV.get(); 9797 Built.LastIteration = LastIteration.get(); 9798 Built.NumIterations = NumIterations.get(); 9799 Built.CalcLastIteration = SemaRef 9800 .ActOnFinishFullExpr(CalcLastIteration.get(), 9801 /*DiscardedValue=*/false) 9802 .get(); 9803 Built.PreCond = PreCond.get(); 9804 Built.PreInits = buildPreInits(C, Captures); 9805 Built.Cond = Cond.get(); 9806 Built.Init = Init.get(); 9807 Built.Inc = Inc.get(); 9808 Built.LB = LB.get(); 9809 Built.UB = UB.get(); 9810 Built.IL = IL.get(); 9811 Built.ST = ST.get(); 9812 Built.EUB = EUB.get(); 9813 Built.NLB = NextLB.get(); 9814 Built.NUB = NextUB.get(); 9815 Built.PrevLB = PrevLB.get(); 9816 Built.PrevUB = PrevUB.get(); 9817 Built.DistInc = DistInc.get(); 9818 Built.PrevEUB = PrevEUB.get(); 9819 Built.DistCombinedFields.LB = CombLB.get(); 9820 Built.DistCombinedFields.UB = CombUB.get(); 9821 Built.DistCombinedFields.EUB = CombEUB.get(); 9822 Built.DistCombinedFields.Init = CombInit.get(); 9823 Built.DistCombinedFields.Cond = CombCond.get(); 9824 Built.DistCombinedFields.NLB = CombNextLB.get(); 9825 Built.DistCombinedFields.NUB = CombNextUB.get(); 9826 Built.DistCombinedFields.DistCond = CombDistCond.get(); 9827 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get(); 9828 9829 return NestedLoopCount; 9830 } 9831 9832 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 9833 auto CollapseClauses = 9834 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 9835 if (CollapseClauses.begin() != CollapseClauses.end()) 9836 return (*CollapseClauses.begin())->getNumForLoops(); 9837 return nullptr; 9838 } 9839 9840 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 9841 auto OrderedClauses = 9842 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 9843 if (OrderedClauses.begin() != OrderedClauses.end()) 9844 return (*OrderedClauses.begin())->getNumForLoops(); 9845 return nullptr; 9846 } 9847 9848 static bool checkSimdlenSafelenSpecified(Sema &S, 9849 const ArrayRef<OMPClause *> Clauses) { 9850 const OMPSafelenClause *Safelen = nullptr; 9851 const OMPSimdlenClause *Simdlen = nullptr; 9852 9853 for (const OMPClause *Clause : Clauses) { 9854 if (Clause->getClauseKind() == OMPC_safelen) 9855 Safelen = cast<OMPSafelenClause>(Clause); 9856 else if (Clause->getClauseKind() == OMPC_simdlen) 9857 Simdlen = cast<OMPSimdlenClause>(Clause); 9858 if (Safelen && Simdlen) 9859 break; 9860 } 9861 9862 if (Simdlen && Safelen) { 9863 const Expr *SimdlenLength = Simdlen->getSimdlen(); 9864 const Expr *SafelenLength = Safelen->getSafelen(); 9865 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 9866 SimdlenLength->isInstantiationDependent() || 9867 SimdlenLength->containsUnexpandedParameterPack()) 9868 return false; 9869 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 9870 SafelenLength->isInstantiationDependent() || 9871 SafelenLength->containsUnexpandedParameterPack()) 9872 return false; 9873 Expr::EvalResult SimdlenResult, SafelenResult; 9874 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context); 9875 SafelenLength->EvaluateAsInt(SafelenResult, S.Context); 9876 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt(); 9877 llvm::APSInt SafelenRes = SafelenResult.Val.getInt(); 9878 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 9879 // If both simdlen and safelen clauses are specified, the value of the 9880 // simdlen parameter must be less than or equal to the value of the safelen 9881 // parameter. 9882 if (SimdlenRes > SafelenRes) { 9883 S.Diag(SimdlenLength->getExprLoc(), 9884 diag::err_omp_wrong_simdlen_safelen_values) 9885 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 9886 return true; 9887 } 9888 } 9889 return false; 9890 } 9891 9892 StmtResult 9893 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 9894 SourceLocation StartLoc, SourceLocation EndLoc, 9895 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9896 if (!AStmt) 9897 return StmtError(); 9898 9899 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9900 OMPLoopBasedDirective::HelperExprs B; 9901 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9902 // define the nested loops number. 9903 unsigned NestedLoopCount = checkOpenMPLoop( 9904 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 9905 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 9906 if (NestedLoopCount == 0) 9907 return StmtError(); 9908 9909 assert((CurContext->isDependentContext() || B.builtAll()) && 9910 "omp simd loop exprs were not built"); 9911 9912 if (!CurContext->isDependentContext()) { 9913 // Finalize the clauses that need pre-built expressions for CodeGen. 9914 for (OMPClause *C : Clauses) { 9915 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9916 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9917 B.NumIterations, *this, CurScope, 9918 DSAStack)) 9919 return StmtError(); 9920 } 9921 } 9922 9923 if (checkSimdlenSafelenSpecified(*this, Clauses)) 9924 return StmtError(); 9925 9926 setFunctionHasBranchProtectedScope(); 9927 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 9928 Clauses, AStmt, B); 9929 } 9930 9931 StmtResult 9932 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 9933 SourceLocation StartLoc, SourceLocation EndLoc, 9934 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9935 if (!AStmt) 9936 return StmtError(); 9937 9938 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9939 OMPLoopBasedDirective::HelperExprs B; 9940 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9941 // define the nested loops number. 9942 unsigned NestedLoopCount = checkOpenMPLoop( 9943 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 9944 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 9945 if (NestedLoopCount == 0) 9946 return StmtError(); 9947 9948 assert((CurContext->isDependentContext() || B.builtAll()) && 9949 "omp for loop exprs were not built"); 9950 9951 if (!CurContext->isDependentContext()) { 9952 // Finalize the clauses that need pre-built expressions for CodeGen. 9953 for (OMPClause *C : Clauses) { 9954 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9955 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9956 B.NumIterations, *this, CurScope, 9957 DSAStack)) 9958 return StmtError(); 9959 } 9960 } 9961 9962 setFunctionHasBranchProtectedScope(); 9963 return OMPForDirective::Create( 9964 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 9965 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 9966 } 9967 9968 StmtResult Sema::ActOnOpenMPForSimdDirective( 9969 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 9970 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9971 if (!AStmt) 9972 return StmtError(); 9973 9974 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9975 OMPLoopBasedDirective::HelperExprs B; 9976 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9977 // define the nested loops number. 9978 unsigned NestedLoopCount = 9979 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 9980 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 9981 VarsWithImplicitDSA, B); 9982 if (NestedLoopCount == 0) 9983 return StmtError(); 9984 9985 assert((CurContext->isDependentContext() || B.builtAll()) && 9986 "omp for simd loop exprs were not built"); 9987 9988 if (!CurContext->isDependentContext()) { 9989 // Finalize the clauses that need pre-built expressions for CodeGen. 9990 for (OMPClause *C : Clauses) { 9991 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9992 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9993 B.NumIterations, *this, CurScope, 9994 DSAStack)) 9995 return StmtError(); 9996 } 9997 } 9998 9999 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10000 return StmtError(); 10001 10002 setFunctionHasBranchProtectedScope(); 10003 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 10004 Clauses, AStmt, B); 10005 } 10006 10007 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 10008 Stmt *AStmt, 10009 SourceLocation StartLoc, 10010 SourceLocation EndLoc) { 10011 if (!AStmt) 10012 return StmtError(); 10013 10014 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10015 auto BaseStmt = AStmt; 10016 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 10017 BaseStmt = CS->getCapturedStmt(); 10018 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 10019 auto S = C->children(); 10020 if (S.begin() == S.end()) 10021 return StmtError(); 10022 // All associated statements must be '#pragma omp section' except for 10023 // the first one. 10024 for (Stmt *SectionStmt : llvm::drop_begin(S)) { 10025 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 10026 if (SectionStmt) 10027 Diag(SectionStmt->getBeginLoc(), 10028 diag::err_omp_sections_substmt_not_section); 10029 return StmtError(); 10030 } 10031 cast<OMPSectionDirective>(SectionStmt) 10032 ->setHasCancel(DSAStack->isCancelRegion()); 10033 } 10034 } else { 10035 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt); 10036 return StmtError(); 10037 } 10038 10039 setFunctionHasBranchProtectedScope(); 10040 10041 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 10042 DSAStack->getTaskgroupReductionRef(), 10043 DSAStack->isCancelRegion()); 10044 } 10045 10046 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 10047 SourceLocation StartLoc, 10048 SourceLocation EndLoc) { 10049 if (!AStmt) 10050 return StmtError(); 10051 10052 setFunctionHasBranchProtectedScope(); 10053 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 10054 10055 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 10056 DSAStack->isCancelRegion()); 10057 } 10058 10059 static Expr *getDirectCallExpr(Expr *E) { 10060 E = E->IgnoreParenCasts()->IgnoreImplicit(); 10061 if (auto *CE = dyn_cast<CallExpr>(E)) 10062 if (CE->getDirectCallee()) 10063 return E; 10064 return nullptr; 10065 } 10066 10067 StmtResult Sema::ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses, 10068 Stmt *AStmt, 10069 SourceLocation StartLoc, 10070 SourceLocation EndLoc) { 10071 if (!AStmt) 10072 return StmtError(); 10073 10074 Stmt *S = cast<CapturedStmt>(AStmt)->getCapturedStmt(); 10075 10076 // 5.1 OpenMP 10077 // expression-stmt : an expression statement with one of the following forms: 10078 // expression = target-call ( [expression-list] ); 10079 // target-call ( [expression-list] ); 10080 10081 SourceLocation TargetCallLoc; 10082 10083 if (!CurContext->isDependentContext()) { 10084 Expr *TargetCall = nullptr; 10085 10086 auto *E = dyn_cast<Expr>(S); 10087 if (!E) { 10088 Diag(S->getBeginLoc(), diag::err_omp_dispatch_statement_call); 10089 return StmtError(); 10090 } 10091 10092 E = E->IgnoreParenCasts()->IgnoreImplicit(); 10093 10094 if (auto *BO = dyn_cast<BinaryOperator>(E)) { 10095 if (BO->getOpcode() == BO_Assign) 10096 TargetCall = getDirectCallExpr(BO->getRHS()); 10097 } else { 10098 if (auto *COCE = dyn_cast<CXXOperatorCallExpr>(E)) 10099 if (COCE->getOperator() == OO_Equal) 10100 TargetCall = getDirectCallExpr(COCE->getArg(1)); 10101 if (!TargetCall) 10102 TargetCall = getDirectCallExpr(E); 10103 } 10104 if (!TargetCall) { 10105 Diag(E->getBeginLoc(), diag::err_omp_dispatch_statement_call); 10106 return StmtError(); 10107 } 10108 TargetCallLoc = TargetCall->getExprLoc(); 10109 } 10110 10111 setFunctionHasBranchProtectedScope(); 10112 10113 return OMPDispatchDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 10114 TargetCallLoc); 10115 } 10116 10117 StmtResult Sema::ActOnOpenMPGenericLoopDirective( 10118 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10119 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10120 if (!AStmt) 10121 return StmtError(); 10122 10123 // OpenMP 5.1 [2.11.7, loop construct] 10124 // A list item may not appear in a lastprivate clause unless it is the 10125 // loop iteration variable of a loop that is associated with the construct. 10126 for (OMPClause *C : Clauses) { 10127 if (auto *LPC = dyn_cast<OMPLastprivateClause>(C)) { 10128 for (Expr *RefExpr : LPC->varlists()) { 10129 SourceLocation ELoc; 10130 SourceRange ERange; 10131 Expr *SimpleRefExpr = RefExpr; 10132 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 10133 if (ValueDecl *D = Res.first) { 10134 auto &&Info = DSAStack->isLoopControlVariable(D); 10135 if (!Info.first) { 10136 Diag(ELoc, diag::err_omp_lastprivate_loop_var_non_loop_iteration); 10137 return StmtError(); 10138 } 10139 } 10140 } 10141 } 10142 } 10143 10144 auto *CS = cast<CapturedStmt>(AStmt); 10145 // 1.2.2 OpenMP Language Terminology 10146 // Structured block - An executable statement with a single entry at the 10147 // top and a single exit at the bottom. 10148 // The point of exit cannot be a branch out of the structured block. 10149 // longjmp() and throw() must not violate the entry/exit criteria. 10150 CS->getCapturedDecl()->setNothrow(); 10151 10152 OMPLoopDirective::HelperExprs B; 10153 // In presence of clause 'collapse', it will define the nested loops number. 10154 unsigned NestedLoopCount = checkOpenMPLoop( 10155 OMPD_loop, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 10156 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 10157 if (NestedLoopCount == 0) 10158 return StmtError(); 10159 10160 assert((CurContext->isDependentContext() || B.builtAll()) && 10161 "omp loop exprs were not built"); 10162 10163 setFunctionHasBranchProtectedScope(); 10164 return OMPGenericLoopDirective::Create(Context, StartLoc, EndLoc, 10165 NestedLoopCount, Clauses, AStmt, B); 10166 } 10167 10168 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 10169 Stmt *AStmt, 10170 SourceLocation StartLoc, 10171 SourceLocation EndLoc) { 10172 if (!AStmt) 10173 return StmtError(); 10174 10175 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10176 10177 setFunctionHasBranchProtectedScope(); 10178 10179 // OpenMP [2.7.3, single Construct, Restrictions] 10180 // The copyprivate clause must not be used with the nowait clause. 10181 const OMPClause *Nowait = nullptr; 10182 const OMPClause *Copyprivate = nullptr; 10183 for (const OMPClause *Clause : Clauses) { 10184 if (Clause->getClauseKind() == OMPC_nowait) 10185 Nowait = Clause; 10186 else if (Clause->getClauseKind() == OMPC_copyprivate) 10187 Copyprivate = Clause; 10188 if (Copyprivate && Nowait) { 10189 Diag(Copyprivate->getBeginLoc(), 10190 diag::err_omp_single_copyprivate_with_nowait); 10191 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here); 10192 return StmtError(); 10193 } 10194 } 10195 10196 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10197 } 10198 10199 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 10200 SourceLocation StartLoc, 10201 SourceLocation EndLoc) { 10202 if (!AStmt) 10203 return StmtError(); 10204 10205 setFunctionHasBranchProtectedScope(); 10206 10207 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 10208 } 10209 10210 StmtResult Sema::ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses, 10211 Stmt *AStmt, 10212 SourceLocation StartLoc, 10213 SourceLocation EndLoc) { 10214 if (!AStmt) 10215 return StmtError(); 10216 10217 setFunctionHasBranchProtectedScope(); 10218 10219 return OMPMaskedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10220 } 10221 10222 StmtResult Sema::ActOnOpenMPCriticalDirective( 10223 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 10224 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 10225 if (!AStmt) 10226 return StmtError(); 10227 10228 bool ErrorFound = false; 10229 llvm::APSInt Hint; 10230 SourceLocation HintLoc; 10231 bool DependentHint = false; 10232 for (const OMPClause *C : Clauses) { 10233 if (C->getClauseKind() == OMPC_hint) { 10234 if (!DirName.getName()) { 10235 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name); 10236 ErrorFound = true; 10237 } 10238 Expr *E = cast<OMPHintClause>(C)->getHint(); 10239 if (E->isTypeDependent() || E->isValueDependent() || 10240 E->isInstantiationDependent()) { 10241 DependentHint = true; 10242 } else { 10243 Hint = E->EvaluateKnownConstInt(Context); 10244 HintLoc = C->getBeginLoc(); 10245 } 10246 } 10247 } 10248 if (ErrorFound) 10249 return StmtError(); 10250 const auto Pair = DSAStack->getCriticalWithHint(DirName); 10251 if (Pair.first && DirName.getName() && !DependentHint) { 10252 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 10253 Diag(StartLoc, diag::err_omp_critical_with_hint); 10254 if (HintLoc.isValid()) 10255 Diag(HintLoc, diag::note_omp_critical_hint_here) 10256 << 0 << toString(Hint, /*Radix=*/10, /*Signed=*/false); 10257 else 10258 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 10259 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 10260 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here) 10261 << 1 10262 << toString(C->getHint()->EvaluateKnownConstInt(Context), 10263 /*Radix=*/10, /*Signed=*/false); 10264 } else { 10265 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1; 10266 } 10267 } 10268 } 10269 10270 setFunctionHasBranchProtectedScope(); 10271 10272 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 10273 Clauses, AStmt); 10274 if (!Pair.first && DirName.getName() && !DependentHint) 10275 DSAStack->addCriticalWithHint(Dir, Hint); 10276 return Dir; 10277 } 10278 10279 StmtResult Sema::ActOnOpenMPParallelForDirective( 10280 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10281 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10282 if (!AStmt) 10283 return StmtError(); 10284 10285 auto *CS = cast<CapturedStmt>(AStmt); 10286 // 1.2.2 OpenMP Language Terminology 10287 // Structured block - An executable statement with a single entry at the 10288 // top and a single exit at the bottom. 10289 // The point of exit cannot be a branch out of the structured block. 10290 // longjmp() and throw() must not violate the entry/exit criteria. 10291 CS->getCapturedDecl()->setNothrow(); 10292 10293 OMPLoopBasedDirective::HelperExprs B; 10294 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10295 // define the nested loops number. 10296 unsigned NestedLoopCount = 10297 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 10298 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 10299 VarsWithImplicitDSA, B); 10300 if (NestedLoopCount == 0) 10301 return StmtError(); 10302 10303 assert((CurContext->isDependentContext() || B.builtAll()) && 10304 "omp parallel for loop exprs were not built"); 10305 10306 if (!CurContext->isDependentContext()) { 10307 // Finalize the clauses that need pre-built expressions for CodeGen. 10308 for (OMPClause *C : Clauses) { 10309 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10310 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10311 B.NumIterations, *this, CurScope, 10312 DSAStack)) 10313 return StmtError(); 10314 } 10315 } 10316 10317 setFunctionHasBranchProtectedScope(); 10318 return OMPParallelForDirective::Create( 10319 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 10320 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 10321 } 10322 10323 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 10324 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10325 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10326 if (!AStmt) 10327 return StmtError(); 10328 10329 auto *CS = cast<CapturedStmt>(AStmt); 10330 // 1.2.2 OpenMP Language Terminology 10331 // Structured block - An executable statement with a single entry at the 10332 // top and a single exit at the bottom. 10333 // The point of exit cannot be a branch out of the structured block. 10334 // longjmp() and throw() must not violate the entry/exit criteria. 10335 CS->getCapturedDecl()->setNothrow(); 10336 10337 OMPLoopBasedDirective::HelperExprs B; 10338 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10339 // define the nested loops number. 10340 unsigned NestedLoopCount = 10341 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 10342 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 10343 VarsWithImplicitDSA, B); 10344 if (NestedLoopCount == 0) 10345 return StmtError(); 10346 10347 if (!CurContext->isDependentContext()) { 10348 // Finalize the clauses that need pre-built expressions for CodeGen. 10349 for (OMPClause *C : Clauses) { 10350 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10351 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10352 B.NumIterations, *this, CurScope, 10353 DSAStack)) 10354 return StmtError(); 10355 } 10356 } 10357 10358 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10359 return StmtError(); 10360 10361 setFunctionHasBranchProtectedScope(); 10362 return OMPParallelForSimdDirective::Create( 10363 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 10364 } 10365 10366 StmtResult 10367 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, 10368 Stmt *AStmt, SourceLocation StartLoc, 10369 SourceLocation EndLoc) { 10370 if (!AStmt) 10371 return StmtError(); 10372 10373 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10374 auto *CS = cast<CapturedStmt>(AStmt); 10375 // 1.2.2 OpenMP Language Terminology 10376 // Structured block - An executable statement with a single entry at the 10377 // top and a single exit at the bottom. 10378 // The point of exit cannot be a branch out of the structured block. 10379 // longjmp() and throw() must not violate the entry/exit criteria. 10380 CS->getCapturedDecl()->setNothrow(); 10381 10382 setFunctionHasBranchProtectedScope(); 10383 10384 return OMPParallelMasterDirective::Create( 10385 Context, StartLoc, EndLoc, Clauses, AStmt, 10386 DSAStack->getTaskgroupReductionRef()); 10387 } 10388 10389 StmtResult 10390 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 10391 Stmt *AStmt, SourceLocation StartLoc, 10392 SourceLocation EndLoc) { 10393 if (!AStmt) 10394 return StmtError(); 10395 10396 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10397 auto BaseStmt = AStmt; 10398 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 10399 BaseStmt = CS->getCapturedStmt(); 10400 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 10401 auto S = C->children(); 10402 if (S.begin() == S.end()) 10403 return StmtError(); 10404 // All associated statements must be '#pragma omp section' except for 10405 // the first one. 10406 for (Stmt *SectionStmt : llvm::drop_begin(S)) { 10407 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 10408 if (SectionStmt) 10409 Diag(SectionStmt->getBeginLoc(), 10410 diag::err_omp_parallel_sections_substmt_not_section); 10411 return StmtError(); 10412 } 10413 cast<OMPSectionDirective>(SectionStmt) 10414 ->setHasCancel(DSAStack->isCancelRegion()); 10415 } 10416 } else { 10417 Diag(AStmt->getBeginLoc(), 10418 diag::err_omp_parallel_sections_not_compound_stmt); 10419 return StmtError(); 10420 } 10421 10422 setFunctionHasBranchProtectedScope(); 10423 10424 return OMPParallelSectionsDirective::Create( 10425 Context, StartLoc, EndLoc, Clauses, AStmt, 10426 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 10427 } 10428 10429 /// Find and diagnose mutually exclusive clause kinds. 10430 static bool checkMutuallyExclusiveClauses( 10431 Sema &S, ArrayRef<OMPClause *> Clauses, 10432 ArrayRef<OpenMPClauseKind> MutuallyExclusiveClauses) { 10433 const OMPClause *PrevClause = nullptr; 10434 bool ErrorFound = false; 10435 for (const OMPClause *C : Clauses) { 10436 if (llvm::is_contained(MutuallyExclusiveClauses, C->getClauseKind())) { 10437 if (!PrevClause) { 10438 PrevClause = C; 10439 } else if (PrevClause->getClauseKind() != C->getClauseKind()) { 10440 S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive) 10441 << getOpenMPClauseName(C->getClauseKind()) 10442 << getOpenMPClauseName(PrevClause->getClauseKind()); 10443 S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause) 10444 << getOpenMPClauseName(PrevClause->getClauseKind()); 10445 ErrorFound = true; 10446 } 10447 } 10448 } 10449 return ErrorFound; 10450 } 10451 10452 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 10453 Stmt *AStmt, SourceLocation StartLoc, 10454 SourceLocation EndLoc) { 10455 if (!AStmt) 10456 return StmtError(); 10457 10458 // OpenMP 5.0, 2.10.1 task Construct 10459 // If a detach clause appears on the directive, then a mergeable clause cannot 10460 // appear on the same directive. 10461 if (checkMutuallyExclusiveClauses(*this, Clauses, 10462 {OMPC_detach, OMPC_mergeable})) 10463 return StmtError(); 10464 10465 auto *CS = cast<CapturedStmt>(AStmt); 10466 // 1.2.2 OpenMP Language Terminology 10467 // Structured block - An executable statement with a single entry at the 10468 // top and a single exit at the bottom. 10469 // The point of exit cannot be a branch out of the structured block. 10470 // longjmp() and throw() must not violate the entry/exit criteria. 10471 CS->getCapturedDecl()->setNothrow(); 10472 10473 setFunctionHasBranchProtectedScope(); 10474 10475 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 10476 DSAStack->isCancelRegion()); 10477 } 10478 10479 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 10480 SourceLocation EndLoc) { 10481 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 10482 } 10483 10484 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 10485 SourceLocation EndLoc) { 10486 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 10487 } 10488 10489 StmtResult Sema::ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses, 10490 SourceLocation StartLoc, 10491 SourceLocation EndLoc) { 10492 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc, Clauses); 10493 } 10494 10495 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 10496 Stmt *AStmt, 10497 SourceLocation StartLoc, 10498 SourceLocation EndLoc) { 10499 if (!AStmt) 10500 return StmtError(); 10501 10502 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10503 10504 setFunctionHasBranchProtectedScope(); 10505 10506 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, 10507 AStmt, 10508 DSAStack->getTaskgroupReductionRef()); 10509 } 10510 10511 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 10512 SourceLocation StartLoc, 10513 SourceLocation EndLoc) { 10514 OMPFlushClause *FC = nullptr; 10515 OMPClause *OrderClause = nullptr; 10516 for (OMPClause *C : Clauses) { 10517 if (C->getClauseKind() == OMPC_flush) 10518 FC = cast<OMPFlushClause>(C); 10519 else 10520 OrderClause = C; 10521 } 10522 OpenMPClauseKind MemOrderKind = OMPC_unknown; 10523 SourceLocation MemOrderLoc; 10524 for (const OMPClause *C : Clauses) { 10525 if (C->getClauseKind() == OMPC_acq_rel || 10526 C->getClauseKind() == OMPC_acquire || 10527 C->getClauseKind() == OMPC_release) { 10528 if (MemOrderKind != OMPC_unknown) { 10529 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses) 10530 << getOpenMPDirectiveName(OMPD_flush) << 1 10531 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 10532 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 10533 << getOpenMPClauseName(MemOrderKind); 10534 } else { 10535 MemOrderKind = C->getClauseKind(); 10536 MemOrderLoc = C->getBeginLoc(); 10537 } 10538 } 10539 } 10540 if (FC && OrderClause) { 10541 Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list) 10542 << getOpenMPClauseName(OrderClause->getClauseKind()); 10543 Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here) 10544 << getOpenMPClauseName(OrderClause->getClauseKind()); 10545 return StmtError(); 10546 } 10547 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 10548 } 10549 10550 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, 10551 SourceLocation StartLoc, 10552 SourceLocation EndLoc) { 10553 if (Clauses.empty()) { 10554 Diag(StartLoc, diag::err_omp_depobj_expected); 10555 return StmtError(); 10556 } else if (Clauses[0]->getClauseKind() != OMPC_depobj) { 10557 Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected); 10558 return StmtError(); 10559 } 10560 // Only depobj expression and another single clause is allowed. 10561 if (Clauses.size() > 2) { 10562 Diag(Clauses[2]->getBeginLoc(), 10563 diag::err_omp_depobj_single_clause_expected); 10564 return StmtError(); 10565 } else if (Clauses.size() < 1) { 10566 Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected); 10567 return StmtError(); 10568 } 10569 return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses); 10570 } 10571 10572 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, 10573 SourceLocation StartLoc, 10574 SourceLocation EndLoc) { 10575 // Check that exactly one clause is specified. 10576 if (Clauses.size() != 1) { 10577 Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(), 10578 diag::err_omp_scan_single_clause_expected); 10579 return StmtError(); 10580 } 10581 // Check that scan directive is used in the scopeof the OpenMP loop body. 10582 if (Scope *S = DSAStack->getCurScope()) { 10583 Scope *ParentS = S->getParent(); 10584 if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() || 10585 !ParentS->getBreakParent()->isOpenMPLoopScope()) 10586 return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive) 10587 << getOpenMPDirectiveName(OMPD_scan) << 5); 10588 } 10589 // Check that only one instance of scan directives is used in the same outer 10590 // region. 10591 if (DSAStack->doesParentHasScanDirective()) { 10592 Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan"; 10593 Diag(DSAStack->getParentScanDirectiveLoc(), 10594 diag::note_omp_previous_directive) 10595 << "scan"; 10596 return StmtError(); 10597 } 10598 DSAStack->setParentHasScanDirective(StartLoc); 10599 return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses); 10600 } 10601 10602 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 10603 Stmt *AStmt, 10604 SourceLocation StartLoc, 10605 SourceLocation EndLoc) { 10606 const OMPClause *DependFound = nullptr; 10607 const OMPClause *DependSourceClause = nullptr; 10608 const OMPClause *DependSinkClause = nullptr; 10609 bool ErrorFound = false; 10610 const OMPThreadsClause *TC = nullptr; 10611 const OMPSIMDClause *SC = nullptr; 10612 for (const OMPClause *C : Clauses) { 10613 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 10614 DependFound = C; 10615 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 10616 if (DependSourceClause) { 10617 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 10618 << getOpenMPDirectiveName(OMPD_ordered) 10619 << getOpenMPClauseName(OMPC_depend) << 2; 10620 ErrorFound = true; 10621 } else { 10622 DependSourceClause = C; 10623 } 10624 if (DependSinkClause) { 10625 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 10626 << 0; 10627 ErrorFound = true; 10628 } 10629 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 10630 if (DependSourceClause) { 10631 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 10632 << 1; 10633 ErrorFound = true; 10634 } 10635 DependSinkClause = C; 10636 } 10637 } else if (C->getClauseKind() == OMPC_threads) { 10638 TC = cast<OMPThreadsClause>(C); 10639 } else if (C->getClauseKind() == OMPC_simd) { 10640 SC = cast<OMPSIMDClause>(C); 10641 } 10642 } 10643 if (!ErrorFound && !SC && 10644 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 10645 // OpenMP [2.8.1,simd Construct, Restrictions] 10646 // An ordered construct with the simd clause is the only OpenMP construct 10647 // that can appear in the simd region. 10648 Diag(StartLoc, diag::err_omp_prohibited_region_simd) 10649 << (LangOpts.OpenMP >= 50 ? 1 : 0); 10650 ErrorFound = true; 10651 } else if (DependFound && (TC || SC)) { 10652 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd) 10653 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 10654 ErrorFound = true; 10655 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) { 10656 Diag(DependFound->getBeginLoc(), 10657 diag::err_omp_ordered_directive_without_param); 10658 ErrorFound = true; 10659 } else if (TC || Clauses.empty()) { 10660 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) { 10661 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc; 10662 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 10663 << (TC != nullptr); 10664 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1; 10665 ErrorFound = true; 10666 } 10667 } 10668 if ((!AStmt && !DependFound) || ErrorFound) 10669 return StmtError(); 10670 10671 // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions. 10672 // During execution of an iteration of a worksharing-loop or a loop nest 10673 // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread 10674 // must not execute more than one ordered region corresponding to an ordered 10675 // construct without a depend clause. 10676 if (!DependFound) { 10677 if (DSAStack->doesParentHasOrderedDirective()) { 10678 Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered"; 10679 Diag(DSAStack->getParentOrderedDirectiveLoc(), 10680 diag::note_omp_previous_directive) 10681 << "ordered"; 10682 return StmtError(); 10683 } 10684 DSAStack->setParentHasOrderedDirective(StartLoc); 10685 } 10686 10687 if (AStmt) { 10688 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10689 10690 setFunctionHasBranchProtectedScope(); 10691 } 10692 10693 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10694 } 10695 10696 namespace { 10697 /// Helper class for checking expression in 'omp atomic [update]' 10698 /// construct. 10699 class OpenMPAtomicUpdateChecker { 10700 /// Error results for atomic update expressions. 10701 enum ExprAnalysisErrorCode { 10702 /// A statement is not an expression statement. 10703 NotAnExpression, 10704 /// Expression is not builtin binary or unary operation. 10705 NotABinaryOrUnaryExpression, 10706 /// Unary operation is not post-/pre- increment/decrement operation. 10707 NotAnUnaryIncDecExpression, 10708 /// An expression is not of scalar type. 10709 NotAScalarType, 10710 /// A binary operation is not an assignment operation. 10711 NotAnAssignmentOp, 10712 /// RHS part of the binary operation is not a binary expression. 10713 NotABinaryExpression, 10714 /// RHS part is not additive/multiplicative/shift/biwise binary 10715 /// expression. 10716 NotABinaryOperator, 10717 /// RHS binary operation does not have reference to the updated LHS 10718 /// part. 10719 NotAnUpdateExpression, 10720 /// No errors is found. 10721 NoError 10722 }; 10723 /// Reference to Sema. 10724 Sema &SemaRef; 10725 /// A location for note diagnostics (when error is found). 10726 SourceLocation NoteLoc; 10727 /// 'x' lvalue part of the source atomic expression. 10728 Expr *X; 10729 /// 'expr' rvalue part of the source atomic expression. 10730 Expr *E; 10731 /// Helper expression of the form 10732 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 10733 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 10734 Expr *UpdateExpr; 10735 /// Is 'x' a LHS in a RHS part of full update expression. It is 10736 /// important for non-associative operations. 10737 bool IsXLHSInRHSPart; 10738 BinaryOperatorKind Op; 10739 SourceLocation OpLoc; 10740 /// true if the source expression is a postfix unary operation, false 10741 /// if it is a prefix unary operation. 10742 bool IsPostfixUpdate; 10743 10744 public: 10745 OpenMPAtomicUpdateChecker(Sema &SemaRef) 10746 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 10747 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 10748 /// Check specified statement that it is suitable for 'atomic update' 10749 /// constructs and extract 'x', 'expr' and Operation from the original 10750 /// expression. If DiagId and NoteId == 0, then only check is performed 10751 /// without error notification. 10752 /// \param DiagId Diagnostic which should be emitted if error is found. 10753 /// \param NoteId Diagnostic note for the main error message. 10754 /// \return true if statement is not an update expression, false otherwise. 10755 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 10756 /// Return the 'x' lvalue part of the source atomic expression. 10757 Expr *getX() const { return X; } 10758 /// Return the 'expr' rvalue part of the source atomic expression. 10759 Expr *getExpr() const { return E; } 10760 /// Return the update expression used in calculation of the updated 10761 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 10762 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 10763 Expr *getUpdateExpr() const { return UpdateExpr; } 10764 /// Return true if 'x' is LHS in RHS part of full update expression, 10765 /// false otherwise. 10766 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 10767 10768 /// true if the source expression is a postfix unary operation, false 10769 /// if it is a prefix unary operation. 10770 bool isPostfixUpdate() const { return IsPostfixUpdate; } 10771 10772 private: 10773 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 10774 unsigned NoteId = 0); 10775 }; 10776 10777 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 10778 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 10779 ExprAnalysisErrorCode ErrorFound = NoError; 10780 SourceLocation ErrorLoc, NoteLoc; 10781 SourceRange ErrorRange, NoteRange; 10782 // Allowed constructs are: 10783 // x = x binop expr; 10784 // x = expr binop x; 10785 if (AtomicBinOp->getOpcode() == BO_Assign) { 10786 X = AtomicBinOp->getLHS(); 10787 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 10788 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 10789 if (AtomicInnerBinOp->isMultiplicativeOp() || 10790 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 10791 AtomicInnerBinOp->isBitwiseOp()) { 10792 Op = AtomicInnerBinOp->getOpcode(); 10793 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 10794 Expr *LHS = AtomicInnerBinOp->getLHS(); 10795 Expr *RHS = AtomicInnerBinOp->getRHS(); 10796 llvm::FoldingSetNodeID XId, LHSId, RHSId; 10797 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 10798 /*Canonical=*/true); 10799 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 10800 /*Canonical=*/true); 10801 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 10802 /*Canonical=*/true); 10803 if (XId == LHSId) { 10804 E = RHS; 10805 IsXLHSInRHSPart = true; 10806 } else if (XId == RHSId) { 10807 E = LHS; 10808 IsXLHSInRHSPart = false; 10809 } else { 10810 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 10811 ErrorRange = AtomicInnerBinOp->getSourceRange(); 10812 NoteLoc = X->getExprLoc(); 10813 NoteRange = X->getSourceRange(); 10814 ErrorFound = NotAnUpdateExpression; 10815 } 10816 } else { 10817 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 10818 ErrorRange = AtomicInnerBinOp->getSourceRange(); 10819 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 10820 NoteRange = SourceRange(NoteLoc, NoteLoc); 10821 ErrorFound = NotABinaryOperator; 10822 } 10823 } else { 10824 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 10825 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 10826 ErrorFound = NotABinaryExpression; 10827 } 10828 } else { 10829 ErrorLoc = AtomicBinOp->getExprLoc(); 10830 ErrorRange = AtomicBinOp->getSourceRange(); 10831 NoteLoc = AtomicBinOp->getOperatorLoc(); 10832 NoteRange = SourceRange(NoteLoc, NoteLoc); 10833 ErrorFound = NotAnAssignmentOp; 10834 } 10835 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 10836 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 10837 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 10838 return true; 10839 } 10840 if (SemaRef.CurContext->isDependentContext()) 10841 E = X = UpdateExpr = nullptr; 10842 return ErrorFound != NoError; 10843 } 10844 10845 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 10846 unsigned NoteId) { 10847 ExprAnalysisErrorCode ErrorFound = NoError; 10848 SourceLocation ErrorLoc, NoteLoc; 10849 SourceRange ErrorRange, NoteRange; 10850 // Allowed constructs are: 10851 // x++; 10852 // x--; 10853 // ++x; 10854 // --x; 10855 // x binop= expr; 10856 // x = x binop expr; 10857 // x = expr binop x; 10858 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 10859 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 10860 if (AtomicBody->getType()->isScalarType() || 10861 AtomicBody->isInstantiationDependent()) { 10862 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 10863 AtomicBody->IgnoreParenImpCasts())) { 10864 // Check for Compound Assignment Operation 10865 Op = BinaryOperator::getOpForCompoundAssignment( 10866 AtomicCompAssignOp->getOpcode()); 10867 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 10868 E = AtomicCompAssignOp->getRHS(); 10869 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 10870 IsXLHSInRHSPart = true; 10871 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 10872 AtomicBody->IgnoreParenImpCasts())) { 10873 // Check for Binary Operation 10874 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 10875 return true; 10876 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 10877 AtomicBody->IgnoreParenImpCasts())) { 10878 // Check for Unary Operation 10879 if (AtomicUnaryOp->isIncrementDecrementOp()) { 10880 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 10881 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 10882 OpLoc = AtomicUnaryOp->getOperatorLoc(); 10883 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 10884 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 10885 IsXLHSInRHSPart = true; 10886 } else { 10887 ErrorFound = NotAnUnaryIncDecExpression; 10888 ErrorLoc = AtomicUnaryOp->getExprLoc(); 10889 ErrorRange = AtomicUnaryOp->getSourceRange(); 10890 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 10891 NoteRange = SourceRange(NoteLoc, NoteLoc); 10892 } 10893 } else if (!AtomicBody->isInstantiationDependent()) { 10894 ErrorFound = NotABinaryOrUnaryExpression; 10895 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 10896 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 10897 } 10898 } else { 10899 ErrorFound = NotAScalarType; 10900 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc(); 10901 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 10902 } 10903 } else { 10904 ErrorFound = NotAnExpression; 10905 NoteLoc = ErrorLoc = S->getBeginLoc(); 10906 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 10907 } 10908 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 10909 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 10910 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 10911 return true; 10912 } 10913 if (SemaRef.CurContext->isDependentContext()) 10914 E = X = UpdateExpr = nullptr; 10915 if (ErrorFound == NoError && E && X) { 10916 // Build an update expression of form 'OpaqueValueExpr(x) binop 10917 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 10918 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 10919 auto *OVEX = new (SemaRef.getASTContext()) 10920 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_PRValue); 10921 auto *OVEExpr = new (SemaRef.getASTContext()) 10922 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_PRValue); 10923 ExprResult Update = 10924 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 10925 IsXLHSInRHSPart ? OVEExpr : OVEX); 10926 if (Update.isInvalid()) 10927 return true; 10928 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 10929 Sema::AA_Casting); 10930 if (Update.isInvalid()) 10931 return true; 10932 UpdateExpr = Update.get(); 10933 } 10934 return ErrorFound != NoError; 10935 } 10936 10937 /// Get the node id of the fixed point of an expression \a S. 10938 llvm::FoldingSetNodeID getNodeId(ASTContext &Context, const Expr *S) { 10939 llvm::FoldingSetNodeID Id; 10940 S->IgnoreParenImpCasts()->Profile(Id, Context, true); 10941 return Id; 10942 } 10943 10944 /// Check if two expressions are same. 10945 bool checkIfTwoExprsAreSame(ASTContext &Context, const Expr *LHS, 10946 const Expr *RHS) { 10947 return getNodeId(Context, LHS) == getNodeId(Context, RHS); 10948 } 10949 10950 class OpenMPAtomicCompareChecker { 10951 public: 10952 /// All kinds of errors that can occur in `atomic compare` 10953 enum ErrorTy { 10954 /// Empty compound statement. 10955 NoStmt = 0, 10956 /// More than one statement in a compound statement. 10957 MoreThanOneStmt, 10958 /// Not an assignment binary operator. 10959 NotAnAssignment, 10960 /// Not a conditional operator. 10961 NotCondOp, 10962 /// Wrong false expr. According to the spec, 'x' should be at the false 10963 /// expression of a conditional expression. 10964 WrongFalseExpr, 10965 /// The condition of a conditional expression is not a binary operator. 10966 NotABinaryOp, 10967 /// Invalid binary operator (not <, >, or ==). 10968 InvalidBinaryOp, 10969 /// Invalid comparison (not x == e, e == x, x ordop expr, or expr ordop x). 10970 InvalidComparison, 10971 /// X is not a lvalue. 10972 XNotLValue, 10973 /// Not a scalar. 10974 NotScalar, 10975 /// Not an integer. 10976 NotInteger, 10977 /// No error. 10978 NoError, 10979 }; 10980 10981 struct ErrorInfoTy { 10982 ErrorTy Error; 10983 SourceLocation ErrorLoc; 10984 SourceRange ErrorRange; 10985 SourceLocation NoteLoc; 10986 SourceRange NoteRange; 10987 }; 10988 10989 OpenMPAtomicCompareChecker(Sema &S) : ContextRef(S.getASTContext()) {} 10990 10991 /// Check if statement \a S is valid for <tt>atomic compare</tt>. 10992 bool checkStmt(Stmt *S, ErrorInfoTy &ErrorInfo); 10993 10994 Expr *getX() const { return X; } 10995 Expr *getE() const { return E; } 10996 Expr *getD() const { return D; } 10997 Expr *getCond() const { return C; } 10998 bool isXBinopExpr() const { return IsXBinopExpr; } 10999 11000 private: 11001 /// Reference to ASTContext 11002 ASTContext &ContextRef; 11003 /// 'x' lvalue part of the source atomic expression. 11004 Expr *X = nullptr; 11005 /// 'expr' or 'e' rvalue part of the source atomic expression. 11006 Expr *E = nullptr; 11007 /// 'd' rvalue part of the source atomic expression. 11008 Expr *D = nullptr; 11009 /// 'cond' part of the source atomic expression. It is in one of the following 11010 /// forms: 11011 /// expr ordop x 11012 /// x ordop expr 11013 /// x == e 11014 /// e == x 11015 Expr *C = nullptr; 11016 /// True if the cond expr is in the form of 'x ordop expr'. 11017 bool IsXBinopExpr = true; 11018 11019 /// Check if it is a valid conditional update statement (cond-update-stmt). 11020 bool checkCondUpdateStmt(IfStmt *S, ErrorInfoTy &ErrorInfo); 11021 11022 /// Check if it is a valid conditional expression statement (cond-expr-stmt). 11023 bool checkCondExprStmt(Stmt *S, ErrorInfoTy &ErrorInfo); 11024 11025 /// Check if all captured values have right type. 11026 bool checkType(ErrorInfoTy &ErrorInfo) const; 11027 }; 11028 11029 bool OpenMPAtomicCompareChecker::checkCondUpdateStmt(IfStmt *S, 11030 ErrorInfoTy &ErrorInfo) { 11031 auto *Then = S->getThen(); 11032 if (auto *CS = dyn_cast<CompoundStmt>(Then)) { 11033 if (CS->body_empty()) { 11034 ErrorInfo.Error = ErrorTy::NoStmt; 11035 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc(); 11036 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange(); 11037 return false; 11038 } 11039 if (CS->size() > 1) { 11040 ErrorInfo.Error = ErrorTy::MoreThanOneStmt; 11041 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc(); 11042 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange(); 11043 return false; 11044 } 11045 Then = CS->body_front(); 11046 } 11047 11048 auto *BO = dyn_cast<BinaryOperator>(Then); 11049 if (!BO) { 11050 ErrorInfo.Error = ErrorTy::NotAnAssignment; 11051 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Then->getBeginLoc(); 11052 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Then->getSourceRange(); 11053 return false; 11054 } 11055 if (BO->getOpcode() != BO_Assign) { 11056 ErrorInfo.Error = ErrorTy::NotAnAssignment; 11057 ErrorInfo.ErrorLoc = BO->getExprLoc(); 11058 ErrorInfo.NoteLoc = BO->getOperatorLoc(); 11059 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange(); 11060 return false; 11061 } 11062 11063 X = BO->getLHS(); 11064 11065 auto *Cond = dyn_cast<BinaryOperator>(S->getCond()); 11066 if (!Cond) { 11067 ErrorInfo.Error = ErrorTy::NotABinaryOp; 11068 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getCond()->getExprLoc(); 11069 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getCond()->getSourceRange(); 11070 return false; 11071 } 11072 11073 switch (Cond->getOpcode()) { 11074 case BO_EQ: { 11075 C = Cond; 11076 D = BO->getRHS(); 11077 if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS())) { 11078 E = Cond->getRHS(); 11079 } else if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) { 11080 E = Cond->getLHS(); 11081 } else { 11082 ErrorInfo.Error = ErrorTy::InvalidComparison; 11083 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc(); 11084 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange(); 11085 return false; 11086 } 11087 break; 11088 } 11089 case BO_LT: 11090 case BO_GT: { 11091 E = BO->getRHS(); 11092 if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS()) && 11093 checkIfTwoExprsAreSame(ContextRef, E, Cond->getRHS())) { 11094 C = Cond; 11095 } else if (checkIfTwoExprsAreSame(ContextRef, E, Cond->getLHS()) && 11096 checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) { 11097 C = Cond; 11098 IsXBinopExpr = false; 11099 } else { 11100 ErrorInfo.Error = ErrorTy::InvalidComparison; 11101 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc(); 11102 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange(); 11103 return false; 11104 } 11105 break; 11106 } 11107 default: 11108 ErrorInfo.Error = ErrorTy::InvalidBinaryOp; 11109 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc(); 11110 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange(); 11111 return false; 11112 } 11113 11114 return true; 11115 } 11116 11117 bool OpenMPAtomicCompareChecker::checkCondExprStmt(Stmt *S, 11118 ErrorInfoTy &ErrorInfo) { 11119 auto *BO = dyn_cast<BinaryOperator>(S); 11120 if (!BO) { 11121 ErrorInfo.Error = ErrorTy::NotAnAssignment; 11122 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = S->getBeginLoc(); 11123 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = S->getSourceRange(); 11124 return false; 11125 } 11126 if (BO->getOpcode() != BO_Assign) { 11127 ErrorInfo.Error = ErrorTy::NotAnAssignment; 11128 ErrorInfo.ErrorLoc = BO->getExprLoc(); 11129 ErrorInfo.NoteLoc = BO->getOperatorLoc(); 11130 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getSourceRange(); 11131 return false; 11132 } 11133 11134 X = BO->getLHS(); 11135 11136 auto *CO = dyn_cast<ConditionalOperator>(BO->getRHS()->IgnoreParenImpCasts()); 11137 if (!CO) { 11138 ErrorInfo.Error = ErrorTy::NotCondOp; 11139 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = BO->getRHS()->getExprLoc(); 11140 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = BO->getRHS()->getSourceRange(); 11141 return false; 11142 } 11143 11144 if (!checkIfTwoExprsAreSame(ContextRef, X, CO->getFalseExpr())) { 11145 ErrorInfo.Error = ErrorTy::WrongFalseExpr; 11146 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CO->getFalseExpr()->getExprLoc(); 11147 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = 11148 CO->getFalseExpr()->getSourceRange(); 11149 return false; 11150 } 11151 11152 auto *Cond = dyn_cast<BinaryOperator>(CO->getCond()); 11153 if (!Cond) { 11154 ErrorInfo.Error = ErrorTy::NotABinaryOp; 11155 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CO->getCond()->getExprLoc(); 11156 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = 11157 CO->getCond()->getSourceRange(); 11158 return false; 11159 } 11160 11161 switch (Cond->getOpcode()) { 11162 case BO_EQ: { 11163 C = Cond; 11164 D = CO->getTrueExpr(); 11165 if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS())) { 11166 E = Cond->getRHS(); 11167 } else if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) { 11168 E = Cond->getLHS(); 11169 } else { 11170 ErrorInfo.Error = ErrorTy::InvalidComparison; 11171 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc(); 11172 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange(); 11173 return false; 11174 } 11175 break; 11176 } 11177 case BO_LT: 11178 case BO_GT: { 11179 E = CO->getTrueExpr(); 11180 if (checkIfTwoExprsAreSame(ContextRef, X, Cond->getLHS()) && 11181 checkIfTwoExprsAreSame(ContextRef, E, Cond->getRHS())) { 11182 C = Cond; 11183 } else if (checkIfTwoExprsAreSame(ContextRef, E, Cond->getLHS()) && 11184 checkIfTwoExprsAreSame(ContextRef, X, Cond->getRHS())) { 11185 C = Cond; 11186 IsXBinopExpr = false; 11187 } else { 11188 ErrorInfo.Error = ErrorTy::InvalidComparison; 11189 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc(); 11190 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange(); 11191 return false; 11192 } 11193 break; 11194 } 11195 default: 11196 ErrorInfo.Error = ErrorTy::InvalidBinaryOp; 11197 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = Cond->getExprLoc(); 11198 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = Cond->getSourceRange(); 11199 return false; 11200 } 11201 11202 return true; 11203 } 11204 11205 bool OpenMPAtomicCompareChecker::checkType(ErrorInfoTy &ErrorInfo) const { 11206 // 'x' and 'e' cannot be nullptr 11207 assert(X && E && "X and E cannot be nullptr"); 11208 11209 auto CheckValue = [&ErrorInfo](const Expr *E, bool ShouldBeLValue) { 11210 if (ShouldBeLValue && !E->isLValue()) { 11211 ErrorInfo.Error = ErrorTy::XNotLValue; 11212 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc(); 11213 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange(); 11214 return false; 11215 } 11216 11217 if (!E->isInstantiationDependent()) { 11218 QualType QTy = E->getType(); 11219 if (!QTy->isScalarType()) { 11220 ErrorInfo.Error = ErrorTy::NotScalar; 11221 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc(); 11222 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange(); 11223 return false; 11224 } 11225 11226 if (!QTy->isIntegerType()) { 11227 ErrorInfo.Error = ErrorTy::NotInteger; 11228 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = E->getExprLoc(); 11229 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = E->getSourceRange(); 11230 return false; 11231 } 11232 } 11233 11234 return true; 11235 }; 11236 11237 if (!CheckValue(X, true)) 11238 return false; 11239 11240 if (!CheckValue(E, false)) 11241 return false; 11242 11243 if (D && !CheckValue(D, false)) 11244 return false; 11245 11246 return true; 11247 } 11248 11249 bool OpenMPAtomicCompareChecker::checkStmt( 11250 Stmt *S, OpenMPAtomicCompareChecker::ErrorInfoTy &ErrorInfo) { 11251 auto *CS = dyn_cast<CompoundStmt>(S); 11252 if (CS) { 11253 if (CS->body_empty()) { 11254 ErrorInfo.Error = ErrorTy::NoStmt; 11255 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc(); 11256 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange(); 11257 return false; 11258 } 11259 11260 if (CS->size() != 1) { 11261 ErrorInfo.Error = ErrorTy::MoreThanOneStmt; 11262 ErrorInfo.ErrorLoc = ErrorInfo.NoteLoc = CS->getBeginLoc(); 11263 ErrorInfo.ErrorRange = ErrorInfo.NoteRange = CS->getSourceRange(); 11264 return false; 11265 } 11266 S = CS->body_front(); 11267 } 11268 11269 auto Res = false; 11270 11271 if (auto *IS = dyn_cast<IfStmt>(S)) { 11272 // Check if the statement is in one of the following forms 11273 // (cond-update-stmt): 11274 // if (expr ordop x) { x = expr; } 11275 // if (x ordop expr) { x = expr; } 11276 // if (x == e) { x = d; } 11277 Res = checkCondUpdateStmt(IS, ErrorInfo); 11278 } else { 11279 // Check if the statement is in one of the following forms (cond-expr-stmt): 11280 // x = expr ordop x ? expr : x; 11281 // x = x ordop expr ? expr : x; 11282 // x = x == e ? d : x; 11283 Res = checkCondExprStmt(S, ErrorInfo); 11284 } 11285 11286 if (!Res) 11287 return false; 11288 11289 return checkType(ErrorInfo); 11290 } 11291 } // namespace 11292 11293 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 11294 Stmt *AStmt, 11295 SourceLocation StartLoc, 11296 SourceLocation EndLoc) { 11297 // Register location of the first atomic directive. 11298 DSAStack->addAtomicDirectiveLoc(StartLoc); 11299 if (!AStmt) 11300 return StmtError(); 11301 11302 // 1.2.2 OpenMP Language Terminology 11303 // Structured block - An executable statement with a single entry at the 11304 // top and a single exit at the bottom. 11305 // The point of exit cannot be a branch out of the structured block. 11306 // longjmp() and throw() must not violate the entry/exit criteria. 11307 OpenMPClauseKind AtomicKind = OMPC_unknown; 11308 SourceLocation AtomicKindLoc; 11309 OpenMPClauseKind MemOrderKind = OMPC_unknown; 11310 SourceLocation MemOrderLoc; 11311 bool MutexClauseEncountered = false; 11312 llvm::SmallSet<OpenMPClauseKind, 2> EncounteredAtomicKinds; 11313 for (const OMPClause *C : Clauses) { 11314 switch (C->getClauseKind()) { 11315 case OMPC_read: 11316 case OMPC_write: 11317 case OMPC_update: 11318 MutexClauseEncountered = true; 11319 LLVM_FALLTHROUGH; 11320 case OMPC_capture: 11321 case OMPC_compare: { 11322 if (AtomicKind != OMPC_unknown && MutexClauseEncountered) { 11323 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses) 11324 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 11325 Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause) 11326 << getOpenMPClauseName(AtomicKind); 11327 } else { 11328 AtomicKind = C->getClauseKind(); 11329 AtomicKindLoc = C->getBeginLoc(); 11330 if (!EncounteredAtomicKinds.insert(C->getClauseKind()).second) { 11331 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses) 11332 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 11333 Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause) 11334 << getOpenMPClauseName(AtomicKind); 11335 } 11336 } 11337 break; 11338 } 11339 case OMPC_seq_cst: 11340 case OMPC_acq_rel: 11341 case OMPC_acquire: 11342 case OMPC_release: 11343 case OMPC_relaxed: { 11344 if (MemOrderKind != OMPC_unknown) { 11345 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses) 11346 << getOpenMPDirectiveName(OMPD_atomic) << 0 11347 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 11348 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 11349 << getOpenMPClauseName(MemOrderKind); 11350 } else { 11351 MemOrderKind = C->getClauseKind(); 11352 MemOrderLoc = C->getBeginLoc(); 11353 } 11354 break; 11355 } 11356 // The following clauses are allowed, but we don't need to do anything here. 11357 case OMPC_hint: 11358 break; 11359 default: 11360 llvm_unreachable("unknown clause is encountered"); 11361 } 11362 } 11363 bool IsCompareCapture = false; 11364 if (EncounteredAtomicKinds.contains(OMPC_compare) && 11365 EncounteredAtomicKinds.contains(OMPC_capture)) { 11366 IsCompareCapture = true; 11367 AtomicKind = OMPC_compare; 11368 } 11369 // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions 11370 // If atomic-clause is read then memory-order-clause must not be acq_rel or 11371 // release. 11372 // If atomic-clause is write then memory-order-clause must not be acq_rel or 11373 // acquire. 11374 // If atomic-clause is update or not present then memory-order-clause must not 11375 // be acq_rel or acquire. 11376 if ((AtomicKind == OMPC_read && 11377 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) || 11378 ((AtomicKind == OMPC_write || AtomicKind == OMPC_update || 11379 AtomicKind == OMPC_unknown) && 11380 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) { 11381 SourceLocation Loc = AtomicKindLoc; 11382 if (AtomicKind == OMPC_unknown) 11383 Loc = StartLoc; 11384 Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause) 11385 << getOpenMPClauseName(AtomicKind) 11386 << (AtomicKind == OMPC_unknown ? 1 : 0) 11387 << getOpenMPClauseName(MemOrderKind); 11388 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 11389 << getOpenMPClauseName(MemOrderKind); 11390 } 11391 11392 Stmt *Body = AStmt; 11393 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 11394 Body = EWC->getSubExpr(); 11395 11396 Expr *X = nullptr; 11397 Expr *V = nullptr; 11398 Expr *E = nullptr; 11399 Expr *UE = nullptr; 11400 bool IsXLHSInRHSPart = false; 11401 bool IsPostfixUpdate = false; 11402 // OpenMP [2.12.6, atomic Construct] 11403 // In the next expressions: 11404 // * x and v (as applicable) are both l-value expressions with scalar type. 11405 // * During the execution of an atomic region, multiple syntactic 11406 // occurrences of x must designate the same storage location. 11407 // * Neither of v and expr (as applicable) may access the storage location 11408 // designated by x. 11409 // * Neither of x and expr (as applicable) may access the storage location 11410 // designated by v. 11411 // * expr is an expression with scalar type. 11412 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 11413 // * binop, binop=, ++, and -- are not overloaded operators. 11414 // * The expression x binop expr must be numerically equivalent to x binop 11415 // (expr). This requirement is satisfied if the operators in expr have 11416 // precedence greater than binop, or by using parentheses around expr or 11417 // subexpressions of expr. 11418 // * The expression expr binop x must be numerically equivalent to (expr) 11419 // binop x. This requirement is satisfied if the operators in expr have 11420 // precedence equal to or greater than binop, or by using parentheses around 11421 // expr or subexpressions of expr. 11422 // * For forms that allow multiple occurrences of x, the number of times 11423 // that x is evaluated is unspecified. 11424 if (AtomicKind == OMPC_read) { 11425 enum { 11426 NotAnExpression, 11427 NotAnAssignmentOp, 11428 NotAScalarType, 11429 NotAnLValue, 11430 NoError 11431 } ErrorFound = NoError; 11432 SourceLocation ErrorLoc, NoteLoc; 11433 SourceRange ErrorRange, NoteRange; 11434 // If clause is read: 11435 // v = x; 11436 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 11437 const auto *AtomicBinOp = 11438 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 11439 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 11440 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 11441 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 11442 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 11443 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 11444 if (!X->isLValue() || !V->isLValue()) { 11445 const Expr *NotLValueExpr = X->isLValue() ? V : X; 11446 ErrorFound = NotAnLValue; 11447 ErrorLoc = AtomicBinOp->getExprLoc(); 11448 ErrorRange = AtomicBinOp->getSourceRange(); 11449 NoteLoc = NotLValueExpr->getExprLoc(); 11450 NoteRange = NotLValueExpr->getSourceRange(); 11451 } 11452 } else if (!X->isInstantiationDependent() || 11453 !V->isInstantiationDependent()) { 11454 const Expr *NotScalarExpr = 11455 (X->isInstantiationDependent() || X->getType()->isScalarType()) 11456 ? V 11457 : X; 11458 ErrorFound = NotAScalarType; 11459 ErrorLoc = AtomicBinOp->getExprLoc(); 11460 ErrorRange = AtomicBinOp->getSourceRange(); 11461 NoteLoc = NotScalarExpr->getExprLoc(); 11462 NoteRange = NotScalarExpr->getSourceRange(); 11463 } 11464 } else if (!AtomicBody->isInstantiationDependent()) { 11465 ErrorFound = NotAnAssignmentOp; 11466 ErrorLoc = AtomicBody->getExprLoc(); 11467 ErrorRange = AtomicBody->getSourceRange(); 11468 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 11469 : AtomicBody->getExprLoc(); 11470 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 11471 : AtomicBody->getSourceRange(); 11472 } 11473 } else { 11474 ErrorFound = NotAnExpression; 11475 NoteLoc = ErrorLoc = Body->getBeginLoc(); 11476 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 11477 } 11478 if (ErrorFound != NoError) { 11479 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 11480 << ErrorRange; 11481 Diag(NoteLoc, diag::note_omp_atomic_read_write) 11482 << ErrorFound << NoteRange; 11483 return StmtError(); 11484 } 11485 if (CurContext->isDependentContext()) 11486 V = X = nullptr; 11487 } else if (AtomicKind == OMPC_write) { 11488 enum { 11489 NotAnExpression, 11490 NotAnAssignmentOp, 11491 NotAScalarType, 11492 NotAnLValue, 11493 NoError 11494 } ErrorFound = NoError; 11495 SourceLocation ErrorLoc, NoteLoc; 11496 SourceRange ErrorRange, NoteRange; 11497 // If clause is write: 11498 // x = expr; 11499 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 11500 const auto *AtomicBinOp = 11501 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 11502 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 11503 X = AtomicBinOp->getLHS(); 11504 E = AtomicBinOp->getRHS(); 11505 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 11506 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 11507 if (!X->isLValue()) { 11508 ErrorFound = NotAnLValue; 11509 ErrorLoc = AtomicBinOp->getExprLoc(); 11510 ErrorRange = AtomicBinOp->getSourceRange(); 11511 NoteLoc = X->getExprLoc(); 11512 NoteRange = X->getSourceRange(); 11513 } 11514 } else if (!X->isInstantiationDependent() || 11515 !E->isInstantiationDependent()) { 11516 const Expr *NotScalarExpr = 11517 (X->isInstantiationDependent() || X->getType()->isScalarType()) 11518 ? E 11519 : X; 11520 ErrorFound = NotAScalarType; 11521 ErrorLoc = AtomicBinOp->getExprLoc(); 11522 ErrorRange = AtomicBinOp->getSourceRange(); 11523 NoteLoc = NotScalarExpr->getExprLoc(); 11524 NoteRange = NotScalarExpr->getSourceRange(); 11525 } 11526 } else if (!AtomicBody->isInstantiationDependent()) { 11527 ErrorFound = NotAnAssignmentOp; 11528 ErrorLoc = AtomicBody->getExprLoc(); 11529 ErrorRange = AtomicBody->getSourceRange(); 11530 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 11531 : AtomicBody->getExprLoc(); 11532 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 11533 : AtomicBody->getSourceRange(); 11534 } 11535 } else { 11536 ErrorFound = NotAnExpression; 11537 NoteLoc = ErrorLoc = Body->getBeginLoc(); 11538 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 11539 } 11540 if (ErrorFound != NoError) { 11541 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 11542 << ErrorRange; 11543 Diag(NoteLoc, diag::note_omp_atomic_read_write) 11544 << ErrorFound << NoteRange; 11545 return StmtError(); 11546 } 11547 if (CurContext->isDependentContext()) 11548 E = X = nullptr; 11549 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 11550 // If clause is update: 11551 // x++; 11552 // x--; 11553 // ++x; 11554 // --x; 11555 // x binop= expr; 11556 // x = x binop expr; 11557 // x = expr binop x; 11558 OpenMPAtomicUpdateChecker Checker(*this); 11559 if (Checker.checkStatement( 11560 Body, 11561 (AtomicKind == OMPC_update) 11562 ? diag::err_omp_atomic_update_not_expression_statement 11563 : diag::err_omp_atomic_not_expression_statement, 11564 diag::note_omp_atomic_update)) 11565 return StmtError(); 11566 if (!CurContext->isDependentContext()) { 11567 E = Checker.getExpr(); 11568 X = Checker.getX(); 11569 UE = Checker.getUpdateExpr(); 11570 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 11571 } 11572 } else if (AtomicKind == OMPC_capture) { 11573 enum { 11574 NotAnAssignmentOp, 11575 NotACompoundStatement, 11576 NotTwoSubstatements, 11577 NotASpecificExpression, 11578 NoError 11579 } ErrorFound = NoError; 11580 SourceLocation ErrorLoc, NoteLoc; 11581 SourceRange ErrorRange, NoteRange; 11582 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 11583 // If clause is a capture: 11584 // v = x++; 11585 // v = x--; 11586 // v = ++x; 11587 // v = --x; 11588 // v = x binop= expr; 11589 // v = x = x binop expr; 11590 // v = x = expr binop x; 11591 const auto *AtomicBinOp = 11592 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 11593 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 11594 V = AtomicBinOp->getLHS(); 11595 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 11596 OpenMPAtomicUpdateChecker Checker(*this); 11597 if (Checker.checkStatement( 11598 Body, diag::err_omp_atomic_capture_not_expression_statement, 11599 diag::note_omp_atomic_update)) 11600 return StmtError(); 11601 E = Checker.getExpr(); 11602 X = Checker.getX(); 11603 UE = Checker.getUpdateExpr(); 11604 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 11605 IsPostfixUpdate = Checker.isPostfixUpdate(); 11606 } else if (!AtomicBody->isInstantiationDependent()) { 11607 ErrorLoc = AtomicBody->getExprLoc(); 11608 ErrorRange = AtomicBody->getSourceRange(); 11609 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 11610 : AtomicBody->getExprLoc(); 11611 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 11612 : AtomicBody->getSourceRange(); 11613 ErrorFound = NotAnAssignmentOp; 11614 } 11615 if (ErrorFound != NoError) { 11616 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 11617 << ErrorRange; 11618 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 11619 return StmtError(); 11620 } 11621 if (CurContext->isDependentContext()) 11622 UE = V = E = X = nullptr; 11623 } else { 11624 // If clause is a capture: 11625 // { v = x; x = expr; } 11626 // { v = x; x++; } 11627 // { v = x; x--; } 11628 // { v = x; ++x; } 11629 // { v = x; --x; } 11630 // { v = x; x binop= expr; } 11631 // { v = x; x = x binop expr; } 11632 // { v = x; x = expr binop x; } 11633 // { x++; v = x; } 11634 // { x--; v = x; } 11635 // { ++x; v = x; } 11636 // { --x; v = x; } 11637 // { x binop= expr; v = x; } 11638 // { x = x binop expr; v = x; } 11639 // { x = expr binop x; v = x; } 11640 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 11641 // Check that this is { expr1; expr2; } 11642 if (CS->size() == 2) { 11643 Stmt *First = CS->body_front(); 11644 Stmt *Second = CS->body_back(); 11645 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 11646 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 11647 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 11648 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 11649 // Need to find what subexpression is 'v' and what is 'x'. 11650 OpenMPAtomicUpdateChecker Checker(*this); 11651 bool IsUpdateExprFound = !Checker.checkStatement(Second); 11652 BinaryOperator *BinOp = nullptr; 11653 if (IsUpdateExprFound) { 11654 BinOp = dyn_cast<BinaryOperator>(First); 11655 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 11656 } 11657 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 11658 // { v = x; x++; } 11659 // { v = x; x--; } 11660 // { v = x; ++x; } 11661 // { v = x; --x; } 11662 // { v = x; x binop= expr; } 11663 // { v = x; x = x binop expr; } 11664 // { v = x; x = expr binop x; } 11665 // Check that the first expression has form v = x. 11666 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 11667 llvm::FoldingSetNodeID XId, PossibleXId; 11668 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 11669 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 11670 IsUpdateExprFound = XId == PossibleXId; 11671 if (IsUpdateExprFound) { 11672 V = BinOp->getLHS(); 11673 X = Checker.getX(); 11674 E = Checker.getExpr(); 11675 UE = Checker.getUpdateExpr(); 11676 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 11677 IsPostfixUpdate = true; 11678 } 11679 } 11680 if (!IsUpdateExprFound) { 11681 IsUpdateExprFound = !Checker.checkStatement(First); 11682 BinOp = nullptr; 11683 if (IsUpdateExprFound) { 11684 BinOp = dyn_cast<BinaryOperator>(Second); 11685 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 11686 } 11687 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 11688 // { x++; v = x; } 11689 // { x--; v = x; } 11690 // { ++x; v = x; } 11691 // { --x; v = x; } 11692 // { x binop= expr; v = x; } 11693 // { x = x binop expr; v = x; } 11694 // { x = expr binop x; v = x; } 11695 // Check that the second expression has form v = x. 11696 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 11697 llvm::FoldingSetNodeID XId, PossibleXId; 11698 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 11699 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 11700 IsUpdateExprFound = XId == PossibleXId; 11701 if (IsUpdateExprFound) { 11702 V = BinOp->getLHS(); 11703 X = Checker.getX(); 11704 E = Checker.getExpr(); 11705 UE = Checker.getUpdateExpr(); 11706 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 11707 IsPostfixUpdate = false; 11708 } 11709 } 11710 } 11711 if (!IsUpdateExprFound) { 11712 // { v = x; x = expr; } 11713 auto *FirstExpr = dyn_cast<Expr>(First); 11714 auto *SecondExpr = dyn_cast<Expr>(Second); 11715 if (!FirstExpr || !SecondExpr || 11716 !(FirstExpr->isInstantiationDependent() || 11717 SecondExpr->isInstantiationDependent())) { 11718 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 11719 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 11720 ErrorFound = NotAnAssignmentOp; 11721 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 11722 : First->getBeginLoc(); 11723 NoteRange = ErrorRange = FirstBinOp 11724 ? FirstBinOp->getSourceRange() 11725 : SourceRange(ErrorLoc, ErrorLoc); 11726 } else { 11727 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 11728 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 11729 ErrorFound = NotAnAssignmentOp; 11730 NoteLoc = ErrorLoc = SecondBinOp 11731 ? SecondBinOp->getOperatorLoc() 11732 : Second->getBeginLoc(); 11733 NoteRange = ErrorRange = 11734 SecondBinOp ? SecondBinOp->getSourceRange() 11735 : SourceRange(ErrorLoc, ErrorLoc); 11736 } else { 11737 Expr *PossibleXRHSInFirst = 11738 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 11739 Expr *PossibleXLHSInSecond = 11740 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 11741 llvm::FoldingSetNodeID X1Id, X2Id; 11742 PossibleXRHSInFirst->Profile(X1Id, Context, 11743 /*Canonical=*/true); 11744 PossibleXLHSInSecond->Profile(X2Id, Context, 11745 /*Canonical=*/true); 11746 IsUpdateExprFound = X1Id == X2Id; 11747 if (IsUpdateExprFound) { 11748 V = FirstBinOp->getLHS(); 11749 X = SecondBinOp->getLHS(); 11750 E = SecondBinOp->getRHS(); 11751 UE = nullptr; 11752 IsXLHSInRHSPart = false; 11753 IsPostfixUpdate = true; 11754 } else { 11755 ErrorFound = NotASpecificExpression; 11756 ErrorLoc = FirstBinOp->getExprLoc(); 11757 ErrorRange = FirstBinOp->getSourceRange(); 11758 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 11759 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 11760 } 11761 } 11762 } 11763 } 11764 } 11765 } else { 11766 NoteLoc = ErrorLoc = Body->getBeginLoc(); 11767 NoteRange = ErrorRange = 11768 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 11769 ErrorFound = NotTwoSubstatements; 11770 } 11771 } else { 11772 NoteLoc = ErrorLoc = Body->getBeginLoc(); 11773 NoteRange = ErrorRange = 11774 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 11775 ErrorFound = NotACompoundStatement; 11776 } 11777 } 11778 if (ErrorFound != NoError) { 11779 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 11780 << ErrorRange; 11781 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 11782 return StmtError(); 11783 } 11784 if (CurContext->isDependentContext()) 11785 UE = V = E = X = nullptr; 11786 } else if (AtomicKind == OMPC_compare) { 11787 if (IsCompareCapture) { 11788 // TODO: We don't set X, D, E, etc. here because in code gen we will emit 11789 // error directly. 11790 } else { 11791 OpenMPAtomicCompareChecker::ErrorInfoTy ErrorInfo; 11792 OpenMPAtomicCompareChecker Checker(*this); 11793 if (!Checker.checkStmt(Body, ErrorInfo)) { 11794 Diag(ErrorInfo.ErrorLoc, diag::err_omp_atomic_compare) 11795 << ErrorInfo.ErrorRange; 11796 Diag(ErrorInfo.NoteLoc, diag::note_omp_atomic_compare) 11797 << ErrorInfo.Error << ErrorInfo.NoteRange; 11798 return StmtError(); 11799 } 11800 // TODO: We don't set X, D, E, etc. here because in code gen we will emit 11801 // error directly. 11802 } 11803 } 11804 11805 setFunctionHasBranchProtectedScope(); 11806 11807 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 11808 X, V, E, UE, IsXLHSInRHSPart, 11809 IsPostfixUpdate); 11810 } 11811 11812 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 11813 Stmt *AStmt, 11814 SourceLocation StartLoc, 11815 SourceLocation EndLoc) { 11816 if (!AStmt) 11817 return StmtError(); 11818 11819 auto *CS = cast<CapturedStmt>(AStmt); 11820 // 1.2.2 OpenMP Language Terminology 11821 // Structured block - An executable statement with a single entry at the 11822 // top and a single exit at the bottom. 11823 // The point of exit cannot be a branch out of the structured block. 11824 // longjmp() and throw() must not violate the entry/exit criteria. 11825 CS->getCapturedDecl()->setNothrow(); 11826 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target); 11827 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11828 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11829 // 1.2.2 OpenMP Language Terminology 11830 // Structured block - An executable statement with a single entry at the 11831 // top and a single exit at the bottom. 11832 // The point of exit cannot be a branch out of the structured block. 11833 // longjmp() and throw() must not violate the entry/exit criteria. 11834 CS->getCapturedDecl()->setNothrow(); 11835 } 11836 11837 // OpenMP [2.16, Nesting of Regions] 11838 // If specified, a teams construct must be contained within a target 11839 // construct. That target construct must contain no statements or directives 11840 // outside of the teams construct. 11841 if (DSAStack->hasInnerTeamsRegion()) { 11842 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true); 11843 bool OMPTeamsFound = true; 11844 if (const auto *CS = dyn_cast<CompoundStmt>(S)) { 11845 auto I = CS->body_begin(); 11846 while (I != CS->body_end()) { 11847 const auto *OED = dyn_cast<OMPExecutableDirective>(*I); 11848 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) || 11849 OMPTeamsFound) { 11850 11851 OMPTeamsFound = false; 11852 break; 11853 } 11854 ++I; 11855 } 11856 assert(I != CS->body_end() && "Not found statement"); 11857 S = *I; 11858 } else { 11859 const auto *OED = dyn_cast<OMPExecutableDirective>(S); 11860 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 11861 } 11862 if (!OMPTeamsFound) { 11863 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 11864 Diag(DSAStack->getInnerTeamsRegionLoc(), 11865 diag::note_omp_nested_teams_construct_here); 11866 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here) 11867 << isa<OMPExecutableDirective>(S); 11868 return StmtError(); 11869 } 11870 } 11871 11872 setFunctionHasBranchProtectedScope(); 11873 11874 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 11875 } 11876 11877 StmtResult 11878 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 11879 Stmt *AStmt, SourceLocation StartLoc, 11880 SourceLocation EndLoc) { 11881 if (!AStmt) 11882 return StmtError(); 11883 11884 auto *CS = cast<CapturedStmt>(AStmt); 11885 // 1.2.2 OpenMP Language Terminology 11886 // Structured block - An executable statement with a single entry at the 11887 // top and a single exit at the bottom. 11888 // The point of exit cannot be a branch out of the structured block. 11889 // longjmp() and throw() must not violate the entry/exit criteria. 11890 CS->getCapturedDecl()->setNothrow(); 11891 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel); 11892 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11893 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11894 // 1.2.2 OpenMP Language Terminology 11895 // Structured block - An executable statement with a single entry at the 11896 // top and a single exit at the bottom. 11897 // The point of exit cannot be a branch out of the structured block. 11898 // longjmp() and throw() must not violate the entry/exit criteria. 11899 CS->getCapturedDecl()->setNothrow(); 11900 } 11901 11902 setFunctionHasBranchProtectedScope(); 11903 11904 return OMPTargetParallelDirective::Create( 11905 Context, StartLoc, EndLoc, Clauses, AStmt, 11906 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 11907 } 11908 11909 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 11910 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11911 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11912 if (!AStmt) 11913 return StmtError(); 11914 11915 auto *CS = cast<CapturedStmt>(AStmt); 11916 // 1.2.2 OpenMP Language Terminology 11917 // Structured block - An executable statement with a single entry at the 11918 // top and a single exit at the bottom. 11919 // The point of exit cannot be a branch out of the structured block. 11920 // longjmp() and throw() must not violate the entry/exit criteria. 11921 CS->getCapturedDecl()->setNothrow(); 11922 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 11923 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11924 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11925 // 1.2.2 OpenMP Language Terminology 11926 // Structured block - An executable statement with a single entry at the 11927 // top and a single exit at the bottom. 11928 // The point of exit cannot be a branch out of the structured block. 11929 // longjmp() and throw() must not violate the entry/exit criteria. 11930 CS->getCapturedDecl()->setNothrow(); 11931 } 11932 11933 OMPLoopBasedDirective::HelperExprs B; 11934 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11935 // define the nested loops number. 11936 unsigned NestedLoopCount = 11937 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 11938 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 11939 VarsWithImplicitDSA, B); 11940 if (NestedLoopCount == 0) 11941 return StmtError(); 11942 11943 assert((CurContext->isDependentContext() || B.builtAll()) && 11944 "omp target parallel for loop exprs were not built"); 11945 11946 if (!CurContext->isDependentContext()) { 11947 // Finalize the clauses that need pre-built expressions for CodeGen. 11948 for (OMPClause *C : Clauses) { 11949 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11950 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11951 B.NumIterations, *this, CurScope, 11952 DSAStack)) 11953 return StmtError(); 11954 } 11955 } 11956 11957 setFunctionHasBranchProtectedScope(); 11958 return OMPTargetParallelForDirective::Create( 11959 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 11960 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 11961 } 11962 11963 /// Check for existence of a map clause in the list of clauses. 11964 static bool hasClauses(ArrayRef<OMPClause *> Clauses, 11965 const OpenMPClauseKind K) { 11966 return llvm::any_of( 11967 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); 11968 } 11969 11970 template <typename... Params> 11971 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, 11972 const Params... ClauseTypes) { 11973 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); 11974 } 11975 11976 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 11977 Stmt *AStmt, 11978 SourceLocation StartLoc, 11979 SourceLocation EndLoc) { 11980 if (!AStmt) 11981 return StmtError(); 11982 11983 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11984 11985 // OpenMP [2.12.2, target data Construct, Restrictions] 11986 // At least one map, use_device_addr or use_device_ptr clause must appear on 11987 // the directive. 11988 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) && 11989 (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) { 11990 StringRef Expected; 11991 if (LangOpts.OpenMP < 50) 11992 Expected = "'map' or 'use_device_ptr'"; 11993 else 11994 Expected = "'map', 'use_device_ptr', or 'use_device_addr'"; 11995 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 11996 << Expected << getOpenMPDirectiveName(OMPD_target_data); 11997 return StmtError(); 11998 } 11999 12000 setFunctionHasBranchProtectedScope(); 12001 12002 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 12003 AStmt); 12004 } 12005 12006 StmtResult 12007 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 12008 SourceLocation StartLoc, 12009 SourceLocation EndLoc, Stmt *AStmt) { 12010 if (!AStmt) 12011 return StmtError(); 12012 12013 auto *CS = cast<CapturedStmt>(AStmt); 12014 // 1.2.2 OpenMP Language Terminology 12015 // Structured block - An executable statement with a single entry at the 12016 // top and a single exit at the bottom. 12017 // The point of exit cannot be a branch out of the structured block. 12018 // longjmp() and throw() must not violate the entry/exit criteria. 12019 CS->getCapturedDecl()->setNothrow(); 12020 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data); 12021 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12022 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12023 // 1.2.2 OpenMP Language Terminology 12024 // Structured block - An executable statement with a single entry at the 12025 // top and a single exit at the bottom. 12026 // The point of exit cannot be a branch out of the structured block. 12027 // longjmp() and throw() must not violate the entry/exit criteria. 12028 CS->getCapturedDecl()->setNothrow(); 12029 } 12030 12031 // OpenMP [2.10.2, Restrictions, p. 99] 12032 // At least one map clause must appear on the directive. 12033 if (!hasClauses(Clauses, OMPC_map)) { 12034 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 12035 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); 12036 return StmtError(); 12037 } 12038 12039 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 12040 AStmt); 12041 } 12042 12043 StmtResult 12044 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 12045 SourceLocation StartLoc, 12046 SourceLocation EndLoc, Stmt *AStmt) { 12047 if (!AStmt) 12048 return StmtError(); 12049 12050 auto *CS = cast<CapturedStmt>(AStmt); 12051 // 1.2.2 OpenMP Language Terminology 12052 // Structured block - An executable statement with a single entry at the 12053 // top and a single exit at the bottom. 12054 // The point of exit cannot be a branch out of the structured block. 12055 // longjmp() and throw() must not violate the entry/exit criteria. 12056 CS->getCapturedDecl()->setNothrow(); 12057 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data); 12058 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12059 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12060 // 1.2.2 OpenMP Language Terminology 12061 // Structured block - An executable statement with a single entry at the 12062 // top and a single exit at the bottom. 12063 // The point of exit cannot be a branch out of the structured block. 12064 // longjmp() and throw() must not violate the entry/exit criteria. 12065 CS->getCapturedDecl()->setNothrow(); 12066 } 12067 12068 // OpenMP [2.10.3, Restrictions, p. 102] 12069 // At least one map clause must appear on the directive. 12070 if (!hasClauses(Clauses, OMPC_map)) { 12071 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 12072 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data); 12073 return StmtError(); 12074 } 12075 12076 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 12077 AStmt); 12078 } 12079 12080 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 12081 SourceLocation StartLoc, 12082 SourceLocation EndLoc, 12083 Stmt *AStmt) { 12084 if (!AStmt) 12085 return StmtError(); 12086 12087 auto *CS = cast<CapturedStmt>(AStmt); 12088 // 1.2.2 OpenMP Language Terminology 12089 // Structured block - An executable statement with a single entry at the 12090 // top and a single exit at the bottom. 12091 // The point of exit cannot be a branch out of the structured block. 12092 // longjmp() and throw() must not violate the entry/exit criteria. 12093 CS->getCapturedDecl()->setNothrow(); 12094 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update); 12095 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12096 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12097 // 1.2.2 OpenMP Language Terminology 12098 // Structured block - An executable statement with a single entry at the 12099 // top and a single exit at the bottom. 12100 // The point of exit cannot be a branch out of the structured block. 12101 // longjmp() and throw() must not violate the entry/exit criteria. 12102 CS->getCapturedDecl()->setNothrow(); 12103 } 12104 12105 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { 12106 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 12107 return StmtError(); 12108 } 12109 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses, 12110 AStmt); 12111 } 12112 12113 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 12114 Stmt *AStmt, SourceLocation StartLoc, 12115 SourceLocation EndLoc) { 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 12127 setFunctionHasBranchProtectedScope(); 12128 12129 DSAStack->setParentTeamsRegionLoc(StartLoc); 12130 12131 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 12132 } 12133 12134 StmtResult 12135 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 12136 SourceLocation EndLoc, 12137 OpenMPDirectiveKind CancelRegion) { 12138 if (DSAStack->isParentNowaitRegion()) { 12139 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 12140 return StmtError(); 12141 } 12142 if (DSAStack->isParentOrderedRegion()) { 12143 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 12144 return StmtError(); 12145 } 12146 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 12147 CancelRegion); 12148 } 12149 12150 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 12151 SourceLocation StartLoc, 12152 SourceLocation EndLoc, 12153 OpenMPDirectiveKind CancelRegion) { 12154 if (DSAStack->isParentNowaitRegion()) { 12155 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 12156 return StmtError(); 12157 } 12158 if (DSAStack->isParentOrderedRegion()) { 12159 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 12160 return StmtError(); 12161 } 12162 DSAStack->setParentCancelRegion(/*Cancel=*/true); 12163 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 12164 CancelRegion); 12165 } 12166 12167 static bool checkReductionClauseWithNogroup(Sema &S, 12168 ArrayRef<OMPClause *> Clauses) { 12169 const OMPClause *ReductionClause = nullptr; 12170 const OMPClause *NogroupClause = nullptr; 12171 for (const OMPClause *C : Clauses) { 12172 if (C->getClauseKind() == OMPC_reduction) { 12173 ReductionClause = C; 12174 if (NogroupClause) 12175 break; 12176 continue; 12177 } 12178 if (C->getClauseKind() == OMPC_nogroup) { 12179 NogroupClause = C; 12180 if (ReductionClause) 12181 break; 12182 continue; 12183 } 12184 } 12185 if (ReductionClause && NogroupClause) { 12186 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup) 12187 << SourceRange(NogroupClause->getBeginLoc(), 12188 NogroupClause->getEndLoc()); 12189 return true; 12190 } 12191 return false; 12192 } 12193 12194 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 12195 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12196 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12197 if (!AStmt) 12198 return StmtError(); 12199 12200 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 12201 OMPLoopBasedDirective::HelperExprs B; 12202 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 12203 // define the nested loops number. 12204 unsigned NestedLoopCount = 12205 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 12206 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 12207 VarsWithImplicitDSA, B); 12208 if (NestedLoopCount == 0) 12209 return StmtError(); 12210 12211 assert((CurContext->isDependentContext() || B.builtAll()) && 12212 "omp for loop exprs were not built"); 12213 12214 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12215 // The grainsize clause and num_tasks clause are mutually exclusive and may 12216 // not appear on the same taskloop directive. 12217 if (checkMutuallyExclusiveClauses(*this, Clauses, 12218 {OMPC_grainsize, OMPC_num_tasks})) 12219 return StmtError(); 12220 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12221 // If a reduction clause is present on the taskloop directive, the nogroup 12222 // clause must not be specified. 12223 if (checkReductionClauseWithNogroup(*this, Clauses)) 12224 return StmtError(); 12225 12226 setFunctionHasBranchProtectedScope(); 12227 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 12228 NestedLoopCount, Clauses, AStmt, B, 12229 DSAStack->isCancelRegion()); 12230 } 12231 12232 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 12233 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12234 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12235 if (!AStmt) 12236 return StmtError(); 12237 12238 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 12239 OMPLoopBasedDirective::HelperExprs B; 12240 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 12241 // define the nested loops number. 12242 unsigned NestedLoopCount = 12243 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 12244 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 12245 VarsWithImplicitDSA, B); 12246 if (NestedLoopCount == 0) 12247 return StmtError(); 12248 12249 assert((CurContext->isDependentContext() || B.builtAll()) && 12250 "omp for loop exprs were not built"); 12251 12252 if (!CurContext->isDependentContext()) { 12253 // Finalize the clauses that need pre-built expressions for CodeGen. 12254 for (OMPClause *C : Clauses) { 12255 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12256 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12257 B.NumIterations, *this, CurScope, 12258 DSAStack)) 12259 return StmtError(); 12260 } 12261 } 12262 12263 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12264 // The grainsize clause and num_tasks clause are mutually exclusive and may 12265 // not appear on the same taskloop directive. 12266 if (checkMutuallyExclusiveClauses(*this, Clauses, 12267 {OMPC_grainsize, OMPC_num_tasks})) 12268 return StmtError(); 12269 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12270 // If a reduction clause is present on the taskloop directive, the nogroup 12271 // clause must not be specified. 12272 if (checkReductionClauseWithNogroup(*this, Clauses)) 12273 return StmtError(); 12274 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12275 return StmtError(); 12276 12277 setFunctionHasBranchProtectedScope(); 12278 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 12279 NestedLoopCount, Clauses, AStmt, B); 12280 } 12281 12282 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective( 12283 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12284 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12285 if (!AStmt) 12286 return StmtError(); 12287 12288 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 12289 OMPLoopBasedDirective::HelperExprs B; 12290 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 12291 // define the nested loops number. 12292 unsigned NestedLoopCount = 12293 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses), 12294 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 12295 VarsWithImplicitDSA, B); 12296 if (NestedLoopCount == 0) 12297 return StmtError(); 12298 12299 assert((CurContext->isDependentContext() || B.builtAll()) && 12300 "omp for loop exprs were not built"); 12301 12302 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12303 // The grainsize clause and num_tasks clause are mutually exclusive and may 12304 // not appear on the same taskloop directive. 12305 if (checkMutuallyExclusiveClauses(*this, Clauses, 12306 {OMPC_grainsize, OMPC_num_tasks})) 12307 return StmtError(); 12308 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12309 // If a reduction clause is present on the taskloop directive, the nogroup 12310 // clause must not be specified. 12311 if (checkReductionClauseWithNogroup(*this, Clauses)) 12312 return StmtError(); 12313 12314 setFunctionHasBranchProtectedScope(); 12315 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc, 12316 NestedLoopCount, Clauses, AStmt, B, 12317 DSAStack->isCancelRegion()); 12318 } 12319 12320 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective( 12321 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12322 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12323 if (!AStmt) 12324 return StmtError(); 12325 12326 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 12327 OMPLoopBasedDirective::HelperExprs B; 12328 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 12329 // define the nested loops number. 12330 unsigned NestedLoopCount = 12331 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses), 12332 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 12333 VarsWithImplicitDSA, B); 12334 if (NestedLoopCount == 0) 12335 return StmtError(); 12336 12337 assert((CurContext->isDependentContext() || B.builtAll()) && 12338 "omp for loop exprs were not built"); 12339 12340 if (!CurContext->isDependentContext()) { 12341 // Finalize the clauses that need pre-built expressions for CodeGen. 12342 for (OMPClause *C : Clauses) { 12343 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12344 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12345 B.NumIterations, *this, CurScope, 12346 DSAStack)) 12347 return StmtError(); 12348 } 12349 } 12350 12351 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12352 // The grainsize clause and num_tasks clause are mutually exclusive and may 12353 // not appear on the same taskloop directive. 12354 if (checkMutuallyExclusiveClauses(*this, Clauses, 12355 {OMPC_grainsize, OMPC_num_tasks})) 12356 return StmtError(); 12357 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12358 // If a reduction clause is present on the taskloop directive, the nogroup 12359 // clause must not be specified. 12360 if (checkReductionClauseWithNogroup(*this, Clauses)) 12361 return StmtError(); 12362 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12363 return StmtError(); 12364 12365 setFunctionHasBranchProtectedScope(); 12366 return OMPMasterTaskLoopSimdDirective::Create( 12367 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12368 } 12369 12370 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective( 12371 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12372 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12373 if (!AStmt) 12374 return StmtError(); 12375 12376 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 12377 auto *CS = cast<CapturedStmt>(AStmt); 12378 // 1.2.2 OpenMP Language Terminology 12379 // Structured block - An executable statement with a single entry at the 12380 // top and a single exit at the bottom. 12381 // The point of exit cannot be a branch out of the structured block. 12382 // longjmp() and throw() must not violate the entry/exit criteria. 12383 CS->getCapturedDecl()->setNothrow(); 12384 for (int ThisCaptureLevel = 12385 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop); 12386 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12387 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 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 } 12395 12396 OMPLoopBasedDirective::HelperExprs B; 12397 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 12398 // define the nested loops number. 12399 unsigned NestedLoopCount = checkOpenMPLoop( 12400 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses), 12401 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 12402 VarsWithImplicitDSA, B); 12403 if (NestedLoopCount == 0) 12404 return StmtError(); 12405 12406 assert((CurContext->isDependentContext() || B.builtAll()) && 12407 "omp for loop exprs were not built"); 12408 12409 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12410 // The grainsize clause and num_tasks clause are mutually exclusive and may 12411 // not appear on the same taskloop directive. 12412 if (checkMutuallyExclusiveClauses(*this, Clauses, 12413 {OMPC_grainsize, OMPC_num_tasks})) 12414 return StmtError(); 12415 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12416 // If a reduction clause is present on the taskloop directive, the nogroup 12417 // clause must not be specified. 12418 if (checkReductionClauseWithNogroup(*this, Clauses)) 12419 return StmtError(); 12420 12421 setFunctionHasBranchProtectedScope(); 12422 return OMPParallelMasterTaskLoopDirective::Create( 12423 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 12424 DSAStack->isCancelRegion()); 12425 } 12426 12427 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective( 12428 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12429 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12430 if (!AStmt) 12431 return StmtError(); 12432 12433 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 12434 auto *CS = cast<CapturedStmt>(AStmt); 12435 // 1.2.2 OpenMP Language Terminology 12436 // Structured block - An executable statement with a single entry at the 12437 // top and a single exit at the bottom. 12438 // The point of exit cannot be a branch out of the structured block. 12439 // longjmp() and throw() must not violate the entry/exit criteria. 12440 CS->getCapturedDecl()->setNothrow(); 12441 for (int ThisCaptureLevel = 12442 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd); 12443 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12444 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12445 // 1.2.2 OpenMP Language Terminology 12446 // Structured block - An executable statement with a single entry at the 12447 // top and a single exit at the bottom. 12448 // The point of exit cannot be a branch out of the structured block. 12449 // longjmp() and throw() must not violate the entry/exit criteria. 12450 CS->getCapturedDecl()->setNothrow(); 12451 } 12452 12453 OMPLoopBasedDirective::HelperExprs B; 12454 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 12455 // define the nested loops number. 12456 unsigned NestedLoopCount = checkOpenMPLoop( 12457 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses), 12458 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 12459 VarsWithImplicitDSA, B); 12460 if (NestedLoopCount == 0) 12461 return StmtError(); 12462 12463 assert((CurContext->isDependentContext() || B.builtAll()) && 12464 "omp for loop exprs were not built"); 12465 12466 if (!CurContext->isDependentContext()) { 12467 // Finalize the clauses that need pre-built expressions for CodeGen. 12468 for (OMPClause *C : Clauses) { 12469 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12470 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12471 B.NumIterations, *this, CurScope, 12472 DSAStack)) 12473 return StmtError(); 12474 } 12475 } 12476 12477 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12478 // The grainsize clause and num_tasks clause are mutually exclusive and may 12479 // not appear on the same taskloop directive. 12480 if (checkMutuallyExclusiveClauses(*this, Clauses, 12481 {OMPC_grainsize, OMPC_num_tasks})) 12482 return StmtError(); 12483 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12484 // If a reduction clause is present on the taskloop directive, the nogroup 12485 // clause must not be specified. 12486 if (checkReductionClauseWithNogroup(*this, Clauses)) 12487 return StmtError(); 12488 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12489 return StmtError(); 12490 12491 setFunctionHasBranchProtectedScope(); 12492 return OMPParallelMasterTaskLoopSimdDirective::Create( 12493 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12494 } 12495 12496 StmtResult Sema::ActOnOpenMPDistributeDirective( 12497 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12498 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12499 if (!AStmt) 12500 return StmtError(); 12501 12502 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 12503 OMPLoopBasedDirective::HelperExprs B; 12504 // In presence of clause 'collapse' with number of loops, it will 12505 // define the nested loops number. 12506 unsigned NestedLoopCount = 12507 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 12508 nullptr /*ordered not a clause on distribute*/, AStmt, 12509 *this, *DSAStack, VarsWithImplicitDSA, B); 12510 if (NestedLoopCount == 0) 12511 return StmtError(); 12512 12513 assert((CurContext->isDependentContext() || B.builtAll()) && 12514 "omp for loop exprs were not built"); 12515 12516 setFunctionHasBranchProtectedScope(); 12517 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 12518 NestedLoopCount, Clauses, AStmt, B); 12519 } 12520 12521 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 12522 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12523 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12524 if (!AStmt) 12525 return StmtError(); 12526 12527 auto *CS = cast<CapturedStmt>(AStmt); 12528 // 1.2.2 OpenMP Language Terminology 12529 // Structured block - An executable statement with a single entry at the 12530 // top and a single exit at the bottom. 12531 // The point of exit cannot be a branch out of the structured block. 12532 // longjmp() and throw() must not violate the entry/exit criteria. 12533 CS->getCapturedDecl()->setNothrow(); 12534 for (int ThisCaptureLevel = 12535 getOpenMPCaptureLevels(OMPD_distribute_parallel_for); 12536 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12537 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12538 // 1.2.2 OpenMP Language Terminology 12539 // Structured block - An executable statement with a single entry at the 12540 // top and a single exit at the bottom. 12541 // The point of exit cannot be a branch out of the structured block. 12542 // longjmp() and throw() must not violate the entry/exit criteria. 12543 CS->getCapturedDecl()->setNothrow(); 12544 } 12545 12546 OMPLoopBasedDirective::HelperExprs B; 12547 // In presence of clause 'collapse' with number of loops, it will 12548 // define the nested loops number. 12549 unsigned NestedLoopCount = checkOpenMPLoop( 12550 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 12551 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12552 VarsWithImplicitDSA, B); 12553 if (NestedLoopCount == 0) 12554 return StmtError(); 12555 12556 assert((CurContext->isDependentContext() || B.builtAll()) && 12557 "omp for loop exprs were not built"); 12558 12559 setFunctionHasBranchProtectedScope(); 12560 return OMPDistributeParallelForDirective::Create( 12561 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 12562 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 12563 } 12564 12565 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 12566 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12567 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12568 if (!AStmt) 12569 return StmtError(); 12570 12571 auto *CS = cast<CapturedStmt>(AStmt); 12572 // 1.2.2 OpenMP Language Terminology 12573 // Structured block - An executable statement with a single entry at the 12574 // top and a single exit at the bottom. 12575 // The point of exit cannot be a branch out of the structured block. 12576 // longjmp() and throw() must not violate the entry/exit criteria. 12577 CS->getCapturedDecl()->setNothrow(); 12578 for (int ThisCaptureLevel = 12579 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd); 12580 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12581 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12582 // 1.2.2 OpenMP Language Terminology 12583 // Structured block - An executable statement with a single entry at the 12584 // top and a single exit at the bottom. 12585 // The point of exit cannot be a branch out of the structured block. 12586 // longjmp() and throw() must not violate the entry/exit criteria. 12587 CS->getCapturedDecl()->setNothrow(); 12588 } 12589 12590 OMPLoopBasedDirective::HelperExprs B; 12591 // In presence of clause 'collapse' with number of loops, it will 12592 // define the nested loops number. 12593 unsigned NestedLoopCount = checkOpenMPLoop( 12594 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 12595 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12596 VarsWithImplicitDSA, B); 12597 if (NestedLoopCount == 0) 12598 return StmtError(); 12599 12600 assert((CurContext->isDependentContext() || B.builtAll()) && 12601 "omp for loop exprs were not built"); 12602 12603 if (!CurContext->isDependentContext()) { 12604 // Finalize the clauses that need pre-built expressions for CodeGen. 12605 for (OMPClause *C : Clauses) { 12606 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12607 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12608 B.NumIterations, *this, CurScope, 12609 DSAStack)) 12610 return StmtError(); 12611 } 12612 } 12613 12614 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12615 return StmtError(); 12616 12617 setFunctionHasBranchProtectedScope(); 12618 return OMPDistributeParallelForSimdDirective::Create( 12619 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12620 } 12621 12622 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 12623 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12624 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12625 if (!AStmt) 12626 return StmtError(); 12627 12628 auto *CS = cast<CapturedStmt>(AStmt); 12629 // 1.2.2 OpenMP Language Terminology 12630 // Structured block - An executable statement with a single entry at the 12631 // top and a single exit at the bottom. 12632 // The point of exit cannot be a branch out of the structured block. 12633 // longjmp() and throw() must not violate the entry/exit criteria. 12634 CS->getCapturedDecl()->setNothrow(); 12635 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd); 12636 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12637 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12638 // 1.2.2 OpenMP Language Terminology 12639 // Structured block - An executable statement with a single entry at the 12640 // top and a single exit at the bottom. 12641 // The point of exit cannot be a branch out of the structured block. 12642 // longjmp() and throw() must not violate the entry/exit criteria. 12643 CS->getCapturedDecl()->setNothrow(); 12644 } 12645 12646 OMPLoopBasedDirective::HelperExprs B; 12647 // In presence of clause 'collapse' with number of loops, it will 12648 // define the nested loops number. 12649 unsigned NestedLoopCount = 12650 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 12651 nullptr /*ordered not a clause on distribute*/, CS, *this, 12652 *DSAStack, VarsWithImplicitDSA, B); 12653 if (NestedLoopCount == 0) 12654 return StmtError(); 12655 12656 assert((CurContext->isDependentContext() || B.builtAll()) && 12657 "omp for loop exprs were not built"); 12658 12659 if (!CurContext->isDependentContext()) { 12660 // Finalize the clauses that need pre-built expressions for CodeGen. 12661 for (OMPClause *C : Clauses) { 12662 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12663 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12664 B.NumIterations, *this, CurScope, 12665 DSAStack)) 12666 return StmtError(); 12667 } 12668 } 12669 12670 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12671 return StmtError(); 12672 12673 setFunctionHasBranchProtectedScope(); 12674 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 12675 NestedLoopCount, Clauses, AStmt, B); 12676 } 12677 12678 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 12679 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12680 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12681 if (!AStmt) 12682 return StmtError(); 12683 12684 auto *CS = cast<CapturedStmt>(AStmt); 12685 // 1.2.2 OpenMP Language Terminology 12686 // Structured block - An executable statement with a single entry at the 12687 // top and a single exit at the bottom. 12688 // The point of exit cannot be a branch out of the structured block. 12689 // longjmp() and throw() must not violate the entry/exit criteria. 12690 CS->getCapturedDecl()->setNothrow(); 12691 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 12692 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12693 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12694 // 1.2.2 OpenMP Language Terminology 12695 // Structured block - An executable statement with a single entry at the 12696 // top and a single exit at the bottom. 12697 // The point of exit cannot be a branch out of the structured block. 12698 // longjmp() and throw() must not violate the entry/exit criteria. 12699 CS->getCapturedDecl()->setNothrow(); 12700 } 12701 12702 OMPLoopBasedDirective::HelperExprs B; 12703 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 12704 // define the nested loops number. 12705 unsigned NestedLoopCount = checkOpenMPLoop( 12706 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 12707 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, VarsWithImplicitDSA, 12708 B); 12709 if (NestedLoopCount == 0) 12710 return StmtError(); 12711 12712 assert((CurContext->isDependentContext() || B.builtAll()) && 12713 "omp target parallel for simd loop exprs were not built"); 12714 12715 if (!CurContext->isDependentContext()) { 12716 // Finalize the clauses that need pre-built expressions for CodeGen. 12717 for (OMPClause *C : Clauses) { 12718 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12719 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12720 B.NumIterations, *this, CurScope, 12721 DSAStack)) 12722 return StmtError(); 12723 } 12724 } 12725 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12726 return StmtError(); 12727 12728 setFunctionHasBranchProtectedScope(); 12729 return OMPTargetParallelForSimdDirective::Create( 12730 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12731 } 12732 12733 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 12734 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12735 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12736 if (!AStmt) 12737 return StmtError(); 12738 12739 auto *CS = cast<CapturedStmt>(AStmt); 12740 // 1.2.2 OpenMP Language Terminology 12741 // Structured block - An executable statement with a single entry at the 12742 // top and a single exit at the bottom. 12743 // The point of exit cannot be a branch out of the structured block. 12744 // longjmp() and throw() must not violate the entry/exit criteria. 12745 CS->getCapturedDecl()->setNothrow(); 12746 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd); 12747 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12748 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12749 // 1.2.2 OpenMP Language Terminology 12750 // Structured block - An executable statement with a single entry at the 12751 // top and a single exit at the bottom. 12752 // The point of exit cannot be a branch out of the structured block. 12753 // longjmp() and throw() must not violate the entry/exit criteria. 12754 CS->getCapturedDecl()->setNothrow(); 12755 } 12756 12757 OMPLoopBasedDirective::HelperExprs B; 12758 // In presence of clause 'collapse' with number of loops, it will define the 12759 // nested loops number. 12760 unsigned NestedLoopCount = 12761 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 12762 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 12763 VarsWithImplicitDSA, B); 12764 if (NestedLoopCount == 0) 12765 return StmtError(); 12766 12767 assert((CurContext->isDependentContext() || B.builtAll()) && 12768 "omp target simd loop exprs were not built"); 12769 12770 if (!CurContext->isDependentContext()) { 12771 // Finalize the clauses that need pre-built expressions for CodeGen. 12772 for (OMPClause *C : Clauses) { 12773 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12774 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12775 B.NumIterations, *this, CurScope, 12776 DSAStack)) 12777 return StmtError(); 12778 } 12779 } 12780 12781 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12782 return StmtError(); 12783 12784 setFunctionHasBranchProtectedScope(); 12785 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 12786 NestedLoopCount, Clauses, AStmt, B); 12787 } 12788 12789 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 12790 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12791 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12792 if (!AStmt) 12793 return StmtError(); 12794 12795 auto *CS = cast<CapturedStmt>(AStmt); 12796 // 1.2.2 OpenMP Language Terminology 12797 // Structured block - An executable statement with a single entry at the 12798 // top and a single exit at the bottom. 12799 // The point of exit cannot be a branch out of the structured block. 12800 // longjmp() and throw() must not violate the entry/exit criteria. 12801 CS->getCapturedDecl()->setNothrow(); 12802 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute); 12803 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12804 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12805 // 1.2.2 OpenMP Language Terminology 12806 // Structured block - An executable statement with a single entry at the 12807 // top and a single exit at the bottom. 12808 // The point of exit cannot be a branch out of the structured block. 12809 // longjmp() and throw() must not violate the entry/exit criteria. 12810 CS->getCapturedDecl()->setNothrow(); 12811 } 12812 12813 OMPLoopBasedDirective::HelperExprs B; 12814 // In presence of clause 'collapse' with number of loops, it will 12815 // define the nested loops number. 12816 unsigned NestedLoopCount = 12817 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 12818 nullptr /*ordered not a clause on distribute*/, CS, *this, 12819 *DSAStack, VarsWithImplicitDSA, B); 12820 if (NestedLoopCount == 0) 12821 return StmtError(); 12822 12823 assert((CurContext->isDependentContext() || B.builtAll()) && 12824 "omp teams distribute loop exprs were not built"); 12825 12826 setFunctionHasBranchProtectedScope(); 12827 12828 DSAStack->setParentTeamsRegionLoc(StartLoc); 12829 12830 return OMPTeamsDistributeDirective::Create( 12831 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12832 } 12833 12834 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 12835 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12836 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12837 if (!AStmt) 12838 return StmtError(); 12839 12840 auto *CS = cast<CapturedStmt>(AStmt); 12841 // 1.2.2 OpenMP Language Terminology 12842 // Structured block - An executable statement with a single entry at the 12843 // top and a single exit at the bottom. 12844 // The point of exit cannot be a branch out of the structured block. 12845 // longjmp() and throw() must not violate the entry/exit criteria. 12846 CS->getCapturedDecl()->setNothrow(); 12847 for (int ThisCaptureLevel = 12848 getOpenMPCaptureLevels(OMPD_teams_distribute_simd); 12849 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12850 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12851 // 1.2.2 OpenMP Language Terminology 12852 // Structured block - An executable statement with a single entry at the 12853 // top and a single exit at the bottom. 12854 // The point of exit cannot be a branch out of the structured block. 12855 // longjmp() and throw() must not violate the entry/exit criteria. 12856 CS->getCapturedDecl()->setNothrow(); 12857 } 12858 12859 OMPLoopBasedDirective::HelperExprs B; 12860 // In presence of clause 'collapse' with number of loops, it will 12861 // define the nested loops number. 12862 unsigned NestedLoopCount = checkOpenMPLoop( 12863 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 12864 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12865 VarsWithImplicitDSA, B); 12866 12867 if (NestedLoopCount == 0) 12868 return StmtError(); 12869 12870 assert((CurContext->isDependentContext() || B.builtAll()) && 12871 "omp teams distribute simd loop exprs were not built"); 12872 12873 if (!CurContext->isDependentContext()) { 12874 // Finalize the clauses that need pre-built expressions for CodeGen. 12875 for (OMPClause *C : Clauses) { 12876 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12877 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12878 B.NumIterations, *this, CurScope, 12879 DSAStack)) 12880 return StmtError(); 12881 } 12882 } 12883 12884 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12885 return StmtError(); 12886 12887 setFunctionHasBranchProtectedScope(); 12888 12889 DSAStack->setParentTeamsRegionLoc(StartLoc); 12890 12891 return OMPTeamsDistributeSimdDirective::Create( 12892 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12893 } 12894 12895 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 12896 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12897 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12898 if (!AStmt) 12899 return StmtError(); 12900 12901 auto *CS = cast<CapturedStmt>(AStmt); 12902 // 1.2.2 OpenMP Language Terminology 12903 // Structured block - An executable statement with a single entry at the 12904 // top and a single exit at the bottom. 12905 // The point of exit cannot be a branch out of the structured block. 12906 // longjmp() and throw() must not violate the entry/exit criteria. 12907 CS->getCapturedDecl()->setNothrow(); 12908 12909 for (int ThisCaptureLevel = 12910 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd); 12911 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12912 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12913 // 1.2.2 OpenMP Language Terminology 12914 // Structured block - An executable statement with a single entry at the 12915 // top and a single exit at the bottom. 12916 // The point of exit cannot be a branch out of the structured block. 12917 // longjmp() and throw() must not violate the entry/exit criteria. 12918 CS->getCapturedDecl()->setNothrow(); 12919 } 12920 12921 OMPLoopBasedDirective::HelperExprs B; 12922 // In presence of clause 'collapse' with number of loops, it will 12923 // define the nested loops number. 12924 unsigned NestedLoopCount = checkOpenMPLoop( 12925 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 12926 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12927 VarsWithImplicitDSA, B); 12928 12929 if (NestedLoopCount == 0) 12930 return StmtError(); 12931 12932 assert((CurContext->isDependentContext() || B.builtAll()) && 12933 "omp for loop exprs were not built"); 12934 12935 if (!CurContext->isDependentContext()) { 12936 // Finalize the clauses that need pre-built expressions for CodeGen. 12937 for (OMPClause *C : Clauses) { 12938 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12939 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12940 B.NumIterations, *this, CurScope, 12941 DSAStack)) 12942 return StmtError(); 12943 } 12944 } 12945 12946 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12947 return StmtError(); 12948 12949 setFunctionHasBranchProtectedScope(); 12950 12951 DSAStack->setParentTeamsRegionLoc(StartLoc); 12952 12953 return OMPTeamsDistributeParallelForSimdDirective::Create( 12954 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12955 } 12956 12957 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 12958 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12959 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12960 if (!AStmt) 12961 return StmtError(); 12962 12963 auto *CS = cast<CapturedStmt>(AStmt); 12964 // 1.2.2 OpenMP Language Terminology 12965 // Structured block - An executable statement with a single entry at the 12966 // top and a single exit at the bottom. 12967 // The point of exit cannot be a branch out of the structured block. 12968 // longjmp() and throw() must not violate the entry/exit criteria. 12969 CS->getCapturedDecl()->setNothrow(); 12970 12971 for (int ThisCaptureLevel = 12972 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for); 12973 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12974 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12975 // 1.2.2 OpenMP Language Terminology 12976 // Structured block - An executable statement with a single entry at the 12977 // top and a single exit at the bottom. 12978 // The point of exit cannot be a branch out of the structured block. 12979 // longjmp() and throw() must not violate the entry/exit criteria. 12980 CS->getCapturedDecl()->setNothrow(); 12981 } 12982 12983 OMPLoopBasedDirective::HelperExprs B; 12984 // In presence of clause 'collapse' with number of loops, it will 12985 // define the nested loops number. 12986 unsigned NestedLoopCount = checkOpenMPLoop( 12987 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 12988 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12989 VarsWithImplicitDSA, B); 12990 12991 if (NestedLoopCount == 0) 12992 return StmtError(); 12993 12994 assert((CurContext->isDependentContext() || B.builtAll()) && 12995 "omp for loop exprs were not built"); 12996 12997 setFunctionHasBranchProtectedScope(); 12998 12999 DSAStack->setParentTeamsRegionLoc(StartLoc); 13000 13001 return OMPTeamsDistributeParallelForDirective::Create( 13002 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 13003 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 13004 } 13005 13006 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 13007 Stmt *AStmt, 13008 SourceLocation StartLoc, 13009 SourceLocation EndLoc) { 13010 if (!AStmt) 13011 return StmtError(); 13012 13013 auto *CS = cast<CapturedStmt>(AStmt); 13014 // 1.2.2 OpenMP Language Terminology 13015 // Structured block - An executable statement with a single entry at the 13016 // top and a single exit at the bottom. 13017 // The point of exit cannot be a branch out of the structured block. 13018 // longjmp() and throw() must not violate the entry/exit criteria. 13019 CS->getCapturedDecl()->setNothrow(); 13020 13021 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams); 13022 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13023 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13024 // 1.2.2 OpenMP Language Terminology 13025 // Structured block - An executable statement with a single entry at the 13026 // top and a single exit at the bottom. 13027 // The point of exit cannot be a branch out of the structured block. 13028 // longjmp() and throw() must not violate the entry/exit criteria. 13029 CS->getCapturedDecl()->setNothrow(); 13030 } 13031 setFunctionHasBranchProtectedScope(); 13032 13033 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 13034 AStmt); 13035 } 13036 13037 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 13038 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13039 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13040 if (!AStmt) 13041 return StmtError(); 13042 13043 auto *CS = cast<CapturedStmt>(AStmt); 13044 // 1.2.2 OpenMP Language Terminology 13045 // Structured block - An executable statement with a single entry at the 13046 // top and a single exit at the bottom. 13047 // The point of exit cannot be a branch out of the structured block. 13048 // longjmp() and throw() must not violate the entry/exit criteria. 13049 CS->getCapturedDecl()->setNothrow(); 13050 for (int ThisCaptureLevel = 13051 getOpenMPCaptureLevels(OMPD_target_teams_distribute); 13052 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13053 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13054 // 1.2.2 OpenMP Language Terminology 13055 // Structured block - An executable statement with a single entry at the 13056 // top and a single exit at the bottom. 13057 // The point of exit cannot be a branch out of the structured block. 13058 // longjmp() and throw() must not violate the entry/exit criteria. 13059 CS->getCapturedDecl()->setNothrow(); 13060 } 13061 13062 OMPLoopBasedDirective::HelperExprs B; 13063 // In presence of clause 'collapse' with number of loops, it will 13064 // define the nested loops number. 13065 unsigned NestedLoopCount = checkOpenMPLoop( 13066 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses), 13067 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 13068 VarsWithImplicitDSA, B); 13069 if (NestedLoopCount == 0) 13070 return StmtError(); 13071 13072 assert((CurContext->isDependentContext() || B.builtAll()) && 13073 "omp target teams distribute loop exprs were not built"); 13074 13075 setFunctionHasBranchProtectedScope(); 13076 return OMPTargetTeamsDistributeDirective::Create( 13077 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 13078 } 13079 13080 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 13081 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13082 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13083 if (!AStmt) 13084 return StmtError(); 13085 13086 auto *CS = cast<CapturedStmt>(AStmt); 13087 // 1.2.2 OpenMP Language Terminology 13088 // Structured block - An executable statement with a single entry at the 13089 // top and a single exit at the bottom. 13090 // The point of exit cannot be a branch out of the structured block. 13091 // longjmp() and throw() must not violate the entry/exit criteria. 13092 CS->getCapturedDecl()->setNothrow(); 13093 for (int ThisCaptureLevel = 13094 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for); 13095 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13096 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13097 // 1.2.2 OpenMP Language Terminology 13098 // Structured block - An executable statement with a single entry at the 13099 // top and a single exit at the bottom. 13100 // The point of exit cannot be a branch out of the structured block. 13101 // longjmp() and throw() must not violate the entry/exit criteria. 13102 CS->getCapturedDecl()->setNothrow(); 13103 } 13104 13105 OMPLoopBasedDirective::HelperExprs B; 13106 // In presence of clause 'collapse' with number of loops, it will 13107 // define the nested loops number. 13108 unsigned NestedLoopCount = checkOpenMPLoop( 13109 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 13110 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 13111 VarsWithImplicitDSA, B); 13112 if (NestedLoopCount == 0) 13113 return StmtError(); 13114 13115 assert((CurContext->isDependentContext() || B.builtAll()) && 13116 "omp target teams distribute parallel for loop exprs were not built"); 13117 13118 if (!CurContext->isDependentContext()) { 13119 // Finalize the clauses that need pre-built expressions for CodeGen. 13120 for (OMPClause *C : Clauses) { 13121 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 13122 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 13123 B.NumIterations, *this, CurScope, 13124 DSAStack)) 13125 return StmtError(); 13126 } 13127 } 13128 13129 setFunctionHasBranchProtectedScope(); 13130 return OMPTargetTeamsDistributeParallelForDirective::Create( 13131 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 13132 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 13133 } 13134 13135 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 13136 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13137 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13138 if (!AStmt) 13139 return StmtError(); 13140 13141 auto *CS = cast<CapturedStmt>(AStmt); 13142 // 1.2.2 OpenMP Language Terminology 13143 // Structured block - An executable statement with a single entry at the 13144 // top and a single exit at the bottom. 13145 // The point of exit cannot be a branch out of the structured block. 13146 // longjmp() and throw() must not violate the entry/exit criteria. 13147 CS->getCapturedDecl()->setNothrow(); 13148 for (int ThisCaptureLevel = getOpenMPCaptureLevels( 13149 OMPD_target_teams_distribute_parallel_for_simd); 13150 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13151 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13152 // 1.2.2 OpenMP Language Terminology 13153 // Structured block - An executable statement with a single entry at the 13154 // top and a single exit at the bottom. 13155 // The point of exit cannot be a branch out of the structured block. 13156 // longjmp() and throw() must not violate the entry/exit criteria. 13157 CS->getCapturedDecl()->setNothrow(); 13158 } 13159 13160 OMPLoopBasedDirective::HelperExprs B; 13161 // In presence of clause 'collapse' with number of loops, it will 13162 // define the nested loops number. 13163 unsigned NestedLoopCount = 13164 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd, 13165 getCollapseNumberExpr(Clauses), 13166 nullptr /*ordered not a clause on distribute*/, CS, *this, 13167 *DSAStack, VarsWithImplicitDSA, B); 13168 if (NestedLoopCount == 0) 13169 return StmtError(); 13170 13171 assert((CurContext->isDependentContext() || B.builtAll()) && 13172 "omp target teams distribute parallel for simd loop exprs were not " 13173 "built"); 13174 13175 if (!CurContext->isDependentContext()) { 13176 // Finalize the clauses that need pre-built expressions for CodeGen. 13177 for (OMPClause *C : Clauses) { 13178 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 13179 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 13180 B.NumIterations, *this, CurScope, 13181 DSAStack)) 13182 return StmtError(); 13183 } 13184 } 13185 13186 if (checkSimdlenSafelenSpecified(*this, Clauses)) 13187 return StmtError(); 13188 13189 setFunctionHasBranchProtectedScope(); 13190 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 13191 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 13192 } 13193 13194 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 13195 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 13196 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 13197 if (!AStmt) 13198 return StmtError(); 13199 13200 auto *CS = cast<CapturedStmt>(AStmt); 13201 // 1.2.2 OpenMP Language Terminology 13202 // Structured block - An executable statement with a single entry at the 13203 // top and a single exit at the bottom. 13204 // The point of exit cannot be a branch out of the structured block. 13205 // longjmp() and throw() must not violate the entry/exit criteria. 13206 CS->getCapturedDecl()->setNothrow(); 13207 for (int ThisCaptureLevel = 13208 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd); 13209 ThisCaptureLevel > 1; --ThisCaptureLevel) { 13210 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 13211 // 1.2.2 OpenMP Language Terminology 13212 // Structured block - An executable statement with a single entry at the 13213 // top and a single exit at the bottom. 13214 // The point of exit cannot be a branch out of the structured block. 13215 // longjmp() and throw() must not violate the entry/exit criteria. 13216 CS->getCapturedDecl()->setNothrow(); 13217 } 13218 13219 OMPLoopBasedDirective::HelperExprs B; 13220 // In presence of clause 'collapse' with number of loops, it will 13221 // define the nested loops number. 13222 unsigned NestedLoopCount = checkOpenMPLoop( 13223 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 13224 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 13225 VarsWithImplicitDSA, B); 13226 if (NestedLoopCount == 0) 13227 return StmtError(); 13228 13229 assert((CurContext->isDependentContext() || B.builtAll()) && 13230 "omp target teams distribute simd loop exprs were not built"); 13231 13232 if (!CurContext->isDependentContext()) { 13233 // Finalize the clauses that need pre-built expressions for CodeGen. 13234 for (OMPClause *C : Clauses) { 13235 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 13236 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 13237 B.NumIterations, *this, CurScope, 13238 DSAStack)) 13239 return StmtError(); 13240 } 13241 } 13242 13243 if (checkSimdlenSafelenSpecified(*this, Clauses)) 13244 return StmtError(); 13245 13246 setFunctionHasBranchProtectedScope(); 13247 return OMPTargetTeamsDistributeSimdDirective::Create( 13248 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 13249 } 13250 13251 bool Sema::checkTransformableLoopNest( 13252 OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops, 13253 SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers, 13254 Stmt *&Body, 13255 SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>> 13256 &OriginalInits) { 13257 OriginalInits.emplace_back(); 13258 bool Result = OMPLoopBasedDirective::doForAllLoops( 13259 AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false, NumLoops, 13260 [this, &LoopHelpers, &Body, &OriginalInits, Kind](unsigned Cnt, 13261 Stmt *CurStmt) { 13262 VarsWithInheritedDSAType TmpDSA; 13263 unsigned SingleNumLoops = 13264 checkOpenMPLoop(Kind, nullptr, nullptr, CurStmt, *this, *DSAStack, 13265 TmpDSA, LoopHelpers[Cnt]); 13266 if (SingleNumLoops == 0) 13267 return true; 13268 assert(SingleNumLoops == 1 && "Expect single loop iteration space"); 13269 if (auto *For = dyn_cast<ForStmt>(CurStmt)) { 13270 OriginalInits.back().push_back(For->getInit()); 13271 Body = For->getBody(); 13272 } else { 13273 assert(isa<CXXForRangeStmt>(CurStmt) && 13274 "Expected canonical for or range-based for loops."); 13275 auto *CXXFor = cast<CXXForRangeStmt>(CurStmt); 13276 OriginalInits.back().push_back(CXXFor->getBeginStmt()); 13277 Body = CXXFor->getBody(); 13278 } 13279 OriginalInits.emplace_back(); 13280 return false; 13281 }, 13282 [&OriginalInits](OMPLoopBasedDirective *Transform) { 13283 Stmt *DependentPreInits; 13284 if (auto *Dir = dyn_cast<OMPTileDirective>(Transform)) 13285 DependentPreInits = Dir->getPreInits(); 13286 else if (auto *Dir = dyn_cast<OMPUnrollDirective>(Transform)) 13287 DependentPreInits = Dir->getPreInits(); 13288 else 13289 llvm_unreachable("Unhandled loop transformation"); 13290 if (!DependentPreInits) 13291 return; 13292 for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) 13293 OriginalInits.back().push_back(C); 13294 }); 13295 assert(OriginalInits.back().empty() && "No preinit after innermost loop"); 13296 OriginalInits.pop_back(); 13297 return Result; 13298 } 13299 13300 StmtResult Sema::ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses, 13301 Stmt *AStmt, SourceLocation StartLoc, 13302 SourceLocation EndLoc) { 13303 auto SizesClauses = 13304 OMPExecutableDirective::getClausesOfKind<OMPSizesClause>(Clauses); 13305 if (SizesClauses.empty()) { 13306 // A missing 'sizes' clause is already reported by the parser. 13307 return StmtError(); 13308 } 13309 const OMPSizesClause *SizesClause = *SizesClauses.begin(); 13310 unsigned NumLoops = SizesClause->getNumSizes(); 13311 13312 // Empty statement should only be possible if there already was an error. 13313 if (!AStmt) 13314 return StmtError(); 13315 13316 // Verify and diagnose loop nest. 13317 SmallVector<OMPLoopBasedDirective::HelperExprs, 4> LoopHelpers(NumLoops); 13318 Stmt *Body = nullptr; 13319 SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, 4> 13320 OriginalInits; 13321 if (!checkTransformableLoopNest(OMPD_tile, AStmt, NumLoops, LoopHelpers, Body, 13322 OriginalInits)) 13323 return StmtError(); 13324 13325 // Delay tiling to when template is completely instantiated. 13326 if (CurContext->isDependentContext()) 13327 return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, 13328 NumLoops, AStmt, nullptr, nullptr); 13329 13330 SmallVector<Decl *, 4> PreInits; 13331 13332 // Create iteration variables for the generated loops. 13333 SmallVector<VarDecl *, 4> FloorIndVars; 13334 SmallVector<VarDecl *, 4> TileIndVars; 13335 FloorIndVars.resize(NumLoops); 13336 TileIndVars.resize(NumLoops); 13337 for (unsigned I = 0; I < NumLoops; ++I) { 13338 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I]; 13339 13340 assert(LoopHelper.Counters.size() == 1 && 13341 "Expect single-dimensional loop iteration space"); 13342 auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front()); 13343 std::string OrigVarName = OrigCntVar->getNameInfo().getAsString(); 13344 DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef); 13345 QualType CntTy = IterVarRef->getType(); 13346 13347 // Iteration variable for the floor (i.e. outer) loop. 13348 { 13349 std::string FloorCntName = 13350 (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str(); 13351 VarDecl *FloorCntDecl = 13352 buildVarDecl(*this, {}, CntTy, FloorCntName, nullptr, OrigCntVar); 13353 FloorIndVars[I] = FloorCntDecl; 13354 } 13355 13356 // Iteration variable for the tile (i.e. inner) loop. 13357 { 13358 std::string TileCntName = 13359 (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str(); 13360 13361 // Reuse the iteration variable created by checkOpenMPLoop. It is also 13362 // used by the expressions to derive the original iteration variable's 13363 // value from the logical iteration number. 13364 auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl()); 13365 TileCntDecl->setDeclName(&PP.getIdentifierTable().get(TileCntName)); 13366 TileIndVars[I] = TileCntDecl; 13367 } 13368 for (auto &P : OriginalInits[I]) { 13369 if (auto *D = P.dyn_cast<Decl *>()) 13370 PreInits.push_back(D); 13371 else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>())) 13372 PreInits.append(PI->decl_begin(), PI->decl_end()); 13373 } 13374 if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits)) 13375 PreInits.append(PI->decl_begin(), PI->decl_end()); 13376 // Gather declarations for the data members used as counters. 13377 for (Expr *CounterRef : LoopHelper.Counters) { 13378 auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl(); 13379 if (isa<OMPCapturedExprDecl>(CounterDecl)) 13380 PreInits.push_back(CounterDecl); 13381 } 13382 } 13383 13384 // Once the original iteration values are set, append the innermost body. 13385 Stmt *Inner = Body; 13386 13387 // Create tile loops from the inside to the outside. 13388 for (int I = NumLoops - 1; I >= 0; --I) { 13389 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I]; 13390 Expr *NumIterations = LoopHelper.NumIterations; 13391 auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]); 13392 QualType CntTy = OrigCntVar->getType(); 13393 Expr *DimTileSize = SizesClause->getSizesRefs()[I]; 13394 Scope *CurScope = getCurScope(); 13395 13396 // Commonly used variables. 13397 DeclRefExpr *TileIV = buildDeclRefExpr(*this, TileIndVars[I], CntTy, 13398 OrigCntVar->getExprLoc()); 13399 DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy, 13400 OrigCntVar->getExprLoc()); 13401 13402 // For init-statement: auto .tile.iv = .floor.iv 13403 AddInitializerToDecl(TileIndVars[I], DefaultLvalueConversion(FloorIV).get(), 13404 /*DirectInit=*/false); 13405 Decl *CounterDecl = TileIndVars[I]; 13406 StmtResult InitStmt = new (Context) 13407 DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1), 13408 OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc()); 13409 if (!InitStmt.isUsable()) 13410 return StmtError(); 13411 13412 // For cond-expression: .tile.iv < min(.floor.iv + DimTileSize, 13413 // NumIterations) 13414 ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13415 BO_Add, FloorIV, DimTileSize); 13416 if (!EndOfTile.isUsable()) 13417 return StmtError(); 13418 ExprResult IsPartialTile = 13419 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, 13420 NumIterations, EndOfTile.get()); 13421 if (!IsPartialTile.isUsable()) 13422 return StmtError(); 13423 ExprResult MinTileAndIterSpace = ActOnConditionalOp( 13424 LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(), 13425 IsPartialTile.get(), NumIterations, EndOfTile.get()); 13426 if (!MinTileAndIterSpace.isUsable()) 13427 return StmtError(); 13428 ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13429 BO_LT, TileIV, MinTileAndIterSpace.get()); 13430 if (!CondExpr.isUsable()) 13431 return StmtError(); 13432 13433 // For incr-statement: ++.tile.iv 13434 ExprResult IncrStmt = 13435 BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV); 13436 if (!IncrStmt.isUsable()) 13437 return StmtError(); 13438 13439 // Statements to set the original iteration variable's value from the 13440 // logical iteration number. 13441 // Generated for loop is: 13442 // Original_for_init; 13443 // for (auto .tile.iv = .floor.iv; .tile.iv < min(.floor.iv + DimTileSize, 13444 // NumIterations); ++.tile.iv) { 13445 // Original_Body; 13446 // Original_counter_update; 13447 // } 13448 // FIXME: If the innermost body is an loop itself, inserting these 13449 // statements stops it being recognized as a perfectly nested loop (e.g. 13450 // for applying tiling again). If this is the case, sink the expressions 13451 // further into the inner loop. 13452 SmallVector<Stmt *, 4> BodyParts; 13453 BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end()); 13454 BodyParts.push_back(Inner); 13455 Inner = CompoundStmt::Create(Context, BodyParts, Inner->getBeginLoc(), 13456 Inner->getEndLoc()); 13457 Inner = new (Context) 13458 ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr, 13459 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(), 13460 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 13461 } 13462 13463 // Create floor loops from the inside to the outside. 13464 for (int I = NumLoops - 1; I >= 0; --I) { 13465 auto &LoopHelper = LoopHelpers[I]; 13466 Expr *NumIterations = LoopHelper.NumIterations; 13467 DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]); 13468 QualType CntTy = OrigCntVar->getType(); 13469 Expr *DimTileSize = SizesClause->getSizesRefs()[I]; 13470 Scope *CurScope = getCurScope(); 13471 13472 // Commonly used variables. 13473 DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy, 13474 OrigCntVar->getExprLoc()); 13475 13476 // For init-statement: auto .floor.iv = 0 13477 AddInitializerToDecl( 13478 FloorIndVars[I], 13479 ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(), 13480 /*DirectInit=*/false); 13481 Decl *CounterDecl = FloorIndVars[I]; 13482 StmtResult InitStmt = new (Context) 13483 DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1), 13484 OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc()); 13485 if (!InitStmt.isUsable()) 13486 return StmtError(); 13487 13488 // For cond-expression: .floor.iv < NumIterations 13489 ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13490 BO_LT, FloorIV, NumIterations); 13491 if (!CondExpr.isUsable()) 13492 return StmtError(); 13493 13494 // For incr-statement: .floor.iv += DimTileSize 13495 ExprResult IncrStmt = BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), 13496 BO_AddAssign, FloorIV, DimTileSize); 13497 if (!IncrStmt.isUsable()) 13498 return StmtError(); 13499 13500 Inner = new (Context) 13501 ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr, 13502 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(), 13503 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 13504 } 13505 13506 return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, NumLoops, 13507 AStmt, Inner, 13508 buildPreInits(Context, PreInits)); 13509 } 13510 13511 StmtResult Sema::ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses, 13512 Stmt *AStmt, 13513 SourceLocation StartLoc, 13514 SourceLocation EndLoc) { 13515 // Empty statement should only be possible if there already was an error. 13516 if (!AStmt) 13517 return StmtError(); 13518 13519 if (checkMutuallyExclusiveClauses(*this, Clauses, {OMPC_partial, OMPC_full})) 13520 return StmtError(); 13521 13522 const OMPFullClause *FullClause = 13523 OMPExecutableDirective::getSingleClause<OMPFullClause>(Clauses); 13524 const OMPPartialClause *PartialClause = 13525 OMPExecutableDirective::getSingleClause<OMPPartialClause>(Clauses); 13526 assert(!(FullClause && PartialClause) && 13527 "mutual exclusivity must have been checked before"); 13528 13529 constexpr unsigned NumLoops = 1; 13530 Stmt *Body = nullptr; 13531 SmallVector<OMPLoopBasedDirective::HelperExprs, NumLoops> LoopHelpers( 13532 NumLoops); 13533 SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, NumLoops + 1> 13534 OriginalInits; 13535 if (!checkTransformableLoopNest(OMPD_unroll, AStmt, NumLoops, LoopHelpers, 13536 Body, OriginalInits)) 13537 return StmtError(); 13538 13539 unsigned NumGeneratedLoops = PartialClause ? 1 : 0; 13540 13541 // Delay unrolling to when template is completely instantiated. 13542 if (CurContext->isDependentContext()) 13543 return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 13544 NumGeneratedLoops, nullptr, nullptr); 13545 13546 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers.front(); 13547 13548 if (FullClause) { 13549 if (!VerifyPositiveIntegerConstantInClause( 13550 LoopHelper.NumIterations, OMPC_full, /*StrictlyPositive=*/false, 13551 /*SuppressExprDiags=*/true) 13552 .isUsable()) { 13553 Diag(AStmt->getBeginLoc(), diag::err_omp_unroll_full_variable_trip_count); 13554 Diag(FullClause->getBeginLoc(), diag::note_omp_directive_here) 13555 << "#pragma omp unroll full"; 13556 return StmtError(); 13557 } 13558 } 13559 13560 // The generated loop may only be passed to other loop-associated directive 13561 // when a partial clause is specified. Without the requirement it is 13562 // sufficient to generate loop unroll metadata at code-generation. 13563 if (NumGeneratedLoops == 0) 13564 return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 13565 NumGeneratedLoops, nullptr, nullptr); 13566 13567 // Otherwise, we need to provide a de-sugared/transformed AST that can be 13568 // associated with another loop directive. 13569 // 13570 // The canonical loop analysis return by checkTransformableLoopNest assumes 13571 // the following structure to be the same loop without transformations or 13572 // directives applied: \code OriginalInits; LoopHelper.PreInits; 13573 // LoopHelper.Counters; 13574 // for (; IV < LoopHelper.NumIterations; ++IV) { 13575 // LoopHelper.Updates; 13576 // Body; 13577 // } 13578 // \endcode 13579 // where IV is a variable declared and initialized to 0 in LoopHelper.PreInits 13580 // and referenced by LoopHelper.IterationVarRef. 13581 // 13582 // The unrolling directive transforms this into the following loop: 13583 // \code 13584 // OriginalInits; \ 13585 // LoopHelper.PreInits; > NewPreInits 13586 // LoopHelper.Counters; / 13587 // for (auto UIV = 0; UIV < LoopHelper.NumIterations; UIV+=Factor) { 13588 // #pragma clang loop unroll_count(Factor) 13589 // for (IV = UIV; IV < UIV + Factor && UIV < LoopHelper.NumIterations; ++IV) 13590 // { 13591 // LoopHelper.Updates; 13592 // Body; 13593 // } 13594 // } 13595 // \endcode 13596 // where UIV is a new logical iteration counter. IV must be the same VarDecl 13597 // as the original LoopHelper.IterationVarRef because LoopHelper.Updates 13598 // references it. If the partially unrolled loop is associated with another 13599 // loop directive (like an OMPForDirective), it will use checkOpenMPLoop to 13600 // analyze this loop, i.e. the outer loop must fulfill the constraints of an 13601 // OpenMP canonical loop. The inner loop is not an associable canonical loop 13602 // and only exists to defer its unrolling to LLVM's LoopUnroll instead of 13603 // doing it in the frontend (by adding loop metadata). NewPreInits becomes a 13604 // property of the OMPLoopBasedDirective instead of statements in 13605 // CompoundStatement. This is to allow the loop to become a non-outermost loop 13606 // of a canonical loop nest where these PreInits are emitted before the 13607 // outermost directive. 13608 13609 // Determine the PreInit declarations. 13610 SmallVector<Decl *, 4> PreInits; 13611 assert(OriginalInits.size() == 1 && 13612 "Expecting a single-dimensional loop iteration space"); 13613 for (auto &P : OriginalInits[0]) { 13614 if (auto *D = P.dyn_cast<Decl *>()) 13615 PreInits.push_back(D); 13616 else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>())) 13617 PreInits.append(PI->decl_begin(), PI->decl_end()); 13618 } 13619 if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits)) 13620 PreInits.append(PI->decl_begin(), PI->decl_end()); 13621 // Gather declarations for the data members used as counters. 13622 for (Expr *CounterRef : LoopHelper.Counters) { 13623 auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl(); 13624 if (isa<OMPCapturedExprDecl>(CounterDecl)) 13625 PreInits.push_back(CounterDecl); 13626 } 13627 13628 auto *IterationVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef); 13629 QualType IVTy = IterationVarRef->getType(); 13630 assert(LoopHelper.Counters.size() == 1 && 13631 "Expecting a single-dimensional loop iteration space"); 13632 auto *OrigVar = cast<DeclRefExpr>(LoopHelper.Counters.front()); 13633 13634 // Determine the unroll factor. 13635 uint64_t Factor; 13636 SourceLocation FactorLoc; 13637 if (Expr *FactorVal = PartialClause->getFactor()) { 13638 Factor = 13639 FactorVal->getIntegerConstantExpr(Context).getValue().getZExtValue(); 13640 FactorLoc = FactorVal->getExprLoc(); 13641 } else { 13642 // TODO: Use a better profitability model. 13643 Factor = 2; 13644 } 13645 assert(Factor > 0 && "Expected positive unroll factor"); 13646 auto MakeFactorExpr = [this, Factor, IVTy, FactorLoc]() { 13647 return IntegerLiteral::Create( 13648 Context, llvm::APInt(Context.getIntWidth(IVTy), Factor), IVTy, 13649 FactorLoc); 13650 }; 13651 13652 // Iteration variable SourceLocations. 13653 SourceLocation OrigVarLoc = OrigVar->getExprLoc(); 13654 SourceLocation OrigVarLocBegin = OrigVar->getBeginLoc(); 13655 SourceLocation OrigVarLocEnd = OrigVar->getEndLoc(); 13656 13657 // Internal variable names. 13658 std::string OrigVarName = OrigVar->getNameInfo().getAsString(); 13659 std::string OuterIVName = (Twine(".unrolled.iv.") + OrigVarName).str(); 13660 std::string InnerIVName = (Twine(".unroll_inner.iv.") + OrigVarName).str(); 13661 std::string InnerTripCountName = 13662 (Twine(".unroll_inner.tripcount.") + OrigVarName).str(); 13663 13664 // Create the iteration variable for the unrolled loop. 13665 VarDecl *OuterIVDecl = 13666 buildVarDecl(*this, {}, IVTy, OuterIVName, nullptr, OrigVar); 13667 auto MakeOuterRef = [this, OuterIVDecl, IVTy, OrigVarLoc]() { 13668 return buildDeclRefExpr(*this, OuterIVDecl, IVTy, OrigVarLoc); 13669 }; 13670 13671 // Iteration variable for the inner loop: Reuse the iteration variable created 13672 // by checkOpenMPLoop. 13673 auto *InnerIVDecl = cast<VarDecl>(IterationVarRef->getDecl()); 13674 InnerIVDecl->setDeclName(&PP.getIdentifierTable().get(InnerIVName)); 13675 auto MakeInnerRef = [this, InnerIVDecl, IVTy, OrigVarLoc]() { 13676 return buildDeclRefExpr(*this, InnerIVDecl, IVTy, OrigVarLoc); 13677 }; 13678 13679 // Make a copy of the NumIterations expression for each use: By the AST 13680 // constraints, every expression object in a DeclContext must be unique. 13681 CaptureVars CopyTransformer(*this); 13682 auto MakeNumIterations = [&CopyTransformer, &LoopHelper]() -> Expr * { 13683 return AssertSuccess( 13684 CopyTransformer.TransformExpr(LoopHelper.NumIterations)); 13685 }; 13686 13687 // Inner For init-statement: auto .unroll_inner.iv = .unrolled.iv 13688 ExprResult LValueConv = DefaultLvalueConversion(MakeOuterRef()); 13689 AddInitializerToDecl(InnerIVDecl, LValueConv.get(), /*DirectInit=*/false); 13690 StmtResult InnerInit = new (Context) 13691 DeclStmt(DeclGroupRef(InnerIVDecl), OrigVarLocBegin, OrigVarLocEnd); 13692 if (!InnerInit.isUsable()) 13693 return StmtError(); 13694 13695 // Inner For cond-expression: 13696 // \code 13697 // .unroll_inner.iv < .unrolled.iv + Factor && 13698 // .unroll_inner.iv < NumIterations 13699 // \endcode 13700 // This conjunction of two conditions allows ScalarEvolution to derive the 13701 // maximum trip count of the inner loop. 13702 ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13703 BO_Add, MakeOuterRef(), MakeFactorExpr()); 13704 if (!EndOfTile.isUsable()) 13705 return StmtError(); 13706 ExprResult InnerCond1 = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13707 BO_LE, MakeInnerRef(), EndOfTile.get()); 13708 if (!InnerCond1.isUsable()) 13709 return StmtError(); 13710 ExprResult InnerCond2 = 13711 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LE, MakeInnerRef(), 13712 MakeNumIterations()); 13713 if (!InnerCond2.isUsable()) 13714 return StmtError(); 13715 ExprResult InnerCond = 13716 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LAnd, 13717 InnerCond1.get(), InnerCond2.get()); 13718 if (!InnerCond.isUsable()) 13719 return StmtError(); 13720 13721 // Inner For incr-statement: ++.unroll_inner.iv 13722 ExprResult InnerIncr = BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), 13723 UO_PreInc, MakeInnerRef()); 13724 if (!InnerIncr.isUsable()) 13725 return StmtError(); 13726 13727 // Inner For statement. 13728 SmallVector<Stmt *> InnerBodyStmts; 13729 InnerBodyStmts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end()); 13730 InnerBodyStmts.push_back(Body); 13731 CompoundStmt *InnerBody = CompoundStmt::Create( 13732 Context, InnerBodyStmts, Body->getBeginLoc(), Body->getEndLoc()); 13733 ForStmt *InnerFor = new (Context) 13734 ForStmt(Context, InnerInit.get(), InnerCond.get(), nullptr, 13735 InnerIncr.get(), InnerBody, LoopHelper.Init->getBeginLoc(), 13736 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 13737 13738 // Unroll metadata for the inner loop. 13739 // This needs to take into account the remainder portion of the unrolled loop, 13740 // hence `unroll(full)` does not apply here, even though the LoopUnroll pass 13741 // supports multiple loop exits. Instead, unroll using a factor equivalent to 13742 // the maximum trip count, which will also generate a remainder loop. Just 13743 // `unroll(enable)` (which could have been useful if the user has not 13744 // specified a concrete factor; even though the outer loop cannot be 13745 // influenced anymore, would avoid more code bloat than necessary) will refuse 13746 // the loop because "Won't unroll; remainder loop could not be generated when 13747 // assuming runtime trip count". Even if it did work, it must not choose a 13748 // larger unroll factor than the maximum loop length, or it would always just 13749 // execute the remainder loop. 13750 LoopHintAttr *UnrollHintAttr = 13751 LoopHintAttr::CreateImplicit(Context, LoopHintAttr::UnrollCount, 13752 LoopHintAttr::Numeric, MakeFactorExpr()); 13753 AttributedStmt *InnerUnrolled = 13754 AttributedStmt::Create(Context, StartLoc, {UnrollHintAttr}, InnerFor); 13755 13756 // Outer For init-statement: auto .unrolled.iv = 0 13757 AddInitializerToDecl( 13758 OuterIVDecl, ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(), 13759 /*DirectInit=*/false); 13760 StmtResult OuterInit = new (Context) 13761 DeclStmt(DeclGroupRef(OuterIVDecl), OrigVarLocBegin, OrigVarLocEnd); 13762 if (!OuterInit.isUsable()) 13763 return StmtError(); 13764 13765 // Outer For cond-expression: .unrolled.iv < NumIterations 13766 ExprResult OuterConde = 13767 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, MakeOuterRef(), 13768 MakeNumIterations()); 13769 if (!OuterConde.isUsable()) 13770 return StmtError(); 13771 13772 // Outer For incr-statement: .unrolled.iv += Factor 13773 ExprResult OuterIncr = 13774 BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), BO_AddAssign, 13775 MakeOuterRef(), MakeFactorExpr()); 13776 if (!OuterIncr.isUsable()) 13777 return StmtError(); 13778 13779 // Outer For statement. 13780 ForStmt *OuterFor = new (Context) 13781 ForStmt(Context, OuterInit.get(), OuterConde.get(), nullptr, 13782 OuterIncr.get(), InnerUnrolled, LoopHelper.Init->getBeginLoc(), 13783 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 13784 13785 return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 13786 NumGeneratedLoops, OuterFor, 13787 buildPreInits(Context, PreInits)); 13788 } 13789 13790 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 13791 SourceLocation StartLoc, 13792 SourceLocation LParenLoc, 13793 SourceLocation EndLoc) { 13794 OMPClause *Res = nullptr; 13795 switch (Kind) { 13796 case OMPC_final: 13797 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 13798 break; 13799 case OMPC_num_threads: 13800 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 13801 break; 13802 case OMPC_safelen: 13803 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 13804 break; 13805 case OMPC_simdlen: 13806 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 13807 break; 13808 case OMPC_allocator: 13809 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc); 13810 break; 13811 case OMPC_collapse: 13812 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 13813 break; 13814 case OMPC_ordered: 13815 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 13816 break; 13817 case OMPC_num_teams: 13818 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 13819 break; 13820 case OMPC_thread_limit: 13821 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 13822 break; 13823 case OMPC_priority: 13824 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 13825 break; 13826 case OMPC_grainsize: 13827 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 13828 break; 13829 case OMPC_num_tasks: 13830 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 13831 break; 13832 case OMPC_hint: 13833 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 13834 break; 13835 case OMPC_depobj: 13836 Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc); 13837 break; 13838 case OMPC_detach: 13839 Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc); 13840 break; 13841 case OMPC_novariants: 13842 Res = ActOnOpenMPNovariantsClause(Expr, StartLoc, LParenLoc, EndLoc); 13843 break; 13844 case OMPC_nocontext: 13845 Res = ActOnOpenMPNocontextClause(Expr, StartLoc, LParenLoc, EndLoc); 13846 break; 13847 case OMPC_filter: 13848 Res = ActOnOpenMPFilterClause(Expr, StartLoc, LParenLoc, EndLoc); 13849 break; 13850 case OMPC_partial: 13851 Res = ActOnOpenMPPartialClause(Expr, StartLoc, LParenLoc, EndLoc); 13852 break; 13853 case OMPC_align: 13854 Res = ActOnOpenMPAlignClause(Expr, StartLoc, LParenLoc, EndLoc); 13855 break; 13856 case OMPC_device: 13857 case OMPC_if: 13858 case OMPC_default: 13859 case OMPC_proc_bind: 13860 case OMPC_schedule: 13861 case OMPC_private: 13862 case OMPC_firstprivate: 13863 case OMPC_lastprivate: 13864 case OMPC_shared: 13865 case OMPC_reduction: 13866 case OMPC_task_reduction: 13867 case OMPC_in_reduction: 13868 case OMPC_linear: 13869 case OMPC_aligned: 13870 case OMPC_copyin: 13871 case OMPC_copyprivate: 13872 case OMPC_nowait: 13873 case OMPC_untied: 13874 case OMPC_mergeable: 13875 case OMPC_threadprivate: 13876 case OMPC_sizes: 13877 case OMPC_allocate: 13878 case OMPC_flush: 13879 case OMPC_read: 13880 case OMPC_write: 13881 case OMPC_update: 13882 case OMPC_capture: 13883 case OMPC_compare: 13884 case OMPC_seq_cst: 13885 case OMPC_acq_rel: 13886 case OMPC_acquire: 13887 case OMPC_release: 13888 case OMPC_relaxed: 13889 case OMPC_depend: 13890 case OMPC_threads: 13891 case OMPC_simd: 13892 case OMPC_map: 13893 case OMPC_nogroup: 13894 case OMPC_dist_schedule: 13895 case OMPC_defaultmap: 13896 case OMPC_unknown: 13897 case OMPC_uniform: 13898 case OMPC_to: 13899 case OMPC_from: 13900 case OMPC_use_device_ptr: 13901 case OMPC_use_device_addr: 13902 case OMPC_is_device_ptr: 13903 case OMPC_unified_address: 13904 case OMPC_unified_shared_memory: 13905 case OMPC_reverse_offload: 13906 case OMPC_dynamic_allocators: 13907 case OMPC_atomic_default_mem_order: 13908 case OMPC_device_type: 13909 case OMPC_match: 13910 case OMPC_nontemporal: 13911 case OMPC_order: 13912 case OMPC_destroy: 13913 case OMPC_inclusive: 13914 case OMPC_exclusive: 13915 case OMPC_uses_allocators: 13916 case OMPC_affinity: 13917 case OMPC_when: 13918 case OMPC_bind: 13919 default: 13920 llvm_unreachable("Clause is not allowed."); 13921 } 13922 return Res; 13923 } 13924 13925 // An OpenMP directive such as 'target parallel' has two captured regions: 13926 // for the 'target' and 'parallel' respectively. This function returns 13927 // the region in which to capture expressions associated with a clause. 13928 // A return value of OMPD_unknown signifies that the expression should not 13929 // be captured. 13930 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 13931 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion, 13932 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 13933 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 13934 switch (CKind) { 13935 case OMPC_if: 13936 switch (DKind) { 13937 case OMPD_target_parallel_for_simd: 13938 if (OpenMPVersion >= 50 && 13939 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 13940 CaptureRegion = OMPD_parallel; 13941 break; 13942 } 13943 LLVM_FALLTHROUGH; 13944 case OMPD_target_parallel: 13945 case OMPD_target_parallel_for: 13946 // If this clause applies to the nested 'parallel' region, capture within 13947 // the 'target' region, otherwise do not capture. 13948 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 13949 CaptureRegion = OMPD_target; 13950 break; 13951 case OMPD_target_teams_distribute_parallel_for_simd: 13952 if (OpenMPVersion >= 50 && 13953 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 13954 CaptureRegion = OMPD_parallel; 13955 break; 13956 } 13957 LLVM_FALLTHROUGH; 13958 case OMPD_target_teams_distribute_parallel_for: 13959 // If this clause applies to the nested 'parallel' region, capture within 13960 // the 'teams' region, otherwise do not capture. 13961 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 13962 CaptureRegion = OMPD_teams; 13963 break; 13964 case OMPD_teams_distribute_parallel_for_simd: 13965 if (OpenMPVersion >= 50 && 13966 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 13967 CaptureRegion = OMPD_parallel; 13968 break; 13969 } 13970 LLVM_FALLTHROUGH; 13971 case OMPD_teams_distribute_parallel_for: 13972 CaptureRegion = OMPD_teams; 13973 break; 13974 case OMPD_target_update: 13975 case OMPD_target_enter_data: 13976 case OMPD_target_exit_data: 13977 CaptureRegion = OMPD_task; 13978 break; 13979 case OMPD_parallel_master_taskloop: 13980 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop) 13981 CaptureRegion = OMPD_parallel; 13982 break; 13983 case OMPD_parallel_master_taskloop_simd: 13984 if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) || 13985 NameModifier == OMPD_taskloop) { 13986 CaptureRegion = OMPD_parallel; 13987 break; 13988 } 13989 if (OpenMPVersion <= 45) 13990 break; 13991 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 13992 CaptureRegion = OMPD_taskloop; 13993 break; 13994 case OMPD_parallel_for_simd: 13995 if (OpenMPVersion <= 45) 13996 break; 13997 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 13998 CaptureRegion = OMPD_parallel; 13999 break; 14000 case OMPD_taskloop_simd: 14001 case OMPD_master_taskloop_simd: 14002 if (OpenMPVersion <= 45) 14003 break; 14004 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 14005 CaptureRegion = OMPD_taskloop; 14006 break; 14007 case OMPD_distribute_parallel_for_simd: 14008 if (OpenMPVersion <= 45) 14009 break; 14010 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 14011 CaptureRegion = OMPD_parallel; 14012 break; 14013 case OMPD_target_simd: 14014 if (OpenMPVersion >= 50 && 14015 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) 14016 CaptureRegion = OMPD_target; 14017 break; 14018 case OMPD_teams_distribute_simd: 14019 case OMPD_target_teams_distribute_simd: 14020 if (OpenMPVersion >= 50 && 14021 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) 14022 CaptureRegion = OMPD_teams; 14023 break; 14024 case OMPD_cancel: 14025 case OMPD_parallel: 14026 case OMPD_parallel_master: 14027 case OMPD_parallel_sections: 14028 case OMPD_parallel_for: 14029 case OMPD_target: 14030 case OMPD_target_teams: 14031 case OMPD_target_teams_distribute: 14032 case OMPD_distribute_parallel_for: 14033 case OMPD_task: 14034 case OMPD_taskloop: 14035 case OMPD_master_taskloop: 14036 case OMPD_target_data: 14037 case OMPD_simd: 14038 case OMPD_for_simd: 14039 case OMPD_distribute_simd: 14040 // Do not capture if-clause expressions. 14041 break; 14042 case OMPD_threadprivate: 14043 case OMPD_allocate: 14044 case OMPD_taskyield: 14045 case OMPD_barrier: 14046 case OMPD_taskwait: 14047 case OMPD_cancellation_point: 14048 case OMPD_flush: 14049 case OMPD_depobj: 14050 case OMPD_scan: 14051 case OMPD_declare_reduction: 14052 case OMPD_declare_mapper: 14053 case OMPD_declare_simd: 14054 case OMPD_declare_variant: 14055 case OMPD_begin_declare_variant: 14056 case OMPD_end_declare_variant: 14057 case OMPD_declare_target: 14058 case OMPD_end_declare_target: 14059 case OMPD_loop: 14060 case OMPD_teams: 14061 case OMPD_tile: 14062 case OMPD_unroll: 14063 case OMPD_for: 14064 case OMPD_sections: 14065 case OMPD_section: 14066 case OMPD_single: 14067 case OMPD_master: 14068 case OMPD_masked: 14069 case OMPD_critical: 14070 case OMPD_taskgroup: 14071 case OMPD_distribute: 14072 case OMPD_ordered: 14073 case OMPD_atomic: 14074 case OMPD_teams_distribute: 14075 case OMPD_requires: 14076 case OMPD_metadirective: 14077 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 14078 case OMPD_unknown: 14079 default: 14080 llvm_unreachable("Unknown OpenMP directive"); 14081 } 14082 break; 14083 case OMPC_num_threads: 14084 switch (DKind) { 14085 case OMPD_target_parallel: 14086 case OMPD_target_parallel_for: 14087 case OMPD_target_parallel_for_simd: 14088 CaptureRegion = OMPD_target; 14089 break; 14090 case OMPD_teams_distribute_parallel_for: 14091 case OMPD_teams_distribute_parallel_for_simd: 14092 case OMPD_target_teams_distribute_parallel_for: 14093 case OMPD_target_teams_distribute_parallel_for_simd: 14094 CaptureRegion = OMPD_teams; 14095 break; 14096 case OMPD_parallel: 14097 case OMPD_parallel_master: 14098 case OMPD_parallel_sections: 14099 case OMPD_parallel_for: 14100 case OMPD_parallel_for_simd: 14101 case OMPD_distribute_parallel_for: 14102 case OMPD_distribute_parallel_for_simd: 14103 case OMPD_parallel_master_taskloop: 14104 case OMPD_parallel_master_taskloop_simd: 14105 // Do not capture num_threads-clause expressions. 14106 break; 14107 case OMPD_target_data: 14108 case OMPD_target_enter_data: 14109 case OMPD_target_exit_data: 14110 case OMPD_target_update: 14111 case OMPD_target: 14112 case OMPD_target_simd: 14113 case OMPD_target_teams: 14114 case OMPD_target_teams_distribute: 14115 case OMPD_target_teams_distribute_simd: 14116 case OMPD_cancel: 14117 case OMPD_task: 14118 case OMPD_taskloop: 14119 case OMPD_taskloop_simd: 14120 case OMPD_master_taskloop: 14121 case OMPD_master_taskloop_simd: 14122 case OMPD_threadprivate: 14123 case OMPD_allocate: 14124 case OMPD_taskyield: 14125 case OMPD_barrier: 14126 case OMPD_taskwait: 14127 case OMPD_cancellation_point: 14128 case OMPD_flush: 14129 case OMPD_depobj: 14130 case OMPD_scan: 14131 case OMPD_declare_reduction: 14132 case OMPD_declare_mapper: 14133 case OMPD_declare_simd: 14134 case OMPD_declare_variant: 14135 case OMPD_begin_declare_variant: 14136 case OMPD_end_declare_variant: 14137 case OMPD_declare_target: 14138 case OMPD_end_declare_target: 14139 case OMPD_loop: 14140 case OMPD_teams: 14141 case OMPD_simd: 14142 case OMPD_tile: 14143 case OMPD_unroll: 14144 case OMPD_for: 14145 case OMPD_for_simd: 14146 case OMPD_sections: 14147 case OMPD_section: 14148 case OMPD_single: 14149 case OMPD_master: 14150 case OMPD_masked: 14151 case OMPD_critical: 14152 case OMPD_taskgroup: 14153 case OMPD_distribute: 14154 case OMPD_ordered: 14155 case OMPD_atomic: 14156 case OMPD_distribute_simd: 14157 case OMPD_teams_distribute: 14158 case OMPD_teams_distribute_simd: 14159 case OMPD_requires: 14160 case OMPD_metadirective: 14161 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 14162 case OMPD_unknown: 14163 default: 14164 llvm_unreachable("Unknown OpenMP directive"); 14165 } 14166 break; 14167 case OMPC_num_teams: 14168 switch (DKind) { 14169 case OMPD_target_teams: 14170 case OMPD_target_teams_distribute: 14171 case OMPD_target_teams_distribute_simd: 14172 case OMPD_target_teams_distribute_parallel_for: 14173 case OMPD_target_teams_distribute_parallel_for_simd: 14174 CaptureRegion = OMPD_target; 14175 break; 14176 case OMPD_teams_distribute_parallel_for: 14177 case OMPD_teams_distribute_parallel_for_simd: 14178 case OMPD_teams: 14179 case OMPD_teams_distribute: 14180 case OMPD_teams_distribute_simd: 14181 // Do not capture num_teams-clause expressions. 14182 break; 14183 case OMPD_distribute_parallel_for: 14184 case OMPD_distribute_parallel_for_simd: 14185 case OMPD_task: 14186 case OMPD_taskloop: 14187 case OMPD_taskloop_simd: 14188 case OMPD_master_taskloop: 14189 case OMPD_master_taskloop_simd: 14190 case OMPD_parallel_master_taskloop: 14191 case OMPD_parallel_master_taskloop_simd: 14192 case OMPD_target_data: 14193 case OMPD_target_enter_data: 14194 case OMPD_target_exit_data: 14195 case OMPD_target_update: 14196 case OMPD_cancel: 14197 case OMPD_parallel: 14198 case OMPD_parallel_master: 14199 case OMPD_parallel_sections: 14200 case OMPD_parallel_for: 14201 case OMPD_parallel_for_simd: 14202 case OMPD_target: 14203 case OMPD_target_simd: 14204 case OMPD_target_parallel: 14205 case OMPD_target_parallel_for: 14206 case OMPD_target_parallel_for_simd: 14207 case OMPD_threadprivate: 14208 case OMPD_allocate: 14209 case OMPD_taskyield: 14210 case OMPD_barrier: 14211 case OMPD_taskwait: 14212 case OMPD_cancellation_point: 14213 case OMPD_flush: 14214 case OMPD_depobj: 14215 case OMPD_scan: 14216 case OMPD_declare_reduction: 14217 case OMPD_declare_mapper: 14218 case OMPD_declare_simd: 14219 case OMPD_declare_variant: 14220 case OMPD_begin_declare_variant: 14221 case OMPD_end_declare_variant: 14222 case OMPD_declare_target: 14223 case OMPD_end_declare_target: 14224 case OMPD_loop: 14225 case OMPD_simd: 14226 case OMPD_tile: 14227 case OMPD_unroll: 14228 case OMPD_for: 14229 case OMPD_for_simd: 14230 case OMPD_sections: 14231 case OMPD_section: 14232 case OMPD_single: 14233 case OMPD_master: 14234 case OMPD_masked: 14235 case OMPD_critical: 14236 case OMPD_taskgroup: 14237 case OMPD_distribute: 14238 case OMPD_ordered: 14239 case OMPD_atomic: 14240 case OMPD_distribute_simd: 14241 case OMPD_requires: 14242 case OMPD_metadirective: 14243 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 14244 case OMPD_unknown: 14245 default: 14246 llvm_unreachable("Unknown OpenMP directive"); 14247 } 14248 break; 14249 case OMPC_thread_limit: 14250 switch (DKind) { 14251 case OMPD_target_teams: 14252 case OMPD_target_teams_distribute: 14253 case OMPD_target_teams_distribute_simd: 14254 case OMPD_target_teams_distribute_parallel_for: 14255 case OMPD_target_teams_distribute_parallel_for_simd: 14256 CaptureRegion = OMPD_target; 14257 break; 14258 case OMPD_teams_distribute_parallel_for: 14259 case OMPD_teams_distribute_parallel_for_simd: 14260 case OMPD_teams: 14261 case OMPD_teams_distribute: 14262 case OMPD_teams_distribute_simd: 14263 // Do not capture thread_limit-clause expressions. 14264 break; 14265 case OMPD_distribute_parallel_for: 14266 case OMPD_distribute_parallel_for_simd: 14267 case OMPD_task: 14268 case OMPD_taskloop: 14269 case OMPD_taskloop_simd: 14270 case OMPD_master_taskloop: 14271 case OMPD_master_taskloop_simd: 14272 case OMPD_parallel_master_taskloop: 14273 case OMPD_parallel_master_taskloop_simd: 14274 case OMPD_target_data: 14275 case OMPD_target_enter_data: 14276 case OMPD_target_exit_data: 14277 case OMPD_target_update: 14278 case OMPD_cancel: 14279 case OMPD_parallel: 14280 case OMPD_parallel_master: 14281 case OMPD_parallel_sections: 14282 case OMPD_parallel_for: 14283 case OMPD_parallel_for_simd: 14284 case OMPD_target: 14285 case OMPD_target_simd: 14286 case OMPD_target_parallel: 14287 case OMPD_target_parallel_for: 14288 case OMPD_target_parallel_for_simd: 14289 case OMPD_threadprivate: 14290 case OMPD_allocate: 14291 case OMPD_taskyield: 14292 case OMPD_barrier: 14293 case OMPD_taskwait: 14294 case OMPD_cancellation_point: 14295 case OMPD_flush: 14296 case OMPD_depobj: 14297 case OMPD_scan: 14298 case OMPD_declare_reduction: 14299 case OMPD_declare_mapper: 14300 case OMPD_declare_simd: 14301 case OMPD_declare_variant: 14302 case OMPD_begin_declare_variant: 14303 case OMPD_end_declare_variant: 14304 case OMPD_declare_target: 14305 case OMPD_end_declare_target: 14306 case OMPD_loop: 14307 case OMPD_simd: 14308 case OMPD_tile: 14309 case OMPD_unroll: 14310 case OMPD_for: 14311 case OMPD_for_simd: 14312 case OMPD_sections: 14313 case OMPD_section: 14314 case OMPD_single: 14315 case OMPD_master: 14316 case OMPD_masked: 14317 case OMPD_critical: 14318 case OMPD_taskgroup: 14319 case OMPD_distribute: 14320 case OMPD_ordered: 14321 case OMPD_atomic: 14322 case OMPD_distribute_simd: 14323 case OMPD_requires: 14324 case OMPD_metadirective: 14325 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 14326 case OMPD_unknown: 14327 default: 14328 llvm_unreachable("Unknown OpenMP directive"); 14329 } 14330 break; 14331 case OMPC_schedule: 14332 switch (DKind) { 14333 case OMPD_parallel_for: 14334 case OMPD_parallel_for_simd: 14335 case OMPD_distribute_parallel_for: 14336 case OMPD_distribute_parallel_for_simd: 14337 case OMPD_teams_distribute_parallel_for: 14338 case OMPD_teams_distribute_parallel_for_simd: 14339 case OMPD_target_parallel_for: 14340 case OMPD_target_parallel_for_simd: 14341 case OMPD_target_teams_distribute_parallel_for: 14342 case OMPD_target_teams_distribute_parallel_for_simd: 14343 CaptureRegion = OMPD_parallel; 14344 break; 14345 case OMPD_for: 14346 case OMPD_for_simd: 14347 // Do not capture schedule-clause expressions. 14348 break; 14349 case OMPD_task: 14350 case OMPD_taskloop: 14351 case OMPD_taskloop_simd: 14352 case OMPD_master_taskloop: 14353 case OMPD_master_taskloop_simd: 14354 case OMPD_parallel_master_taskloop: 14355 case OMPD_parallel_master_taskloop_simd: 14356 case OMPD_target_data: 14357 case OMPD_target_enter_data: 14358 case OMPD_target_exit_data: 14359 case OMPD_target_update: 14360 case OMPD_teams: 14361 case OMPD_teams_distribute: 14362 case OMPD_teams_distribute_simd: 14363 case OMPD_target_teams_distribute: 14364 case OMPD_target_teams_distribute_simd: 14365 case OMPD_target: 14366 case OMPD_target_simd: 14367 case OMPD_target_parallel: 14368 case OMPD_cancel: 14369 case OMPD_parallel: 14370 case OMPD_parallel_master: 14371 case OMPD_parallel_sections: 14372 case OMPD_threadprivate: 14373 case OMPD_allocate: 14374 case OMPD_taskyield: 14375 case OMPD_barrier: 14376 case OMPD_taskwait: 14377 case OMPD_cancellation_point: 14378 case OMPD_flush: 14379 case OMPD_depobj: 14380 case OMPD_scan: 14381 case OMPD_declare_reduction: 14382 case OMPD_declare_mapper: 14383 case OMPD_declare_simd: 14384 case OMPD_declare_variant: 14385 case OMPD_begin_declare_variant: 14386 case OMPD_end_declare_variant: 14387 case OMPD_declare_target: 14388 case OMPD_end_declare_target: 14389 case OMPD_loop: 14390 case OMPD_simd: 14391 case OMPD_tile: 14392 case OMPD_unroll: 14393 case OMPD_sections: 14394 case OMPD_section: 14395 case OMPD_single: 14396 case OMPD_master: 14397 case OMPD_masked: 14398 case OMPD_critical: 14399 case OMPD_taskgroup: 14400 case OMPD_distribute: 14401 case OMPD_ordered: 14402 case OMPD_atomic: 14403 case OMPD_distribute_simd: 14404 case OMPD_target_teams: 14405 case OMPD_requires: 14406 case OMPD_metadirective: 14407 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 14408 case OMPD_unknown: 14409 default: 14410 llvm_unreachable("Unknown OpenMP directive"); 14411 } 14412 break; 14413 case OMPC_dist_schedule: 14414 switch (DKind) { 14415 case OMPD_teams_distribute_parallel_for: 14416 case OMPD_teams_distribute_parallel_for_simd: 14417 case OMPD_teams_distribute: 14418 case OMPD_teams_distribute_simd: 14419 case OMPD_target_teams_distribute_parallel_for: 14420 case OMPD_target_teams_distribute_parallel_for_simd: 14421 case OMPD_target_teams_distribute: 14422 case OMPD_target_teams_distribute_simd: 14423 CaptureRegion = OMPD_teams; 14424 break; 14425 case OMPD_distribute_parallel_for: 14426 case OMPD_distribute_parallel_for_simd: 14427 case OMPD_distribute: 14428 case OMPD_distribute_simd: 14429 // Do not capture dist_schedule-clause expressions. 14430 break; 14431 case OMPD_parallel_for: 14432 case OMPD_parallel_for_simd: 14433 case OMPD_target_parallel_for_simd: 14434 case OMPD_target_parallel_for: 14435 case OMPD_task: 14436 case OMPD_taskloop: 14437 case OMPD_taskloop_simd: 14438 case OMPD_master_taskloop: 14439 case OMPD_master_taskloop_simd: 14440 case OMPD_parallel_master_taskloop: 14441 case OMPD_parallel_master_taskloop_simd: 14442 case OMPD_target_data: 14443 case OMPD_target_enter_data: 14444 case OMPD_target_exit_data: 14445 case OMPD_target_update: 14446 case OMPD_teams: 14447 case OMPD_target: 14448 case OMPD_target_simd: 14449 case OMPD_target_parallel: 14450 case OMPD_cancel: 14451 case OMPD_parallel: 14452 case OMPD_parallel_master: 14453 case OMPD_parallel_sections: 14454 case OMPD_threadprivate: 14455 case OMPD_allocate: 14456 case OMPD_taskyield: 14457 case OMPD_barrier: 14458 case OMPD_taskwait: 14459 case OMPD_cancellation_point: 14460 case OMPD_flush: 14461 case OMPD_depobj: 14462 case OMPD_scan: 14463 case OMPD_declare_reduction: 14464 case OMPD_declare_mapper: 14465 case OMPD_declare_simd: 14466 case OMPD_declare_variant: 14467 case OMPD_begin_declare_variant: 14468 case OMPD_end_declare_variant: 14469 case OMPD_declare_target: 14470 case OMPD_end_declare_target: 14471 case OMPD_loop: 14472 case OMPD_simd: 14473 case OMPD_tile: 14474 case OMPD_unroll: 14475 case OMPD_for: 14476 case OMPD_for_simd: 14477 case OMPD_sections: 14478 case OMPD_section: 14479 case OMPD_single: 14480 case OMPD_master: 14481 case OMPD_masked: 14482 case OMPD_critical: 14483 case OMPD_taskgroup: 14484 case OMPD_ordered: 14485 case OMPD_atomic: 14486 case OMPD_target_teams: 14487 case OMPD_requires: 14488 case OMPD_metadirective: 14489 llvm_unreachable("Unexpected OpenMP directive with dist_schedule clause"); 14490 case OMPD_unknown: 14491 default: 14492 llvm_unreachable("Unknown OpenMP directive"); 14493 } 14494 break; 14495 case OMPC_device: 14496 switch (DKind) { 14497 case OMPD_target_update: 14498 case OMPD_target_enter_data: 14499 case OMPD_target_exit_data: 14500 case OMPD_target: 14501 case OMPD_target_simd: 14502 case OMPD_target_teams: 14503 case OMPD_target_parallel: 14504 case OMPD_target_teams_distribute: 14505 case OMPD_target_teams_distribute_simd: 14506 case OMPD_target_parallel_for: 14507 case OMPD_target_parallel_for_simd: 14508 case OMPD_target_teams_distribute_parallel_for: 14509 case OMPD_target_teams_distribute_parallel_for_simd: 14510 case OMPD_dispatch: 14511 CaptureRegion = OMPD_task; 14512 break; 14513 case OMPD_target_data: 14514 case OMPD_interop: 14515 // Do not capture device-clause expressions. 14516 break; 14517 case OMPD_teams_distribute_parallel_for: 14518 case OMPD_teams_distribute_parallel_for_simd: 14519 case OMPD_teams: 14520 case OMPD_teams_distribute: 14521 case OMPD_teams_distribute_simd: 14522 case OMPD_distribute_parallel_for: 14523 case OMPD_distribute_parallel_for_simd: 14524 case OMPD_task: 14525 case OMPD_taskloop: 14526 case OMPD_taskloop_simd: 14527 case OMPD_master_taskloop: 14528 case OMPD_master_taskloop_simd: 14529 case OMPD_parallel_master_taskloop: 14530 case OMPD_parallel_master_taskloop_simd: 14531 case OMPD_cancel: 14532 case OMPD_parallel: 14533 case OMPD_parallel_master: 14534 case OMPD_parallel_sections: 14535 case OMPD_parallel_for: 14536 case OMPD_parallel_for_simd: 14537 case OMPD_threadprivate: 14538 case OMPD_allocate: 14539 case OMPD_taskyield: 14540 case OMPD_barrier: 14541 case OMPD_taskwait: 14542 case OMPD_cancellation_point: 14543 case OMPD_flush: 14544 case OMPD_depobj: 14545 case OMPD_scan: 14546 case OMPD_declare_reduction: 14547 case OMPD_declare_mapper: 14548 case OMPD_declare_simd: 14549 case OMPD_declare_variant: 14550 case OMPD_begin_declare_variant: 14551 case OMPD_end_declare_variant: 14552 case OMPD_declare_target: 14553 case OMPD_end_declare_target: 14554 case OMPD_loop: 14555 case OMPD_simd: 14556 case OMPD_tile: 14557 case OMPD_unroll: 14558 case OMPD_for: 14559 case OMPD_for_simd: 14560 case OMPD_sections: 14561 case OMPD_section: 14562 case OMPD_single: 14563 case OMPD_master: 14564 case OMPD_masked: 14565 case OMPD_critical: 14566 case OMPD_taskgroup: 14567 case OMPD_distribute: 14568 case OMPD_ordered: 14569 case OMPD_atomic: 14570 case OMPD_distribute_simd: 14571 case OMPD_requires: 14572 case OMPD_metadirective: 14573 llvm_unreachable("Unexpected OpenMP directive with device-clause"); 14574 case OMPD_unknown: 14575 default: 14576 llvm_unreachable("Unknown OpenMP directive"); 14577 } 14578 break; 14579 case OMPC_grainsize: 14580 case OMPC_num_tasks: 14581 case OMPC_final: 14582 case OMPC_priority: 14583 switch (DKind) { 14584 case OMPD_task: 14585 case OMPD_taskloop: 14586 case OMPD_taskloop_simd: 14587 case OMPD_master_taskloop: 14588 case OMPD_master_taskloop_simd: 14589 break; 14590 case OMPD_parallel_master_taskloop: 14591 case OMPD_parallel_master_taskloop_simd: 14592 CaptureRegion = OMPD_parallel; 14593 break; 14594 case OMPD_target_update: 14595 case OMPD_target_enter_data: 14596 case OMPD_target_exit_data: 14597 case OMPD_target: 14598 case OMPD_target_simd: 14599 case OMPD_target_teams: 14600 case OMPD_target_parallel: 14601 case OMPD_target_teams_distribute: 14602 case OMPD_target_teams_distribute_simd: 14603 case OMPD_target_parallel_for: 14604 case OMPD_target_parallel_for_simd: 14605 case OMPD_target_teams_distribute_parallel_for: 14606 case OMPD_target_teams_distribute_parallel_for_simd: 14607 case OMPD_target_data: 14608 case OMPD_teams_distribute_parallel_for: 14609 case OMPD_teams_distribute_parallel_for_simd: 14610 case OMPD_teams: 14611 case OMPD_teams_distribute: 14612 case OMPD_teams_distribute_simd: 14613 case OMPD_distribute_parallel_for: 14614 case OMPD_distribute_parallel_for_simd: 14615 case OMPD_cancel: 14616 case OMPD_parallel: 14617 case OMPD_parallel_master: 14618 case OMPD_parallel_sections: 14619 case OMPD_parallel_for: 14620 case OMPD_parallel_for_simd: 14621 case OMPD_threadprivate: 14622 case OMPD_allocate: 14623 case OMPD_taskyield: 14624 case OMPD_barrier: 14625 case OMPD_taskwait: 14626 case OMPD_cancellation_point: 14627 case OMPD_flush: 14628 case OMPD_depobj: 14629 case OMPD_scan: 14630 case OMPD_declare_reduction: 14631 case OMPD_declare_mapper: 14632 case OMPD_declare_simd: 14633 case OMPD_declare_variant: 14634 case OMPD_begin_declare_variant: 14635 case OMPD_end_declare_variant: 14636 case OMPD_declare_target: 14637 case OMPD_end_declare_target: 14638 case OMPD_loop: 14639 case OMPD_simd: 14640 case OMPD_tile: 14641 case OMPD_unroll: 14642 case OMPD_for: 14643 case OMPD_for_simd: 14644 case OMPD_sections: 14645 case OMPD_section: 14646 case OMPD_single: 14647 case OMPD_master: 14648 case OMPD_masked: 14649 case OMPD_critical: 14650 case OMPD_taskgroup: 14651 case OMPD_distribute: 14652 case OMPD_ordered: 14653 case OMPD_atomic: 14654 case OMPD_distribute_simd: 14655 case OMPD_requires: 14656 case OMPD_metadirective: 14657 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause"); 14658 case OMPD_unknown: 14659 default: 14660 llvm_unreachable("Unknown OpenMP directive"); 14661 } 14662 break; 14663 case OMPC_novariants: 14664 case OMPC_nocontext: 14665 switch (DKind) { 14666 case OMPD_dispatch: 14667 CaptureRegion = OMPD_task; 14668 break; 14669 default: 14670 llvm_unreachable("Unexpected OpenMP directive"); 14671 } 14672 break; 14673 case OMPC_filter: 14674 // Do not capture filter-clause expressions. 14675 break; 14676 case OMPC_when: 14677 if (DKind == OMPD_metadirective) { 14678 CaptureRegion = OMPD_metadirective; 14679 } else if (DKind == OMPD_unknown) { 14680 llvm_unreachable("Unknown OpenMP directive"); 14681 } else { 14682 llvm_unreachable("Unexpected OpenMP directive with when clause"); 14683 } 14684 break; 14685 case OMPC_firstprivate: 14686 case OMPC_lastprivate: 14687 case OMPC_reduction: 14688 case OMPC_task_reduction: 14689 case OMPC_in_reduction: 14690 case OMPC_linear: 14691 case OMPC_default: 14692 case OMPC_proc_bind: 14693 case OMPC_safelen: 14694 case OMPC_simdlen: 14695 case OMPC_sizes: 14696 case OMPC_allocator: 14697 case OMPC_collapse: 14698 case OMPC_private: 14699 case OMPC_shared: 14700 case OMPC_aligned: 14701 case OMPC_copyin: 14702 case OMPC_copyprivate: 14703 case OMPC_ordered: 14704 case OMPC_nowait: 14705 case OMPC_untied: 14706 case OMPC_mergeable: 14707 case OMPC_threadprivate: 14708 case OMPC_allocate: 14709 case OMPC_flush: 14710 case OMPC_depobj: 14711 case OMPC_read: 14712 case OMPC_write: 14713 case OMPC_update: 14714 case OMPC_capture: 14715 case OMPC_compare: 14716 case OMPC_seq_cst: 14717 case OMPC_acq_rel: 14718 case OMPC_acquire: 14719 case OMPC_release: 14720 case OMPC_relaxed: 14721 case OMPC_depend: 14722 case OMPC_threads: 14723 case OMPC_simd: 14724 case OMPC_map: 14725 case OMPC_nogroup: 14726 case OMPC_hint: 14727 case OMPC_defaultmap: 14728 case OMPC_unknown: 14729 case OMPC_uniform: 14730 case OMPC_to: 14731 case OMPC_from: 14732 case OMPC_use_device_ptr: 14733 case OMPC_use_device_addr: 14734 case OMPC_is_device_ptr: 14735 case OMPC_unified_address: 14736 case OMPC_unified_shared_memory: 14737 case OMPC_reverse_offload: 14738 case OMPC_dynamic_allocators: 14739 case OMPC_atomic_default_mem_order: 14740 case OMPC_device_type: 14741 case OMPC_match: 14742 case OMPC_nontemporal: 14743 case OMPC_order: 14744 case OMPC_destroy: 14745 case OMPC_detach: 14746 case OMPC_inclusive: 14747 case OMPC_exclusive: 14748 case OMPC_uses_allocators: 14749 case OMPC_affinity: 14750 case OMPC_bind: 14751 default: 14752 llvm_unreachable("Unexpected OpenMP clause."); 14753 } 14754 return CaptureRegion; 14755 } 14756 14757 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 14758 Expr *Condition, SourceLocation StartLoc, 14759 SourceLocation LParenLoc, 14760 SourceLocation NameModifierLoc, 14761 SourceLocation ColonLoc, 14762 SourceLocation EndLoc) { 14763 Expr *ValExpr = Condition; 14764 Stmt *HelperValStmt = nullptr; 14765 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 14766 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 14767 !Condition->isInstantiationDependent() && 14768 !Condition->containsUnexpandedParameterPack()) { 14769 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 14770 if (Val.isInvalid()) 14771 return nullptr; 14772 14773 ValExpr = Val.get(); 14774 14775 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 14776 CaptureRegion = getOpenMPCaptureRegionForClause( 14777 DKind, OMPC_if, LangOpts.OpenMP, NameModifier); 14778 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 14779 ValExpr = MakeFullExpr(ValExpr).get(); 14780 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14781 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 14782 HelperValStmt = buildPreInits(Context, Captures); 14783 } 14784 } 14785 14786 return new (Context) 14787 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 14788 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 14789 } 14790 14791 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 14792 SourceLocation StartLoc, 14793 SourceLocation LParenLoc, 14794 SourceLocation EndLoc) { 14795 Expr *ValExpr = Condition; 14796 Stmt *HelperValStmt = nullptr; 14797 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 14798 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 14799 !Condition->isInstantiationDependent() && 14800 !Condition->containsUnexpandedParameterPack()) { 14801 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 14802 if (Val.isInvalid()) 14803 return nullptr; 14804 14805 ValExpr = MakeFullExpr(Val.get()).get(); 14806 14807 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 14808 CaptureRegion = 14809 getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP); 14810 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 14811 ValExpr = MakeFullExpr(ValExpr).get(); 14812 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14813 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 14814 HelperValStmt = buildPreInits(Context, Captures); 14815 } 14816 } 14817 14818 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion, 14819 StartLoc, LParenLoc, EndLoc); 14820 } 14821 14822 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 14823 Expr *Op) { 14824 if (!Op) 14825 return ExprError(); 14826 14827 class IntConvertDiagnoser : public ICEConvertDiagnoser { 14828 public: 14829 IntConvertDiagnoser() 14830 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 14831 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14832 QualType T) override { 14833 return S.Diag(Loc, diag::err_omp_not_integral) << T; 14834 } 14835 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 14836 QualType T) override { 14837 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 14838 } 14839 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 14840 QualType T, 14841 QualType ConvTy) override { 14842 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 14843 } 14844 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 14845 QualType ConvTy) override { 14846 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 14847 << ConvTy->isEnumeralType() << ConvTy; 14848 } 14849 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 14850 QualType T) override { 14851 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 14852 } 14853 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 14854 QualType ConvTy) override { 14855 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 14856 << ConvTy->isEnumeralType() << ConvTy; 14857 } 14858 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 14859 QualType) override { 14860 llvm_unreachable("conversion functions are permitted"); 14861 } 14862 } ConvertDiagnoser; 14863 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 14864 } 14865 14866 static bool 14867 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind, 14868 bool StrictlyPositive, bool BuildCapture = false, 14869 OpenMPDirectiveKind DKind = OMPD_unknown, 14870 OpenMPDirectiveKind *CaptureRegion = nullptr, 14871 Stmt **HelperValStmt = nullptr) { 14872 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 14873 !ValExpr->isInstantiationDependent()) { 14874 SourceLocation Loc = ValExpr->getExprLoc(); 14875 ExprResult Value = 14876 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 14877 if (Value.isInvalid()) 14878 return false; 14879 14880 ValExpr = Value.get(); 14881 // The expression must evaluate to a non-negative integer value. 14882 if (Optional<llvm::APSInt> Result = 14883 ValExpr->getIntegerConstantExpr(SemaRef.Context)) { 14884 if (Result->isSigned() && 14885 !((!StrictlyPositive && Result->isNonNegative()) || 14886 (StrictlyPositive && Result->isStrictlyPositive()))) { 14887 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 14888 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 14889 << ValExpr->getSourceRange(); 14890 return false; 14891 } 14892 } 14893 if (!BuildCapture) 14894 return true; 14895 *CaptureRegion = 14896 getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP); 14897 if (*CaptureRegion != OMPD_unknown && 14898 !SemaRef.CurContext->isDependentContext()) { 14899 ValExpr = SemaRef.MakeFullExpr(ValExpr).get(); 14900 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14901 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get(); 14902 *HelperValStmt = buildPreInits(SemaRef.Context, Captures); 14903 } 14904 } 14905 return true; 14906 } 14907 14908 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 14909 SourceLocation StartLoc, 14910 SourceLocation LParenLoc, 14911 SourceLocation EndLoc) { 14912 Expr *ValExpr = NumThreads; 14913 Stmt *HelperValStmt = nullptr; 14914 14915 // OpenMP [2.5, Restrictions] 14916 // The num_threads expression must evaluate to a positive integer value. 14917 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 14918 /*StrictlyPositive=*/true)) 14919 return nullptr; 14920 14921 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 14922 OpenMPDirectiveKind CaptureRegion = 14923 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP); 14924 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 14925 ValExpr = MakeFullExpr(ValExpr).get(); 14926 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14927 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 14928 HelperValStmt = buildPreInits(Context, Captures); 14929 } 14930 14931 return new (Context) OMPNumThreadsClause( 14932 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 14933 } 14934 14935 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 14936 OpenMPClauseKind CKind, 14937 bool StrictlyPositive, 14938 bool SuppressExprDiags) { 14939 if (!E) 14940 return ExprError(); 14941 if (E->isValueDependent() || E->isTypeDependent() || 14942 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 14943 return E; 14944 14945 llvm::APSInt Result; 14946 ExprResult ICE; 14947 if (SuppressExprDiags) { 14948 // Use a custom diagnoser that suppresses 'note' diagnostics about the 14949 // expression. 14950 struct SuppressedDiagnoser : public Sema::VerifyICEDiagnoser { 14951 SuppressedDiagnoser() : VerifyICEDiagnoser(/*Suppress=*/true) {} 14952 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 14953 SourceLocation Loc) override { 14954 llvm_unreachable("Diagnostic suppressed"); 14955 } 14956 } Diagnoser; 14957 ICE = VerifyIntegerConstantExpression(E, &Result, Diagnoser, AllowFold); 14958 } else { 14959 ICE = VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold); 14960 } 14961 if (ICE.isInvalid()) 14962 return ExprError(); 14963 14964 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 14965 (!StrictlyPositive && !Result.isNonNegative())) { 14966 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 14967 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 14968 << E->getSourceRange(); 14969 return ExprError(); 14970 } 14971 if ((CKind == OMPC_aligned || CKind == OMPC_align) && !Result.isPowerOf2()) { 14972 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 14973 << E->getSourceRange(); 14974 return ExprError(); 14975 } 14976 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 14977 DSAStack->setAssociatedLoops(Result.getExtValue()); 14978 else if (CKind == OMPC_ordered) 14979 DSAStack->setAssociatedLoops(Result.getExtValue()); 14980 return ICE; 14981 } 14982 14983 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 14984 SourceLocation LParenLoc, 14985 SourceLocation EndLoc) { 14986 // OpenMP [2.8.1, simd construct, Description] 14987 // The parameter of the safelen clause must be a constant 14988 // positive integer expression. 14989 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 14990 if (Safelen.isInvalid()) 14991 return nullptr; 14992 return new (Context) 14993 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 14994 } 14995 14996 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 14997 SourceLocation LParenLoc, 14998 SourceLocation EndLoc) { 14999 // OpenMP [2.8.1, simd construct, Description] 15000 // The parameter of the simdlen clause must be a constant 15001 // positive integer expression. 15002 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 15003 if (Simdlen.isInvalid()) 15004 return nullptr; 15005 return new (Context) 15006 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 15007 } 15008 15009 /// Tries to find omp_allocator_handle_t type. 15010 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc, 15011 DSAStackTy *Stack) { 15012 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT(); 15013 if (!OMPAllocatorHandleT.isNull()) 15014 return true; 15015 // Build the predefined allocator expressions. 15016 bool ErrorFound = false; 15017 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 15018 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 15019 StringRef Allocator = 15020 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind); 15021 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator); 15022 auto *VD = dyn_cast_or_null<ValueDecl>( 15023 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName)); 15024 if (!VD) { 15025 ErrorFound = true; 15026 break; 15027 } 15028 QualType AllocatorType = 15029 VD->getType().getNonLValueExprType(S.getASTContext()); 15030 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc); 15031 if (!Res.isUsable()) { 15032 ErrorFound = true; 15033 break; 15034 } 15035 if (OMPAllocatorHandleT.isNull()) 15036 OMPAllocatorHandleT = AllocatorType; 15037 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) { 15038 ErrorFound = true; 15039 break; 15040 } 15041 Stack->setAllocator(AllocatorKind, Res.get()); 15042 } 15043 if (ErrorFound) { 15044 S.Diag(Loc, diag::err_omp_implied_type_not_found) 15045 << "omp_allocator_handle_t"; 15046 return false; 15047 } 15048 OMPAllocatorHandleT.addConst(); 15049 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT); 15050 return true; 15051 } 15052 15053 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc, 15054 SourceLocation LParenLoc, 15055 SourceLocation EndLoc) { 15056 // OpenMP [2.11.3, allocate Directive, Description] 15057 // allocator is an expression of omp_allocator_handle_t type. 15058 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack)) 15059 return nullptr; 15060 15061 ExprResult Allocator = DefaultLvalueConversion(A); 15062 if (Allocator.isInvalid()) 15063 return nullptr; 15064 Allocator = PerformImplicitConversion(Allocator.get(), 15065 DSAStack->getOMPAllocatorHandleT(), 15066 Sema::AA_Initializing, 15067 /*AllowExplicit=*/true); 15068 if (Allocator.isInvalid()) 15069 return nullptr; 15070 return new (Context) 15071 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc); 15072 } 15073 15074 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 15075 SourceLocation StartLoc, 15076 SourceLocation LParenLoc, 15077 SourceLocation EndLoc) { 15078 // OpenMP [2.7.1, loop construct, Description] 15079 // OpenMP [2.8.1, simd construct, Description] 15080 // OpenMP [2.9.6, distribute construct, Description] 15081 // The parameter of the collapse clause must be a constant 15082 // positive integer expression. 15083 ExprResult NumForLoopsResult = 15084 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 15085 if (NumForLoopsResult.isInvalid()) 15086 return nullptr; 15087 return new (Context) 15088 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 15089 } 15090 15091 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 15092 SourceLocation EndLoc, 15093 SourceLocation LParenLoc, 15094 Expr *NumForLoops) { 15095 // OpenMP [2.7.1, loop construct, Description] 15096 // OpenMP [2.8.1, simd construct, Description] 15097 // OpenMP [2.9.6, distribute construct, Description] 15098 // The parameter of the ordered clause must be a constant 15099 // positive integer expression if any. 15100 if (NumForLoops && LParenLoc.isValid()) { 15101 ExprResult NumForLoopsResult = 15102 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 15103 if (NumForLoopsResult.isInvalid()) 15104 return nullptr; 15105 NumForLoops = NumForLoopsResult.get(); 15106 } else { 15107 NumForLoops = nullptr; 15108 } 15109 auto *Clause = OMPOrderedClause::Create( 15110 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0, 15111 StartLoc, LParenLoc, EndLoc); 15112 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause); 15113 return Clause; 15114 } 15115 15116 OMPClause *Sema::ActOnOpenMPSimpleClause( 15117 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 15118 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 15119 OMPClause *Res = nullptr; 15120 switch (Kind) { 15121 case OMPC_default: 15122 Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument), 15123 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 15124 break; 15125 case OMPC_proc_bind: 15126 Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument), 15127 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 15128 break; 15129 case OMPC_atomic_default_mem_order: 15130 Res = ActOnOpenMPAtomicDefaultMemOrderClause( 15131 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument), 15132 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 15133 break; 15134 case OMPC_order: 15135 Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument), 15136 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 15137 break; 15138 case OMPC_update: 15139 Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument), 15140 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 15141 break; 15142 case OMPC_bind: 15143 Res = ActOnOpenMPBindClause(static_cast<OpenMPBindClauseKind>(Argument), 15144 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 15145 break; 15146 case OMPC_if: 15147 case OMPC_final: 15148 case OMPC_num_threads: 15149 case OMPC_safelen: 15150 case OMPC_simdlen: 15151 case OMPC_sizes: 15152 case OMPC_allocator: 15153 case OMPC_collapse: 15154 case OMPC_schedule: 15155 case OMPC_private: 15156 case OMPC_firstprivate: 15157 case OMPC_lastprivate: 15158 case OMPC_shared: 15159 case OMPC_reduction: 15160 case OMPC_task_reduction: 15161 case OMPC_in_reduction: 15162 case OMPC_linear: 15163 case OMPC_aligned: 15164 case OMPC_copyin: 15165 case OMPC_copyprivate: 15166 case OMPC_ordered: 15167 case OMPC_nowait: 15168 case OMPC_untied: 15169 case OMPC_mergeable: 15170 case OMPC_threadprivate: 15171 case OMPC_allocate: 15172 case OMPC_flush: 15173 case OMPC_depobj: 15174 case OMPC_read: 15175 case OMPC_write: 15176 case OMPC_capture: 15177 case OMPC_compare: 15178 case OMPC_seq_cst: 15179 case OMPC_acq_rel: 15180 case OMPC_acquire: 15181 case OMPC_release: 15182 case OMPC_relaxed: 15183 case OMPC_depend: 15184 case OMPC_device: 15185 case OMPC_threads: 15186 case OMPC_simd: 15187 case OMPC_map: 15188 case OMPC_num_teams: 15189 case OMPC_thread_limit: 15190 case OMPC_priority: 15191 case OMPC_grainsize: 15192 case OMPC_nogroup: 15193 case OMPC_num_tasks: 15194 case OMPC_hint: 15195 case OMPC_dist_schedule: 15196 case OMPC_defaultmap: 15197 case OMPC_unknown: 15198 case OMPC_uniform: 15199 case OMPC_to: 15200 case OMPC_from: 15201 case OMPC_use_device_ptr: 15202 case OMPC_use_device_addr: 15203 case OMPC_is_device_ptr: 15204 case OMPC_unified_address: 15205 case OMPC_unified_shared_memory: 15206 case OMPC_reverse_offload: 15207 case OMPC_dynamic_allocators: 15208 case OMPC_device_type: 15209 case OMPC_match: 15210 case OMPC_nontemporal: 15211 case OMPC_destroy: 15212 case OMPC_novariants: 15213 case OMPC_nocontext: 15214 case OMPC_detach: 15215 case OMPC_inclusive: 15216 case OMPC_exclusive: 15217 case OMPC_uses_allocators: 15218 case OMPC_affinity: 15219 case OMPC_when: 15220 default: 15221 llvm_unreachable("Clause is not allowed."); 15222 } 15223 return Res; 15224 } 15225 15226 static std::string 15227 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 15228 ArrayRef<unsigned> Exclude = llvm::None) { 15229 SmallString<256> Buffer; 15230 llvm::raw_svector_ostream Out(Buffer); 15231 unsigned Skipped = Exclude.size(); 15232 auto S = Exclude.begin(), E = Exclude.end(); 15233 for (unsigned I = First; I < Last; ++I) { 15234 if (std::find(S, E, I) != E) { 15235 --Skipped; 15236 continue; 15237 } 15238 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'"; 15239 if (I + Skipped + 2 == Last) 15240 Out << " or "; 15241 else if (I + Skipped + 1 != Last) 15242 Out << ", "; 15243 } 15244 return std::string(Out.str()); 15245 } 15246 15247 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind, 15248 SourceLocation KindKwLoc, 15249 SourceLocation StartLoc, 15250 SourceLocation LParenLoc, 15251 SourceLocation EndLoc) { 15252 if (Kind == OMP_DEFAULT_unknown) { 15253 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 15254 << getListOfPossibleValues(OMPC_default, /*First=*/0, 15255 /*Last=*/unsigned(OMP_DEFAULT_unknown)) 15256 << getOpenMPClauseName(OMPC_default); 15257 return nullptr; 15258 } 15259 15260 switch (Kind) { 15261 case OMP_DEFAULT_none: 15262 DSAStack->setDefaultDSANone(KindKwLoc); 15263 break; 15264 case OMP_DEFAULT_shared: 15265 DSAStack->setDefaultDSAShared(KindKwLoc); 15266 break; 15267 case OMP_DEFAULT_firstprivate: 15268 DSAStack->setDefaultDSAFirstPrivate(KindKwLoc); 15269 break; 15270 default: 15271 llvm_unreachable("DSA unexpected in OpenMP default clause"); 15272 } 15273 15274 return new (Context) 15275 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 15276 } 15277 15278 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind, 15279 SourceLocation KindKwLoc, 15280 SourceLocation StartLoc, 15281 SourceLocation LParenLoc, 15282 SourceLocation EndLoc) { 15283 if (Kind == OMP_PROC_BIND_unknown) { 15284 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 15285 << getListOfPossibleValues(OMPC_proc_bind, 15286 /*First=*/unsigned(OMP_PROC_BIND_master), 15287 /*Last=*/ 15288 unsigned(LangOpts.OpenMP > 50 15289 ? OMP_PROC_BIND_primary 15290 : OMP_PROC_BIND_spread) + 15291 1) 15292 << getOpenMPClauseName(OMPC_proc_bind); 15293 return nullptr; 15294 } 15295 if (Kind == OMP_PROC_BIND_primary && LangOpts.OpenMP < 51) 15296 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 15297 << getListOfPossibleValues(OMPC_proc_bind, 15298 /*First=*/unsigned(OMP_PROC_BIND_master), 15299 /*Last=*/ 15300 unsigned(OMP_PROC_BIND_spread) + 1) 15301 << getOpenMPClauseName(OMPC_proc_bind); 15302 return new (Context) 15303 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 15304 } 15305 15306 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause( 15307 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc, 15308 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 15309 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) { 15310 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 15311 << getListOfPossibleValues( 15312 OMPC_atomic_default_mem_order, /*First=*/0, 15313 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) 15314 << getOpenMPClauseName(OMPC_atomic_default_mem_order); 15315 return nullptr; 15316 } 15317 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc, 15318 LParenLoc, EndLoc); 15319 } 15320 15321 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, 15322 SourceLocation KindKwLoc, 15323 SourceLocation StartLoc, 15324 SourceLocation LParenLoc, 15325 SourceLocation EndLoc) { 15326 if (Kind == OMPC_ORDER_unknown) { 15327 static_assert(OMPC_ORDER_unknown > 0, 15328 "OMPC_ORDER_unknown not greater than 0"); 15329 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 15330 << getListOfPossibleValues(OMPC_order, /*First=*/0, 15331 /*Last=*/OMPC_ORDER_unknown) 15332 << getOpenMPClauseName(OMPC_order); 15333 return nullptr; 15334 } 15335 return new (Context) 15336 OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 15337 } 15338 15339 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, 15340 SourceLocation KindKwLoc, 15341 SourceLocation StartLoc, 15342 SourceLocation LParenLoc, 15343 SourceLocation EndLoc) { 15344 if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source || 15345 Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) { 15346 SmallVector<unsigned> Except = {OMPC_DEPEND_source, OMPC_DEPEND_sink, 15347 OMPC_DEPEND_depobj}; 15348 if (LangOpts.OpenMP < 51) 15349 Except.push_back(OMPC_DEPEND_inoutset); 15350 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 15351 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 15352 /*Last=*/OMPC_DEPEND_unknown, Except) 15353 << getOpenMPClauseName(OMPC_update); 15354 return nullptr; 15355 } 15356 return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind, 15357 EndLoc); 15358 } 15359 15360 OMPClause *Sema::ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs, 15361 SourceLocation StartLoc, 15362 SourceLocation LParenLoc, 15363 SourceLocation EndLoc) { 15364 for (Expr *SizeExpr : SizeExprs) { 15365 ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause( 15366 SizeExpr, OMPC_sizes, /*StrictlyPositive=*/true); 15367 if (!NumForLoopsResult.isUsable()) 15368 return nullptr; 15369 } 15370 15371 DSAStack->setAssociatedLoops(SizeExprs.size()); 15372 return OMPSizesClause::Create(Context, StartLoc, LParenLoc, EndLoc, 15373 SizeExprs); 15374 } 15375 15376 OMPClause *Sema::ActOnOpenMPFullClause(SourceLocation StartLoc, 15377 SourceLocation EndLoc) { 15378 return OMPFullClause::Create(Context, StartLoc, EndLoc); 15379 } 15380 15381 OMPClause *Sema::ActOnOpenMPPartialClause(Expr *FactorExpr, 15382 SourceLocation StartLoc, 15383 SourceLocation LParenLoc, 15384 SourceLocation EndLoc) { 15385 if (FactorExpr) { 15386 // If an argument is specified, it must be a constant (or an unevaluated 15387 // template expression). 15388 ExprResult FactorResult = VerifyPositiveIntegerConstantInClause( 15389 FactorExpr, OMPC_partial, /*StrictlyPositive=*/true); 15390 if (FactorResult.isInvalid()) 15391 return nullptr; 15392 FactorExpr = FactorResult.get(); 15393 } 15394 15395 return OMPPartialClause::Create(Context, StartLoc, LParenLoc, EndLoc, 15396 FactorExpr); 15397 } 15398 15399 OMPClause *Sema::ActOnOpenMPAlignClause(Expr *A, SourceLocation StartLoc, 15400 SourceLocation LParenLoc, 15401 SourceLocation EndLoc) { 15402 ExprResult AlignVal; 15403 AlignVal = VerifyPositiveIntegerConstantInClause(A, OMPC_align); 15404 if (AlignVal.isInvalid()) 15405 return nullptr; 15406 return OMPAlignClause::Create(Context, AlignVal.get(), StartLoc, LParenLoc, 15407 EndLoc); 15408 } 15409 15410 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 15411 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 15412 SourceLocation StartLoc, SourceLocation LParenLoc, 15413 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 15414 SourceLocation EndLoc) { 15415 OMPClause *Res = nullptr; 15416 switch (Kind) { 15417 case OMPC_schedule: 15418 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 15419 assert(Argument.size() == NumberOfElements && 15420 ArgumentLoc.size() == NumberOfElements); 15421 Res = ActOnOpenMPScheduleClause( 15422 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 15423 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 15424 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 15425 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 15426 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 15427 break; 15428 case OMPC_if: 15429 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 15430 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 15431 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 15432 DelimLoc, EndLoc); 15433 break; 15434 case OMPC_dist_schedule: 15435 Res = ActOnOpenMPDistScheduleClause( 15436 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 15437 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 15438 break; 15439 case OMPC_defaultmap: 15440 enum { Modifier, DefaultmapKind }; 15441 Res = ActOnOpenMPDefaultmapClause( 15442 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 15443 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 15444 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 15445 EndLoc); 15446 break; 15447 case OMPC_device: 15448 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 15449 Res = ActOnOpenMPDeviceClause( 15450 static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr, 15451 StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc); 15452 break; 15453 case OMPC_final: 15454 case OMPC_num_threads: 15455 case OMPC_safelen: 15456 case OMPC_simdlen: 15457 case OMPC_sizes: 15458 case OMPC_allocator: 15459 case OMPC_collapse: 15460 case OMPC_default: 15461 case OMPC_proc_bind: 15462 case OMPC_private: 15463 case OMPC_firstprivate: 15464 case OMPC_lastprivate: 15465 case OMPC_shared: 15466 case OMPC_reduction: 15467 case OMPC_task_reduction: 15468 case OMPC_in_reduction: 15469 case OMPC_linear: 15470 case OMPC_aligned: 15471 case OMPC_copyin: 15472 case OMPC_copyprivate: 15473 case OMPC_ordered: 15474 case OMPC_nowait: 15475 case OMPC_untied: 15476 case OMPC_mergeable: 15477 case OMPC_threadprivate: 15478 case OMPC_allocate: 15479 case OMPC_flush: 15480 case OMPC_depobj: 15481 case OMPC_read: 15482 case OMPC_write: 15483 case OMPC_update: 15484 case OMPC_capture: 15485 case OMPC_compare: 15486 case OMPC_seq_cst: 15487 case OMPC_acq_rel: 15488 case OMPC_acquire: 15489 case OMPC_release: 15490 case OMPC_relaxed: 15491 case OMPC_depend: 15492 case OMPC_threads: 15493 case OMPC_simd: 15494 case OMPC_map: 15495 case OMPC_num_teams: 15496 case OMPC_thread_limit: 15497 case OMPC_priority: 15498 case OMPC_grainsize: 15499 case OMPC_nogroup: 15500 case OMPC_num_tasks: 15501 case OMPC_hint: 15502 case OMPC_unknown: 15503 case OMPC_uniform: 15504 case OMPC_to: 15505 case OMPC_from: 15506 case OMPC_use_device_ptr: 15507 case OMPC_use_device_addr: 15508 case OMPC_is_device_ptr: 15509 case OMPC_unified_address: 15510 case OMPC_unified_shared_memory: 15511 case OMPC_reverse_offload: 15512 case OMPC_dynamic_allocators: 15513 case OMPC_atomic_default_mem_order: 15514 case OMPC_device_type: 15515 case OMPC_match: 15516 case OMPC_nontemporal: 15517 case OMPC_order: 15518 case OMPC_destroy: 15519 case OMPC_novariants: 15520 case OMPC_nocontext: 15521 case OMPC_detach: 15522 case OMPC_inclusive: 15523 case OMPC_exclusive: 15524 case OMPC_uses_allocators: 15525 case OMPC_affinity: 15526 case OMPC_when: 15527 case OMPC_bind: 15528 default: 15529 llvm_unreachable("Clause is not allowed."); 15530 } 15531 return Res; 15532 } 15533 15534 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 15535 OpenMPScheduleClauseModifier M2, 15536 SourceLocation M1Loc, SourceLocation M2Loc) { 15537 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 15538 SmallVector<unsigned, 2> Excluded; 15539 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 15540 Excluded.push_back(M2); 15541 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 15542 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 15543 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 15544 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 15545 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 15546 << getListOfPossibleValues(OMPC_schedule, 15547 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 15548 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 15549 Excluded) 15550 << getOpenMPClauseName(OMPC_schedule); 15551 return true; 15552 } 15553 return false; 15554 } 15555 15556 OMPClause *Sema::ActOnOpenMPScheduleClause( 15557 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 15558 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 15559 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 15560 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 15561 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 15562 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 15563 return nullptr; 15564 // OpenMP, 2.7.1, Loop Construct, Restrictions 15565 // Either the monotonic modifier or the nonmonotonic modifier can be specified 15566 // but not both. 15567 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 15568 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 15569 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 15570 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 15571 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 15572 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 15573 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 15574 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 15575 return nullptr; 15576 } 15577 if (Kind == OMPC_SCHEDULE_unknown) { 15578 std::string Values; 15579 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 15580 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 15581 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 15582 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 15583 Exclude); 15584 } else { 15585 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 15586 /*Last=*/OMPC_SCHEDULE_unknown); 15587 } 15588 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 15589 << Values << getOpenMPClauseName(OMPC_schedule); 15590 return nullptr; 15591 } 15592 // OpenMP, 2.7.1, Loop Construct, Restrictions 15593 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 15594 // schedule(guided). 15595 // OpenMP 5.0 does not have this restriction. 15596 if (LangOpts.OpenMP < 50 && 15597 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 15598 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 15599 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 15600 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 15601 diag::err_omp_schedule_nonmonotonic_static); 15602 return nullptr; 15603 } 15604 Expr *ValExpr = ChunkSize; 15605 Stmt *HelperValStmt = nullptr; 15606 if (ChunkSize) { 15607 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 15608 !ChunkSize->isInstantiationDependent() && 15609 !ChunkSize->containsUnexpandedParameterPack()) { 15610 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 15611 ExprResult Val = 15612 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 15613 if (Val.isInvalid()) 15614 return nullptr; 15615 15616 ValExpr = Val.get(); 15617 15618 // OpenMP [2.7.1, Restrictions] 15619 // chunk_size must be a loop invariant integer expression with a positive 15620 // value. 15621 if (Optional<llvm::APSInt> Result = 15622 ValExpr->getIntegerConstantExpr(Context)) { 15623 if (Result->isSigned() && !Result->isStrictlyPositive()) { 15624 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 15625 << "schedule" << 1 << ChunkSize->getSourceRange(); 15626 return nullptr; 15627 } 15628 } else if (getOpenMPCaptureRegionForClause( 15629 DSAStack->getCurrentDirective(), OMPC_schedule, 15630 LangOpts.OpenMP) != OMPD_unknown && 15631 !CurContext->isDependentContext()) { 15632 ValExpr = MakeFullExpr(ValExpr).get(); 15633 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 15634 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 15635 HelperValStmt = buildPreInits(Context, Captures); 15636 } 15637 } 15638 } 15639 15640 return new (Context) 15641 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 15642 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 15643 } 15644 15645 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 15646 SourceLocation StartLoc, 15647 SourceLocation EndLoc) { 15648 OMPClause *Res = nullptr; 15649 switch (Kind) { 15650 case OMPC_ordered: 15651 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 15652 break; 15653 case OMPC_nowait: 15654 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 15655 break; 15656 case OMPC_untied: 15657 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 15658 break; 15659 case OMPC_mergeable: 15660 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 15661 break; 15662 case OMPC_read: 15663 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 15664 break; 15665 case OMPC_write: 15666 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 15667 break; 15668 case OMPC_update: 15669 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 15670 break; 15671 case OMPC_capture: 15672 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 15673 break; 15674 case OMPC_compare: 15675 Res = ActOnOpenMPCompareClause(StartLoc, EndLoc); 15676 break; 15677 case OMPC_seq_cst: 15678 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 15679 break; 15680 case OMPC_acq_rel: 15681 Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc); 15682 break; 15683 case OMPC_acquire: 15684 Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc); 15685 break; 15686 case OMPC_release: 15687 Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc); 15688 break; 15689 case OMPC_relaxed: 15690 Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc); 15691 break; 15692 case OMPC_threads: 15693 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 15694 break; 15695 case OMPC_simd: 15696 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 15697 break; 15698 case OMPC_nogroup: 15699 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 15700 break; 15701 case OMPC_unified_address: 15702 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc); 15703 break; 15704 case OMPC_unified_shared_memory: 15705 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 15706 break; 15707 case OMPC_reverse_offload: 15708 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc); 15709 break; 15710 case OMPC_dynamic_allocators: 15711 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc); 15712 break; 15713 case OMPC_destroy: 15714 Res = ActOnOpenMPDestroyClause(/*InteropVar=*/nullptr, StartLoc, 15715 /*LParenLoc=*/SourceLocation(), 15716 /*VarLoc=*/SourceLocation(), EndLoc); 15717 break; 15718 case OMPC_full: 15719 Res = ActOnOpenMPFullClause(StartLoc, EndLoc); 15720 break; 15721 case OMPC_partial: 15722 Res = ActOnOpenMPPartialClause(nullptr, StartLoc, /*LParenLoc=*/{}, EndLoc); 15723 break; 15724 case OMPC_if: 15725 case OMPC_final: 15726 case OMPC_num_threads: 15727 case OMPC_safelen: 15728 case OMPC_simdlen: 15729 case OMPC_sizes: 15730 case OMPC_allocator: 15731 case OMPC_collapse: 15732 case OMPC_schedule: 15733 case OMPC_private: 15734 case OMPC_firstprivate: 15735 case OMPC_lastprivate: 15736 case OMPC_shared: 15737 case OMPC_reduction: 15738 case OMPC_task_reduction: 15739 case OMPC_in_reduction: 15740 case OMPC_linear: 15741 case OMPC_aligned: 15742 case OMPC_copyin: 15743 case OMPC_copyprivate: 15744 case OMPC_default: 15745 case OMPC_proc_bind: 15746 case OMPC_threadprivate: 15747 case OMPC_allocate: 15748 case OMPC_flush: 15749 case OMPC_depobj: 15750 case OMPC_depend: 15751 case OMPC_device: 15752 case OMPC_map: 15753 case OMPC_num_teams: 15754 case OMPC_thread_limit: 15755 case OMPC_priority: 15756 case OMPC_grainsize: 15757 case OMPC_num_tasks: 15758 case OMPC_hint: 15759 case OMPC_dist_schedule: 15760 case OMPC_defaultmap: 15761 case OMPC_unknown: 15762 case OMPC_uniform: 15763 case OMPC_to: 15764 case OMPC_from: 15765 case OMPC_use_device_ptr: 15766 case OMPC_use_device_addr: 15767 case OMPC_is_device_ptr: 15768 case OMPC_atomic_default_mem_order: 15769 case OMPC_device_type: 15770 case OMPC_match: 15771 case OMPC_nontemporal: 15772 case OMPC_order: 15773 case OMPC_novariants: 15774 case OMPC_nocontext: 15775 case OMPC_detach: 15776 case OMPC_inclusive: 15777 case OMPC_exclusive: 15778 case OMPC_uses_allocators: 15779 case OMPC_affinity: 15780 case OMPC_when: 15781 default: 15782 llvm_unreachable("Clause is not allowed."); 15783 } 15784 return Res; 15785 } 15786 15787 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 15788 SourceLocation EndLoc) { 15789 DSAStack->setNowaitRegion(); 15790 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 15791 } 15792 15793 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 15794 SourceLocation EndLoc) { 15795 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 15796 } 15797 15798 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 15799 SourceLocation EndLoc) { 15800 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 15801 } 15802 15803 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 15804 SourceLocation EndLoc) { 15805 return new (Context) OMPReadClause(StartLoc, EndLoc); 15806 } 15807 15808 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 15809 SourceLocation EndLoc) { 15810 return new (Context) OMPWriteClause(StartLoc, EndLoc); 15811 } 15812 15813 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 15814 SourceLocation EndLoc) { 15815 return OMPUpdateClause::Create(Context, StartLoc, EndLoc); 15816 } 15817 15818 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 15819 SourceLocation EndLoc) { 15820 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 15821 } 15822 15823 OMPClause *Sema::ActOnOpenMPCompareClause(SourceLocation StartLoc, 15824 SourceLocation EndLoc) { 15825 return new (Context) OMPCompareClause(StartLoc, EndLoc); 15826 } 15827 15828 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 15829 SourceLocation EndLoc) { 15830 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 15831 } 15832 15833 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc, 15834 SourceLocation EndLoc) { 15835 return new (Context) OMPAcqRelClause(StartLoc, EndLoc); 15836 } 15837 15838 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc, 15839 SourceLocation EndLoc) { 15840 return new (Context) OMPAcquireClause(StartLoc, EndLoc); 15841 } 15842 15843 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc, 15844 SourceLocation EndLoc) { 15845 return new (Context) OMPReleaseClause(StartLoc, EndLoc); 15846 } 15847 15848 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc, 15849 SourceLocation EndLoc) { 15850 return new (Context) OMPRelaxedClause(StartLoc, EndLoc); 15851 } 15852 15853 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 15854 SourceLocation EndLoc) { 15855 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 15856 } 15857 15858 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 15859 SourceLocation EndLoc) { 15860 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 15861 } 15862 15863 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 15864 SourceLocation EndLoc) { 15865 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 15866 } 15867 15868 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, 15869 SourceLocation EndLoc) { 15870 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc); 15871 } 15872 15873 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, 15874 SourceLocation EndLoc) { 15875 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 15876 } 15877 15878 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, 15879 SourceLocation EndLoc) { 15880 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc); 15881 } 15882 15883 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, 15884 SourceLocation EndLoc) { 15885 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc); 15886 } 15887 15888 StmtResult Sema::ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses, 15889 SourceLocation StartLoc, 15890 SourceLocation EndLoc) { 15891 15892 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 15893 // At least one action-clause must appear on a directive. 15894 if (!hasClauses(Clauses, OMPC_init, OMPC_use, OMPC_destroy, OMPC_nowait)) { 15895 StringRef Expected = "'init', 'use', 'destroy', or 'nowait'"; 15896 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 15897 << Expected << getOpenMPDirectiveName(OMPD_interop); 15898 return StmtError(); 15899 } 15900 15901 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 15902 // A depend clause can only appear on the directive if a targetsync 15903 // interop-type is present or the interop-var was initialized with 15904 // the targetsync interop-type. 15905 15906 // If there is any 'init' clause diagnose if there is no 'init' clause with 15907 // interop-type of 'targetsync'. Cases involving other directives cannot be 15908 // diagnosed. 15909 const OMPDependClause *DependClause = nullptr; 15910 bool HasInitClause = false; 15911 bool IsTargetSync = false; 15912 for (const OMPClause *C : Clauses) { 15913 if (IsTargetSync) 15914 break; 15915 if (const auto *InitClause = dyn_cast<OMPInitClause>(C)) { 15916 HasInitClause = true; 15917 if (InitClause->getIsTargetSync()) 15918 IsTargetSync = true; 15919 } else if (const auto *DC = dyn_cast<OMPDependClause>(C)) { 15920 DependClause = DC; 15921 } 15922 } 15923 if (DependClause && HasInitClause && !IsTargetSync) { 15924 Diag(DependClause->getBeginLoc(), diag::err_omp_interop_bad_depend_clause); 15925 return StmtError(); 15926 } 15927 15928 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 15929 // Each interop-var may be specified for at most one action-clause of each 15930 // interop construct. 15931 llvm::SmallPtrSet<const VarDecl *, 4> InteropVars; 15932 for (const OMPClause *C : Clauses) { 15933 OpenMPClauseKind ClauseKind = C->getClauseKind(); 15934 const DeclRefExpr *DRE = nullptr; 15935 SourceLocation VarLoc; 15936 15937 if (ClauseKind == OMPC_init) { 15938 const auto *IC = cast<OMPInitClause>(C); 15939 VarLoc = IC->getVarLoc(); 15940 DRE = dyn_cast_or_null<DeclRefExpr>(IC->getInteropVar()); 15941 } else if (ClauseKind == OMPC_use) { 15942 const auto *UC = cast<OMPUseClause>(C); 15943 VarLoc = UC->getVarLoc(); 15944 DRE = dyn_cast_or_null<DeclRefExpr>(UC->getInteropVar()); 15945 } else if (ClauseKind == OMPC_destroy) { 15946 const auto *DC = cast<OMPDestroyClause>(C); 15947 VarLoc = DC->getVarLoc(); 15948 DRE = dyn_cast_or_null<DeclRefExpr>(DC->getInteropVar()); 15949 } 15950 15951 if (!DRE) 15952 continue; 15953 15954 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 15955 if (!InteropVars.insert(VD->getCanonicalDecl()).second) { 15956 Diag(VarLoc, diag::err_omp_interop_var_multiple_actions) << VD; 15957 return StmtError(); 15958 } 15959 } 15960 } 15961 15962 return OMPInteropDirective::Create(Context, StartLoc, EndLoc, Clauses); 15963 } 15964 15965 static bool isValidInteropVariable(Sema &SemaRef, Expr *InteropVarExpr, 15966 SourceLocation VarLoc, 15967 OpenMPClauseKind Kind) { 15968 if (InteropVarExpr->isValueDependent() || InteropVarExpr->isTypeDependent() || 15969 InteropVarExpr->isInstantiationDependent() || 15970 InteropVarExpr->containsUnexpandedParameterPack()) 15971 return true; 15972 15973 const auto *DRE = dyn_cast<DeclRefExpr>(InteropVarExpr); 15974 if (!DRE || !isa<VarDecl>(DRE->getDecl())) { 15975 SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) << 0; 15976 return false; 15977 } 15978 15979 // Interop variable should be of type omp_interop_t. 15980 bool HasError = false; 15981 QualType InteropType; 15982 LookupResult Result(SemaRef, &SemaRef.Context.Idents.get("omp_interop_t"), 15983 VarLoc, Sema::LookupOrdinaryName); 15984 if (SemaRef.LookupName(Result, SemaRef.getCurScope())) { 15985 NamedDecl *ND = Result.getFoundDecl(); 15986 if (const auto *TD = dyn_cast<TypeDecl>(ND)) { 15987 InteropType = QualType(TD->getTypeForDecl(), 0); 15988 } else { 15989 HasError = true; 15990 } 15991 } else { 15992 HasError = true; 15993 } 15994 15995 if (HasError) { 15996 SemaRef.Diag(VarLoc, diag::err_omp_implied_type_not_found) 15997 << "omp_interop_t"; 15998 return false; 15999 } 16000 16001 QualType VarType = InteropVarExpr->getType().getUnqualifiedType(); 16002 if (!SemaRef.Context.hasSameType(InteropType, VarType)) { 16003 SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_wrong_type); 16004 return false; 16005 } 16006 16007 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 16008 // The interop-var passed to init or destroy must be non-const. 16009 if ((Kind == OMPC_init || Kind == OMPC_destroy) && 16010 isConstNotMutableType(SemaRef, InteropVarExpr->getType())) { 16011 SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) 16012 << /*non-const*/ 1; 16013 return false; 16014 } 16015 return true; 16016 } 16017 16018 OMPClause * 16019 Sema::ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs, 16020 bool IsTarget, bool IsTargetSync, 16021 SourceLocation StartLoc, SourceLocation LParenLoc, 16022 SourceLocation VarLoc, SourceLocation EndLoc) { 16023 16024 if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_init)) 16025 return nullptr; 16026 16027 // Check prefer_type values. These foreign-runtime-id values are either 16028 // string literals or constant integral expressions. 16029 for (const Expr *E : PrefExprs) { 16030 if (E->isValueDependent() || E->isTypeDependent() || 16031 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 16032 continue; 16033 if (E->isIntegerConstantExpr(Context)) 16034 continue; 16035 if (isa<StringLiteral>(E)) 16036 continue; 16037 Diag(E->getExprLoc(), diag::err_omp_interop_prefer_type); 16038 return nullptr; 16039 } 16040 16041 return OMPInitClause::Create(Context, InteropVar, PrefExprs, IsTarget, 16042 IsTargetSync, StartLoc, LParenLoc, VarLoc, 16043 EndLoc); 16044 } 16045 16046 OMPClause *Sema::ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc, 16047 SourceLocation LParenLoc, 16048 SourceLocation VarLoc, 16049 SourceLocation EndLoc) { 16050 16051 if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_use)) 16052 return nullptr; 16053 16054 return new (Context) 16055 OMPUseClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc); 16056 } 16057 16058 OMPClause *Sema::ActOnOpenMPDestroyClause(Expr *InteropVar, 16059 SourceLocation StartLoc, 16060 SourceLocation LParenLoc, 16061 SourceLocation VarLoc, 16062 SourceLocation EndLoc) { 16063 if (InteropVar && 16064 !isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_destroy)) 16065 return nullptr; 16066 16067 return new (Context) 16068 OMPDestroyClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc); 16069 } 16070 16071 OMPClause *Sema::ActOnOpenMPNovariantsClause(Expr *Condition, 16072 SourceLocation StartLoc, 16073 SourceLocation LParenLoc, 16074 SourceLocation EndLoc) { 16075 Expr *ValExpr = Condition; 16076 Stmt *HelperValStmt = nullptr; 16077 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 16078 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 16079 !Condition->isInstantiationDependent() && 16080 !Condition->containsUnexpandedParameterPack()) { 16081 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 16082 if (Val.isInvalid()) 16083 return nullptr; 16084 16085 ValExpr = MakeFullExpr(Val.get()).get(); 16086 16087 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 16088 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_novariants, 16089 LangOpts.OpenMP); 16090 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 16091 ValExpr = MakeFullExpr(ValExpr).get(); 16092 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 16093 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 16094 HelperValStmt = buildPreInits(Context, Captures); 16095 } 16096 } 16097 16098 return new (Context) OMPNovariantsClause( 16099 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 16100 } 16101 16102 OMPClause *Sema::ActOnOpenMPNocontextClause(Expr *Condition, 16103 SourceLocation StartLoc, 16104 SourceLocation LParenLoc, 16105 SourceLocation EndLoc) { 16106 Expr *ValExpr = Condition; 16107 Stmt *HelperValStmt = nullptr; 16108 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 16109 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 16110 !Condition->isInstantiationDependent() && 16111 !Condition->containsUnexpandedParameterPack()) { 16112 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 16113 if (Val.isInvalid()) 16114 return nullptr; 16115 16116 ValExpr = MakeFullExpr(Val.get()).get(); 16117 16118 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 16119 CaptureRegion = 16120 getOpenMPCaptureRegionForClause(DKind, OMPC_nocontext, LangOpts.OpenMP); 16121 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 16122 ValExpr = MakeFullExpr(ValExpr).get(); 16123 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 16124 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 16125 HelperValStmt = buildPreInits(Context, Captures); 16126 } 16127 } 16128 16129 return new (Context) OMPNocontextClause(ValExpr, HelperValStmt, CaptureRegion, 16130 StartLoc, LParenLoc, EndLoc); 16131 } 16132 16133 OMPClause *Sema::ActOnOpenMPFilterClause(Expr *ThreadID, 16134 SourceLocation StartLoc, 16135 SourceLocation LParenLoc, 16136 SourceLocation EndLoc) { 16137 Expr *ValExpr = ThreadID; 16138 Stmt *HelperValStmt = nullptr; 16139 16140 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 16141 OpenMPDirectiveKind CaptureRegion = 16142 getOpenMPCaptureRegionForClause(DKind, OMPC_filter, LangOpts.OpenMP); 16143 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 16144 ValExpr = MakeFullExpr(ValExpr).get(); 16145 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 16146 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 16147 HelperValStmt = buildPreInits(Context, Captures); 16148 } 16149 16150 return new (Context) OMPFilterClause(ValExpr, HelperValStmt, CaptureRegion, 16151 StartLoc, LParenLoc, EndLoc); 16152 } 16153 16154 OMPClause *Sema::ActOnOpenMPVarListClause( 16155 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr, 16156 const OMPVarListLocTy &Locs, SourceLocation ColonLoc, 16157 CXXScopeSpec &ReductionOrMapperIdScopeSpec, 16158 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, 16159 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 16160 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, 16161 SourceLocation ExtraModifierLoc, 16162 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 16163 ArrayRef<SourceLocation> MotionModifiersLoc) { 16164 SourceLocation StartLoc = Locs.StartLoc; 16165 SourceLocation LParenLoc = Locs.LParenLoc; 16166 SourceLocation EndLoc = Locs.EndLoc; 16167 OMPClause *Res = nullptr; 16168 switch (Kind) { 16169 case OMPC_private: 16170 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 16171 break; 16172 case OMPC_firstprivate: 16173 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 16174 break; 16175 case OMPC_lastprivate: 16176 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown && 16177 "Unexpected lastprivate modifier."); 16178 Res = ActOnOpenMPLastprivateClause( 16179 VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier), 16180 ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc); 16181 break; 16182 case OMPC_shared: 16183 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 16184 break; 16185 case OMPC_reduction: 16186 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown && 16187 "Unexpected lastprivate modifier."); 16188 Res = ActOnOpenMPReductionClause( 16189 VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier), 16190 StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc, 16191 ReductionOrMapperIdScopeSpec, ReductionOrMapperId); 16192 break; 16193 case OMPC_task_reduction: 16194 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 16195 EndLoc, ReductionOrMapperIdScopeSpec, 16196 ReductionOrMapperId); 16197 break; 16198 case OMPC_in_reduction: 16199 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 16200 EndLoc, ReductionOrMapperIdScopeSpec, 16201 ReductionOrMapperId); 16202 break; 16203 case OMPC_linear: 16204 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown && 16205 "Unexpected linear modifier."); 16206 Res = ActOnOpenMPLinearClause( 16207 VarList, DepModOrTailExpr, StartLoc, LParenLoc, 16208 static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc, 16209 ColonLoc, EndLoc); 16210 break; 16211 case OMPC_aligned: 16212 Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc, 16213 LParenLoc, ColonLoc, EndLoc); 16214 break; 16215 case OMPC_copyin: 16216 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 16217 break; 16218 case OMPC_copyprivate: 16219 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 16220 break; 16221 case OMPC_flush: 16222 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 16223 break; 16224 case OMPC_depend: 16225 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown && 16226 "Unexpected depend modifier."); 16227 Res = ActOnOpenMPDependClause( 16228 DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier), 16229 ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc); 16230 break; 16231 case OMPC_map: 16232 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown && 16233 "Unexpected map modifier."); 16234 Res = ActOnOpenMPMapClause( 16235 MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec, 16236 ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier), 16237 IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs); 16238 break; 16239 case OMPC_to: 16240 Res = ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc, 16241 ReductionOrMapperIdScopeSpec, ReductionOrMapperId, 16242 ColonLoc, VarList, Locs); 16243 break; 16244 case OMPC_from: 16245 Res = ActOnOpenMPFromClause(MotionModifiers, MotionModifiersLoc, 16246 ReductionOrMapperIdScopeSpec, 16247 ReductionOrMapperId, ColonLoc, VarList, Locs); 16248 break; 16249 case OMPC_use_device_ptr: 16250 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs); 16251 break; 16252 case OMPC_use_device_addr: 16253 Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs); 16254 break; 16255 case OMPC_is_device_ptr: 16256 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs); 16257 break; 16258 case OMPC_allocate: 16259 Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc, 16260 LParenLoc, ColonLoc, EndLoc); 16261 break; 16262 case OMPC_nontemporal: 16263 Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc); 16264 break; 16265 case OMPC_inclusive: 16266 Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc); 16267 break; 16268 case OMPC_exclusive: 16269 Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc); 16270 break; 16271 case OMPC_affinity: 16272 Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc, 16273 DepModOrTailExpr, VarList); 16274 break; 16275 case OMPC_if: 16276 case OMPC_depobj: 16277 case OMPC_final: 16278 case OMPC_num_threads: 16279 case OMPC_safelen: 16280 case OMPC_simdlen: 16281 case OMPC_sizes: 16282 case OMPC_allocator: 16283 case OMPC_collapse: 16284 case OMPC_default: 16285 case OMPC_proc_bind: 16286 case OMPC_schedule: 16287 case OMPC_ordered: 16288 case OMPC_nowait: 16289 case OMPC_untied: 16290 case OMPC_mergeable: 16291 case OMPC_threadprivate: 16292 case OMPC_read: 16293 case OMPC_write: 16294 case OMPC_update: 16295 case OMPC_capture: 16296 case OMPC_compare: 16297 case OMPC_seq_cst: 16298 case OMPC_acq_rel: 16299 case OMPC_acquire: 16300 case OMPC_release: 16301 case OMPC_relaxed: 16302 case OMPC_device: 16303 case OMPC_threads: 16304 case OMPC_simd: 16305 case OMPC_num_teams: 16306 case OMPC_thread_limit: 16307 case OMPC_priority: 16308 case OMPC_grainsize: 16309 case OMPC_nogroup: 16310 case OMPC_num_tasks: 16311 case OMPC_hint: 16312 case OMPC_dist_schedule: 16313 case OMPC_defaultmap: 16314 case OMPC_unknown: 16315 case OMPC_uniform: 16316 case OMPC_unified_address: 16317 case OMPC_unified_shared_memory: 16318 case OMPC_reverse_offload: 16319 case OMPC_dynamic_allocators: 16320 case OMPC_atomic_default_mem_order: 16321 case OMPC_device_type: 16322 case OMPC_match: 16323 case OMPC_order: 16324 case OMPC_destroy: 16325 case OMPC_novariants: 16326 case OMPC_nocontext: 16327 case OMPC_detach: 16328 case OMPC_uses_allocators: 16329 case OMPC_when: 16330 case OMPC_bind: 16331 default: 16332 llvm_unreachable("Clause is not allowed."); 16333 } 16334 return Res; 16335 } 16336 16337 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 16338 ExprObjectKind OK, SourceLocation Loc) { 16339 ExprResult Res = BuildDeclRefExpr( 16340 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 16341 if (!Res.isUsable()) 16342 return ExprError(); 16343 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 16344 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 16345 if (!Res.isUsable()) 16346 return ExprError(); 16347 } 16348 if (VK != VK_LValue && Res.get()->isGLValue()) { 16349 Res = DefaultLvalueConversion(Res.get()); 16350 if (!Res.isUsable()) 16351 return ExprError(); 16352 } 16353 return Res; 16354 } 16355 16356 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 16357 SourceLocation StartLoc, 16358 SourceLocation LParenLoc, 16359 SourceLocation EndLoc) { 16360 SmallVector<Expr *, 8> Vars; 16361 SmallVector<Expr *, 8> PrivateCopies; 16362 for (Expr *RefExpr : VarList) { 16363 assert(RefExpr && "NULL expr in OpenMP private clause."); 16364 SourceLocation ELoc; 16365 SourceRange ERange; 16366 Expr *SimpleRefExpr = RefExpr; 16367 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 16368 if (Res.second) { 16369 // It will be analyzed later. 16370 Vars.push_back(RefExpr); 16371 PrivateCopies.push_back(nullptr); 16372 } 16373 ValueDecl *D = Res.first; 16374 if (!D) 16375 continue; 16376 16377 QualType Type = D->getType(); 16378 auto *VD = dyn_cast<VarDecl>(D); 16379 16380 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 16381 // A variable that appears in a private clause must not have an incomplete 16382 // type or a reference type. 16383 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 16384 continue; 16385 Type = Type.getNonReferenceType(); 16386 16387 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 16388 // A variable that is privatized must not have a const-qualified type 16389 // unless it is of class type with a mutable member. This restriction does 16390 // not apply to the firstprivate clause. 16391 // 16392 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions] 16393 // A variable that appears in a private clause must not have a 16394 // const-qualified type unless it is of class type with a mutable member. 16395 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc)) 16396 continue; 16397 16398 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 16399 // in a Construct] 16400 // Variables with the predetermined data-sharing attributes may not be 16401 // listed in data-sharing attributes clauses, except for the cases 16402 // listed below. For these exceptions only, listing a predetermined 16403 // variable in a data-sharing attribute clause is allowed and overrides 16404 // the variable's predetermined data-sharing attributes. 16405 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 16406 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 16407 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 16408 << getOpenMPClauseName(OMPC_private); 16409 reportOriginalDsa(*this, DSAStack, D, DVar); 16410 continue; 16411 } 16412 16413 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 16414 // Variably modified types are not supported for tasks. 16415 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 16416 isOpenMPTaskingDirective(CurrDir)) { 16417 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 16418 << getOpenMPClauseName(OMPC_private) << Type 16419 << getOpenMPDirectiveName(CurrDir); 16420 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 16421 VarDecl::DeclarationOnly; 16422 Diag(D->getLocation(), 16423 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 16424 << D; 16425 continue; 16426 } 16427 16428 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 16429 // A list item cannot appear in both a map clause and a data-sharing 16430 // attribute clause on the same construct 16431 // 16432 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 16433 // A list item cannot appear in both a map clause and a data-sharing 16434 // attribute clause on the same construct unless the construct is a 16435 // combined construct. 16436 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) || 16437 CurrDir == OMPD_target) { 16438 OpenMPClauseKind ConflictKind; 16439 if (DSAStack->checkMappableExprComponentListsForDecl( 16440 VD, /*CurrentRegionOnly=*/true, 16441 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 16442 OpenMPClauseKind WhereFoundClauseKind) -> bool { 16443 ConflictKind = WhereFoundClauseKind; 16444 return true; 16445 })) { 16446 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 16447 << getOpenMPClauseName(OMPC_private) 16448 << getOpenMPClauseName(ConflictKind) 16449 << getOpenMPDirectiveName(CurrDir); 16450 reportOriginalDsa(*this, DSAStack, D, DVar); 16451 continue; 16452 } 16453 } 16454 16455 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 16456 // A variable of class type (or array thereof) that appears in a private 16457 // clause requires an accessible, unambiguous default constructor for the 16458 // class type. 16459 // Generate helper private variable and initialize it with the default 16460 // value. The address of the original variable is replaced by the address of 16461 // the new private variable in CodeGen. This new variable is not added to 16462 // IdResolver, so the code in the OpenMP region uses original variable for 16463 // proper diagnostics. 16464 Type = Type.getUnqualifiedType(); 16465 VarDecl *VDPrivate = 16466 buildVarDecl(*this, ELoc, Type, D->getName(), 16467 D->hasAttrs() ? &D->getAttrs() : nullptr, 16468 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 16469 ActOnUninitializedDecl(VDPrivate); 16470 if (VDPrivate->isInvalidDecl()) 16471 continue; 16472 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 16473 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 16474 16475 DeclRefExpr *Ref = nullptr; 16476 if (!VD && !CurContext->isDependentContext()) 16477 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 16478 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 16479 Vars.push_back((VD || CurContext->isDependentContext()) 16480 ? RefExpr->IgnoreParens() 16481 : Ref); 16482 PrivateCopies.push_back(VDPrivateRefExpr); 16483 } 16484 16485 if (Vars.empty()) 16486 return nullptr; 16487 16488 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 16489 PrivateCopies); 16490 } 16491 16492 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 16493 SourceLocation StartLoc, 16494 SourceLocation LParenLoc, 16495 SourceLocation EndLoc) { 16496 SmallVector<Expr *, 8> Vars; 16497 SmallVector<Expr *, 8> PrivateCopies; 16498 SmallVector<Expr *, 8> Inits; 16499 SmallVector<Decl *, 4> ExprCaptures; 16500 bool IsImplicitClause = 16501 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 16502 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc(); 16503 16504 for (Expr *RefExpr : VarList) { 16505 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 16506 SourceLocation ELoc; 16507 SourceRange ERange; 16508 Expr *SimpleRefExpr = RefExpr; 16509 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 16510 if (Res.second) { 16511 // It will be analyzed later. 16512 Vars.push_back(RefExpr); 16513 PrivateCopies.push_back(nullptr); 16514 Inits.push_back(nullptr); 16515 } 16516 ValueDecl *D = Res.first; 16517 if (!D) 16518 continue; 16519 16520 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 16521 QualType Type = D->getType(); 16522 auto *VD = dyn_cast<VarDecl>(D); 16523 16524 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 16525 // A variable that appears in a private clause must not have an incomplete 16526 // type or a reference type. 16527 if (RequireCompleteType(ELoc, Type, 16528 diag::err_omp_firstprivate_incomplete_type)) 16529 continue; 16530 Type = Type.getNonReferenceType(); 16531 16532 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 16533 // A variable of class type (or array thereof) that appears in a private 16534 // clause requires an accessible, unambiguous copy constructor for the 16535 // class type. 16536 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 16537 16538 // If an implicit firstprivate variable found it was checked already. 16539 DSAStackTy::DSAVarData TopDVar; 16540 if (!IsImplicitClause) { 16541 DSAStackTy::DSAVarData DVar = 16542 DSAStack->getTopDSA(D, /*FromParent=*/false); 16543 TopDVar = DVar; 16544 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 16545 bool IsConstant = ElemType.isConstant(Context); 16546 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 16547 // A list item that specifies a given variable may not appear in more 16548 // than one clause on the same directive, except that a variable may be 16549 // specified in both firstprivate and lastprivate clauses. 16550 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 16551 // A list item may appear in a firstprivate or lastprivate clause but not 16552 // both. 16553 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 16554 (isOpenMPDistributeDirective(CurrDir) || 16555 DVar.CKind != OMPC_lastprivate) && 16556 DVar.RefExpr) { 16557 Diag(ELoc, diag::err_omp_wrong_dsa) 16558 << getOpenMPClauseName(DVar.CKind) 16559 << getOpenMPClauseName(OMPC_firstprivate); 16560 reportOriginalDsa(*this, DSAStack, D, DVar); 16561 continue; 16562 } 16563 16564 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 16565 // in a Construct] 16566 // Variables with the predetermined data-sharing attributes may not be 16567 // listed in data-sharing attributes clauses, except for the cases 16568 // listed below. For these exceptions only, listing a predetermined 16569 // variable in a data-sharing attribute clause is allowed and overrides 16570 // the variable's predetermined data-sharing attributes. 16571 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 16572 // in a Construct, C/C++, p.2] 16573 // Variables with const-qualified type having no mutable member may be 16574 // listed in a firstprivate clause, even if they are static data members. 16575 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 16576 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 16577 Diag(ELoc, diag::err_omp_wrong_dsa) 16578 << getOpenMPClauseName(DVar.CKind) 16579 << getOpenMPClauseName(OMPC_firstprivate); 16580 reportOriginalDsa(*this, DSAStack, D, DVar); 16581 continue; 16582 } 16583 16584 // OpenMP [2.9.3.4, Restrictions, p.2] 16585 // A list item that is private within a parallel region must not appear 16586 // in a firstprivate clause on a worksharing construct if any of the 16587 // worksharing regions arising from the worksharing construct ever bind 16588 // to any of the parallel regions arising from the parallel construct. 16589 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 16590 // A list item that is private within a teams region must not appear in a 16591 // firstprivate clause on a distribute construct if any of the distribute 16592 // regions arising from the distribute construct ever bind to any of the 16593 // teams regions arising from the teams construct. 16594 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 16595 // A list item that appears in a reduction clause of a teams construct 16596 // must not appear in a firstprivate clause on a distribute construct if 16597 // any of the distribute regions arising from the distribute construct 16598 // ever bind to any of the teams regions arising from the teams construct. 16599 if ((isOpenMPWorksharingDirective(CurrDir) || 16600 isOpenMPDistributeDirective(CurrDir)) && 16601 !isOpenMPParallelDirective(CurrDir) && 16602 !isOpenMPTeamsDirective(CurrDir)) { 16603 DVar = DSAStack->getImplicitDSA(D, true); 16604 if (DVar.CKind != OMPC_shared && 16605 (isOpenMPParallelDirective(DVar.DKind) || 16606 isOpenMPTeamsDirective(DVar.DKind) || 16607 DVar.DKind == OMPD_unknown)) { 16608 Diag(ELoc, diag::err_omp_required_access) 16609 << getOpenMPClauseName(OMPC_firstprivate) 16610 << getOpenMPClauseName(OMPC_shared); 16611 reportOriginalDsa(*this, DSAStack, D, DVar); 16612 continue; 16613 } 16614 } 16615 // OpenMP [2.9.3.4, Restrictions, p.3] 16616 // A list item that appears in a reduction clause of a parallel construct 16617 // must not appear in a firstprivate clause on a worksharing or task 16618 // construct if any of the worksharing or task regions arising from the 16619 // worksharing or task construct ever bind to any of the parallel regions 16620 // arising from the parallel construct. 16621 // OpenMP [2.9.3.4, Restrictions, p.4] 16622 // A list item that appears in a reduction clause in worksharing 16623 // construct must not appear in a firstprivate clause in a task construct 16624 // encountered during execution of any of the worksharing regions arising 16625 // from the worksharing construct. 16626 if (isOpenMPTaskingDirective(CurrDir)) { 16627 DVar = DSAStack->hasInnermostDSA( 16628 D, 16629 [](OpenMPClauseKind C, bool AppliedToPointee) { 16630 return C == OMPC_reduction && !AppliedToPointee; 16631 }, 16632 [](OpenMPDirectiveKind K) { 16633 return isOpenMPParallelDirective(K) || 16634 isOpenMPWorksharingDirective(K) || 16635 isOpenMPTeamsDirective(K); 16636 }, 16637 /*FromParent=*/true); 16638 if (DVar.CKind == OMPC_reduction && 16639 (isOpenMPParallelDirective(DVar.DKind) || 16640 isOpenMPWorksharingDirective(DVar.DKind) || 16641 isOpenMPTeamsDirective(DVar.DKind))) { 16642 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 16643 << getOpenMPDirectiveName(DVar.DKind); 16644 reportOriginalDsa(*this, DSAStack, D, DVar); 16645 continue; 16646 } 16647 } 16648 16649 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 16650 // A list item cannot appear in both a map clause and a data-sharing 16651 // attribute clause on the same construct 16652 // 16653 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 16654 // A list item cannot appear in both a map clause and a data-sharing 16655 // attribute clause on the same construct unless the construct is a 16656 // combined construct. 16657 if ((LangOpts.OpenMP <= 45 && 16658 isOpenMPTargetExecutionDirective(CurrDir)) || 16659 CurrDir == OMPD_target) { 16660 OpenMPClauseKind ConflictKind; 16661 if (DSAStack->checkMappableExprComponentListsForDecl( 16662 VD, /*CurrentRegionOnly=*/true, 16663 [&ConflictKind]( 16664 OMPClauseMappableExprCommon::MappableExprComponentListRef, 16665 OpenMPClauseKind WhereFoundClauseKind) { 16666 ConflictKind = WhereFoundClauseKind; 16667 return true; 16668 })) { 16669 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 16670 << getOpenMPClauseName(OMPC_firstprivate) 16671 << getOpenMPClauseName(ConflictKind) 16672 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 16673 reportOriginalDsa(*this, DSAStack, D, DVar); 16674 continue; 16675 } 16676 } 16677 } 16678 16679 // Variably modified types are not supported for tasks. 16680 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 16681 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 16682 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 16683 << getOpenMPClauseName(OMPC_firstprivate) << Type 16684 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 16685 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 16686 VarDecl::DeclarationOnly; 16687 Diag(D->getLocation(), 16688 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 16689 << D; 16690 continue; 16691 } 16692 16693 Type = Type.getUnqualifiedType(); 16694 VarDecl *VDPrivate = 16695 buildVarDecl(*this, ELoc, Type, D->getName(), 16696 D->hasAttrs() ? &D->getAttrs() : nullptr, 16697 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 16698 // Generate helper private variable and initialize it with the value of the 16699 // original variable. The address of the original variable is replaced by 16700 // the address of the new private variable in the CodeGen. This new variable 16701 // is not added to IdResolver, so the code in the OpenMP region uses 16702 // original variable for proper diagnostics and variable capturing. 16703 Expr *VDInitRefExpr = nullptr; 16704 // For arrays generate initializer for single element and replace it by the 16705 // original array element in CodeGen. 16706 if (Type->isArrayType()) { 16707 VarDecl *VDInit = 16708 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 16709 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 16710 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get(); 16711 ElemType = ElemType.getUnqualifiedType(); 16712 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 16713 ".firstprivate.temp"); 16714 InitializedEntity Entity = 16715 InitializedEntity::InitializeVariable(VDInitTemp); 16716 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 16717 16718 InitializationSequence InitSeq(*this, Entity, Kind, Init); 16719 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 16720 if (Result.isInvalid()) 16721 VDPrivate->setInvalidDecl(); 16722 else 16723 VDPrivate->setInit(Result.getAs<Expr>()); 16724 // Remove temp variable declaration. 16725 Context.Deallocate(VDInitTemp); 16726 } else { 16727 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 16728 ".firstprivate.temp"); 16729 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 16730 RefExpr->getExprLoc()); 16731 AddInitializerToDecl(VDPrivate, 16732 DefaultLvalueConversion(VDInitRefExpr).get(), 16733 /*DirectInit=*/false); 16734 } 16735 if (VDPrivate->isInvalidDecl()) { 16736 if (IsImplicitClause) { 16737 Diag(RefExpr->getExprLoc(), 16738 diag::note_omp_task_predetermined_firstprivate_here); 16739 } 16740 continue; 16741 } 16742 CurContext->addDecl(VDPrivate); 16743 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 16744 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 16745 RefExpr->getExprLoc()); 16746 DeclRefExpr *Ref = nullptr; 16747 if (!VD && !CurContext->isDependentContext()) { 16748 if (TopDVar.CKind == OMPC_lastprivate) { 16749 Ref = TopDVar.PrivateCopy; 16750 } else { 16751 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 16752 if (!isOpenMPCapturedDecl(D)) 16753 ExprCaptures.push_back(Ref->getDecl()); 16754 } 16755 } 16756 if (!IsImplicitClause) 16757 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 16758 Vars.push_back((VD || CurContext->isDependentContext()) 16759 ? RefExpr->IgnoreParens() 16760 : Ref); 16761 PrivateCopies.push_back(VDPrivateRefExpr); 16762 Inits.push_back(VDInitRefExpr); 16763 } 16764 16765 if (Vars.empty()) 16766 return nullptr; 16767 16768 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 16769 Vars, PrivateCopies, Inits, 16770 buildPreInits(Context, ExprCaptures)); 16771 } 16772 16773 OMPClause *Sema::ActOnOpenMPLastprivateClause( 16774 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, 16775 SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc, 16776 SourceLocation LParenLoc, SourceLocation EndLoc) { 16777 if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) { 16778 assert(ColonLoc.isValid() && "Colon location must be valid."); 16779 Diag(LPKindLoc, diag::err_omp_unexpected_clause_value) 16780 << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0, 16781 /*Last=*/OMPC_LASTPRIVATE_unknown) 16782 << getOpenMPClauseName(OMPC_lastprivate); 16783 return nullptr; 16784 } 16785 16786 SmallVector<Expr *, 8> Vars; 16787 SmallVector<Expr *, 8> SrcExprs; 16788 SmallVector<Expr *, 8> DstExprs; 16789 SmallVector<Expr *, 8> AssignmentOps; 16790 SmallVector<Decl *, 4> ExprCaptures; 16791 SmallVector<Expr *, 4> ExprPostUpdates; 16792 for (Expr *RefExpr : VarList) { 16793 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 16794 SourceLocation ELoc; 16795 SourceRange ERange; 16796 Expr *SimpleRefExpr = RefExpr; 16797 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 16798 if (Res.second) { 16799 // It will be analyzed later. 16800 Vars.push_back(RefExpr); 16801 SrcExprs.push_back(nullptr); 16802 DstExprs.push_back(nullptr); 16803 AssignmentOps.push_back(nullptr); 16804 } 16805 ValueDecl *D = Res.first; 16806 if (!D) 16807 continue; 16808 16809 QualType Type = D->getType(); 16810 auto *VD = dyn_cast<VarDecl>(D); 16811 16812 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 16813 // A variable that appears in a lastprivate clause must not have an 16814 // incomplete type or a reference type. 16815 if (RequireCompleteType(ELoc, Type, 16816 diag::err_omp_lastprivate_incomplete_type)) 16817 continue; 16818 Type = Type.getNonReferenceType(); 16819 16820 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 16821 // A variable that is privatized must not have a const-qualified type 16822 // unless it is of class type with a mutable member. This restriction does 16823 // not apply to the firstprivate clause. 16824 // 16825 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions] 16826 // A variable that appears in a lastprivate clause must not have a 16827 // const-qualified type unless it is of class type with a mutable member. 16828 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc)) 16829 continue; 16830 16831 // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions] 16832 // A list item that appears in a lastprivate clause with the conditional 16833 // modifier must be a scalar variable. 16834 if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) { 16835 Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar); 16836 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 16837 VarDecl::DeclarationOnly; 16838 Diag(D->getLocation(), 16839 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 16840 << D; 16841 continue; 16842 } 16843 16844 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 16845 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 16846 // in a Construct] 16847 // Variables with the predetermined data-sharing attributes may not be 16848 // listed in data-sharing attributes clauses, except for the cases 16849 // listed below. 16850 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 16851 // A list item may appear in a firstprivate or lastprivate clause but not 16852 // both. 16853 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 16854 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 16855 (isOpenMPDistributeDirective(CurrDir) || 16856 DVar.CKind != OMPC_firstprivate) && 16857 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 16858 Diag(ELoc, diag::err_omp_wrong_dsa) 16859 << getOpenMPClauseName(DVar.CKind) 16860 << getOpenMPClauseName(OMPC_lastprivate); 16861 reportOriginalDsa(*this, DSAStack, D, DVar); 16862 continue; 16863 } 16864 16865 // OpenMP [2.14.3.5, Restrictions, p.2] 16866 // A list item that is private within a parallel region, or that appears in 16867 // the reduction clause of a parallel construct, must not appear in a 16868 // lastprivate clause on a worksharing construct if any of the corresponding 16869 // worksharing regions ever binds to any of the corresponding parallel 16870 // regions. 16871 DSAStackTy::DSAVarData TopDVar = DVar; 16872 if (isOpenMPWorksharingDirective(CurrDir) && 16873 !isOpenMPParallelDirective(CurrDir) && 16874 !isOpenMPTeamsDirective(CurrDir)) { 16875 DVar = DSAStack->getImplicitDSA(D, true); 16876 if (DVar.CKind != OMPC_shared) { 16877 Diag(ELoc, diag::err_omp_required_access) 16878 << getOpenMPClauseName(OMPC_lastprivate) 16879 << getOpenMPClauseName(OMPC_shared); 16880 reportOriginalDsa(*this, DSAStack, D, DVar); 16881 continue; 16882 } 16883 } 16884 16885 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 16886 // A variable of class type (or array thereof) that appears in a 16887 // lastprivate clause requires an accessible, unambiguous default 16888 // constructor for the class type, unless the list item is also specified 16889 // in a firstprivate clause. 16890 // A variable of class type (or array thereof) that appears in a 16891 // lastprivate clause requires an accessible, unambiguous copy assignment 16892 // operator for the class type. 16893 Type = Context.getBaseElementType(Type).getNonReferenceType(); 16894 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(), 16895 Type.getUnqualifiedType(), ".lastprivate.src", 16896 D->hasAttrs() ? &D->getAttrs() : nullptr); 16897 DeclRefExpr *PseudoSrcExpr = 16898 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 16899 VarDecl *DstVD = 16900 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 16901 D->hasAttrs() ? &D->getAttrs() : nullptr); 16902 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 16903 // For arrays generate assignment operation for single element and replace 16904 // it by the original array element in CodeGen. 16905 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 16906 PseudoDstExpr, PseudoSrcExpr); 16907 if (AssignmentOp.isInvalid()) 16908 continue; 16909 AssignmentOp = 16910 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 16911 if (AssignmentOp.isInvalid()) 16912 continue; 16913 16914 DeclRefExpr *Ref = nullptr; 16915 if (!VD && !CurContext->isDependentContext()) { 16916 if (TopDVar.CKind == OMPC_firstprivate) { 16917 Ref = TopDVar.PrivateCopy; 16918 } else { 16919 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 16920 if (!isOpenMPCapturedDecl(D)) 16921 ExprCaptures.push_back(Ref->getDecl()); 16922 } 16923 if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) || 16924 (!isOpenMPCapturedDecl(D) && 16925 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 16926 ExprResult RefRes = DefaultLvalueConversion(Ref); 16927 if (!RefRes.isUsable()) 16928 continue; 16929 ExprResult PostUpdateRes = 16930 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 16931 RefRes.get()); 16932 if (!PostUpdateRes.isUsable()) 16933 continue; 16934 ExprPostUpdates.push_back( 16935 IgnoredValueConversions(PostUpdateRes.get()).get()); 16936 } 16937 } 16938 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 16939 Vars.push_back((VD || CurContext->isDependentContext()) 16940 ? RefExpr->IgnoreParens() 16941 : Ref); 16942 SrcExprs.push_back(PseudoSrcExpr); 16943 DstExprs.push_back(PseudoDstExpr); 16944 AssignmentOps.push_back(AssignmentOp.get()); 16945 } 16946 16947 if (Vars.empty()) 16948 return nullptr; 16949 16950 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 16951 Vars, SrcExprs, DstExprs, AssignmentOps, 16952 LPKind, LPKindLoc, ColonLoc, 16953 buildPreInits(Context, ExprCaptures), 16954 buildPostUpdate(*this, ExprPostUpdates)); 16955 } 16956 16957 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 16958 SourceLocation StartLoc, 16959 SourceLocation LParenLoc, 16960 SourceLocation EndLoc) { 16961 SmallVector<Expr *, 8> Vars; 16962 for (Expr *RefExpr : VarList) { 16963 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 16964 SourceLocation ELoc; 16965 SourceRange ERange; 16966 Expr *SimpleRefExpr = RefExpr; 16967 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 16968 if (Res.second) { 16969 // It will be analyzed later. 16970 Vars.push_back(RefExpr); 16971 } 16972 ValueDecl *D = Res.first; 16973 if (!D) 16974 continue; 16975 16976 auto *VD = dyn_cast<VarDecl>(D); 16977 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 16978 // in a Construct] 16979 // Variables with the predetermined data-sharing attributes may not be 16980 // listed in data-sharing attributes clauses, except for the cases 16981 // listed below. For these exceptions only, listing a predetermined 16982 // variable in a data-sharing attribute clause is allowed and overrides 16983 // the variable's predetermined data-sharing attributes. 16984 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 16985 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 16986 DVar.RefExpr) { 16987 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 16988 << getOpenMPClauseName(OMPC_shared); 16989 reportOriginalDsa(*this, DSAStack, D, DVar); 16990 continue; 16991 } 16992 16993 DeclRefExpr *Ref = nullptr; 16994 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 16995 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 16996 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 16997 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 16998 ? RefExpr->IgnoreParens() 16999 : Ref); 17000 } 17001 17002 if (Vars.empty()) 17003 return nullptr; 17004 17005 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 17006 } 17007 17008 namespace { 17009 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 17010 DSAStackTy *Stack; 17011 17012 public: 17013 bool VisitDeclRefExpr(DeclRefExpr *E) { 17014 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 17015 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 17016 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 17017 return false; 17018 if (DVar.CKind != OMPC_unknown) 17019 return true; 17020 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 17021 VD, 17022 [](OpenMPClauseKind C, bool AppliedToPointee) { 17023 return isOpenMPPrivate(C) && !AppliedToPointee; 17024 }, 17025 [](OpenMPDirectiveKind) { return true; }, 17026 /*FromParent=*/true); 17027 return DVarPrivate.CKind != OMPC_unknown; 17028 } 17029 return false; 17030 } 17031 bool VisitStmt(Stmt *S) { 17032 for (Stmt *Child : S->children()) { 17033 if (Child && Visit(Child)) 17034 return true; 17035 } 17036 return false; 17037 } 17038 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 17039 }; 17040 } // namespace 17041 17042 namespace { 17043 // Transform MemberExpression for specified FieldDecl of current class to 17044 // DeclRefExpr to specified OMPCapturedExprDecl. 17045 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 17046 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 17047 ValueDecl *Field = nullptr; 17048 DeclRefExpr *CapturedExpr = nullptr; 17049 17050 public: 17051 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 17052 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 17053 17054 ExprResult TransformMemberExpr(MemberExpr *E) { 17055 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 17056 E->getMemberDecl() == Field) { 17057 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 17058 return CapturedExpr; 17059 } 17060 return BaseTransform::TransformMemberExpr(E); 17061 } 17062 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 17063 }; 17064 } // namespace 17065 17066 template <typename T, typename U> 17067 static T filterLookupForUDReductionAndMapper( 17068 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) { 17069 for (U &Set : Lookups) { 17070 for (auto *D : Set) { 17071 if (T Res = Gen(cast<ValueDecl>(D))) 17072 return Res; 17073 } 17074 } 17075 return T(); 17076 } 17077 17078 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) { 17079 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case"); 17080 17081 for (auto RD : D->redecls()) { 17082 // Don't bother with extra checks if we already know this one isn't visible. 17083 if (RD == D) 17084 continue; 17085 17086 auto ND = cast<NamedDecl>(RD); 17087 if (LookupResult::isVisible(SemaRef, ND)) 17088 return ND; 17089 } 17090 17091 return nullptr; 17092 } 17093 17094 static void 17095 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id, 17096 SourceLocation Loc, QualType Ty, 17097 SmallVectorImpl<UnresolvedSet<8>> &Lookups) { 17098 // Find all of the associated namespaces and classes based on the 17099 // arguments we have. 17100 Sema::AssociatedNamespaceSet AssociatedNamespaces; 17101 Sema::AssociatedClassSet AssociatedClasses; 17102 OpaqueValueExpr OVE(Loc, Ty, VK_LValue); 17103 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces, 17104 AssociatedClasses); 17105 17106 // C++ [basic.lookup.argdep]p3: 17107 // Let X be the lookup set produced by unqualified lookup (3.4.1) 17108 // and let Y be the lookup set produced by argument dependent 17109 // lookup (defined as follows). If X contains [...] then Y is 17110 // empty. Otherwise Y is the set of declarations found in the 17111 // namespaces associated with the argument types as described 17112 // below. The set of declarations found by the lookup of the name 17113 // is the union of X and Y. 17114 // 17115 // Here, we compute Y and add its members to the overloaded 17116 // candidate set. 17117 for (auto *NS : AssociatedNamespaces) { 17118 // When considering an associated namespace, the lookup is the 17119 // same as the lookup performed when the associated namespace is 17120 // used as a qualifier (3.4.3.2) except that: 17121 // 17122 // -- Any using-directives in the associated namespace are 17123 // ignored. 17124 // 17125 // -- Any namespace-scope friend functions declared in 17126 // associated classes are visible within their respective 17127 // namespaces even if they are not visible during an ordinary 17128 // lookup (11.4). 17129 DeclContext::lookup_result R = NS->lookup(Id.getName()); 17130 for (auto *D : R) { 17131 auto *Underlying = D; 17132 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 17133 Underlying = USD->getTargetDecl(); 17134 17135 if (!isa<OMPDeclareReductionDecl>(Underlying) && 17136 !isa<OMPDeclareMapperDecl>(Underlying)) 17137 continue; 17138 17139 if (!SemaRef.isVisible(D)) { 17140 D = findAcceptableDecl(SemaRef, D); 17141 if (!D) 17142 continue; 17143 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 17144 Underlying = USD->getTargetDecl(); 17145 } 17146 Lookups.emplace_back(); 17147 Lookups.back().addDecl(Underlying); 17148 } 17149 } 17150 } 17151 17152 static ExprResult 17153 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 17154 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 17155 const DeclarationNameInfo &ReductionId, QualType Ty, 17156 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 17157 if (ReductionIdScopeSpec.isInvalid()) 17158 return ExprError(); 17159 SmallVector<UnresolvedSet<8>, 4> Lookups; 17160 if (S) { 17161 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 17162 Lookup.suppressDiagnostics(); 17163 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 17164 NamedDecl *D = Lookup.getRepresentativeDecl(); 17165 do { 17166 S = S->getParent(); 17167 } while (S && !S->isDeclScope(D)); 17168 if (S) 17169 S = S->getParent(); 17170 Lookups.emplace_back(); 17171 Lookups.back().append(Lookup.begin(), Lookup.end()); 17172 Lookup.clear(); 17173 } 17174 } else if (auto *ULE = 17175 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 17176 Lookups.push_back(UnresolvedSet<8>()); 17177 Decl *PrevD = nullptr; 17178 for (NamedDecl *D : ULE->decls()) { 17179 if (D == PrevD) 17180 Lookups.push_back(UnresolvedSet<8>()); 17181 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D)) 17182 Lookups.back().addDecl(DRD); 17183 PrevD = D; 17184 } 17185 } 17186 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || 17187 Ty->isInstantiationDependentType() || 17188 Ty->containsUnexpandedParameterPack() || 17189 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 17190 return !D->isInvalidDecl() && 17191 (D->getType()->isDependentType() || 17192 D->getType()->isInstantiationDependentType() || 17193 D->getType()->containsUnexpandedParameterPack()); 17194 })) { 17195 UnresolvedSet<8> ResSet; 17196 for (const UnresolvedSet<8> &Set : Lookups) { 17197 if (Set.empty()) 17198 continue; 17199 ResSet.append(Set.begin(), Set.end()); 17200 // The last item marks the end of all declarations at the specified scope. 17201 ResSet.addDecl(Set[Set.size() - 1]); 17202 } 17203 return UnresolvedLookupExpr::Create( 17204 SemaRef.Context, /*NamingClass=*/nullptr, 17205 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 17206 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 17207 } 17208 // Lookup inside the classes. 17209 // C++ [over.match.oper]p3: 17210 // For a unary operator @ with an operand of a type whose 17211 // cv-unqualified version is T1, and for a binary operator @ with 17212 // a left operand of a type whose cv-unqualified version is T1 and 17213 // a right operand of a type whose cv-unqualified version is T2, 17214 // three sets of candidate functions, designated member 17215 // candidates, non-member candidates and built-in candidates, are 17216 // constructed as follows: 17217 // -- If T1 is a complete class type or a class currently being 17218 // defined, the set of member candidates is the result of the 17219 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 17220 // the set of member candidates is empty. 17221 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 17222 Lookup.suppressDiagnostics(); 17223 if (const auto *TyRec = Ty->getAs<RecordType>()) { 17224 // Complete the type if it can be completed. 17225 // If the type is neither complete nor being defined, bail out now. 17226 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() || 17227 TyRec->getDecl()->getDefinition()) { 17228 Lookup.clear(); 17229 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl()); 17230 if (Lookup.empty()) { 17231 Lookups.emplace_back(); 17232 Lookups.back().append(Lookup.begin(), Lookup.end()); 17233 } 17234 } 17235 } 17236 // Perform ADL. 17237 if (SemaRef.getLangOpts().CPlusPlus) 17238 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups); 17239 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 17240 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 17241 if (!D->isInvalidDecl() && 17242 SemaRef.Context.hasSameType(D->getType(), Ty)) 17243 return D; 17244 return nullptr; 17245 })) 17246 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), 17247 VK_LValue, Loc); 17248 if (SemaRef.getLangOpts().CPlusPlus) { 17249 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 17250 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 17251 if (!D->isInvalidDecl() && 17252 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 17253 !Ty.isMoreQualifiedThan(D->getType())) 17254 return D; 17255 return nullptr; 17256 })) { 17257 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 17258 /*DetectVirtual=*/false); 17259 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 17260 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 17261 VD->getType().getUnqualifiedType()))) { 17262 if (SemaRef.CheckBaseClassAccess( 17263 Loc, VD->getType(), Ty, Paths.front(), 17264 /*DiagID=*/0) != Sema::AR_inaccessible) { 17265 SemaRef.BuildBasePathArray(Paths, BasePath); 17266 return SemaRef.BuildDeclRefExpr( 17267 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc); 17268 } 17269 } 17270 } 17271 } 17272 } 17273 if (ReductionIdScopeSpec.isSet()) { 17274 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) 17275 << Ty << Range; 17276 return ExprError(); 17277 } 17278 return ExprEmpty(); 17279 } 17280 17281 namespace { 17282 /// Data for the reduction-based clauses. 17283 struct ReductionData { 17284 /// List of original reduction items. 17285 SmallVector<Expr *, 8> Vars; 17286 /// List of private copies of the reduction items. 17287 SmallVector<Expr *, 8> Privates; 17288 /// LHS expressions for the reduction_op expressions. 17289 SmallVector<Expr *, 8> LHSs; 17290 /// RHS expressions for the reduction_op expressions. 17291 SmallVector<Expr *, 8> RHSs; 17292 /// Reduction operation expression. 17293 SmallVector<Expr *, 8> ReductionOps; 17294 /// inscan copy operation expressions. 17295 SmallVector<Expr *, 8> InscanCopyOps; 17296 /// inscan copy temp array expressions for prefix sums. 17297 SmallVector<Expr *, 8> InscanCopyArrayTemps; 17298 /// inscan copy temp array element expressions for prefix sums. 17299 SmallVector<Expr *, 8> InscanCopyArrayElems; 17300 /// Taskgroup descriptors for the corresponding reduction items in 17301 /// in_reduction clauses. 17302 SmallVector<Expr *, 8> TaskgroupDescriptors; 17303 /// List of captures for clause. 17304 SmallVector<Decl *, 4> ExprCaptures; 17305 /// List of postupdate expressions. 17306 SmallVector<Expr *, 4> ExprPostUpdates; 17307 /// Reduction modifier. 17308 unsigned RedModifier = 0; 17309 ReductionData() = delete; 17310 /// Reserves required memory for the reduction data. 17311 ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) { 17312 Vars.reserve(Size); 17313 Privates.reserve(Size); 17314 LHSs.reserve(Size); 17315 RHSs.reserve(Size); 17316 ReductionOps.reserve(Size); 17317 if (RedModifier == OMPC_REDUCTION_inscan) { 17318 InscanCopyOps.reserve(Size); 17319 InscanCopyArrayTemps.reserve(Size); 17320 InscanCopyArrayElems.reserve(Size); 17321 } 17322 TaskgroupDescriptors.reserve(Size); 17323 ExprCaptures.reserve(Size); 17324 ExprPostUpdates.reserve(Size); 17325 } 17326 /// Stores reduction item and reduction operation only (required for dependent 17327 /// reduction item). 17328 void push(Expr *Item, Expr *ReductionOp) { 17329 Vars.emplace_back(Item); 17330 Privates.emplace_back(nullptr); 17331 LHSs.emplace_back(nullptr); 17332 RHSs.emplace_back(nullptr); 17333 ReductionOps.emplace_back(ReductionOp); 17334 TaskgroupDescriptors.emplace_back(nullptr); 17335 if (RedModifier == OMPC_REDUCTION_inscan) { 17336 InscanCopyOps.push_back(nullptr); 17337 InscanCopyArrayTemps.push_back(nullptr); 17338 InscanCopyArrayElems.push_back(nullptr); 17339 } 17340 } 17341 /// Stores reduction data. 17342 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp, 17343 Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp, 17344 Expr *CopyArrayElem) { 17345 Vars.emplace_back(Item); 17346 Privates.emplace_back(Private); 17347 LHSs.emplace_back(LHS); 17348 RHSs.emplace_back(RHS); 17349 ReductionOps.emplace_back(ReductionOp); 17350 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor); 17351 if (RedModifier == OMPC_REDUCTION_inscan) { 17352 InscanCopyOps.push_back(CopyOp); 17353 InscanCopyArrayTemps.push_back(CopyArrayTemp); 17354 InscanCopyArrayElems.push_back(CopyArrayElem); 17355 } else { 17356 assert(CopyOp == nullptr && CopyArrayTemp == nullptr && 17357 CopyArrayElem == nullptr && 17358 "Copy operation must be used for inscan reductions only."); 17359 } 17360 } 17361 }; 17362 } // namespace 17363 17364 static bool checkOMPArraySectionConstantForReduction( 17365 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement, 17366 SmallVectorImpl<llvm::APSInt> &ArraySizes) { 17367 const Expr *Length = OASE->getLength(); 17368 if (Length == nullptr) { 17369 // For array sections of the form [1:] or [:], we would need to analyze 17370 // the lower bound... 17371 if (OASE->getColonLocFirst().isValid()) 17372 return false; 17373 17374 // This is an array subscript which has implicit length 1! 17375 SingleElement = true; 17376 ArraySizes.push_back(llvm::APSInt::get(1)); 17377 } else { 17378 Expr::EvalResult Result; 17379 if (!Length->EvaluateAsInt(Result, Context)) 17380 return false; 17381 17382 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 17383 SingleElement = (ConstantLengthValue.getSExtValue() == 1); 17384 ArraySizes.push_back(ConstantLengthValue); 17385 } 17386 17387 // Get the base of this array section and walk up from there. 17388 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 17389 17390 // We require length = 1 for all array sections except the right-most to 17391 // guarantee that the memory region is contiguous and has no holes in it. 17392 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) { 17393 Length = TempOASE->getLength(); 17394 if (Length == nullptr) { 17395 // For array sections of the form [1:] or [:], we would need to analyze 17396 // the lower bound... 17397 if (OASE->getColonLocFirst().isValid()) 17398 return false; 17399 17400 // This is an array subscript which has implicit length 1! 17401 ArraySizes.push_back(llvm::APSInt::get(1)); 17402 } else { 17403 Expr::EvalResult Result; 17404 if (!Length->EvaluateAsInt(Result, Context)) 17405 return false; 17406 17407 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 17408 if (ConstantLengthValue.getSExtValue() != 1) 17409 return false; 17410 17411 ArraySizes.push_back(ConstantLengthValue); 17412 } 17413 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 17414 } 17415 17416 // If we have a single element, we don't need to add the implicit lengths. 17417 if (!SingleElement) { 17418 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) { 17419 // Has implicit length 1! 17420 ArraySizes.push_back(llvm::APSInt::get(1)); 17421 Base = TempASE->getBase()->IgnoreParenImpCasts(); 17422 } 17423 } 17424 17425 // This array section can be privatized as a single value or as a constant 17426 // sized array. 17427 return true; 17428 } 17429 17430 static BinaryOperatorKind 17431 getRelatedCompoundReductionOp(BinaryOperatorKind BOK) { 17432 if (BOK == BO_Add) 17433 return BO_AddAssign; 17434 if (BOK == BO_Mul) 17435 return BO_MulAssign; 17436 if (BOK == BO_And) 17437 return BO_AndAssign; 17438 if (BOK == BO_Or) 17439 return BO_OrAssign; 17440 if (BOK == BO_Xor) 17441 return BO_XorAssign; 17442 return BOK; 17443 } 17444 17445 static bool actOnOMPReductionKindClause( 17446 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, 17447 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 17448 SourceLocation ColonLoc, SourceLocation EndLoc, 17449 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 17450 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { 17451 DeclarationName DN = ReductionId.getName(); 17452 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator(); 17453 BinaryOperatorKind BOK = BO_Comma; 17454 17455 ASTContext &Context = S.Context; 17456 // OpenMP [2.14.3.6, reduction clause] 17457 // C 17458 // reduction-identifier is either an identifier or one of the following 17459 // operators: +, -, *, &, |, ^, && and || 17460 // C++ 17461 // reduction-identifier is either an id-expression or one of the following 17462 // operators: +, -, *, &, |, ^, && and || 17463 switch (OOK) { 17464 case OO_Plus: 17465 case OO_Minus: 17466 BOK = BO_Add; 17467 break; 17468 case OO_Star: 17469 BOK = BO_Mul; 17470 break; 17471 case OO_Amp: 17472 BOK = BO_And; 17473 break; 17474 case OO_Pipe: 17475 BOK = BO_Or; 17476 break; 17477 case OO_Caret: 17478 BOK = BO_Xor; 17479 break; 17480 case OO_AmpAmp: 17481 BOK = BO_LAnd; 17482 break; 17483 case OO_PipePipe: 17484 BOK = BO_LOr; 17485 break; 17486 case OO_New: 17487 case OO_Delete: 17488 case OO_Array_New: 17489 case OO_Array_Delete: 17490 case OO_Slash: 17491 case OO_Percent: 17492 case OO_Tilde: 17493 case OO_Exclaim: 17494 case OO_Equal: 17495 case OO_Less: 17496 case OO_Greater: 17497 case OO_LessEqual: 17498 case OO_GreaterEqual: 17499 case OO_PlusEqual: 17500 case OO_MinusEqual: 17501 case OO_StarEqual: 17502 case OO_SlashEqual: 17503 case OO_PercentEqual: 17504 case OO_CaretEqual: 17505 case OO_AmpEqual: 17506 case OO_PipeEqual: 17507 case OO_LessLess: 17508 case OO_GreaterGreater: 17509 case OO_LessLessEqual: 17510 case OO_GreaterGreaterEqual: 17511 case OO_EqualEqual: 17512 case OO_ExclaimEqual: 17513 case OO_Spaceship: 17514 case OO_PlusPlus: 17515 case OO_MinusMinus: 17516 case OO_Comma: 17517 case OO_ArrowStar: 17518 case OO_Arrow: 17519 case OO_Call: 17520 case OO_Subscript: 17521 case OO_Conditional: 17522 case OO_Coawait: 17523 case NUM_OVERLOADED_OPERATORS: 17524 llvm_unreachable("Unexpected reduction identifier"); 17525 case OO_None: 17526 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) { 17527 if (II->isStr("max")) 17528 BOK = BO_GT; 17529 else if (II->isStr("min")) 17530 BOK = BO_LT; 17531 } 17532 break; 17533 } 17534 SourceRange ReductionIdRange; 17535 if (ReductionIdScopeSpec.isValid()) 17536 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 17537 else 17538 ReductionIdRange.setBegin(ReductionId.getBeginLoc()); 17539 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 17540 17541 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 17542 bool FirstIter = true; 17543 for (Expr *RefExpr : VarList) { 17544 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 17545 // OpenMP [2.1, C/C++] 17546 // A list item is a variable or array section, subject to the restrictions 17547 // specified in Section 2.4 on page 42 and in each of the sections 17548 // describing clauses and directives for which a list appears. 17549 // OpenMP [2.14.3.3, Restrictions, p.1] 17550 // A variable that is part of another variable (as an array or 17551 // structure element) cannot appear in a private clause. 17552 if (!FirstIter && IR != ER) 17553 ++IR; 17554 FirstIter = false; 17555 SourceLocation ELoc; 17556 SourceRange ERange; 17557 Expr *SimpleRefExpr = RefExpr; 17558 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 17559 /*AllowArraySection=*/true); 17560 if (Res.second) { 17561 // Try to find 'declare reduction' corresponding construct before using 17562 // builtin/overloaded operators. 17563 QualType Type = Context.DependentTy; 17564 CXXCastPath BasePath; 17565 ExprResult DeclareReductionRef = buildDeclareReductionRef( 17566 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 17567 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 17568 Expr *ReductionOp = nullptr; 17569 if (S.CurContext->isDependentContext() && 17570 (DeclareReductionRef.isUnset() || 17571 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 17572 ReductionOp = DeclareReductionRef.get(); 17573 // It will be analyzed later. 17574 RD.push(RefExpr, ReductionOp); 17575 } 17576 ValueDecl *D = Res.first; 17577 if (!D) 17578 continue; 17579 17580 Expr *TaskgroupDescriptor = nullptr; 17581 QualType Type; 17582 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 17583 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 17584 if (ASE) { 17585 Type = ASE->getType().getNonReferenceType(); 17586 } else if (OASE) { 17587 QualType BaseType = 17588 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 17589 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 17590 Type = ATy->getElementType(); 17591 else 17592 Type = BaseType->getPointeeType(); 17593 Type = Type.getNonReferenceType(); 17594 } else { 17595 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 17596 } 17597 auto *VD = dyn_cast<VarDecl>(D); 17598 17599 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 17600 // A variable that appears in a private clause must not have an incomplete 17601 // type or a reference type. 17602 if (S.RequireCompleteType(ELoc, D->getType(), 17603 diag::err_omp_reduction_incomplete_type)) 17604 continue; 17605 // OpenMP [2.14.3.6, reduction clause, Restrictions] 17606 // A list item that appears in a reduction clause must not be 17607 // const-qualified. 17608 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc, 17609 /*AcceptIfMutable*/ false, ASE || OASE)) 17610 continue; 17611 17612 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); 17613 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 17614 // If a list-item is a reference type then it must bind to the same object 17615 // for all threads of the team. 17616 if (!ASE && !OASE) { 17617 if (VD) { 17618 VarDecl *VDDef = VD->getDefinition(); 17619 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 17620 DSARefChecker Check(Stack); 17621 if (Check.Visit(VDDef->getInit())) { 17622 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) 17623 << getOpenMPClauseName(ClauseKind) << ERange; 17624 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 17625 continue; 17626 } 17627 } 17628 } 17629 17630 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 17631 // in a Construct] 17632 // Variables with the predetermined data-sharing attributes may not be 17633 // listed in data-sharing attributes clauses, except for the cases 17634 // listed below. For these exceptions only, listing a predetermined 17635 // variable in a data-sharing attribute clause is allowed and overrides 17636 // the variable's predetermined data-sharing attributes. 17637 // OpenMP [2.14.3.6, Restrictions, p.3] 17638 // Any number of reduction clauses can be specified on the directive, 17639 // but a list item can appear only once in the reduction clauses for that 17640 // directive. 17641 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 17642 if (DVar.CKind == OMPC_reduction) { 17643 S.Diag(ELoc, diag::err_omp_once_referenced) 17644 << getOpenMPClauseName(ClauseKind); 17645 if (DVar.RefExpr) 17646 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 17647 continue; 17648 } 17649 if (DVar.CKind != OMPC_unknown) { 17650 S.Diag(ELoc, diag::err_omp_wrong_dsa) 17651 << getOpenMPClauseName(DVar.CKind) 17652 << getOpenMPClauseName(OMPC_reduction); 17653 reportOriginalDsa(S, Stack, D, DVar); 17654 continue; 17655 } 17656 17657 // OpenMP [2.14.3.6, Restrictions, p.1] 17658 // A list item that appears in a reduction clause of a worksharing 17659 // construct must be shared in the parallel regions to which any of the 17660 // worksharing regions arising from the worksharing construct bind. 17661 if (isOpenMPWorksharingDirective(CurrDir) && 17662 !isOpenMPParallelDirective(CurrDir) && 17663 !isOpenMPTeamsDirective(CurrDir)) { 17664 DVar = Stack->getImplicitDSA(D, true); 17665 if (DVar.CKind != OMPC_shared) { 17666 S.Diag(ELoc, diag::err_omp_required_access) 17667 << getOpenMPClauseName(OMPC_reduction) 17668 << getOpenMPClauseName(OMPC_shared); 17669 reportOriginalDsa(S, Stack, D, DVar); 17670 continue; 17671 } 17672 } 17673 } else { 17674 // Threadprivates cannot be shared between threads, so dignose if the base 17675 // is a threadprivate variable. 17676 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 17677 if (DVar.CKind == OMPC_threadprivate) { 17678 S.Diag(ELoc, diag::err_omp_wrong_dsa) 17679 << getOpenMPClauseName(DVar.CKind) 17680 << getOpenMPClauseName(OMPC_reduction); 17681 reportOriginalDsa(S, Stack, D, DVar); 17682 continue; 17683 } 17684 } 17685 17686 // Try to find 'declare reduction' corresponding construct before using 17687 // builtin/overloaded operators. 17688 CXXCastPath BasePath; 17689 ExprResult DeclareReductionRef = buildDeclareReductionRef( 17690 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 17691 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 17692 if (DeclareReductionRef.isInvalid()) 17693 continue; 17694 if (S.CurContext->isDependentContext() && 17695 (DeclareReductionRef.isUnset() || 17696 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 17697 RD.push(RefExpr, DeclareReductionRef.get()); 17698 continue; 17699 } 17700 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 17701 // Not allowed reduction identifier is found. 17702 S.Diag(ReductionId.getBeginLoc(), 17703 diag::err_omp_unknown_reduction_identifier) 17704 << Type << ReductionIdRange; 17705 continue; 17706 } 17707 17708 // OpenMP [2.14.3.6, reduction clause, Restrictions] 17709 // The type of a list item that appears in a reduction clause must be valid 17710 // for the reduction-identifier. For a max or min reduction in C, the type 17711 // of the list item must be an allowed arithmetic data type: char, int, 17712 // float, double, or _Bool, possibly modified with long, short, signed, or 17713 // unsigned. For a max or min reduction in C++, the type of the list item 17714 // must be an allowed arithmetic data type: char, wchar_t, int, float, 17715 // double, or bool, possibly modified with long, short, signed, or unsigned. 17716 if (DeclareReductionRef.isUnset()) { 17717 if ((BOK == BO_GT || BOK == BO_LT) && 17718 !(Type->isScalarType() || 17719 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 17720 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 17721 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; 17722 if (!ASE && !OASE) { 17723 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 17724 VarDecl::DeclarationOnly; 17725 S.Diag(D->getLocation(), 17726 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17727 << D; 17728 } 17729 continue; 17730 } 17731 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 17732 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { 17733 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) 17734 << getOpenMPClauseName(ClauseKind); 17735 if (!ASE && !OASE) { 17736 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 17737 VarDecl::DeclarationOnly; 17738 S.Diag(D->getLocation(), 17739 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17740 << D; 17741 } 17742 continue; 17743 } 17744 } 17745 17746 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 17747 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", 17748 D->hasAttrs() ? &D->getAttrs() : nullptr); 17749 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), 17750 D->hasAttrs() ? &D->getAttrs() : nullptr); 17751 QualType PrivateTy = Type; 17752 17753 // Try if we can determine constant lengths for all array sections and avoid 17754 // the VLA. 17755 bool ConstantLengthOASE = false; 17756 if (OASE) { 17757 bool SingleElement; 17758 llvm::SmallVector<llvm::APSInt, 4> ArraySizes; 17759 ConstantLengthOASE = checkOMPArraySectionConstantForReduction( 17760 Context, OASE, SingleElement, ArraySizes); 17761 17762 // If we don't have a single element, we must emit a constant array type. 17763 if (ConstantLengthOASE && !SingleElement) { 17764 for (llvm::APSInt &Size : ArraySizes) 17765 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr, 17766 ArrayType::Normal, 17767 /*IndexTypeQuals=*/0); 17768 } 17769 } 17770 17771 if ((OASE && !ConstantLengthOASE) || 17772 (!OASE && !ASE && 17773 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 17774 if (!Context.getTargetInfo().isVLASupported()) { 17775 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) { 17776 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 17777 S.Diag(ELoc, diag::note_vla_unsupported); 17778 continue; 17779 } else { 17780 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 17781 S.targetDiag(ELoc, diag::note_vla_unsupported); 17782 } 17783 } 17784 // For arrays/array sections only: 17785 // Create pseudo array type for private copy. The size for this array will 17786 // be generated during codegen. 17787 // For array subscripts or single variables Private Ty is the same as Type 17788 // (type of the variable or single array element). 17789 PrivateTy = Context.getVariableArrayType( 17790 Type, 17791 new (Context) 17792 OpaqueValueExpr(ELoc, Context.getSizeType(), VK_PRValue), 17793 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 17794 } else if (!ASE && !OASE && 17795 Context.getAsArrayType(D->getType().getNonReferenceType())) { 17796 PrivateTy = D->getType().getNonReferenceType(); 17797 } 17798 // Private copy. 17799 VarDecl *PrivateVD = 17800 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 17801 D->hasAttrs() ? &D->getAttrs() : nullptr, 17802 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 17803 // Add initializer for private variable. 17804 Expr *Init = nullptr; 17805 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); 17806 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); 17807 if (DeclareReductionRef.isUsable()) { 17808 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 17809 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 17810 if (DRD->getInitializer()) { 17811 Init = DRDRef; 17812 RHSVD->setInit(DRDRef); 17813 RHSVD->setInitStyle(VarDecl::CallInit); 17814 } 17815 } else { 17816 switch (BOK) { 17817 case BO_Add: 17818 case BO_Xor: 17819 case BO_Or: 17820 case BO_LOr: 17821 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 17822 if (Type->isScalarType() || Type->isAnyComplexType()) 17823 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 17824 break; 17825 case BO_Mul: 17826 case BO_LAnd: 17827 if (Type->isScalarType() || Type->isAnyComplexType()) { 17828 // '*' and '&&' reduction ops - initializer is '1'. 17829 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 17830 } 17831 break; 17832 case BO_And: { 17833 // '&' reduction op - initializer is '~0'. 17834 QualType OrigType = Type; 17835 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 17836 Type = ComplexTy->getElementType(); 17837 if (Type->isRealFloatingType()) { 17838 llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue( 17839 Context.getFloatTypeSemantics(Type)); 17840 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 17841 Type, ELoc); 17842 } else if (Type->isScalarType()) { 17843 uint64_t Size = Context.getTypeSize(Type); 17844 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 17845 llvm::APInt InitValue = llvm::APInt::getAllOnes(Size); 17846 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 17847 } 17848 if (Init && OrigType->isAnyComplexType()) { 17849 // Init = 0xFFFF + 0xFFFFi; 17850 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 17851 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 17852 } 17853 Type = OrigType; 17854 break; 17855 } 17856 case BO_LT: 17857 case BO_GT: { 17858 // 'min' reduction op - initializer is 'Largest representable number in 17859 // the reduction list item type'. 17860 // 'max' reduction op - initializer is 'Least representable number in 17861 // the reduction list item type'. 17862 if (Type->isIntegerType() || Type->isPointerType()) { 17863 bool IsSigned = Type->hasSignedIntegerRepresentation(); 17864 uint64_t Size = Context.getTypeSize(Type); 17865 QualType IntTy = 17866 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 17867 llvm::APInt InitValue = 17868 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 17869 : llvm::APInt::getMinValue(Size) 17870 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 17871 : llvm::APInt::getMaxValue(Size); 17872 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 17873 if (Type->isPointerType()) { 17874 // Cast to pointer type. 17875 ExprResult CastExpr = S.BuildCStyleCastExpr( 17876 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init); 17877 if (CastExpr.isInvalid()) 17878 continue; 17879 Init = CastExpr.get(); 17880 } 17881 } else if (Type->isRealFloatingType()) { 17882 llvm::APFloat InitValue = llvm::APFloat::getLargest( 17883 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 17884 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 17885 Type, ELoc); 17886 } 17887 break; 17888 } 17889 case BO_PtrMemD: 17890 case BO_PtrMemI: 17891 case BO_MulAssign: 17892 case BO_Div: 17893 case BO_Rem: 17894 case BO_Sub: 17895 case BO_Shl: 17896 case BO_Shr: 17897 case BO_LE: 17898 case BO_GE: 17899 case BO_EQ: 17900 case BO_NE: 17901 case BO_Cmp: 17902 case BO_AndAssign: 17903 case BO_XorAssign: 17904 case BO_OrAssign: 17905 case BO_Assign: 17906 case BO_AddAssign: 17907 case BO_SubAssign: 17908 case BO_DivAssign: 17909 case BO_RemAssign: 17910 case BO_ShlAssign: 17911 case BO_ShrAssign: 17912 case BO_Comma: 17913 llvm_unreachable("Unexpected reduction operation"); 17914 } 17915 } 17916 if (Init && DeclareReductionRef.isUnset()) { 17917 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 17918 // Store initializer for single element in private copy. Will be used 17919 // during codegen. 17920 PrivateVD->setInit(RHSVD->getInit()); 17921 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 17922 } else if (!Init) { 17923 S.ActOnUninitializedDecl(RHSVD); 17924 // Store initializer for single element in private copy. Will be used 17925 // during codegen. 17926 PrivateVD->setInit(RHSVD->getInit()); 17927 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 17928 } 17929 if (RHSVD->isInvalidDecl()) 17930 continue; 17931 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 17932 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) 17933 << Type << ReductionIdRange; 17934 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 17935 VarDecl::DeclarationOnly; 17936 S.Diag(D->getLocation(), 17937 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17938 << D; 17939 continue; 17940 } 17941 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); 17942 ExprResult ReductionOp; 17943 if (DeclareReductionRef.isUsable()) { 17944 QualType RedTy = DeclareReductionRef.get()->getType(); 17945 QualType PtrRedTy = Context.getPointerType(RedTy); 17946 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 17947 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 17948 if (!BasePath.empty()) { 17949 LHS = S.DefaultLvalueConversion(LHS.get()); 17950 RHS = S.DefaultLvalueConversion(RHS.get()); 17951 LHS = ImplicitCastExpr::Create( 17952 Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath, 17953 LHS.get()->getValueKind(), FPOptionsOverride()); 17954 RHS = ImplicitCastExpr::Create( 17955 Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath, 17956 RHS.get()->getValueKind(), FPOptionsOverride()); 17957 } 17958 FunctionProtoType::ExtProtoInfo EPI; 17959 QualType Params[] = {PtrRedTy, PtrRedTy}; 17960 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 17961 auto *OVE = new (Context) OpaqueValueExpr( 17962 ELoc, Context.getPointerType(FnTy), VK_PRValue, OK_Ordinary, 17963 S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); 17964 Expr *Args[] = {LHS.get(), RHS.get()}; 17965 ReductionOp = 17966 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_PRValue, ELoc, 17967 S.CurFPFeatureOverrides()); 17968 } else { 17969 BinaryOperatorKind CombBOK = getRelatedCompoundReductionOp(BOK); 17970 if (Type->isRecordType() && CombBOK != BOK) { 17971 Sema::TentativeAnalysisScope Trap(S); 17972 ReductionOp = 17973 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 17974 CombBOK, LHSDRE, RHSDRE); 17975 } 17976 if (!ReductionOp.isUsable()) { 17977 ReductionOp = 17978 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, 17979 LHSDRE, RHSDRE); 17980 if (ReductionOp.isUsable()) { 17981 if (BOK != BO_LT && BOK != BO_GT) { 17982 ReductionOp = 17983 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 17984 BO_Assign, LHSDRE, ReductionOp.get()); 17985 } else { 17986 auto *ConditionalOp = new (Context) 17987 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, 17988 RHSDRE, Type, VK_LValue, OK_Ordinary); 17989 ReductionOp = 17990 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 17991 BO_Assign, LHSDRE, ConditionalOp); 17992 } 17993 } 17994 } 17995 if (ReductionOp.isUsable()) 17996 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(), 17997 /*DiscardedValue*/ false); 17998 if (!ReductionOp.isUsable()) 17999 continue; 18000 } 18001 18002 // Add copy operations for inscan reductions. 18003 // LHS = RHS; 18004 ExprResult CopyOpRes, TempArrayRes, TempArrayElem; 18005 if (ClauseKind == OMPC_reduction && 18006 RD.RedModifier == OMPC_REDUCTION_inscan) { 18007 ExprResult RHS = S.DefaultLvalueConversion(RHSDRE); 18008 CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE, 18009 RHS.get()); 18010 if (!CopyOpRes.isUsable()) 18011 continue; 18012 CopyOpRes = 18013 S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true); 18014 if (!CopyOpRes.isUsable()) 18015 continue; 18016 // For simd directive and simd-based directives in simd mode no need to 18017 // construct temp array, need just a single temp element. 18018 if (Stack->getCurrentDirective() == OMPD_simd || 18019 (S.getLangOpts().OpenMPSimd && 18020 isOpenMPSimdDirective(Stack->getCurrentDirective()))) { 18021 VarDecl *TempArrayVD = 18022 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 18023 D->hasAttrs() ? &D->getAttrs() : nullptr); 18024 // Add a constructor to the temp decl. 18025 S.ActOnUninitializedDecl(TempArrayVD); 18026 TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc); 18027 } else { 18028 // Build temp array for prefix sum. 18029 auto *Dim = new (S.Context) 18030 OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue); 18031 QualType ArrayTy = 18032 S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal, 18033 /*IndexTypeQuals=*/0, {ELoc, ELoc}); 18034 VarDecl *TempArrayVD = 18035 buildVarDecl(S, ELoc, ArrayTy, D->getName(), 18036 D->hasAttrs() ? &D->getAttrs() : nullptr); 18037 // Add a constructor to the temp decl. 18038 S.ActOnUninitializedDecl(TempArrayVD); 18039 TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc); 18040 TempArrayElem = 18041 S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get()); 18042 auto *Idx = new (S.Context) 18043 OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue); 18044 TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(), 18045 ELoc, Idx, ELoc); 18046 } 18047 } 18048 18049 // OpenMP [2.15.4.6, Restrictions, p.2] 18050 // A list item that appears in an in_reduction clause of a task construct 18051 // must appear in a task_reduction clause of a construct associated with a 18052 // taskgroup region that includes the participating task in its taskgroup 18053 // set. The construct associated with the innermost region that meets this 18054 // condition must specify the same reduction-identifier as the in_reduction 18055 // clause. 18056 if (ClauseKind == OMPC_in_reduction) { 18057 SourceRange ParentSR; 18058 BinaryOperatorKind ParentBOK; 18059 const Expr *ParentReductionOp = nullptr; 18060 Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr; 18061 DSAStackTy::DSAVarData ParentBOKDSA = 18062 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK, 18063 ParentBOKTD); 18064 DSAStackTy::DSAVarData ParentReductionOpDSA = 18065 Stack->getTopMostTaskgroupReductionData( 18066 D, ParentSR, ParentReductionOp, ParentReductionOpTD); 18067 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown; 18068 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown; 18069 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) || 18070 (DeclareReductionRef.isUsable() && IsParentBOK) || 18071 (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) { 18072 bool EmitError = true; 18073 if (IsParentReductionOp && DeclareReductionRef.isUsable()) { 18074 llvm::FoldingSetNodeID RedId, ParentRedId; 18075 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true); 18076 DeclareReductionRef.get()->Profile(RedId, Context, 18077 /*Canonical=*/true); 18078 EmitError = RedId != ParentRedId; 18079 } 18080 if (EmitError) { 18081 S.Diag(ReductionId.getBeginLoc(), 18082 diag::err_omp_reduction_identifier_mismatch) 18083 << ReductionIdRange << RefExpr->getSourceRange(); 18084 S.Diag(ParentSR.getBegin(), 18085 diag::note_omp_previous_reduction_identifier) 18086 << ParentSR 18087 << (IsParentBOK ? ParentBOKDSA.RefExpr 18088 : ParentReductionOpDSA.RefExpr) 18089 ->getSourceRange(); 18090 continue; 18091 } 18092 } 18093 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD; 18094 } 18095 18096 DeclRefExpr *Ref = nullptr; 18097 Expr *VarsExpr = RefExpr->IgnoreParens(); 18098 if (!VD && !S.CurContext->isDependentContext()) { 18099 if (ASE || OASE) { 18100 TransformExprToCaptures RebuildToCapture(S, D); 18101 VarsExpr = 18102 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 18103 Ref = RebuildToCapture.getCapturedExpr(); 18104 } else { 18105 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); 18106 } 18107 if (!S.isOpenMPCapturedDecl(D)) { 18108 RD.ExprCaptures.emplace_back(Ref->getDecl()); 18109 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 18110 ExprResult RefRes = S.DefaultLvalueConversion(Ref); 18111 if (!RefRes.isUsable()) 18112 continue; 18113 ExprResult PostUpdateRes = 18114 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 18115 RefRes.get()); 18116 if (!PostUpdateRes.isUsable()) 18117 continue; 18118 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 18119 Stack->getCurrentDirective() == OMPD_taskgroup) { 18120 S.Diag(RefExpr->getExprLoc(), 18121 diag::err_omp_reduction_non_addressable_expression) 18122 << RefExpr->getSourceRange(); 18123 continue; 18124 } 18125 RD.ExprPostUpdates.emplace_back( 18126 S.IgnoredValueConversions(PostUpdateRes.get()).get()); 18127 } 18128 } 18129 } 18130 // All reduction items are still marked as reduction (to do not increase 18131 // code base size). 18132 unsigned Modifier = RD.RedModifier; 18133 // Consider task_reductions as reductions with task modifier. Required for 18134 // correct analysis of in_reduction clauses. 18135 if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction) 18136 Modifier = OMPC_REDUCTION_task; 18137 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier, 18138 ASE || OASE); 18139 if (Modifier == OMPC_REDUCTION_task && 18140 (CurrDir == OMPD_taskgroup || 18141 ((isOpenMPParallelDirective(CurrDir) || 18142 isOpenMPWorksharingDirective(CurrDir)) && 18143 !isOpenMPSimdDirective(CurrDir)))) { 18144 if (DeclareReductionRef.isUsable()) 18145 Stack->addTaskgroupReductionData(D, ReductionIdRange, 18146 DeclareReductionRef.get()); 18147 else 18148 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK); 18149 } 18150 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(), 18151 TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(), 18152 TempArrayElem.get()); 18153 } 18154 return RD.Vars.empty(); 18155 } 18156 18157 OMPClause *Sema::ActOnOpenMPReductionClause( 18158 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, 18159 SourceLocation StartLoc, SourceLocation LParenLoc, 18160 SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, 18161 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 18162 ArrayRef<Expr *> UnresolvedReductions) { 18163 if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) { 18164 Diag(LParenLoc, diag::err_omp_unexpected_clause_value) 18165 << getListOfPossibleValues(OMPC_reduction, /*First=*/0, 18166 /*Last=*/OMPC_REDUCTION_unknown) 18167 << getOpenMPClauseName(OMPC_reduction); 18168 return nullptr; 18169 } 18170 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions 18171 // A reduction clause with the inscan reduction-modifier may only appear on a 18172 // worksharing-loop construct, a worksharing-loop SIMD construct, a simd 18173 // construct, a parallel worksharing-loop construct or a parallel 18174 // worksharing-loop SIMD construct. 18175 if (Modifier == OMPC_REDUCTION_inscan && 18176 (DSAStack->getCurrentDirective() != OMPD_for && 18177 DSAStack->getCurrentDirective() != OMPD_for_simd && 18178 DSAStack->getCurrentDirective() != OMPD_simd && 18179 DSAStack->getCurrentDirective() != OMPD_parallel_for && 18180 DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) { 18181 Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction); 18182 return nullptr; 18183 } 18184 18185 ReductionData RD(VarList.size(), Modifier); 18186 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, 18187 StartLoc, LParenLoc, ColonLoc, EndLoc, 18188 ReductionIdScopeSpec, ReductionId, 18189 UnresolvedReductions, RD)) 18190 return nullptr; 18191 18192 return OMPReductionClause::Create( 18193 Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier, 18194 RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 18195 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps, 18196 RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems, 18197 buildPreInits(Context, RD.ExprCaptures), 18198 buildPostUpdate(*this, RD.ExprPostUpdates)); 18199 } 18200 18201 OMPClause *Sema::ActOnOpenMPTaskReductionClause( 18202 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 18203 SourceLocation ColonLoc, SourceLocation EndLoc, 18204 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 18205 ArrayRef<Expr *> UnresolvedReductions) { 18206 ReductionData RD(VarList.size()); 18207 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList, 18208 StartLoc, LParenLoc, ColonLoc, EndLoc, 18209 ReductionIdScopeSpec, ReductionId, 18210 UnresolvedReductions, RD)) 18211 return nullptr; 18212 18213 return OMPTaskReductionClause::Create( 18214 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 18215 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 18216 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 18217 buildPreInits(Context, RD.ExprCaptures), 18218 buildPostUpdate(*this, RD.ExprPostUpdates)); 18219 } 18220 18221 OMPClause *Sema::ActOnOpenMPInReductionClause( 18222 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 18223 SourceLocation ColonLoc, SourceLocation EndLoc, 18224 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 18225 ArrayRef<Expr *> UnresolvedReductions) { 18226 ReductionData RD(VarList.size()); 18227 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList, 18228 StartLoc, LParenLoc, ColonLoc, EndLoc, 18229 ReductionIdScopeSpec, ReductionId, 18230 UnresolvedReductions, RD)) 18231 return nullptr; 18232 18233 return OMPInReductionClause::Create( 18234 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 18235 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 18236 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors, 18237 buildPreInits(Context, RD.ExprCaptures), 18238 buildPostUpdate(*this, RD.ExprPostUpdates)); 18239 } 18240 18241 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 18242 SourceLocation LinLoc) { 18243 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 18244 LinKind == OMPC_LINEAR_unknown) { 18245 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 18246 return true; 18247 } 18248 return false; 18249 } 18250 18251 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, 18252 OpenMPLinearClauseKind LinKind, QualType Type, 18253 bool IsDeclareSimd) { 18254 const auto *VD = dyn_cast_or_null<VarDecl>(D); 18255 // A variable must not have an incomplete type or a reference type. 18256 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 18257 return true; 18258 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 18259 !Type->isReferenceType()) { 18260 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 18261 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 18262 return true; 18263 } 18264 Type = Type.getNonReferenceType(); 18265 18266 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 18267 // A variable that is privatized must not have a const-qualified type 18268 // unless it is of class type with a mutable member. This restriction does 18269 // not apply to the firstprivate clause, nor to the linear clause on 18270 // declarative directives (like declare simd). 18271 if (!IsDeclareSimd && 18272 rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc)) 18273 return true; 18274 18275 // A list item must be of integral or pointer type. 18276 Type = Type.getUnqualifiedType().getCanonicalType(); 18277 const auto *Ty = Type.getTypePtrOrNull(); 18278 if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() && 18279 !Ty->isIntegralType(Context) && !Ty->isPointerType())) { 18280 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 18281 if (D) { 18282 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 18283 VarDecl::DeclarationOnly; 18284 Diag(D->getLocation(), 18285 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 18286 << D; 18287 } 18288 return true; 18289 } 18290 return false; 18291 } 18292 18293 OMPClause *Sema::ActOnOpenMPLinearClause( 18294 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 18295 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 18296 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 18297 SmallVector<Expr *, 8> Vars; 18298 SmallVector<Expr *, 8> Privates; 18299 SmallVector<Expr *, 8> Inits; 18300 SmallVector<Decl *, 4> ExprCaptures; 18301 SmallVector<Expr *, 4> ExprPostUpdates; 18302 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 18303 LinKind = OMPC_LINEAR_val; 18304 for (Expr *RefExpr : VarList) { 18305 assert(RefExpr && "NULL expr in OpenMP linear clause."); 18306 SourceLocation ELoc; 18307 SourceRange ERange; 18308 Expr *SimpleRefExpr = RefExpr; 18309 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 18310 if (Res.second) { 18311 // It will be analyzed later. 18312 Vars.push_back(RefExpr); 18313 Privates.push_back(nullptr); 18314 Inits.push_back(nullptr); 18315 } 18316 ValueDecl *D = Res.first; 18317 if (!D) 18318 continue; 18319 18320 QualType Type = D->getType(); 18321 auto *VD = dyn_cast<VarDecl>(D); 18322 18323 // OpenMP [2.14.3.7, linear clause] 18324 // A list-item cannot appear in more than one linear clause. 18325 // A list-item that appears in a linear clause cannot appear in any 18326 // other data-sharing attribute clause. 18327 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 18328 if (DVar.RefExpr) { 18329 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 18330 << getOpenMPClauseName(OMPC_linear); 18331 reportOriginalDsa(*this, DSAStack, D, DVar); 18332 continue; 18333 } 18334 18335 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 18336 continue; 18337 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 18338 18339 // Build private copy of original var. 18340 VarDecl *Private = 18341 buildVarDecl(*this, ELoc, Type, D->getName(), 18342 D->hasAttrs() ? &D->getAttrs() : nullptr, 18343 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 18344 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 18345 // Build var to save initial value. 18346 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 18347 Expr *InitExpr; 18348 DeclRefExpr *Ref = nullptr; 18349 if (!VD && !CurContext->isDependentContext()) { 18350 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 18351 if (!isOpenMPCapturedDecl(D)) { 18352 ExprCaptures.push_back(Ref->getDecl()); 18353 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 18354 ExprResult RefRes = DefaultLvalueConversion(Ref); 18355 if (!RefRes.isUsable()) 18356 continue; 18357 ExprResult PostUpdateRes = 18358 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 18359 SimpleRefExpr, RefRes.get()); 18360 if (!PostUpdateRes.isUsable()) 18361 continue; 18362 ExprPostUpdates.push_back( 18363 IgnoredValueConversions(PostUpdateRes.get()).get()); 18364 } 18365 } 18366 } 18367 if (LinKind == OMPC_LINEAR_uval) 18368 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 18369 else 18370 InitExpr = VD ? SimpleRefExpr : Ref; 18371 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 18372 /*DirectInit=*/false); 18373 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 18374 18375 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 18376 Vars.push_back((VD || CurContext->isDependentContext()) 18377 ? RefExpr->IgnoreParens() 18378 : Ref); 18379 Privates.push_back(PrivateRef); 18380 Inits.push_back(InitRef); 18381 } 18382 18383 if (Vars.empty()) 18384 return nullptr; 18385 18386 Expr *StepExpr = Step; 18387 Expr *CalcStepExpr = nullptr; 18388 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 18389 !Step->isInstantiationDependent() && 18390 !Step->containsUnexpandedParameterPack()) { 18391 SourceLocation StepLoc = Step->getBeginLoc(); 18392 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 18393 if (Val.isInvalid()) 18394 return nullptr; 18395 StepExpr = Val.get(); 18396 18397 // Build var to save the step value. 18398 VarDecl *SaveVar = 18399 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 18400 ExprResult SaveRef = 18401 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 18402 ExprResult CalcStep = 18403 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 18404 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false); 18405 18406 // Warn about zero linear step (it would be probably better specified as 18407 // making corresponding variables 'const'). 18408 if (Optional<llvm::APSInt> Result = 18409 StepExpr->getIntegerConstantExpr(Context)) { 18410 if (!Result->isNegative() && !Result->isStrictlyPositive()) 18411 Diag(StepLoc, diag::warn_omp_linear_step_zero) 18412 << Vars[0] << (Vars.size() > 1); 18413 } else if (CalcStep.isUsable()) { 18414 // Calculate the step beforehand instead of doing this on each iteration. 18415 // (This is not used if the number of iterations may be kfold-ed). 18416 CalcStepExpr = CalcStep.get(); 18417 } 18418 } 18419 18420 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 18421 ColonLoc, EndLoc, Vars, Privates, Inits, 18422 StepExpr, CalcStepExpr, 18423 buildPreInits(Context, ExprCaptures), 18424 buildPostUpdate(*this, ExprPostUpdates)); 18425 } 18426 18427 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 18428 Expr *NumIterations, Sema &SemaRef, 18429 Scope *S, DSAStackTy *Stack) { 18430 // Walk the vars and build update/final expressions for the CodeGen. 18431 SmallVector<Expr *, 8> Updates; 18432 SmallVector<Expr *, 8> Finals; 18433 SmallVector<Expr *, 8> UsedExprs; 18434 Expr *Step = Clause.getStep(); 18435 Expr *CalcStep = Clause.getCalcStep(); 18436 // OpenMP [2.14.3.7, linear clause] 18437 // If linear-step is not specified it is assumed to be 1. 18438 if (!Step) 18439 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 18440 else if (CalcStep) 18441 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 18442 bool HasErrors = false; 18443 auto CurInit = Clause.inits().begin(); 18444 auto CurPrivate = Clause.privates().begin(); 18445 OpenMPLinearClauseKind LinKind = Clause.getModifier(); 18446 for (Expr *RefExpr : Clause.varlists()) { 18447 SourceLocation ELoc; 18448 SourceRange ERange; 18449 Expr *SimpleRefExpr = RefExpr; 18450 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange); 18451 ValueDecl *D = Res.first; 18452 if (Res.second || !D) { 18453 Updates.push_back(nullptr); 18454 Finals.push_back(nullptr); 18455 HasErrors = true; 18456 continue; 18457 } 18458 auto &&Info = Stack->isLoopControlVariable(D); 18459 // OpenMP [2.15.11, distribute simd Construct] 18460 // A list item may not appear in a linear clause, unless it is the loop 18461 // iteration variable. 18462 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) && 18463 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) { 18464 SemaRef.Diag(ELoc, 18465 diag::err_omp_linear_distribute_var_non_loop_iteration); 18466 Updates.push_back(nullptr); 18467 Finals.push_back(nullptr); 18468 HasErrors = true; 18469 continue; 18470 } 18471 Expr *InitExpr = *CurInit; 18472 18473 // Build privatized reference to the current linear var. 18474 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 18475 Expr *CapturedRef; 18476 if (LinKind == OMPC_LINEAR_uval) 18477 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 18478 else 18479 CapturedRef = 18480 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 18481 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 18482 /*RefersToCapture=*/true); 18483 18484 // Build update: Var = InitExpr + IV * Step 18485 ExprResult Update; 18486 if (!Info.first) 18487 Update = buildCounterUpdate( 18488 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step, 18489 /*Subtract=*/false, /*IsNonRectangularLB=*/false); 18490 else 18491 Update = *CurPrivate; 18492 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(), 18493 /*DiscardedValue*/ false); 18494 18495 // Build final: Var = PrivCopy; 18496 ExprResult Final; 18497 if (!Info.first) 18498 Final = SemaRef.BuildBinOp( 18499 S, RefExpr->getExprLoc(), BO_Assign, CapturedRef, 18500 SemaRef.DefaultLvalueConversion(*CurPrivate).get()); 18501 else 18502 Final = *CurPrivate; 18503 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(), 18504 /*DiscardedValue*/ false); 18505 18506 if (!Update.isUsable() || !Final.isUsable()) { 18507 Updates.push_back(nullptr); 18508 Finals.push_back(nullptr); 18509 UsedExprs.push_back(nullptr); 18510 HasErrors = true; 18511 } else { 18512 Updates.push_back(Update.get()); 18513 Finals.push_back(Final.get()); 18514 if (!Info.first) 18515 UsedExprs.push_back(SimpleRefExpr); 18516 } 18517 ++CurInit; 18518 ++CurPrivate; 18519 } 18520 if (Expr *S = Clause.getStep()) 18521 UsedExprs.push_back(S); 18522 // Fill the remaining part with the nullptr. 18523 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr); 18524 Clause.setUpdates(Updates); 18525 Clause.setFinals(Finals); 18526 Clause.setUsedExprs(UsedExprs); 18527 return HasErrors; 18528 } 18529 18530 OMPClause *Sema::ActOnOpenMPAlignedClause( 18531 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 18532 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 18533 SmallVector<Expr *, 8> Vars; 18534 for (Expr *RefExpr : VarList) { 18535 assert(RefExpr && "NULL expr in OpenMP linear clause."); 18536 SourceLocation ELoc; 18537 SourceRange ERange; 18538 Expr *SimpleRefExpr = RefExpr; 18539 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 18540 if (Res.second) { 18541 // It will be analyzed later. 18542 Vars.push_back(RefExpr); 18543 } 18544 ValueDecl *D = Res.first; 18545 if (!D) 18546 continue; 18547 18548 QualType QType = D->getType(); 18549 auto *VD = dyn_cast<VarDecl>(D); 18550 18551 // OpenMP [2.8.1, simd construct, Restrictions] 18552 // The type of list items appearing in the aligned clause must be 18553 // array, pointer, reference to array, or reference to pointer. 18554 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 18555 const Type *Ty = QType.getTypePtrOrNull(); 18556 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 18557 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 18558 << QType << getLangOpts().CPlusPlus << ERange; 18559 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 18560 VarDecl::DeclarationOnly; 18561 Diag(D->getLocation(), 18562 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 18563 << D; 18564 continue; 18565 } 18566 18567 // OpenMP [2.8.1, simd construct, Restrictions] 18568 // A list-item cannot appear in more than one aligned clause. 18569 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 18570 Diag(ELoc, diag::err_omp_used_in_clause_twice) 18571 << 0 << getOpenMPClauseName(OMPC_aligned) << ERange; 18572 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 18573 << getOpenMPClauseName(OMPC_aligned); 18574 continue; 18575 } 18576 18577 DeclRefExpr *Ref = nullptr; 18578 if (!VD && isOpenMPCapturedDecl(D)) 18579 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 18580 Vars.push_back(DefaultFunctionArrayConversion( 18581 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 18582 .get()); 18583 } 18584 18585 // OpenMP [2.8.1, simd construct, Description] 18586 // The parameter of the aligned clause, alignment, must be a constant 18587 // positive integer expression. 18588 // If no optional parameter is specified, implementation-defined default 18589 // alignments for SIMD instructions on the target platforms are assumed. 18590 if (Alignment != nullptr) { 18591 ExprResult AlignResult = 18592 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 18593 if (AlignResult.isInvalid()) 18594 return nullptr; 18595 Alignment = AlignResult.get(); 18596 } 18597 if (Vars.empty()) 18598 return nullptr; 18599 18600 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 18601 EndLoc, Vars, Alignment); 18602 } 18603 18604 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 18605 SourceLocation StartLoc, 18606 SourceLocation LParenLoc, 18607 SourceLocation EndLoc) { 18608 SmallVector<Expr *, 8> Vars; 18609 SmallVector<Expr *, 8> SrcExprs; 18610 SmallVector<Expr *, 8> DstExprs; 18611 SmallVector<Expr *, 8> AssignmentOps; 18612 for (Expr *RefExpr : VarList) { 18613 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 18614 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 18615 // It will be analyzed later. 18616 Vars.push_back(RefExpr); 18617 SrcExprs.push_back(nullptr); 18618 DstExprs.push_back(nullptr); 18619 AssignmentOps.push_back(nullptr); 18620 continue; 18621 } 18622 18623 SourceLocation ELoc = RefExpr->getExprLoc(); 18624 // OpenMP [2.1, C/C++] 18625 // A list item is a variable name. 18626 // OpenMP [2.14.4.1, Restrictions, p.1] 18627 // A list item that appears in a copyin clause must be threadprivate. 18628 auto *DE = dyn_cast<DeclRefExpr>(RefExpr); 18629 if (!DE || !isa<VarDecl>(DE->getDecl())) { 18630 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 18631 << 0 << RefExpr->getSourceRange(); 18632 continue; 18633 } 18634 18635 Decl *D = DE->getDecl(); 18636 auto *VD = cast<VarDecl>(D); 18637 18638 QualType Type = VD->getType(); 18639 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 18640 // It will be analyzed later. 18641 Vars.push_back(DE); 18642 SrcExprs.push_back(nullptr); 18643 DstExprs.push_back(nullptr); 18644 AssignmentOps.push_back(nullptr); 18645 continue; 18646 } 18647 18648 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 18649 // A list item that appears in a copyin clause must be threadprivate. 18650 if (!DSAStack->isThreadPrivate(VD)) { 18651 Diag(ELoc, diag::err_omp_required_access) 18652 << getOpenMPClauseName(OMPC_copyin) 18653 << getOpenMPDirectiveName(OMPD_threadprivate); 18654 continue; 18655 } 18656 18657 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 18658 // A variable of class type (or array thereof) that appears in a 18659 // copyin clause requires an accessible, unambiguous copy assignment 18660 // operator for the class type. 18661 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 18662 VarDecl *SrcVD = 18663 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(), 18664 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 18665 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr( 18666 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 18667 VarDecl *DstVD = 18668 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst", 18669 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 18670 DeclRefExpr *PseudoDstExpr = 18671 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 18672 // For arrays generate assignment operation for single element and replace 18673 // it by the original array element in CodeGen. 18674 ExprResult AssignmentOp = 18675 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr, 18676 PseudoSrcExpr); 18677 if (AssignmentOp.isInvalid()) 18678 continue; 18679 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 18680 /*DiscardedValue*/ false); 18681 if (AssignmentOp.isInvalid()) 18682 continue; 18683 18684 DSAStack->addDSA(VD, DE, OMPC_copyin); 18685 Vars.push_back(DE); 18686 SrcExprs.push_back(PseudoSrcExpr); 18687 DstExprs.push_back(PseudoDstExpr); 18688 AssignmentOps.push_back(AssignmentOp.get()); 18689 } 18690 18691 if (Vars.empty()) 18692 return nullptr; 18693 18694 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 18695 SrcExprs, DstExprs, AssignmentOps); 18696 } 18697 18698 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 18699 SourceLocation StartLoc, 18700 SourceLocation LParenLoc, 18701 SourceLocation EndLoc) { 18702 SmallVector<Expr *, 8> Vars; 18703 SmallVector<Expr *, 8> SrcExprs; 18704 SmallVector<Expr *, 8> DstExprs; 18705 SmallVector<Expr *, 8> AssignmentOps; 18706 for (Expr *RefExpr : VarList) { 18707 assert(RefExpr && "NULL expr in OpenMP linear clause."); 18708 SourceLocation ELoc; 18709 SourceRange ERange; 18710 Expr *SimpleRefExpr = RefExpr; 18711 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 18712 if (Res.second) { 18713 // It will be analyzed later. 18714 Vars.push_back(RefExpr); 18715 SrcExprs.push_back(nullptr); 18716 DstExprs.push_back(nullptr); 18717 AssignmentOps.push_back(nullptr); 18718 } 18719 ValueDecl *D = Res.first; 18720 if (!D) 18721 continue; 18722 18723 QualType Type = D->getType(); 18724 auto *VD = dyn_cast<VarDecl>(D); 18725 18726 // OpenMP [2.14.4.2, Restrictions, p.2] 18727 // A list item that appears in a copyprivate clause may not appear in a 18728 // private or firstprivate clause on the single construct. 18729 if (!VD || !DSAStack->isThreadPrivate(VD)) { 18730 DSAStackTy::DSAVarData DVar = 18731 DSAStack->getTopDSA(D, /*FromParent=*/false); 18732 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 18733 DVar.RefExpr) { 18734 Diag(ELoc, diag::err_omp_wrong_dsa) 18735 << getOpenMPClauseName(DVar.CKind) 18736 << getOpenMPClauseName(OMPC_copyprivate); 18737 reportOriginalDsa(*this, DSAStack, D, DVar); 18738 continue; 18739 } 18740 18741 // OpenMP [2.11.4.2, Restrictions, p.1] 18742 // All list items that appear in a copyprivate clause must be either 18743 // threadprivate or private in the enclosing context. 18744 if (DVar.CKind == OMPC_unknown) { 18745 DVar = DSAStack->getImplicitDSA(D, false); 18746 if (DVar.CKind == OMPC_shared) { 18747 Diag(ELoc, diag::err_omp_required_access) 18748 << getOpenMPClauseName(OMPC_copyprivate) 18749 << "threadprivate or private in the enclosing context"; 18750 reportOriginalDsa(*this, DSAStack, D, DVar); 18751 continue; 18752 } 18753 } 18754 } 18755 18756 // Variably modified types are not supported. 18757 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 18758 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 18759 << getOpenMPClauseName(OMPC_copyprivate) << Type 18760 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 18761 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 18762 VarDecl::DeclarationOnly; 18763 Diag(D->getLocation(), 18764 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 18765 << D; 18766 continue; 18767 } 18768 18769 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 18770 // A variable of class type (or array thereof) that appears in a 18771 // copyin clause requires an accessible, unambiguous copy assignment 18772 // operator for the class type. 18773 Type = Context.getBaseElementType(Type.getNonReferenceType()) 18774 .getUnqualifiedType(); 18775 VarDecl *SrcVD = 18776 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src", 18777 D->hasAttrs() ? &D->getAttrs() : nullptr); 18778 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 18779 VarDecl *DstVD = 18780 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst", 18781 D->hasAttrs() ? &D->getAttrs() : nullptr); 18782 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 18783 ExprResult AssignmentOp = BuildBinOp( 18784 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr); 18785 if (AssignmentOp.isInvalid()) 18786 continue; 18787 AssignmentOp = 18788 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 18789 if (AssignmentOp.isInvalid()) 18790 continue; 18791 18792 // No need to mark vars as copyprivate, they are already threadprivate or 18793 // implicitly private. 18794 assert(VD || isOpenMPCapturedDecl(D)); 18795 Vars.push_back( 18796 VD ? RefExpr->IgnoreParens() 18797 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 18798 SrcExprs.push_back(PseudoSrcExpr); 18799 DstExprs.push_back(PseudoDstExpr); 18800 AssignmentOps.push_back(AssignmentOp.get()); 18801 } 18802 18803 if (Vars.empty()) 18804 return nullptr; 18805 18806 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 18807 Vars, SrcExprs, DstExprs, AssignmentOps); 18808 } 18809 18810 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 18811 SourceLocation StartLoc, 18812 SourceLocation LParenLoc, 18813 SourceLocation EndLoc) { 18814 if (VarList.empty()) 18815 return nullptr; 18816 18817 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 18818 } 18819 18820 /// Tries to find omp_depend_t. type. 18821 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack, 18822 bool Diagnose = true) { 18823 QualType OMPDependT = Stack->getOMPDependT(); 18824 if (!OMPDependT.isNull()) 18825 return true; 18826 IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t"); 18827 ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope()); 18828 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 18829 if (Diagnose) 18830 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t"; 18831 return false; 18832 } 18833 Stack->setOMPDependT(PT.get()); 18834 return true; 18835 } 18836 18837 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, 18838 SourceLocation LParenLoc, 18839 SourceLocation EndLoc) { 18840 if (!Depobj) 18841 return nullptr; 18842 18843 bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack); 18844 18845 // OpenMP 5.0, 2.17.10.1 depobj Construct 18846 // depobj is an lvalue expression of type omp_depend_t. 18847 if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() && 18848 !Depobj->isInstantiationDependent() && 18849 !Depobj->containsUnexpandedParameterPack() && 18850 (OMPDependTFound && 18851 !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(), 18852 /*CompareUnqualified=*/true))) { 18853 Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue) 18854 << 0 << Depobj->getType() << Depobj->getSourceRange(); 18855 } 18856 18857 if (!Depobj->isLValue()) { 18858 Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue) 18859 << 1 << Depobj->getSourceRange(); 18860 } 18861 18862 return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj); 18863 } 18864 18865 OMPClause * 18866 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind, 18867 SourceLocation DepLoc, SourceLocation ColonLoc, 18868 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 18869 SourceLocation LParenLoc, SourceLocation EndLoc) { 18870 if (DSAStack->getCurrentDirective() == OMPD_ordered && 18871 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 18872 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 18873 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 18874 return nullptr; 18875 } 18876 if (DSAStack->getCurrentDirective() == OMPD_taskwait && 18877 DepKind == OMPC_DEPEND_mutexinoutset) { 18878 Diag(DepLoc, diag::err_omp_taskwait_depend_mutexinoutset_not_allowed); 18879 return nullptr; 18880 } 18881 if ((DSAStack->getCurrentDirective() != OMPD_ordered || 18882 DSAStack->getCurrentDirective() == OMPD_depobj) && 18883 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 18884 DepKind == OMPC_DEPEND_sink || 18885 ((LangOpts.OpenMP < 50 || 18886 DSAStack->getCurrentDirective() == OMPD_depobj) && 18887 DepKind == OMPC_DEPEND_depobj))) { 18888 SmallVector<unsigned, 3> Except; 18889 Except.push_back(OMPC_DEPEND_source); 18890 Except.push_back(OMPC_DEPEND_sink); 18891 if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj) 18892 Except.push_back(OMPC_DEPEND_depobj); 18893 if (LangOpts.OpenMP < 51) 18894 Except.push_back(OMPC_DEPEND_inoutset); 18895 std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier) 18896 ? "depend modifier(iterator) or " 18897 : ""; 18898 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 18899 << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0, 18900 /*Last=*/OMPC_DEPEND_unknown, 18901 Except) 18902 << getOpenMPClauseName(OMPC_depend); 18903 return nullptr; 18904 } 18905 if (DepModifier && 18906 (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) { 18907 Diag(DepModifier->getExprLoc(), 18908 diag::err_omp_depend_sink_source_with_modifier); 18909 return nullptr; 18910 } 18911 if (DepModifier && 18912 !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator)) 18913 Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator); 18914 18915 SmallVector<Expr *, 8> Vars; 18916 DSAStackTy::OperatorOffsetTy OpsOffs; 18917 llvm::APSInt DepCounter(/*BitWidth=*/32); 18918 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 18919 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) { 18920 if (const Expr *OrderedCountExpr = 18921 DSAStack->getParentOrderedRegionParam().first) { 18922 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 18923 TotalDepCount.setIsUnsigned(/*Val=*/true); 18924 } 18925 } 18926 for (Expr *RefExpr : VarList) { 18927 assert(RefExpr && "NULL expr in OpenMP shared clause."); 18928 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 18929 // It will be analyzed later. 18930 Vars.push_back(RefExpr); 18931 continue; 18932 } 18933 18934 SourceLocation ELoc = RefExpr->getExprLoc(); 18935 Expr *SimpleExpr = RefExpr->IgnoreParenCasts(); 18936 if (DepKind == OMPC_DEPEND_sink) { 18937 if (DSAStack->getParentOrderedRegionParam().first && 18938 DepCounter >= TotalDepCount) { 18939 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 18940 continue; 18941 } 18942 ++DepCounter; 18943 // OpenMP [2.13.9, Summary] 18944 // depend(dependence-type : vec), where dependence-type is: 18945 // 'sink' and where vec is the iteration vector, which has the form: 18946 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 18947 // where n is the value specified by the ordered clause in the loop 18948 // directive, xi denotes the loop iteration variable of the i-th nested 18949 // loop associated with the loop directive, and di is a constant 18950 // non-negative integer. 18951 if (CurContext->isDependentContext()) { 18952 // It will be analyzed later. 18953 Vars.push_back(RefExpr); 18954 continue; 18955 } 18956 SimpleExpr = SimpleExpr->IgnoreImplicit(); 18957 OverloadedOperatorKind OOK = OO_None; 18958 SourceLocation OOLoc; 18959 Expr *LHS = SimpleExpr; 18960 Expr *RHS = nullptr; 18961 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 18962 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 18963 OOLoc = BO->getOperatorLoc(); 18964 LHS = BO->getLHS()->IgnoreParenImpCasts(); 18965 RHS = BO->getRHS()->IgnoreParenImpCasts(); 18966 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 18967 OOK = OCE->getOperator(); 18968 OOLoc = OCE->getOperatorLoc(); 18969 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 18970 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 18971 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 18972 OOK = MCE->getMethodDecl() 18973 ->getNameInfo() 18974 .getName() 18975 .getCXXOverloadedOperator(); 18976 OOLoc = MCE->getCallee()->getExprLoc(); 18977 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 18978 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 18979 } 18980 SourceLocation ELoc; 18981 SourceRange ERange; 18982 auto Res = getPrivateItem(*this, LHS, ELoc, ERange); 18983 if (Res.second) { 18984 // It will be analyzed later. 18985 Vars.push_back(RefExpr); 18986 } 18987 ValueDecl *D = Res.first; 18988 if (!D) 18989 continue; 18990 18991 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 18992 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 18993 continue; 18994 } 18995 if (RHS) { 18996 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 18997 RHS, OMPC_depend, /*StrictlyPositive=*/false); 18998 if (RHSRes.isInvalid()) 18999 continue; 19000 } 19001 if (!CurContext->isDependentContext() && 19002 DSAStack->getParentOrderedRegionParam().first && 19003 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 19004 const ValueDecl *VD = 19005 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue()); 19006 if (VD) 19007 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 19008 << 1 << VD; 19009 else 19010 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; 19011 continue; 19012 } 19013 OpsOffs.emplace_back(RHS, OOK); 19014 } else { 19015 bool OMPDependTFound = LangOpts.OpenMP >= 50; 19016 if (OMPDependTFound) 19017 OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack, 19018 DepKind == OMPC_DEPEND_depobj); 19019 if (DepKind == OMPC_DEPEND_depobj) { 19020 // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++ 19021 // List items used in depend clauses with the depobj dependence type 19022 // must be expressions of the omp_depend_t type. 19023 if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() && 19024 !RefExpr->isInstantiationDependent() && 19025 !RefExpr->containsUnexpandedParameterPack() && 19026 (OMPDependTFound && 19027 !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(), 19028 RefExpr->getType()))) { 19029 Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue) 19030 << 0 << RefExpr->getType() << RefExpr->getSourceRange(); 19031 continue; 19032 } 19033 if (!RefExpr->isLValue()) { 19034 Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue) 19035 << 1 << RefExpr->getType() << RefExpr->getSourceRange(); 19036 continue; 19037 } 19038 } else { 19039 // OpenMP 5.0 [2.17.11, Restrictions] 19040 // List items used in depend clauses cannot be zero-length array 19041 // sections. 19042 QualType ExprTy = RefExpr->getType().getNonReferenceType(); 19043 const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr); 19044 if (OASE) { 19045 QualType BaseType = 19046 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 19047 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 19048 ExprTy = ATy->getElementType(); 19049 else 19050 ExprTy = BaseType->getPointeeType(); 19051 ExprTy = ExprTy.getNonReferenceType(); 19052 const Expr *Length = OASE->getLength(); 19053 Expr::EvalResult Result; 19054 if (Length && !Length->isValueDependent() && 19055 Length->EvaluateAsInt(Result, Context) && 19056 Result.Val.getInt().isZero()) { 19057 Diag(ELoc, 19058 diag::err_omp_depend_zero_length_array_section_not_allowed) 19059 << SimpleExpr->getSourceRange(); 19060 continue; 19061 } 19062 } 19063 19064 // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++ 19065 // List items used in depend clauses with the in, out, inout, 19066 // inoutset, or mutexinoutset dependence types cannot be 19067 // expressions of the omp_depend_t type. 19068 if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() && 19069 !RefExpr->isInstantiationDependent() && 19070 !RefExpr->containsUnexpandedParameterPack() && 19071 (!RefExpr->IgnoreParenImpCasts()->isLValue() || 19072 (OMPDependTFound && 19073 DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr()))) { 19074 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 19075 << (LangOpts.OpenMP >= 50 ? 1 : 0) 19076 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 19077 continue; 19078 } 19079 19080 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 19081 if (ASE && !ASE->getBase()->isTypeDependent() && 19082 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() && 19083 !ASE->getBase()->getType().getNonReferenceType()->isArrayType()) { 19084 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 19085 << (LangOpts.OpenMP >= 50 ? 1 : 0) 19086 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 19087 continue; 19088 } 19089 19090 ExprResult Res; 19091 { 19092 Sema::TentativeAnalysisScope Trap(*this); 19093 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, 19094 RefExpr->IgnoreParenImpCasts()); 19095 } 19096 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) && 19097 !isa<OMPArrayShapingExpr>(SimpleExpr)) { 19098 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 19099 << (LangOpts.OpenMP >= 50 ? 1 : 0) 19100 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 19101 continue; 19102 } 19103 } 19104 } 19105 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 19106 } 19107 19108 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 19109 TotalDepCount > VarList.size() && 19110 DSAStack->getParentOrderedRegionParam().first && 19111 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { 19112 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 19113 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 19114 } 19115 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 19116 Vars.empty()) 19117 return nullptr; 19118 19119 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 19120 DepModifier, DepKind, DepLoc, ColonLoc, 19121 Vars, TotalDepCount.getZExtValue()); 19122 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) && 19123 DSAStack->isParentOrderedRegion()) 19124 DSAStack->addDoacrossDependClause(C, OpsOffs); 19125 return C; 19126 } 19127 19128 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, 19129 Expr *Device, SourceLocation StartLoc, 19130 SourceLocation LParenLoc, 19131 SourceLocation ModifierLoc, 19132 SourceLocation EndLoc) { 19133 assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) && 19134 "Unexpected device modifier in OpenMP < 50."); 19135 19136 bool ErrorFound = false; 19137 if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) { 19138 std::string Values = 19139 getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown); 19140 Diag(ModifierLoc, diag::err_omp_unexpected_clause_value) 19141 << Values << getOpenMPClauseName(OMPC_device); 19142 ErrorFound = true; 19143 } 19144 19145 Expr *ValExpr = Device; 19146 Stmt *HelperValStmt = nullptr; 19147 19148 // OpenMP [2.9.1, Restrictions] 19149 // The device expression must evaluate to a non-negative integer value. 19150 ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 19151 /*StrictlyPositive=*/false) || 19152 ErrorFound; 19153 if (ErrorFound) 19154 return nullptr; 19155 19156 // OpenMP 5.0 [2.12.5, Restrictions] 19157 // In case of ancestor device-modifier, a requires directive with 19158 // the reverse_offload clause must be specified. 19159 if (Modifier == OMPC_DEVICE_ancestor) { 19160 if (!DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>()) { 19161 targetDiag( 19162 StartLoc, 19163 diag::err_omp_device_ancestor_without_requires_reverse_offload); 19164 ErrorFound = true; 19165 } 19166 } 19167 19168 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 19169 OpenMPDirectiveKind CaptureRegion = 19170 getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP); 19171 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 19172 ValExpr = MakeFullExpr(ValExpr).get(); 19173 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 19174 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 19175 HelperValStmt = buildPreInits(Context, Captures); 19176 } 19177 19178 return new (Context) 19179 OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 19180 LParenLoc, ModifierLoc, EndLoc); 19181 } 19182 19183 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 19184 DSAStackTy *Stack, QualType QTy, 19185 bool FullCheck = true) { 19186 if (SemaRef.RequireCompleteType(SL, QTy, diag::err_incomplete_type)) 19187 return false; 19188 if (FullCheck && !SemaRef.CurContext->isDependentContext() && 19189 !QTy.isTriviallyCopyableType(SemaRef.Context)) 19190 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR; 19191 return true; 19192 } 19193 19194 /// Return true if it can be proven that the provided array expression 19195 /// (array section or array subscript) does NOT specify the whole size of the 19196 /// array whose base type is \a BaseQTy. 19197 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 19198 const Expr *E, 19199 QualType BaseQTy) { 19200 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 19201 19202 // If this is an array subscript, it refers to the whole size if the size of 19203 // the dimension is constant and equals 1. Also, an array section assumes the 19204 // format of an array subscript if no colon is used. 19205 if (isa<ArraySubscriptExpr>(E) || 19206 (OASE && OASE->getColonLocFirst().isInvalid())) { 19207 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 19208 return ATy->getSize().getSExtValue() != 1; 19209 // Size can't be evaluated statically. 19210 return false; 19211 } 19212 19213 assert(OASE && "Expecting array section if not an array subscript."); 19214 const Expr *LowerBound = OASE->getLowerBound(); 19215 const Expr *Length = OASE->getLength(); 19216 19217 // If there is a lower bound that does not evaluates to zero, we are not 19218 // covering the whole dimension. 19219 if (LowerBound) { 19220 Expr::EvalResult Result; 19221 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext())) 19222 return false; // Can't get the integer value as a constant. 19223 19224 llvm::APSInt ConstLowerBound = Result.Val.getInt(); 19225 if (ConstLowerBound.getSExtValue()) 19226 return true; 19227 } 19228 19229 // If we don't have a length we covering the whole dimension. 19230 if (!Length) 19231 return false; 19232 19233 // If the base is a pointer, we don't have a way to get the size of the 19234 // pointee. 19235 if (BaseQTy->isPointerType()) 19236 return false; 19237 19238 // We can only check if the length is the same as the size of the dimension 19239 // if we have a constant array. 19240 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 19241 if (!CATy) 19242 return false; 19243 19244 Expr::EvalResult Result; 19245 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 19246 return false; // Can't get the integer value as a constant. 19247 19248 llvm::APSInt ConstLength = Result.Val.getInt(); 19249 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 19250 } 19251 19252 // Return true if it can be proven that the provided array expression (array 19253 // section or array subscript) does NOT specify a single element of the array 19254 // whose base type is \a BaseQTy. 19255 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 19256 const Expr *E, 19257 QualType BaseQTy) { 19258 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 19259 19260 // An array subscript always refer to a single element. Also, an array section 19261 // assumes the format of an array subscript if no colon is used. 19262 if (isa<ArraySubscriptExpr>(E) || 19263 (OASE && OASE->getColonLocFirst().isInvalid())) 19264 return false; 19265 19266 assert(OASE && "Expecting array section if not an array subscript."); 19267 const Expr *Length = OASE->getLength(); 19268 19269 // If we don't have a length we have to check if the array has unitary size 19270 // for this dimension. Also, we should always expect a length if the base type 19271 // is pointer. 19272 if (!Length) { 19273 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 19274 return ATy->getSize().getSExtValue() != 1; 19275 // We cannot assume anything. 19276 return false; 19277 } 19278 19279 // Check if the length evaluates to 1. 19280 Expr::EvalResult Result; 19281 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 19282 return false; // Can't get the integer value as a constant. 19283 19284 llvm::APSInt ConstLength = Result.Val.getInt(); 19285 return ConstLength.getSExtValue() != 1; 19286 } 19287 19288 // The base of elements of list in a map clause have to be either: 19289 // - a reference to variable or field. 19290 // - a member expression. 19291 // - an array expression. 19292 // 19293 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 19294 // reference to 'r'. 19295 // 19296 // If we have: 19297 // 19298 // struct SS { 19299 // Bla S; 19300 // foo() { 19301 // #pragma omp target map (S.Arr[:12]); 19302 // } 19303 // } 19304 // 19305 // We want to retrieve the member expression 'this->S'; 19306 19307 // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2] 19308 // If a list item is an array section, it must specify contiguous storage. 19309 // 19310 // For this restriction it is sufficient that we make sure only references 19311 // to variables or fields and array expressions, and that no array sections 19312 // exist except in the rightmost expression (unless they cover the whole 19313 // dimension of the array). E.g. these would be invalid: 19314 // 19315 // r.ArrS[3:5].Arr[6:7] 19316 // 19317 // r.ArrS[3:5].x 19318 // 19319 // but these would be valid: 19320 // r.ArrS[3].Arr[6:7] 19321 // 19322 // r.ArrS[3].x 19323 namespace { 19324 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> { 19325 Sema &SemaRef; 19326 OpenMPClauseKind CKind = OMPC_unknown; 19327 OpenMPDirectiveKind DKind = OMPD_unknown; 19328 OMPClauseMappableExprCommon::MappableExprComponentList &Components; 19329 bool IsNonContiguous = false; 19330 bool NoDiagnose = false; 19331 const Expr *RelevantExpr = nullptr; 19332 bool AllowUnitySizeArraySection = true; 19333 bool AllowWholeSizeArraySection = true; 19334 bool AllowAnotherPtr = true; 19335 SourceLocation ELoc; 19336 SourceRange ERange; 19337 19338 void emitErrorMsg() { 19339 // If nothing else worked, this is not a valid map clause expression. 19340 if (SemaRef.getLangOpts().OpenMP < 50) { 19341 SemaRef.Diag(ELoc, 19342 diag::err_omp_expected_named_var_member_or_array_expression) 19343 << ERange; 19344 } else { 19345 SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses) 19346 << getOpenMPClauseName(CKind) << ERange; 19347 } 19348 } 19349 19350 public: 19351 bool VisitDeclRefExpr(DeclRefExpr *DRE) { 19352 if (!isa<VarDecl>(DRE->getDecl())) { 19353 emitErrorMsg(); 19354 return false; 19355 } 19356 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19357 RelevantExpr = DRE; 19358 // Record the component. 19359 Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous); 19360 return true; 19361 } 19362 19363 bool VisitMemberExpr(MemberExpr *ME) { 19364 Expr *E = ME; 19365 Expr *BaseE = ME->getBase()->IgnoreParenCasts(); 19366 19367 if (isa<CXXThisExpr>(BaseE)) { 19368 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19369 // We found a base expression: this->Val. 19370 RelevantExpr = ME; 19371 } else { 19372 E = BaseE; 19373 } 19374 19375 if (!isa<FieldDecl>(ME->getMemberDecl())) { 19376 if (!NoDiagnose) { 19377 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 19378 << ME->getSourceRange(); 19379 return false; 19380 } 19381 if (RelevantExpr) 19382 return false; 19383 return Visit(E); 19384 } 19385 19386 auto *FD = cast<FieldDecl>(ME->getMemberDecl()); 19387 19388 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 19389 // A bit-field cannot appear in a map clause. 19390 // 19391 if (FD->isBitField()) { 19392 if (!NoDiagnose) { 19393 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 19394 << ME->getSourceRange() << getOpenMPClauseName(CKind); 19395 return false; 19396 } 19397 if (RelevantExpr) 19398 return false; 19399 return Visit(E); 19400 } 19401 19402 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 19403 // If the type of a list item is a reference to a type T then the type 19404 // will be considered to be T for all purposes of this clause. 19405 QualType CurType = BaseE->getType().getNonReferenceType(); 19406 19407 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 19408 // A list item cannot be a variable that is a member of a structure with 19409 // a union type. 19410 // 19411 if (CurType->isUnionType()) { 19412 if (!NoDiagnose) { 19413 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 19414 << ME->getSourceRange(); 19415 return false; 19416 } 19417 return RelevantExpr || Visit(E); 19418 } 19419 19420 // If we got a member expression, we should not expect any array section 19421 // before that: 19422 // 19423 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 19424 // If a list item is an element of a structure, only the rightmost symbol 19425 // of the variable reference can be an array section. 19426 // 19427 AllowUnitySizeArraySection = false; 19428 AllowWholeSizeArraySection = false; 19429 19430 // Record the component. 19431 Components.emplace_back(ME, FD, IsNonContiguous); 19432 return RelevantExpr || Visit(E); 19433 } 19434 19435 bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) { 19436 Expr *E = AE->getBase()->IgnoreParenImpCasts(); 19437 19438 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 19439 if (!NoDiagnose) { 19440 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 19441 << 0 << AE->getSourceRange(); 19442 return false; 19443 } 19444 return RelevantExpr || Visit(E); 19445 } 19446 19447 // If we got an array subscript that express the whole dimension we 19448 // can have any array expressions before. If it only expressing part of 19449 // the dimension, we can only have unitary-size array expressions. 19450 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE, E->getType())) 19451 AllowWholeSizeArraySection = false; 19452 19453 if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) { 19454 Expr::EvalResult Result; 19455 if (!AE->getIdx()->isValueDependent() && 19456 AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) && 19457 !Result.Val.getInt().isZero()) { 19458 SemaRef.Diag(AE->getIdx()->getExprLoc(), 19459 diag::err_omp_invalid_map_this_expr); 19460 SemaRef.Diag(AE->getIdx()->getExprLoc(), 19461 diag::note_omp_invalid_subscript_on_this_ptr_map); 19462 } 19463 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19464 RelevantExpr = TE; 19465 } 19466 19467 // Record the component - we don't have any declaration associated. 19468 Components.emplace_back(AE, nullptr, IsNonContiguous); 19469 19470 return RelevantExpr || Visit(E); 19471 } 19472 19473 bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) { 19474 // After OMP 5.0 Array section in reduction clause will be implicitly 19475 // mapped 19476 assert(!(SemaRef.getLangOpts().OpenMP < 50 && NoDiagnose) && 19477 "Array sections cannot be implicitly mapped."); 19478 Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 19479 QualType CurType = 19480 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 19481 19482 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 19483 // If the type of a list item is a reference to a type T then the type 19484 // will be considered to be T for all purposes of this clause. 19485 if (CurType->isReferenceType()) 19486 CurType = CurType->getPointeeType(); 19487 19488 bool IsPointer = CurType->isAnyPointerType(); 19489 19490 if (!IsPointer && !CurType->isArrayType()) { 19491 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 19492 << 0 << OASE->getSourceRange(); 19493 return false; 19494 } 19495 19496 bool NotWhole = 19497 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType); 19498 bool NotUnity = 19499 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType); 19500 19501 if (AllowWholeSizeArraySection) { 19502 // Any array section is currently allowed. Allowing a whole size array 19503 // section implies allowing a unity array section as well. 19504 // 19505 // If this array section refers to the whole dimension we can still 19506 // accept other array sections before this one, except if the base is a 19507 // pointer. Otherwise, only unitary sections are accepted. 19508 if (NotWhole || IsPointer) 19509 AllowWholeSizeArraySection = false; 19510 } else if (DKind == OMPD_target_update && 19511 SemaRef.getLangOpts().OpenMP >= 50) { 19512 if (IsPointer && !AllowAnotherPtr) 19513 SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined) 19514 << /*array of unknown bound */ 1; 19515 else 19516 IsNonContiguous = true; 19517 } else if (AllowUnitySizeArraySection && NotUnity) { 19518 // A unity or whole array section is not allowed and that is not 19519 // compatible with the properties of the current array section. 19520 if (NoDiagnose) 19521 return false; 19522 SemaRef.Diag(ELoc, 19523 diag::err_array_section_does_not_specify_contiguous_storage) 19524 << OASE->getSourceRange(); 19525 return false; 19526 } 19527 19528 if (IsPointer) 19529 AllowAnotherPtr = false; 19530 19531 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) { 19532 Expr::EvalResult ResultR; 19533 Expr::EvalResult ResultL; 19534 if (!OASE->getLength()->isValueDependent() && 19535 OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) && 19536 !ResultR.Val.getInt().isOne()) { 19537 SemaRef.Diag(OASE->getLength()->getExprLoc(), 19538 diag::err_omp_invalid_map_this_expr); 19539 SemaRef.Diag(OASE->getLength()->getExprLoc(), 19540 diag::note_omp_invalid_length_on_this_ptr_mapping); 19541 } 19542 if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() && 19543 OASE->getLowerBound()->EvaluateAsInt(ResultL, 19544 SemaRef.getASTContext()) && 19545 !ResultL.Val.getInt().isZero()) { 19546 SemaRef.Diag(OASE->getLowerBound()->getExprLoc(), 19547 diag::err_omp_invalid_map_this_expr); 19548 SemaRef.Diag(OASE->getLowerBound()->getExprLoc(), 19549 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping); 19550 } 19551 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19552 RelevantExpr = TE; 19553 } 19554 19555 // Record the component - we don't have any declaration associated. 19556 Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false); 19557 return RelevantExpr || Visit(E); 19558 } 19559 bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) { 19560 Expr *Base = E->getBase(); 19561 19562 // Record the component - we don't have any declaration associated. 19563 Components.emplace_back(E, nullptr, IsNonContiguous); 19564 19565 return Visit(Base->IgnoreParenImpCasts()); 19566 } 19567 19568 bool VisitUnaryOperator(UnaryOperator *UO) { 19569 if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() || 19570 UO->getOpcode() != UO_Deref) { 19571 emitErrorMsg(); 19572 return false; 19573 } 19574 if (!RelevantExpr) { 19575 // Record the component if haven't found base decl. 19576 Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false); 19577 } 19578 return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts()); 19579 } 19580 bool VisitBinaryOperator(BinaryOperator *BO) { 19581 if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) { 19582 emitErrorMsg(); 19583 return false; 19584 } 19585 19586 // Pointer arithmetic is the only thing we expect to happen here so after we 19587 // make sure the binary operator is a pointer type, the we only thing need 19588 // to to is to visit the subtree that has the same type as root (so that we 19589 // know the other subtree is just an offset) 19590 Expr *LE = BO->getLHS()->IgnoreParenImpCasts(); 19591 Expr *RE = BO->getRHS()->IgnoreParenImpCasts(); 19592 Components.emplace_back(BO, nullptr, false); 19593 assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() || 19594 RE->getType().getTypePtr() == BO->getType().getTypePtr()) && 19595 "Either LHS or RHS have base decl inside"); 19596 if (BO->getType().getTypePtr() == LE->getType().getTypePtr()) 19597 return RelevantExpr || Visit(LE); 19598 return RelevantExpr || Visit(RE); 19599 } 19600 bool VisitCXXThisExpr(CXXThisExpr *CTE) { 19601 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19602 RelevantExpr = CTE; 19603 Components.emplace_back(CTE, nullptr, IsNonContiguous); 19604 return true; 19605 } 19606 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) { 19607 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19608 Components.emplace_back(COCE, nullptr, IsNonContiguous); 19609 return true; 19610 } 19611 bool VisitOpaqueValueExpr(OpaqueValueExpr *E) { 19612 Expr *Source = E->getSourceExpr(); 19613 if (!Source) { 19614 emitErrorMsg(); 19615 return false; 19616 } 19617 return Visit(Source); 19618 } 19619 bool VisitStmt(Stmt *) { 19620 emitErrorMsg(); 19621 return false; 19622 } 19623 const Expr *getFoundBase() const { return RelevantExpr; } 19624 explicit MapBaseChecker( 19625 Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, 19626 OMPClauseMappableExprCommon::MappableExprComponentList &Components, 19627 bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange) 19628 : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components), 19629 NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {} 19630 }; 19631 } // namespace 19632 19633 /// Return the expression of the base of the mappable expression or null if it 19634 /// cannot be determined and do all the necessary checks to see if the 19635 /// expression is valid as a standalone mappable expression. In the process, 19636 /// record all the components of the expression. 19637 static const Expr *checkMapClauseExpressionBase( 19638 Sema &SemaRef, Expr *E, 19639 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 19640 OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) { 19641 SourceLocation ELoc = E->getExprLoc(); 19642 SourceRange ERange = E->getSourceRange(); 19643 MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc, 19644 ERange); 19645 if (Checker.Visit(E->IgnoreParens())) { 19646 // Check if the highest dimension array section has length specified 19647 if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() && 19648 (CKind == OMPC_to || CKind == OMPC_from)) { 19649 auto CI = CurComponents.rbegin(); 19650 auto CE = CurComponents.rend(); 19651 for (; CI != CE; ++CI) { 19652 const auto *OASE = 19653 dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression()); 19654 if (!OASE) 19655 continue; 19656 if (OASE && OASE->getLength()) 19657 break; 19658 SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length) 19659 << ERange; 19660 } 19661 } 19662 return Checker.getFoundBase(); 19663 } 19664 return nullptr; 19665 } 19666 19667 // Return true if expression E associated with value VD has conflicts with other 19668 // map information. 19669 static bool checkMapConflicts( 19670 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E, 19671 bool CurrentRegionOnly, 19672 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 19673 OpenMPClauseKind CKind) { 19674 assert(VD && E); 19675 SourceLocation ELoc = E->getExprLoc(); 19676 SourceRange ERange = E->getSourceRange(); 19677 19678 // In order to easily check the conflicts we need to match each component of 19679 // the expression under test with the components of the expressions that are 19680 // already in the stack. 19681 19682 assert(!CurComponents.empty() && "Map clause expression with no components!"); 19683 assert(CurComponents.back().getAssociatedDeclaration() == VD && 19684 "Map clause expression with unexpected base!"); 19685 19686 // Variables to help detecting enclosing problems in data environment nests. 19687 bool IsEnclosedByDataEnvironmentExpr = false; 19688 const Expr *EnclosingExpr = nullptr; 19689 19690 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 19691 VD, CurrentRegionOnly, 19692 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc, 19693 ERange, CKind, &EnclosingExpr, 19694 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef 19695 StackComponents, 19696 OpenMPClauseKind Kind) { 19697 if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50) 19698 return false; 19699 assert(!StackComponents.empty() && 19700 "Map clause expression with no components!"); 19701 assert(StackComponents.back().getAssociatedDeclaration() == VD && 19702 "Map clause expression with unexpected base!"); 19703 (void)VD; 19704 19705 // The whole expression in the stack. 19706 const Expr *RE = StackComponents.front().getAssociatedExpression(); 19707 19708 // Expressions must start from the same base. Here we detect at which 19709 // point both expressions diverge from each other and see if we can 19710 // detect if the memory referred to both expressions is contiguous and 19711 // do not overlap. 19712 auto CI = CurComponents.rbegin(); 19713 auto CE = CurComponents.rend(); 19714 auto SI = StackComponents.rbegin(); 19715 auto SE = StackComponents.rend(); 19716 for (; CI != CE && SI != SE; ++CI, ++SI) { 19717 19718 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 19719 // At most one list item can be an array item derived from a given 19720 // variable in map clauses of the same construct. 19721 if (CurrentRegionOnly && 19722 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 19723 isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) || 19724 isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) && 19725 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 19726 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) || 19727 isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) { 19728 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 19729 diag::err_omp_multiple_array_items_in_map_clause) 19730 << CI->getAssociatedExpression()->getSourceRange(); 19731 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 19732 diag::note_used_here) 19733 << SI->getAssociatedExpression()->getSourceRange(); 19734 return true; 19735 } 19736 19737 // Do both expressions have the same kind? 19738 if (CI->getAssociatedExpression()->getStmtClass() != 19739 SI->getAssociatedExpression()->getStmtClass()) 19740 break; 19741 19742 // Are we dealing with different variables/fields? 19743 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 19744 break; 19745 } 19746 // Check if the extra components of the expressions in the enclosing 19747 // data environment are redundant for the current base declaration. 19748 // If they are, the maps completely overlap, which is legal. 19749 for (; SI != SE; ++SI) { 19750 QualType Type; 19751 if (const auto *ASE = 19752 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 19753 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 19754 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>( 19755 SI->getAssociatedExpression())) { 19756 const Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 19757 Type = 19758 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 19759 } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>( 19760 SI->getAssociatedExpression())) { 19761 Type = OASE->getBase()->getType()->getPointeeType(); 19762 } 19763 if (Type.isNull() || Type->isAnyPointerType() || 19764 checkArrayExpressionDoesNotReferToWholeSize( 19765 SemaRef, SI->getAssociatedExpression(), Type)) 19766 break; 19767 } 19768 19769 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 19770 // List items of map clauses in the same construct must not share 19771 // original storage. 19772 // 19773 // If the expressions are exactly the same or one is a subset of the 19774 // other, it means they are sharing storage. 19775 if (CI == CE && SI == SE) { 19776 if (CurrentRegionOnly) { 19777 if (CKind == OMPC_map) { 19778 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 19779 } else { 19780 assert(CKind == OMPC_to || CKind == OMPC_from); 19781 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 19782 << ERange; 19783 } 19784 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 19785 << RE->getSourceRange(); 19786 return true; 19787 } 19788 // If we find the same expression in the enclosing data environment, 19789 // that is legal. 19790 IsEnclosedByDataEnvironmentExpr = true; 19791 return false; 19792 } 19793 19794 QualType DerivedType = 19795 std::prev(CI)->getAssociatedDeclaration()->getType(); 19796 SourceLocation DerivedLoc = 19797 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 19798 19799 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 19800 // If the type of a list item is a reference to a type T then the type 19801 // will be considered to be T for all purposes of this clause. 19802 DerivedType = DerivedType.getNonReferenceType(); 19803 19804 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 19805 // A variable for which the type is pointer and an array section 19806 // derived from that variable must not appear as list items of map 19807 // clauses of the same construct. 19808 // 19809 // Also, cover one of the cases in: 19810 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 19811 // If any part of the original storage of a list item has corresponding 19812 // storage in the device data environment, all of the original storage 19813 // must have corresponding storage in the device data environment. 19814 // 19815 if (DerivedType->isAnyPointerType()) { 19816 if (CI == CE || SI == SE) { 19817 SemaRef.Diag( 19818 DerivedLoc, 19819 diag::err_omp_pointer_mapped_along_with_derived_section) 19820 << DerivedLoc; 19821 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 19822 << RE->getSourceRange(); 19823 return true; 19824 } 19825 if (CI->getAssociatedExpression()->getStmtClass() != 19826 SI->getAssociatedExpression()->getStmtClass() || 19827 CI->getAssociatedDeclaration()->getCanonicalDecl() == 19828 SI->getAssociatedDeclaration()->getCanonicalDecl()) { 19829 assert(CI != CE && SI != SE); 19830 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced) 19831 << DerivedLoc; 19832 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 19833 << RE->getSourceRange(); 19834 return true; 19835 } 19836 } 19837 19838 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 19839 // List items of map clauses in the same construct must not share 19840 // original storage. 19841 // 19842 // An expression is a subset of the other. 19843 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 19844 if (CKind == OMPC_map) { 19845 if (CI != CE || SI != SE) { 19846 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is 19847 // a pointer. 19848 auto Begin = 19849 CI != CE ? CurComponents.begin() : StackComponents.begin(); 19850 auto End = CI != CE ? CurComponents.end() : StackComponents.end(); 19851 auto It = Begin; 19852 while (It != End && !It->getAssociatedDeclaration()) 19853 std::advance(It, 1); 19854 assert(It != End && 19855 "Expected at least one component with the declaration."); 19856 if (It != Begin && It->getAssociatedDeclaration() 19857 ->getType() 19858 .getCanonicalType() 19859 ->isAnyPointerType()) { 19860 IsEnclosedByDataEnvironmentExpr = false; 19861 EnclosingExpr = nullptr; 19862 return false; 19863 } 19864 } 19865 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 19866 } else { 19867 assert(CKind == OMPC_to || CKind == OMPC_from); 19868 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 19869 << ERange; 19870 } 19871 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 19872 << RE->getSourceRange(); 19873 return true; 19874 } 19875 19876 // The current expression uses the same base as other expression in the 19877 // data environment but does not contain it completely. 19878 if (!CurrentRegionOnly && SI != SE) 19879 EnclosingExpr = RE; 19880 19881 // The current expression is a subset of the expression in the data 19882 // environment. 19883 IsEnclosedByDataEnvironmentExpr |= 19884 (!CurrentRegionOnly && CI != CE && SI == SE); 19885 19886 return false; 19887 }); 19888 19889 if (CurrentRegionOnly) 19890 return FoundError; 19891 19892 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 19893 // If any part of the original storage of a list item has corresponding 19894 // storage in the device data environment, all of the original storage must 19895 // have corresponding storage in the device data environment. 19896 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 19897 // If a list item is an element of a structure, and a different element of 19898 // the structure has a corresponding list item in the device data environment 19899 // prior to a task encountering the construct associated with the map clause, 19900 // then the list item must also have a corresponding list item in the device 19901 // data environment prior to the task encountering the construct. 19902 // 19903 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 19904 SemaRef.Diag(ELoc, 19905 diag::err_omp_original_storage_is_shared_and_does_not_contain) 19906 << ERange; 19907 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 19908 << EnclosingExpr->getSourceRange(); 19909 return true; 19910 } 19911 19912 return FoundError; 19913 } 19914 19915 // Look up the user-defined mapper given the mapper name and mapped type, and 19916 // build a reference to it. 19917 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S, 19918 CXXScopeSpec &MapperIdScopeSpec, 19919 const DeclarationNameInfo &MapperId, 19920 QualType Type, 19921 Expr *UnresolvedMapper) { 19922 if (MapperIdScopeSpec.isInvalid()) 19923 return ExprError(); 19924 // Get the actual type for the array type. 19925 if (Type->isArrayType()) { 19926 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type"); 19927 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType(); 19928 } 19929 // Find all user-defined mappers with the given MapperId. 19930 SmallVector<UnresolvedSet<8>, 4> Lookups; 19931 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName); 19932 Lookup.suppressDiagnostics(); 19933 if (S) { 19934 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) { 19935 NamedDecl *D = Lookup.getRepresentativeDecl(); 19936 while (S && !S->isDeclScope(D)) 19937 S = S->getParent(); 19938 if (S) 19939 S = S->getParent(); 19940 Lookups.emplace_back(); 19941 Lookups.back().append(Lookup.begin(), Lookup.end()); 19942 Lookup.clear(); 19943 } 19944 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) { 19945 // Extract the user-defined mappers with the given MapperId. 19946 Lookups.push_back(UnresolvedSet<8>()); 19947 for (NamedDecl *D : ULE->decls()) { 19948 auto *DMD = cast<OMPDeclareMapperDecl>(D); 19949 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation."); 19950 Lookups.back().addDecl(DMD); 19951 } 19952 } 19953 // Defer the lookup for dependent types. The results will be passed through 19954 // UnresolvedMapper on instantiation. 19955 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() || 19956 Type->isInstantiationDependentType() || 19957 Type->containsUnexpandedParameterPack() || 19958 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 19959 return !D->isInvalidDecl() && 19960 (D->getType()->isDependentType() || 19961 D->getType()->isInstantiationDependentType() || 19962 D->getType()->containsUnexpandedParameterPack()); 19963 })) { 19964 UnresolvedSet<8> URS; 19965 for (const UnresolvedSet<8> &Set : Lookups) { 19966 if (Set.empty()) 19967 continue; 19968 URS.append(Set.begin(), Set.end()); 19969 } 19970 return UnresolvedLookupExpr::Create( 19971 SemaRef.Context, /*NamingClass=*/nullptr, 19972 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId, 19973 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end()); 19974 } 19975 SourceLocation Loc = MapperId.getLoc(); 19976 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 19977 // The type must be of struct, union or class type in C and C++ 19978 if (!Type->isStructureOrClassType() && !Type->isUnionType() && 19979 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) { 19980 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type); 19981 return ExprError(); 19982 } 19983 // Perform argument dependent lookup. 19984 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet()) 19985 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups); 19986 // Return the first user-defined mapper with the desired type. 19987 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 19988 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * { 19989 if (!D->isInvalidDecl() && 19990 SemaRef.Context.hasSameType(D->getType(), Type)) 19991 return D; 19992 return nullptr; 19993 })) 19994 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 19995 // Find the first user-defined mapper with a type derived from the desired 19996 // type. 19997 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 19998 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * { 19999 if (!D->isInvalidDecl() && 20000 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) && 20001 !Type.isMoreQualifiedThan(D->getType())) 20002 return D; 20003 return nullptr; 20004 })) { 20005 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 20006 /*DetectVirtual=*/false); 20007 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) { 20008 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 20009 VD->getType().getUnqualifiedType()))) { 20010 if (SemaRef.CheckBaseClassAccess( 20011 Loc, VD->getType(), Type, Paths.front(), 20012 /*DiagID=*/0) != Sema::AR_inaccessible) { 20013 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 20014 } 20015 } 20016 } 20017 } 20018 // Report error if a mapper is specified, but cannot be found. 20019 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") { 20020 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper) 20021 << Type << MapperId.getName(); 20022 return ExprError(); 20023 } 20024 return ExprEmpty(); 20025 } 20026 20027 namespace { 20028 // Utility struct that gathers all the related lists associated with a mappable 20029 // expression. 20030 struct MappableVarListInfo { 20031 // The list of expressions. 20032 ArrayRef<Expr *> VarList; 20033 // The list of processed expressions. 20034 SmallVector<Expr *, 16> ProcessedVarList; 20035 // The mappble components for each expression. 20036 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 20037 // The base declaration of the variable. 20038 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 20039 // The reference to the user-defined mapper associated with every expression. 20040 SmallVector<Expr *, 16> UDMapperList; 20041 20042 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 20043 // We have a list of components and base declarations for each entry in the 20044 // variable list. 20045 VarComponents.reserve(VarList.size()); 20046 VarBaseDeclarations.reserve(VarList.size()); 20047 } 20048 }; 20049 } // namespace 20050 20051 // Check the validity of the provided variable list for the provided clause kind 20052 // \a CKind. In the check process the valid expressions, mappable expression 20053 // components, variables, and user-defined mappers are extracted and used to 20054 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a 20055 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec, 20056 // and \a MapperId are expected to be valid if the clause kind is 'map'. 20057 static void checkMappableExpressionList( 20058 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind, 20059 MappableVarListInfo &MVLI, SourceLocation StartLoc, 20060 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId, 20061 ArrayRef<Expr *> UnresolvedMappers, 20062 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 20063 ArrayRef<OpenMPMapModifierKind> Modifiers = None, 20064 bool IsMapTypeImplicit = false, bool NoDiagnose = false) { 20065 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 20066 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 20067 "Unexpected clause kind with mappable expressions!"); 20068 20069 // If the identifier of user-defined mapper is not specified, it is "default". 20070 // We do not change the actual name in this clause to distinguish whether a 20071 // mapper is specified explicitly, i.e., it is not explicitly specified when 20072 // MapperId.getName() is empty. 20073 if (!MapperId.getName() || MapperId.getName().isEmpty()) { 20074 auto &DeclNames = SemaRef.getASTContext().DeclarationNames; 20075 MapperId.setName(DeclNames.getIdentifier( 20076 &SemaRef.getASTContext().Idents.get("default"))); 20077 MapperId.setLoc(StartLoc); 20078 } 20079 20080 // Iterators to find the current unresolved mapper expression. 20081 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end(); 20082 bool UpdateUMIt = false; 20083 Expr *UnresolvedMapper = nullptr; 20084 20085 bool HasHoldModifier = 20086 llvm::is_contained(Modifiers, OMPC_MAP_MODIFIER_ompx_hold); 20087 20088 // Keep track of the mappable components and base declarations in this clause. 20089 // Each entry in the list is going to have a list of components associated. We 20090 // record each set of the components so that we can build the clause later on. 20091 // In the end we should have the same amount of declarations and component 20092 // lists. 20093 20094 for (Expr *RE : MVLI.VarList) { 20095 assert(RE && "Null expr in omp to/from/map clause"); 20096 SourceLocation ELoc = RE->getExprLoc(); 20097 20098 // Find the current unresolved mapper expression. 20099 if (UpdateUMIt && UMIt != UMEnd) { 20100 UMIt++; 20101 assert( 20102 UMIt != UMEnd && 20103 "Expect the size of UnresolvedMappers to match with that of VarList"); 20104 } 20105 UpdateUMIt = true; 20106 if (UMIt != UMEnd) 20107 UnresolvedMapper = *UMIt; 20108 20109 const Expr *VE = RE->IgnoreParenLValueCasts(); 20110 20111 if (VE->isValueDependent() || VE->isTypeDependent() || 20112 VE->isInstantiationDependent() || 20113 VE->containsUnexpandedParameterPack()) { 20114 // Try to find the associated user-defined mapper. 20115 ExprResult ER = buildUserDefinedMapperRef( 20116 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 20117 VE->getType().getCanonicalType(), UnresolvedMapper); 20118 if (ER.isInvalid()) 20119 continue; 20120 MVLI.UDMapperList.push_back(ER.get()); 20121 // We can only analyze this information once the missing information is 20122 // resolved. 20123 MVLI.ProcessedVarList.push_back(RE); 20124 continue; 20125 } 20126 20127 Expr *SimpleExpr = RE->IgnoreParenCasts(); 20128 20129 if (!RE->isLValue()) { 20130 if (SemaRef.getLangOpts().OpenMP < 50) { 20131 SemaRef.Diag( 20132 ELoc, diag::err_omp_expected_named_var_member_or_array_expression) 20133 << RE->getSourceRange(); 20134 } else { 20135 SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses) 20136 << getOpenMPClauseName(CKind) << RE->getSourceRange(); 20137 } 20138 continue; 20139 } 20140 20141 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 20142 ValueDecl *CurDeclaration = nullptr; 20143 20144 // Obtain the array or member expression bases if required. Also, fill the 20145 // components array with all the components identified in the process. 20146 const Expr *BE = 20147 checkMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind, 20148 DSAS->getCurrentDirective(), NoDiagnose); 20149 if (!BE) 20150 continue; 20151 20152 assert(!CurComponents.empty() && 20153 "Invalid mappable expression information."); 20154 20155 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) { 20156 // Add store "this" pointer to class in DSAStackTy for future checking 20157 DSAS->addMappedClassesQualTypes(TE->getType()); 20158 // Try to find the associated user-defined mapper. 20159 ExprResult ER = buildUserDefinedMapperRef( 20160 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 20161 VE->getType().getCanonicalType(), UnresolvedMapper); 20162 if (ER.isInvalid()) 20163 continue; 20164 MVLI.UDMapperList.push_back(ER.get()); 20165 // Skip restriction checking for variable or field declarations 20166 MVLI.ProcessedVarList.push_back(RE); 20167 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 20168 MVLI.VarComponents.back().append(CurComponents.begin(), 20169 CurComponents.end()); 20170 MVLI.VarBaseDeclarations.push_back(nullptr); 20171 continue; 20172 } 20173 20174 // For the following checks, we rely on the base declaration which is 20175 // expected to be associated with the last component. The declaration is 20176 // expected to be a variable or a field (if 'this' is being mapped). 20177 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 20178 assert(CurDeclaration && "Null decl on map clause."); 20179 assert( 20180 CurDeclaration->isCanonicalDecl() && 20181 "Expecting components to have associated only canonical declarations."); 20182 20183 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 20184 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 20185 20186 assert((VD || FD) && "Only variables or fields are expected here!"); 20187 (void)FD; 20188 20189 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 20190 // threadprivate variables cannot appear in a map clause. 20191 // OpenMP 4.5 [2.10.5, target update Construct] 20192 // threadprivate variables cannot appear in a from clause. 20193 if (VD && DSAS->isThreadPrivate(VD)) { 20194 if (NoDiagnose) 20195 continue; 20196 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 20197 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 20198 << getOpenMPClauseName(CKind); 20199 reportOriginalDsa(SemaRef, DSAS, VD, DVar); 20200 continue; 20201 } 20202 20203 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 20204 // A list item cannot appear in both a map clause and a data-sharing 20205 // attribute clause on the same construct. 20206 20207 // Check conflicts with other map clause expressions. We check the conflicts 20208 // with the current construct separately from the enclosing data 20209 // environment, because the restrictions are different. We only have to 20210 // check conflicts across regions for the map clauses. 20211 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 20212 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 20213 break; 20214 if (CKind == OMPC_map && 20215 (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) && 20216 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 20217 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 20218 break; 20219 20220 // OpenMP 4.5 [2.10.5, target update Construct] 20221 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 20222 // If the type of a list item is a reference to a type T then the type will 20223 // be considered to be T for all purposes of this clause. 20224 auto I = llvm::find_if( 20225 CurComponents, 20226 [](const OMPClauseMappableExprCommon::MappableComponent &MC) { 20227 return MC.getAssociatedDeclaration(); 20228 }); 20229 assert(I != CurComponents.end() && "Null decl on map clause."); 20230 (void)I; 20231 QualType Type; 20232 auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens()); 20233 auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens()); 20234 auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens()); 20235 if (ASE) { 20236 Type = ASE->getType().getNonReferenceType(); 20237 } else if (OASE) { 20238 QualType BaseType = 20239 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 20240 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 20241 Type = ATy->getElementType(); 20242 else 20243 Type = BaseType->getPointeeType(); 20244 Type = Type.getNonReferenceType(); 20245 } else if (OAShE) { 20246 Type = OAShE->getBase()->getType()->getPointeeType(); 20247 } else { 20248 Type = VE->getType(); 20249 } 20250 20251 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 20252 // A list item in a to or from clause must have a mappable type. 20253 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 20254 // A list item must have a mappable type. 20255 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 20256 DSAS, Type, /*FullCheck=*/true)) 20257 continue; 20258 20259 if (CKind == OMPC_map) { 20260 // target enter data 20261 // OpenMP [2.10.2, Restrictions, p. 99] 20262 // A map-type must be specified in all map clauses and must be either 20263 // to or alloc. 20264 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 20265 if (DKind == OMPD_target_enter_data && 20266 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 20267 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 20268 << (IsMapTypeImplicit ? 1 : 0) 20269 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 20270 << getOpenMPDirectiveName(DKind); 20271 continue; 20272 } 20273 20274 // target exit_data 20275 // OpenMP [2.10.3, Restrictions, p. 102] 20276 // A map-type must be specified in all map clauses and must be either 20277 // from, release, or delete. 20278 if (DKind == OMPD_target_exit_data && 20279 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 20280 MapType == OMPC_MAP_delete)) { 20281 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 20282 << (IsMapTypeImplicit ? 1 : 0) 20283 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 20284 << getOpenMPDirectiveName(DKind); 20285 continue; 20286 } 20287 20288 // The 'ompx_hold' modifier is specifically intended to be used on a 20289 // 'target' or 'target data' directive to prevent data from being unmapped 20290 // during the associated statement. It is not permitted on a 'target 20291 // enter data' or 'target exit data' directive, which have no associated 20292 // statement. 20293 if ((DKind == OMPD_target_enter_data || DKind == OMPD_target_exit_data) && 20294 HasHoldModifier) { 20295 SemaRef.Diag(StartLoc, 20296 diag::err_omp_invalid_map_type_modifier_for_directive) 20297 << getOpenMPSimpleClauseTypeName(OMPC_map, 20298 OMPC_MAP_MODIFIER_ompx_hold) 20299 << getOpenMPDirectiveName(DKind); 20300 continue; 20301 } 20302 20303 // target, target data 20304 // OpenMP 5.0 [2.12.2, Restrictions, p. 163] 20305 // OpenMP 5.0 [2.12.5, Restrictions, p. 174] 20306 // A map-type in a map clause must be to, from, tofrom or alloc 20307 if ((DKind == OMPD_target_data || 20308 isOpenMPTargetExecutionDirective(DKind)) && 20309 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from || 20310 MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) { 20311 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 20312 << (IsMapTypeImplicit ? 1 : 0) 20313 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 20314 << getOpenMPDirectiveName(DKind); 20315 continue; 20316 } 20317 20318 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 20319 // A list item cannot appear in both a map clause and a data-sharing 20320 // attribute clause on the same construct 20321 // 20322 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 20323 // A list item cannot appear in both a map clause and a data-sharing 20324 // attribute clause on the same construct unless the construct is a 20325 // combined construct. 20326 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 && 20327 isOpenMPTargetExecutionDirective(DKind)) || 20328 DKind == OMPD_target)) { 20329 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 20330 if (isOpenMPPrivate(DVar.CKind)) { 20331 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 20332 << getOpenMPClauseName(DVar.CKind) 20333 << getOpenMPClauseName(OMPC_map) 20334 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 20335 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar); 20336 continue; 20337 } 20338 } 20339 } 20340 20341 // Try to find the associated user-defined mapper. 20342 ExprResult ER = buildUserDefinedMapperRef( 20343 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 20344 Type.getCanonicalType(), UnresolvedMapper); 20345 if (ER.isInvalid()) 20346 continue; 20347 MVLI.UDMapperList.push_back(ER.get()); 20348 20349 // Save the current expression. 20350 MVLI.ProcessedVarList.push_back(RE); 20351 20352 // Store the components in the stack so that they can be used to check 20353 // against other clauses later on. 20354 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 20355 /*WhereFoundClauseKind=*/OMPC_map); 20356 20357 // Save the components and declaration to create the clause. For purposes of 20358 // the clause creation, any component list that has has base 'this' uses 20359 // null as base declaration. 20360 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 20361 MVLI.VarComponents.back().append(CurComponents.begin(), 20362 CurComponents.end()); 20363 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 20364 : CurDeclaration); 20365 } 20366 } 20367 20368 OMPClause *Sema::ActOnOpenMPMapClause( 20369 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 20370 ArrayRef<SourceLocation> MapTypeModifiersLoc, 20371 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 20372 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, 20373 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 20374 const OMPVarListLocTy &Locs, bool NoDiagnose, 20375 ArrayRef<Expr *> UnresolvedMappers) { 20376 OpenMPMapModifierKind Modifiers[] = { 20377 OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown, 20378 OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown, 20379 OMPC_MAP_MODIFIER_unknown}; 20380 SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers]; 20381 20382 // Process map-type-modifiers, flag errors for duplicate modifiers. 20383 unsigned Count = 0; 20384 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) { 20385 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown && 20386 llvm::is_contained(Modifiers, MapTypeModifiers[I])) { 20387 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier); 20388 continue; 20389 } 20390 assert(Count < NumberOfOMPMapClauseModifiers && 20391 "Modifiers exceed the allowed number of map type modifiers"); 20392 Modifiers[Count] = MapTypeModifiers[I]; 20393 ModifiersLoc[Count] = MapTypeModifiersLoc[I]; 20394 ++Count; 20395 } 20396 20397 MappableVarListInfo MVLI(VarList); 20398 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc, 20399 MapperIdScopeSpec, MapperId, UnresolvedMappers, 20400 MapType, Modifiers, IsMapTypeImplicit, 20401 NoDiagnose); 20402 20403 // We need to produce a map clause even if we don't have variables so that 20404 // other diagnostics related with non-existing map clauses are accurate. 20405 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList, 20406 MVLI.VarBaseDeclarations, MVLI.VarComponents, 20407 MVLI.UDMapperList, Modifiers, ModifiersLoc, 20408 MapperIdScopeSpec.getWithLocInContext(Context), 20409 MapperId, MapType, IsMapTypeImplicit, MapLoc); 20410 } 20411 20412 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 20413 TypeResult ParsedType) { 20414 assert(ParsedType.isUsable()); 20415 20416 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 20417 if (ReductionType.isNull()) 20418 return QualType(); 20419 20420 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 20421 // A type name in a declare reduction directive cannot be a function type, an 20422 // array type, a reference type, or a type qualified with const, volatile or 20423 // restrict. 20424 if (ReductionType.hasQualifiers()) { 20425 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 20426 return QualType(); 20427 } 20428 20429 if (ReductionType->isFunctionType()) { 20430 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 20431 return QualType(); 20432 } 20433 if (ReductionType->isReferenceType()) { 20434 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 20435 return QualType(); 20436 } 20437 if (ReductionType->isArrayType()) { 20438 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 20439 return QualType(); 20440 } 20441 return ReductionType; 20442 } 20443 20444 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 20445 Scope *S, DeclContext *DC, DeclarationName Name, 20446 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 20447 AccessSpecifier AS, Decl *PrevDeclInScope) { 20448 SmallVector<Decl *, 8> Decls; 20449 Decls.reserve(ReductionTypes.size()); 20450 20451 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 20452 forRedeclarationInCurContext()); 20453 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 20454 // A reduction-identifier may not be re-declared in the current scope for the 20455 // same type or for a type that is compatible according to the base language 20456 // rules. 20457 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 20458 OMPDeclareReductionDecl *PrevDRD = nullptr; 20459 bool InCompoundScope = true; 20460 if (S != nullptr) { 20461 // Find previous declaration with the same name not referenced in other 20462 // declarations. 20463 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 20464 InCompoundScope = 20465 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 20466 LookupName(Lookup, S); 20467 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 20468 /*AllowInlineNamespace=*/false); 20469 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 20470 LookupResult::Filter Filter = Lookup.makeFilter(); 20471 while (Filter.hasNext()) { 20472 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 20473 if (InCompoundScope) { 20474 auto I = UsedAsPrevious.find(PrevDecl); 20475 if (I == UsedAsPrevious.end()) 20476 UsedAsPrevious[PrevDecl] = false; 20477 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope()) 20478 UsedAsPrevious[D] = true; 20479 } 20480 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 20481 PrevDecl->getLocation(); 20482 } 20483 Filter.done(); 20484 if (InCompoundScope) { 20485 for (const auto &PrevData : UsedAsPrevious) { 20486 if (!PrevData.second) { 20487 PrevDRD = PrevData.first; 20488 break; 20489 } 20490 } 20491 } 20492 } else if (PrevDeclInScope != nullptr) { 20493 auto *PrevDRDInScope = PrevDRD = 20494 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 20495 do { 20496 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 20497 PrevDRDInScope->getLocation(); 20498 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 20499 } while (PrevDRDInScope != nullptr); 20500 } 20501 for (const auto &TyData : ReductionTypes) { 20502 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 20503 bool Invalid = false; 20504 if (I != PreviousRedeclTypes.end()) { 20505 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 20506 << TyData.first; 20507 Diag(I->second, diag::note_previous_definition); 20508 Invalid = true; 20509 } 20510 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 20511 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 20512 Name, TyData.first, PrevDRD); 20513 DC->addDecl(DRD); 20514 DRD->setAccess(AS); 20515 Decls.push_back(DRD); 20516 if (Invalid) 20517 DRD->setInvalidDecl(); 20518 else 20519 PrevDRD = DRD; 20520 } 20521 20522 return DeclGroupPtrTy::make( 20523 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 20524 } 20525 20526 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 20527 auto *DRD = cast<OMPDeclareReductionDecl>(D); 20528 20529 // Enter new function scope. 20530 PushFunctionScope(); 20531 setFunctionHasBranchProtectedScope(); 20532 getCurFunction()->setHasOMPDeclareReductionCombiner(); 20533 20534 if (S != nullptr) 20535 PushDeclContext(S, DRD); 20536 else 20537 CurContext = DRD; 20538 20539 PushExpressionEvaluationContext( 20540 ExpressionEvaluationContext::PotentiallyEvaluated); 20541 20542 QualType ReductionType = DRD->getType(); 20543 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 20544 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 20545 // uses semantics of argument handles by value, but it should be passed by 20546 // reference. C lang does not support references, so pass all parameters as 20547 // pointers. 20548 // Create 'T omp_in;' variable. 20549 VarDecl *OmpInParm = 20550 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 20551 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 20552 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 20553 // uses semantics of argument handles by value, but it should be passed by 20554 // reference. C lang does not support references, so pass all parameters as 20555 // pointers. 20556 // Create 'T omp_out;' variable. 20557 VarDecl *OmpOutParm = 20558 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 20559 if (S != nullptr) { 20560 PushOnScopeChains(OmpInParm, S); 20561 PushOnScopeChains(OmpOutParm, S); 20562 } else { 20563 DRD->addDecl(OmpInParm); 20564 DRD->addDecl(OmpOutParm); 20565 } 20566 Expr *InE = 20567 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation()); 20568 Expr *OutE = 20569 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation()); 20570 DRD->setCombinerData(InE, OutE); 20571 } 20572 20573 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 20574 auto *DRD = cast<OMPDeclareReductionDecl>(D); 20575 DiscardCleanupsInEvaluationContext(); 20576 PopExpressionEvaluationContext(); 20577 20578 PopDeclContext(); 20579 PopFunctionScopeInfo(); 20580 20581 if (Combiner != nullptr) 20582 DRD->setCombiner(Combiner); 20583 else 20584 DRD->setInvalidDecl(); 20585 } 20586 20587 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 20588 auto *DRD = cast<OMPDeclareReductionDecl>(D); 20589 20590 // Enter new function scope. 20591 PushFunctionScope(); 20592 setFunctionHasBranchProtectedScope(); 20593 20594 if (S != nullptr) 20595 PushDeclContext(S, DRD); 20596 else 20597 CurContext = DRD; 20598 20599 PushExpressionEvaluationContext( 20600 ExpressionEvaluationContext::PotentiallyEvaluated); 20601 20602 QualType ReductionType = DRD->getType(); 20603 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 20604 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 20605 // uses semantics of argument handles by value, but it should be passed by 20606 // reference. C lang does not support references, so pass all parameters as 20607 // pointers. 20608 // Create 'T omp_priv;' variable. 20609 VarDecl *OmpPrivParm = 20610 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 20611 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 20612 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 20613 // uses semantics of argument handles by value, but it should be passed by 20614 // reference. C lang does not support references, so pass all parameters as 20615 // pointers. 20616 // Create 'T omp_orig;' variable. 20617 VarDecl *OmpOrigParm = 20618 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 20619 if (S != nullptr) { 20620 PushOnScopeChains(OmpPrivParm, S); 20621 PushOnScopeChains(OmpOrigParm, S); 20622 } else { 20623 DRD->addDecl(OmpPrivParm); 20624 DRD->addDecl(OmpOrigParm); 20625 } 20626 Expr *OrigE = 20627 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation()); 20628 Expr *PrivE = 20629 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation()); 20630 DRD->setInitializerData(OrigE, PrivE); 20631 return OmpPrivParm; 20632 } 20633 20634 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 20635 VarDecl *OmpPrivParm) { 20636 auto *DRD = cast<OMPDeclareReductionDecl>(D); 20637 DiscardCleanupsInEvaluationContext(); 20638 PopExpressionEvaluationContext(); 20639 20640 PopDeclContext(); 20641 PopFunctionScopeInfo(); 20642 20643 if (Initializer != nullptr) { 20644 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit); 20645 } else if (OmpPrivParm->hasInit()) { 20646 DRD->setInitializer(OmpPrivParm->getInit(), 20647 OmpPrivParm->isDirectInit() 20648 ? OMPDeclareReductionDecl::DirectInit 20649 : OMPDeclareReductionDecl::CopyInit); 20650 } else { 20651 DRD->setInvalidDecl(); 20652 } 20653 } 20654 20655 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 20656 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 20657 for (Decl *D : DeclReductions.get()) { 20658 if (IsValid) { 20659 if (S) 20660 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S, 20661 /*AddToContext=*/false); 20662 } else { 20663 D->setInvalidDecl(); 20664 } 20665 } 20666 return DeclReductions; 20667 } 20668 20669 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) { 20670 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 20671 QualType T = TInfo->getType(); 20672 if (D.isInvalidType()) 20673 return true; 20674 20675 if (getLangOpts().CPlusPlus) { 20676 // Check that there are no default arguments (C++ only). 20677 CheckExtraCXXDefaultArguments(D); 20678 } 20679 20680 return CreateParsedType(T, TInfo); 20681 } 20682 20683 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, 20684 TypeResult ParsedType) { 20685 assert(ParsedType.isUsable() && "Expect usable parsed mapper type"); 20686 20687 QualType MapperType = GetTypeFromParser(ParsedType.get()); 20688 assert(!MapperType.isNull() && "Expect valid mapper type"); 20689 20690 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 20691 // The type must be of struct, union or class type in C and C++ 20692 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) { 20693 Diag(TyLoc, diag::err_omp_mapper_wrong_type); 20694 return QualType(); 20695 } 20696 return MapperType; 20697 } 20698 20699 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective( 20700 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, 20701 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, 20702 Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) { 20703 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName, 20704 forRedeclarationInCurContext()); 20705 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 20706 // A mapper-identifier may not be redeclared in the current scope for the 20707 // same type or for a type that is compatible according to the base language 20708 // rules. 20709 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 20710 OMPDeclareMapperDecl *PrevDMD = nullptr; 20711 bool InCompoundScope = true; 20712 if (S != nullptr) { 20713 // Find previous declaration with the same name not referenced in other 20714 // declarations. 20715 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 20716 InCompoundScope = 20717 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 20718 LookupName(Lookup, S); 20719 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 20720 /*AllowInlineNamespace=*/false); 20721 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious; 20722 LookupResult::Filter Filter = Lookup.makeFilter(); 20723 while (Filter.hasNext()) { 20724 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next()); 20725 if (InCompoundScope) { 20726 auto I = UsedAsPrevious.find(PrevDecl); 20727 if (I == UsedAsPrevious.end()) 20728 UsedAsPrevious[PrevDecl] = false; 20729 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope()) 20730 UsedAsPrevious[D] = true; 20731 } 20732 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 20733 PrevDecl->getLocation(); 20734 } 20735 Filter.done(); 20736 if (InCompoundScope) { 20737 for (const auto &PrevData : UsedAsPrevious) { 20738 if (!PrevData.second) { 20739 PrevDMD = PrevData.first; 20740 break; 20741 } 20742 } 20743 } 20744 } else if (PrevDeclInScope) { 20745 auto *PrevDMDInScope = PrevDMD = 20746 cast<OMPDeclareMapperDecl>(PrevDeclInScope); 20747 do { 20748 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] = 20749 PrevDMDInScope->getLocation(); 20750 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope(); 20751 } while (PrevDMDInScope != nullptr); 20752 } 20753 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType()); 20754 bool Invalid = false; 20755 if (I != PreviousRedeclTypes.end()) { 20756 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition) 20757 << MapperType << Name; 20758 Diag(I->second, diag::note_previous_definition); 20759 Invalid = true; 20760 } 20761 // Build expressions for implicit maps of data members with 'default' 20762 // mappers. 20763 SmallVector<OMPClause *, 4> ClausesWithImplicit(Clauses.begin(), 20764 Clauses.end()); 20765 if (LangOpts.OpenMP >= 50) 20766 processImplicitMapsWithDefaultMappers(*this, DSAStack, ClausesWithImplicit); 20767 auto *DMD = 20768 OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, MapperType, VN, 20769 ClausesWithImplicit, PrevDMD); 20770 if (S) 20771 PushOnScopeChains(DMD, S); 20772 else 20773 DC->addDecl(DMD); 20774 DMD->setAccess(AS); 20775 if (Invalid) 20776 DMD->setInvalidDecl(); 20777 20778 auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl(); 20779 VD->setDeclContext(DMD); 20780 VD->setLexicalDeclContext(DMD); 20781 DMD->addDecl(VD); 20782 DMD->setMapperVarRef(MapperVarRef); 20783 20784 return DeclGroupPtrTy::make(DeclGroupRef(DMD)); 20785 } 20786 20787 ExprResult 20788 Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType, 20789 SourceLocation StartLoc, 20790 DeclarationName VN) { 20791 TypeSourceInfo *TInfo = 20792 Context.getTrivialTypeSourceInfo(MapperType, StartLoc); 20793 auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(), 20794 StartLoc, StartLoc, VN.getAsIdentifierInfo(), 20795 MapperType, TInfo, SC_None); 20796 if (S) 20797 PushOnScopeChains(VD, S, /*AddToContext=*/false); 20798 Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc); 20799 DSAStack->addDeclareMapperVarRef(E); 20800 return E; 20801 } 20802 20803 bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const { 20804 assert(LangOpts.OpenMP && "Expected OpenMP mode."); 20805 const Expr *Ref = DSAStack->getDeclareMapperVarRef(); 20806 if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref)) { 20807 if (VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl()) 20808 return true; 20809 if (VD->isUsableInConstantExpressions(Context)) 20810 return true; 20811 return false; 20812 } 20813 return true; 20814 } 20815 20816 const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const { 20817 assert(LangOpts.OpenMP && "Expected OpenMP mode."); 20818 return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl(); 20819 } 20820 20821 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 20822 SourceLocation StartLoc, 20823 SourceLocation LParenLoc, 20824 SourceLocation EndLoc) { 20825 Expr *ValExpr = NumTeams; 20826 Stmt *HelperValStmt = nullptr; 20827 20828 // OpenMP [teams Constrcut, Restrictions] 20829 // The num_teams expression must evaluate to a positive integer value. 20830 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 20831 /*StrictlyPositive=*/true)) 20832 return nullptr; 20833 20834 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 20835 OpenMPDirectiveKind CaptureRegion = 20836 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP); 20837 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 20838 ValExpr = MakeFullExpr(ValExpr).get(); 20839 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 20840 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 20841 HelperValStmt = buildPreInits(Context, Captures); 20842 } 20843 20844 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 20845 StartLoc, LParenLoc, EndLoc); 20846 } 20847 20848 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 20849 SourceLocation StartLoc, 20850 SourceLocation LParenLoc, 20851 SourceLocation EndLoc) { 20852 Expr *ValExpr = ThreadLimit; 20853 Stmt *HelperValStmt = nullptr; 20854 20855 // OpenMP [teams Constrcut, Restrictions] 20856 // The thread_limit expression must evaluate to a positive integer value. 20857 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 20858 /*StrictlyPositive=*/true)) 20859 return nullptr; 20860 20861 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 20862 OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause( 20863 DKind, OMPC_thread_limit, LangOpts.OpenMP); 20864 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 20865 ValExpr = MakeFullExpr(ValExpr).get(); 20866 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 20867 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 20868 HelperValStmt = buildPreInits(Context, Captures); 20869 } 20870 20871 return new (Context) OMPThreadLimitClause( 20872 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 20873 } 20874 20875 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 20876 SourceLocation StartLoc, 20877 SourceLocation LParenLoc, 20878 SourceLocation EndLoc) { 20879 Expr *ValExpr = Priority; 20880 Stmt *HelperValStmt = nullptr; 20881 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 20882 20883 // OpenMP [2.9.1, task Constrcut] 20884 // The priority-value is a non-negative numerical scalar expression. 20885 if (!isNonNegativeIntegerValue( 20886 ValExpr, *this, OMPC_priority, 20887 /*StrictlyPositive=*/false, /*BuildCapture=*/true, 20888 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 20889 return nullptr; 20890 20891 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion, 20892 StartLoc, LParenLoc, EndLoc); 20893 } 20894 20895 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 20896 SourceLocation StartLoc, 20897 SourceLocation LParenLoc, 20898 SourceLocation EndLoc) { 20899 Expr *ValExpr = Grainsize; 20900 Stmt *HelperValStmt = nullptr; 20901 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 20902 20903 // OpenMP [2.9.2, taskloop Constrcut] 20904 // The parameter of the grainsize clause must be a positive integer 20905 // expression. 20906 if (!isNonNegativeIntegerValue( 20907 ValExpr, *this, OMPC_grainsize, 20908 /*StrictlyPositive=*/true, /*BuildCapture=*/true, 20909 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 20910 return nullptr; 20911 20912 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion, 20913 StartLoc, LParenLoc, EndLoc); 20914 } 20915 20916 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 20917 SourceLocation StartLoc, 20918 SourceLocation LParenLoc, 20919 SourceLocation EndLoc) { 20920 Expr *ValExpr = NumTasks; 20921 Stmt *HelperValStmt = nullptr; 20922 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 20923 20924 // OpenMP [2.9.2, taskloop Constrcut] 20925 // The parameter of the num_tasks clause must be a positive integer 20926 // expression. 20927 if (!isNonNegativeIntegerValue( 20928 ValExpr, *this, OMPC_num_tasks, 20929 /*StrictlyPositive=*/true, /*BuildCapture=*/true, 20930 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 20931 return nullptr; 20932 20933 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion, 20934 StartLoc, LParenLoc, EndLoc); 20935 } 20936 20937 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 20938 SourceLocation LParenLoc, 20939 SourceLocation EndLoc) { 20940 // OpenMP [2.13.2, critical construct, Description] 20941 // ... where hint-expression is an integer constant expression that evaluates 20942 // to a valid lock hint. 20943 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 20944 if (HintExpr.isInvalid()) 20945 return nullptr; 20946 return new (Context) 20947 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 20948 } 20949 20950 /// Tries to find omp_event_handle_t type. 20951 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc, 20952 DSAStackTy *Stack) { 20953 QualType OMPEventHandleT = Stack->getOMPEventHandleT(); 20954 if (!OMPEventHandleT.isNull()) 20955 return true; 20956 IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t"); 20957 ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope()); 20958 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 20959 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t"; 20960 return false; 20961 } 20962 Stack->setOMPEventHandleT(PT.get()); 20963 return true; 20964 } 20965 20966 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, 20967 SourceLocation LParenLoc, 20968 SourceLocation EndLoc) { 20969 if (!Evt->isValueDependent() && !Evt->isTypeDependent() && 20970 !Evt->isInstantiationDependent() && 20971 !Evt->containsUnexpandedParameterPack()) { 20972 if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack)) 20973 return nullptr; 20974 // OpenMP 5.0, 2.10.1 task Construct. 20975 // event-handle is a variable of the omp_event_handle_t type. 20976 auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts()); 20977 if (!Ref) { 20978 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 20979 << "omp_event_handle_t" << 0 << Evt->getSourceRange(); 20980 return nullptr; 20981 } 20982 auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl()); 20983 if (!VD) { 20984 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 20985 << "omp_event_handle_t" << 0 << Evt->getSourceRange(); 20986 return nullptr; 20987 } 20988 if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(), 20989 VD->getType()) || 20990 VD->getType().isConstant(Context)) { 20991 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 20992 << "omp_event_handle_t" << 1 << VD->getType() 20993 << Evt->getSourceRange(); 20994 return nullptr; 20995 } 20996 // OpenMP 5.0, 2.10.1 task Construct 20997 // [detach clause]... The event-handle will be considered as if it was 20998 // specified on a firstprivate clause. 20999 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false); 21000 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 21001 DVar.RefExpr) { 21002 Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa) 21003 << getOpenMPClauseName(DVar.CKind) 21004 << getOpenMPClauseName(OMPC_firstprivate); 21005 reportOriginalDsa(*this, DSAStack, VD, DVar); 21006 return nullptr; 21007 } 21008 } 21009 21010 return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc); 21011 } 21012 21013 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 21014 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 21015 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 21016 SourceLocation EndLoc) { 21017 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 21018 std::string Values; 21019 Values += "'"; 21020 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 21021 Values += "'"; 21022 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 21023 << Values << getOpenMPClauseName(OMPC_dist_schedule); 21024 return nullptr; 21025 } 21026 Expr *ValExpr = ChunkSize; 21027 Stmt *HelperValStmt = nullptr; 21028 if (ChunkSize) { 21029 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 21030 !ChunkSize->isInstantiationDependent() && 21031 !ChunkSize->containsUnexpandedParameterPack()) { 21032 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 21033 ExprResult Val = 21034 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 21035 if (Val.isInvalid()) 21036 return nullptr; 21037 21038 ValExpr = Val.get(); 21039 21040 // OpenMP [2.7.1, Restrictions] 21041 // chunk_size must be a loop invariant integer expression with a positive 21042 // value. 21043 if (Optional<llvm::APSInt> Result = 21044 ValExpr->getIntegerConstantExpr(Context)) { 21045 if (Result->isSigned() && !Result->isStrictlyPositive()) { 21046 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 21047 << "dist_schedule" << ChunkSize->getSourceRange(); 21048 return nullptr; 21049 } 21050 } else if (getOpenMPCaptureRegionForClause( 21051 DSAStack->getCurrentDirective(), OMPC_dist_schedule, 21052 LangOpts.OpenMP) != OMPD_unknown && 21053 !CurContext->isDependentContext()) { 21054 ValExpr = MakeFullExpr(ValExpr).get(); 21055 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 21056 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 21057 HelperValStmt = buildPreInits(Context, Captures); 21058 } 21059 } 21060 } 21061 21062 return new (Context) 21063 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 21064 Kind, ValExpr, HelperValStmt); 21065 } 21066 21067 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 21068 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 21069 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 21070 SourceLocation KindLoc, SourceLocation EndLoc) { 21071 if (getLangOpts().OpenMP < 50) { 21072 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || 21073 Kind != OMPC_DEFAULTMAP_scalar) { 21074 std::string Value; 21075 SourceLocation Loc; 21076 Value += "'"; 21077 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 21078 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 21079 OMPC_DEFAULTMAP_MODIFIER_tofrom); 21080 Loc = MLoc; 21081 } else { 21082 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 21083 OMPC_DEFAULTMAP_scalar); 21084 Loc = KindLoc; 21085 } 21086 Value += "'"; 21087 Diag(Loc, diag::err_omp_unexpected_clause_value) 21088 << Value << getOpenMPClauseName(OMPC_defaultmap); 21089 return nullptr; 21090 } 21091 } else { 21092 bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown); 21093 bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) || 21094 (LangOpts.OpenMP >= 50 && KindLoc.isInvalid()); 21095 if (!isDefaultmapKind || !isDefaultmapModifier) { 21096 StringRef KindValue = "'scalar', 'aggregate', 'pointer'"; 21097 if (LangOpts.OpenMP == 50) { 21098 StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', " 21099 "'firstprivate', 'none', 'default'"; 21100 if (!isDefaultmapKind && isDefaultmapModifier) { 21101 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 21102 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 21103 } else if (isDefaultmapKind && !isDefaultmapModifier) { 21104 Diag(MLoc, diag::err_omp_unexpected_clause_value) 21105 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 21106 } else { 21107 Diag(MLoc, diag::err_omp_unexpected_clause_value) 21108 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 21109 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 21110 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 21111 } 21112 } else { 21113 StringRef ModifierValue = 21114 "'alloc', 'from', 'to', 'tofrom', " 21115 "'firstprivate', 'none', 'default', 'present'"; 21116 if (!isDefaultmapKind && isDefaultmapModifier) { 21117 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 21118 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 21119 } else if (isDefaultmapKind && !isDefaultmapModifier) { 21120 Diag(MLoc, diag::err_omp_unexpected_clause_value) 21121 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 21122 } else { 21123 Diag(MLoc, diag::err_omp_unexpected_clause_value) 21124 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 21125 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 21126 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 21127 } 21128 } 21129 return nullptr; 21130 } 21131 21132 // OpenMP [5.0, 2.12.5, Restrictions, p. 174] 21133 // At most one defaultmap clause for each category can appear on the 21134 // directive. 21135 if (DSAStack->checkDefaultmapCategory(Kind)) { 21136 Diag(StartLoc, diag::err_omp_one_defaultmap_each_category); 21137 return nullptr; 21138 } 21139 } 21140 if (Kind == OMPC_DEFAULTMAP_unknown) { 21141 // Variable category is not specified - mark all categories. 21142 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc); 21143 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc); 21144 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc); 21145 } else { 21146 DSAStack->setDefaultDMAAttr(M, Kind, StartLoc); 21147 } 21148 21149 return new (Context) 21150 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 21151 } 21152 21153 bool Sema::ActOnStartOpenMPDeclareTargetContext( 21154 DeclareTargetContextInfo &DTCI) { 21155 DeclContext *CurLexicalContext = getCurLexicalContext(); 21156 if (!CurLexicalContext->isFileContext() && 21157 !CurLexicalContext->isExternCContext() && 21158 !CurLexicalContext->isExternCXXContext() && 21159 !isa<CXXRecordDecl>(CurLexicalContext) && 21160 !isa<ClassTemplateDecl>(CurLexicalContext) && 21161 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) && 21162 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) { 21163 Diag(DTCI.Loc, diag::err_omp_region_not_file_context); 21164 return false; 21165 } 21166 DeclareTargetNesting.push_back(DTCI); 21167 return true; 21168 } 21169 21170 const Sema::DeclareTargetContextInfo 21171 Sema::ActOnOpenMPEndDeclareTargetDirective() { 21172 assert(!DeclareTargetNesting.empty() && 21173 "check isInOpenMPDeclareTargetContext() first!"); 21174 return DeclareTargetNesting.pop_back_val(); 21175 } 21176 21177 void Sema::ActOnFinishedOpenMPDeclareTargetContext( 21178 DeclareTargetContextInfo &DTCI) { 21179 for (auto &It : DTCI.ExplicitlyMapped) 21180 ActOnOpenMPDeclareTargetName(It.first, It.second.Loc, It.second.MT, DTCI); 21181 } 21182 21183 NamedDecl *Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, 21184 CXXScopeSpec &ScopeSpec, 21185 const DeclarationNameInfo &Id) { 21186 LookupResult Lookup(*this, Id, LookupOrdinaryName); 21187 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 21188 21189 if (Lookup.isAmbiguous()) 21190 return nullptr; 21191 Lookup.suppressDiagnostics(); 21192 21193 if (!Lookup.isSingleResult()) { 21194 VarOrFuncDeclFilterCCC CCC(*this); 21195 if (TypoCorrection Corrected = 21196 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC, 21197 CTK_ErrorRecovery)) { 21198 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 21199 << Id.getName()); 21200 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 21201 return nullptr; 21202 } 21203 21204 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 21205 return nullptr; 21206 } 21207 21208 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 21209 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) && 21210 !isa<FunctionTemplateDecl>(ND)) { 21211 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 21212 return nullptr; 21213 } 21214 return ND; 21215 } 21216 21217 void Sema::ActOnOpenMPDeclareTargetName(NamedDecl *ND, SourceLocation Loc, 21218 OMPDeclareTargetDeclAttr::MapTypeTy MT, 21219 DeclareTargetContextInfo &DTCI) { 21220 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) || 21221 isa<FunctionTemplateDecl>(ND)) && 21222 "Expected variable, function or function template."); 21223 21224 // Diagnose marking after use as it may lead to incorrect diagnosis and 21225 // codegen. 21226 if (LangOpts.OpenMP >= 50 && 21227 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced())) 21228 Diag(Loc, diag::warn_omp_declare_target_after_first_use); 21229 21230 // Explicit declare target lists have precedence. 21231 const unsigned Level = -1; 21232 21233 auto *VD = cast<ValueDecl>(ND); 21234 llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 21235 OMPDeclareTargetDeclAttr::getActiveAttr(VD); 21236 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getDevType() != DTCI.DT && 21237 ActiveAttr.getValue()->getLevel() == Level) { 21238 Diag(Loc, diag::err_omp_device_type_mismatch) 21239 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DTCI.DT) 21240 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr( 21241 ActiveAttr.getValue()->getDevType()); 21242 return; 21243 } 21244 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getMapType() != MT && 21245 ActiveAttr.getValue()->getLevel() == Level) { 21246 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND; 21247 return; 21248 } 21249 21250 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() == Level) 21251 return; 21252 21253 Expr *IndirectE = nullptr; 21254 bool IsIndirect = false; 21255 if (DTCI.Indirect.hasValue()) { 21256 IndirectE = DTCI.Indirect.getValue(); 21257 if (!IndirectE) 21258 IsIndirect = true; 21259 } 21260 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit( 21261 Context, MT, DTCI.DT, IndirectE, IsIndirect, Level, 21262 SourceRange(Loc, Loc)); 21263 ND->addAttr(A); 21264 if (ASTMutationListener *ML = Context.getASTMutationListener()) 21265 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 21266 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc); 21267 } 21268 21269 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 21270 Sema &SemaRef, Decl *D) { 21271 if (!D || !isa<VarDecl>(D)) 21272 return; 21273 auto *VD = cast<VarDecl>(D); 21274 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy = 21275 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 21276 if (SemaRef.LangOpts.OpenMP >= 50 && 21277 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) || 21278 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) && 21279 VD->hasGlobalStorage()) { 21280 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) { 21281 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions 21282 // If a lambda declaration and definition appears between a 21283 // declare target directive and the matching end declare target 21284 // directive, all variables that are captured by the lambda 21285 // expression must also appear in a to clause. 21286 SemaRef.Diag(VD->getLocation(), 21287 diag::err_omp_lambda_capture_in_declare_target_not_to); 21288 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here) 21289 << VD << 0 << SR; 21290 return; 21291 } 21292 } 21293 if (MapTy.hasValue()) 21294 return; 21295 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context); 21296 SemaRef.Diag(SL, diag::note_used_here) << SR; 21297 } 21298 21299 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 21300 Sema &SemaRef, DSAStackTy *Stack, 21301 ValueDecl *VD) { 21302 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) || 21303 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(), 21304 /*FullCheck=*/false); 21305 } 21306 21307 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 21308 SourceLocation IdLoc) { 21309 if (!D || D->isInvalidDecl()) 21310 return; 21311 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 21312 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation(); 21313 if (auto *VD = dyn_cast<VarDecl>(D)) { 21314 // Only global variables can be marked as declare target. 21315 if (!VD->isFileVarDecl() && !VD->isStaticLocal() && 21316 !VD->isStaticDataMember()) 21317 return; 21318 // 2.10.6: threadprivate variable cannot appear in a declare target 21319 // directive. 21320 if (DSAStack->isThreadPrivate(VD)) { 21321 Diag(SL, diag::err_omp_threadprivate_in_target); 21322 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 21323 return; 21324 } 21325 } 21326 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) 21327 D = FTD->getTemplatedDecl(); 21328 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 21329 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 21330 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD); 21331 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) { 21332 Diag(IdLoc, diag::err_omp_function_in_link_clause); 21333 Diag(FD->getLocation(), diag::note_defined_here) << FD; 21334 return; 21335 } 21336 } 21337 if (auto *VD = dyn_cast<ValueDecl>(D)) { 21338 // Problem if any with var declared with incomplete type will be reported 21339 // as normal, so no need to check it here. 21340 if ((E || !VD->getType()->isIncompleteType()) && 21341 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) 21342 return; 21343 if (!E && isInOpenMPDeclareTargetContext()) { 21344 // Checking declaration inside declare target region. 21345 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) || 21346 isa<FunctionTemplateDecl>(D)) { 21347 llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 21348 OMPDeclareTargetDeclAttr::getActiveAttr(VD); 21349 unsigned Level = DeclareTargetNesting.size(); 21350 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() >= Level) 21351 return; 21352 DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back(); 21353 Expr *IndirectE = nullptr; 21354 bool IsIndirect = false; 21355 if (DTCI.Indirect.hasValue()) { 21356 IndirectE = DTCI.Indirect.getValue(); 21357 if (!IndirectE) 21358 IsIndirect = true; 21359 } 21360 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit( 21361 Context, OMPDeclareTargetDeclAttr::MT_To, DTCI.DT, IndirectE, 21362 IsIndirect, Level, SourceRange(DTCI.Loc, DTCI.Loc)); 21363 D->addAttr(A); 21364 if (ASTMutationListener *ML = Context.getASTMutationListener()) 21365 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 21366 } 21367 return; 21368 } 21369 } 21370 if (!E) 21371 return; 21372 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 21373 } 21374 21375 OMPClause *Sema::ActOnOpenMPToClause( 21376 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 21377 ArrayRef<SourceLocation> MotionModifiersLoc, 21378 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 21379 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 21380 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) { 21381 OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown, 21382 OMPC_MOTION_MODIFIER_unknown}; 21383 SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers]; 21384 21385 // Process motion-modifiers, flag errors for duplicate modifiers. 21386 unsigned Count = 0; 21387 for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) { 21388 if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown && 21389 llvm::is_contained(Modifiers, MotionModifiers[I])) { 21390 Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier); 21391 continue; 21392 } 21393 assert(Count < NumberOfOMPMotionModifiers && 21394 "Modifiers exceed the allowed number of motion modifiers"); 21395 Modifiers[Count] = MotionModifiers[I]; 21396 ModifiersLoc[Count] = MotionModifiersLoc[I]; 21397 ++Count; 21398 } 21399 21400 MappableVarListInfo MVLI(VarList); 21401 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc, 21402 MapperIdScopeSpec, MapperId, UnresolvedMappers); 21403 if (MVLI.ProcessedVarList.empty()) 21404 return nullptr; 21405 21406 return OMPToClause::Create( 21407 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 21408 MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc, 21409 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 21410 } 21411 21412 OMPClause *Sema::ActOnOpenMPFromClause( 21413 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 21414 ArrayRef<SourceLocation> MotionModifiersLoc, 21415 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 21416 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 21417 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) { 21418 OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown, 21419 OMPC_MOTION_MODIFIER_unknown}; 21420 SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers]; 21421 21422 // Process motion-modifiers, flag errors for duplicate modifiers. 21423 unsigned Count = 0; 21424 for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) { 21425 if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown && 21426 llvm::is_contained(Modifiers, MotionModifiers[I])) { 21427 Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier); 21428 continue; 21429 } 21430 assert(Count < NumberOfOMPMotionModifiers && 21431 "Modifiers exceed the allowed number of motion modifiers"); 21432 Modifiers[Count] = MotionModifiers[I]; 21433 ModifiersLoc[Count] = MotionModifiersLoc[I]; 21434 ++Count; 21435 } 21436 21437 MappableVarListInfo MVLI(VarList); 21438 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc, 21439 MapperIdScopeSpec, MapperId, UnresolvedMappers); 21440 if (MVLI.ProcessedVarList.empty()) 21441 return nullptr; 21442 21443 return OMPFromClause::Create( 21444 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 21445 MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc, 21446 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 21447 } 21448 21449 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 21450 const OMPVarListLocTy &Locs) { 21451 MappableVarListInfo MVLI(VarList); 21452 SmallVector<Expr *, 8> PrivateCopies; 21453 SmallVector<Expr *, 8> Inits; 21454 21455 for (Expr *RefExpr : VarList) { 21456 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 21457 SourceLocation ELoc; 21458 SourceRange ERange; 21459 Expr *SimpleRefExpr = RefExpr; 21460 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 21461 if (Res.second) { 21462 // It will be analyzed later. 21463 MVLI.ProcessedVarList.push_back(RefExpr); 21464 PrivateCopies.push_back(nullptr); 21465 Inits.push_back(nullptr); 21466 } 21467 ValueDecl *D = Res.first; 21468 if (!D) 21469 continue; 21470 21471 QualType Type = D->getType(); 21472 Type = Type.getNonReferenceType().getUnqualifiedType(); 21473 21474 auto *VD = dyn_cast<VarDecl>(D); 21475 21476 // Item should be a pointer or reference to pointer. 21477 if (!Type->isPointerType()) { 21478 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 21479 << 0 << RefExpr->getSourceRange(); 21480 continue; 21481 } 21482 21483 // Build the private variable and the expression that refers to it. 21484 auto VDPrivate = 21485 buildVarDecl(*this, ELoc, Type, D->getName(), 21486 D->hasAttrs() ? &D->getAttrs() : nullptr, 21487 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 21488 if (VDPrivate->isInvalidDecl()) 21489 continue; 21490 21491 CurContext->addDecl(VDPrivate); 21492 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 21493 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 21494 21495 // Add temporary variable to initialize the private copy of the pointer. 21496 VarDecl *VDInit = 21497 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 21498 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr( 21499 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc()); 21500 AddInitializerToDecl(VDPrivate, 21501 DefaultLvalueConversion(VDInitRefExpr).get(), 21502 /*DirectInit=*/false); 21503 21504 // If required, build a capture to implement the privatization initialized 21505 // with the current list item value. 21506 DeclRefExpr *Ref = nullptr; 21507 if (!VD) 21508 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 21509 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 21510 PrivateCopies.push_back(VDPrivateRefExpr); 21511 Inits.push_back(VDInitRefExpr); 21512 21513 // We need to add a data sharing attribute for this variable to make sure it 21514 // is correctly captured. A variable that shows up in a use_device_ptr has 21515 // similar properties of a first private variable. 21516 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 21517 21518 // Create a mappable component for the list item. List items in this clause 21519 // only need a component. 21520 MVLI.VarBaseDeclarations.push_back(D); 21521 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 21522 MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D, 21523 /*IsNonContiguous=*/false); 21524 } 21525 21526 if (MVLI.ProcessedVarList.empty()) 21527 return nullptr; 21528 21529 return OMPUseDevicePtrClause::Create( 21530 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits, 21531 MVLI.VarBaseDeclarations, MVLI.VarComponents); 21532 } 21533 21534 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, 21535 const OMPVarListLocTy &Locs) { 21536 MappableVarListInfo MVLI(VarList); 21537 21538 for (Expr *RefExpr : VarList) { 21539 assert(RefExpr && "NULL expr in OpenMP use_device_addr clause."); 21540 SourceLocation ELoc; 21541 SourceRange ERange; 21542 Expr *SimpleRefExpr = RefExpr; 21543 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 21544 /*AllowArraySection=*/true); 21545 if (Res.second) { 21546 // It will be analyzed later. 21547 MVLI.ProcessedVarList.push_back(RefExpr); 21548 } 21549 ValueDecl *D = Res.first; 21550 if (!D) 21551 continue; 21552 auto *VD = dyn_cast<VarDecl>(D); 21553 21554 // If required, build a capture to implement the privatization initialized 21555 // with the current list item value. 21556 DeclRefExpr *Ref = nullptr; 21557 if (!VD) 21558 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 21559 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 21560 21561 // We need to add a data sharing attribute for this variable to make sure it 21562 // is correctly captured. A variable that shows up in a use_device_addr has 21563 // similar properties of a first private variable. 21564 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 21565 21566 // Create a mappable component for the list item. List items in this clause 21567 // only need a component. 21568 MVLI.VarBaseDeclarations.push_back(D); 21569 MVLI.VarComponents.emplace_back(); 21570 Expr *Component = SimpleRefExpr; 21571 if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) || 21572 isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts()))) 21573 Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get(); 21574 MVLI.VarComponents.back().emplace_back(Component, D, 21575 /*IsNonContiguous=*/false); 21576 } 21577 21578 if (MVLI.ProcessedVarList.empty()) 21579 return nullptr; 21580 21581 return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList, 21582 MVLI.VarBaseDeclarations, 21583 MVLI.VarComponents); 21584 } 21585 21586 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 21587 const OMPVarListLocTy &Locs) { 21588 MappableVarListInfo MVLI(VarList); 21589 for (Expr *RefExpr : VarList) { 21590 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 21591 SourceLocation ELoc; 21592 SourceRange ERange; 21593 Expr *SimpleRefExpr = RefExpr; 21594 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 21595 if (Res.second) { 21596 // It will be analyzed later. 21597 MVLI.ProcessedVarList.push_back(RefExpr); 21598 } 21599 ValueDecl *D = Res.first; 21600 if (!D) 21601 continue; 21602 21603 QualType Type = D->getType(); 21604 // item should be a pointer or array or reference to pointer or array 21605 if (!Type.getNonReferenceType()->isPointerType() && 21606 !Type.getNonReferenceType()->isArrayType()) { 21607 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 21608 << 0 << RefExpr->getSourceRange(); 21609 continue; 21610 } 21611 21612 // Check if the declaration in the clause does not show up in any data 21613 // sharing attribute. 21614 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 21615 if (isOpenMPPrivate(DVar.CKind)) { 21616 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 21617 << getOpenMPClauseName(DVar.CKind) 21618 << getOpenMPClauseName(OMPC_is_device_ptr) 21619 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 21620 reportOriginalDsa(*this, DSAStack, D, DVar); 21621 continue; 21622 } 21623 21624 const Expr *ConflictExpr; 21625 if (DSAStack->checkMappableExprComponentListsForDecl( 21626 D, /*CurrentRegionOnly=*/true, 21627 [&ConflictExpr]( 21628 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 21629 OpenMPClauseKind) -> bool { 21630 ConflictExpr = R.front().getAssociatedExpression(); 21631 return true; 21632 })) { 21633 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 21634 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 21635 << ConflictExpr->getSourceRange(); 21636 continue; 21637 } 21638 21639 // Store the components in the stack so that they can be used to check 21640 // against other clauses later on. 21641 OMPClauseMappableExprCommon::MappableComponent MC( 21642 SimpleRefExpr, D, /*IsNonContiguous=*/false); 21643 DSAStack->addMappableExpressionComponents( 21644 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 21645 21646 // Record the expression we've just processed. 21647 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 21648 21649 // Create a mappable component for the list item. List items in this clause 21650 // only need a component. We use a null declaration to signal fields in 21651 // 'this'. 21652 assert((isa<DeclRefExpr>(SimpleRefExpr) || 21653 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 21654 "Unexpected device pointer expression!"); 21655 MVLI.VarBaseDeclarations.push_back( 21656 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 21657 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 21658 MVLI.VarComponents.back().push_back(MC); 21659 } 21660 21661 if (MVLI.ProcessedVarList.empty()) 21662 return nullptr; 21663 21664 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList, 21665 MVLI.VarBaseDeclarations, 21666 MVLI.VarComponents); 21667 } 21668 21669 OMPClause *Sema::ActOnOpenMPAllocateClause( 21670 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, 21671 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 21672 if (Allocator) { 21673 // OpenMP [2.11.4 allocate Clause, Description] 21674 // allocator is an expression of omp_allocator_handle_t type. 21675 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack)) 21676 return nullptr; 21677 21678 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator); 21679 if (AllocatorRes.isInvalid()) 21680 return nullptr; 21681 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(), 21682 DSAStack->getOMPAllocatorHandleT(), 21683 Sema::AA_Initializing, 21684 /*AllowExplicit=*/true); 21685 if (AllocatorRes.isInvalid()) 21686 return nullptr; 21687 Allocator = AllocatorRes.get(); 21688 } else { 21689 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions. 21690 // allocate clauses that appear on a target construct or on constructs in a 21691 // target region must specify an allocator expression unless a requires 21692 // directive with the dynamic_allocators clause is present in the same 21693 // compilation unit. 21694 if (LangOpts.OpenMPIsDevice && 21695 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>()) 21696 targetDiag(StartLoc, diag::err_expected_allocator_expression); 21697 } 21698 // Analyze and build list of variables. 21699 SmallVector<Expr *, 8> Vars; 21700 for (Expr *RefExpr : VarList) { 21701 assert(RefExpr && "NULL expr in OpenMP private clause."); 21702 SourceLocation ELoc; 21703 SourceRange ERange; 21704 Expr *SimpleRefExpr = RefExpr; 21705 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 21706 if (Res.second) { 21707 // It will be analyzed later. 21708 Vars.push_back(RefExpr); 21709 } 21710 ValueDecl *D = Res.first; 21711 if (!D) 21712 continue; 21713 21714 auto *VD = dyn_cast<VarDecl>(D); 21715 DeclRefExpr *Ref = nullptr; 21716 if (!VD && !CurContext->isDependentContext()) 21717 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 21718 Vars.push_back((VD || CurContext->isDependentContext()) 21719 ? RefExpr->IgnoreParens() 21720 : Ref); 21721 } 21722 21723 if (Vars.empty()) 21724 return nullptr; 21725 21726 if (Allocator) 21727 DSAStack->addInnerAllocatorExpr(Allocator); 21728 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator, 21729 ColonLoc, EndLoc, Vars); 21730 } 21731 21732 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, 21733 SourceLocation StartLoc, 21734 SourceLocation LParenLoc, 21735 SourceLocation EndLoc) { 21736 SmallVector<Expr *, 8> Vars; 21737 for (Expr *RefExpr : VarList) { 21738 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 21739 SourceLocation ELoc; 21740 SourceRange ERange; 21741 Expr *SimpleRefExpr = RefExpr; 21742 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 21743 if (Res.second) 21744 // It will be analyzed later. 21745 Vars.push_back(RefExpr); 21746 ValueDecl *D = Res.first; 21747 if (!D) 21748 continue; 21749 21750 // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions. 21751 // A list-item cannot appear in more than one nontemporal clause. 21752 if (const Expr *PrevRef = 21753 DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) { 21754 Diag(ELoc, diag::err_omp_used_in_clause_twice) 21755 << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange; 21756 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 21757 << getOpenMPClauseName(OMPC_nontemporal); 21758 continue; 21759 } 21760 21761 Vars.push_back(RefExpr); 21762 } 21763 21764 if (Vars.empty()) 21765 return nullptr; 21766 21767 return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc, 21768 Vars); 21769 } 21770 21771 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, 21772 SourceLocation StartLoc, 21773 SourceLocation LParenLoc, 21774 SourceLocation EndLoc) { 21775 SmallVector<Expr *, 8> Vars; 21776 for (Expr *RefExpr : VarList) { 21777 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 21778 SourceLocation ELoc; 21779 SourceRange ERange; 21780 Expr *SimpleRefExpr = RefExpr; 21781 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 21782 /*AllowArraySection=*/true); 21783 if (Res.second) 21784 // It will be analyzed later. 21785 Vars.push_back(RefExpr); 21786 ValueDecl *D = Res.first; 21787 if (!D) 21788 continue; 21789 21790 const DSAStackTy::DSAVarData DVar = 21791 DSAStack->getTopDSA(D, /*FromParent=*/true); 21792 // OpenMP 5.0, 2.9.6, scan Directive, Restrictions. 21793 // A list item that appears in the inclusive or exclusive clause must appear 21794 // in a reduction clause with the inscan modifier on the enclosing 21795 // worksharing-loop, worksharing-loop SIMD, or simd construct. 21796 if (DVar.CKind != OMPC_reduction || DVar.Modifier != OMPC_REDUCTION_inscan) 21797 Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction) 21798 << RefExpr->getSourceRange(); 21799 21800 if (DSAStack->getParentDirective() != OMPD_unknown) 21801 DSAStack->markDeclAsUsedInScanDirective(D); 21802 Vars.push_back(RefExpr); 21803 } 21804 21805 if (Vars.empty()) 21806 return nullptr; 21807 21808 return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 21809 } 21810 21811 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, 21812 SourceLocation StartLoc, 21813 SourceLocation LParenLoc, 21814 SourceLocation EndLoc) { 21815 SmallVector<Expr *, 8> Vars; 21816 for (Expr *RefExpr : VarList) { 21817 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 21818 SourceLocation ELoc; 21819 SourceRange ERange; 21820 Expr *SimpleRefExpr = RefExpr; 21821 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 21822 /*AllowArraySection=*/true); 21823 if (Res.second) 21824 // It will be analyzed later. 21825 Vars.push_back(RefExpr); 21826 ValueDecl *D = Res.first; 21827 if (!D) 21828 continue; 21829 21830 OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective(); 21831 DSAStackTy::DSAVarData DVar; 21832 if (ParentDirective != OMPD_unknown) 21833 DVar = DSAStack->getTopDSA(D, /*FromParent=*/true); 21834 // OpenMP 5.0, 2.9.6, scan Directive, Restrictions. 21835 // A list item that appears in the inclusive or exclusive clause must appear 21836 // in a reduction clause with the inscan modifier on the enclosing 21837 // worksharing-loop, worksharing-loop SIMD, or simd construct. 21838 if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction || 21839 DVar.Modifier != OMPC_REDUCTION_inscan) { 21840 Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction) 21841 << RefExpr->getSourceRange(); 21842 } else { 21843 DSAStack->markDeclAsUsedInScanDirective(D); 21844 } 21845 Vars.push_back(RefExpr); 21846 } 21847 21848 if (Vars.empty()) 21849 return nullptr; 21850 21851 return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 21852 } 21853 21854 /// Tries to find omp_alloctrait_t type. 21855 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) { 21856 QualType OMPAlloctraitT = Stack->getOMPAlloctraitT(); 21857 if (!OMPAlloctraitT.isNull()) 21858 return true; 21859 IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t"); 21860 ParsedType PT = S.getTypeName(II, Loc, S.getCurScope()); 21861 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 21862 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t"; 21863 return false; 21864 } 21865 Stack->setOMPAlloctraitT(PT.get()); 21866 return true; 21867 } 21868 21869 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause( 21870 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, 21871 ArrayRef<UsesAllocatorsData> Data) { 21872 // OpenMP [2.12.5, target Construct] 21873 // allocator is an identifier of omp_allocator_handle_t type. 21874 if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack)) 21875 return nullptr; 21876 // OpenMP [2.12.5, target Construct] 21877 // allocator-traits-array is an identifier of const omp_alloctrait_t * type. 21878 if (llvm::any_of( 21879 Data, 21880 [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) && 21881 !findOMPAlloctraitT(*this, StartLoc, DSAStack)) 21882 return nullptr; 21883 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators; 21884 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 21885 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 21886 StringRef Allocator = 21887 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind); 21888 DeclarationName AllocatorName = &Context.Idents.get(Allocator); 21889 PredefinedAllocators.insert(LookupSingleName( 21890 TUScope, AllocatorName, StartLoc, Sema::LookupAnyName)); 21891 } 21892 21893 SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData; 21894 for (const UsesAllocatorsData &D : Data) { 21895 Expr *AllocatorExpr = nullptr; 21896 // Check allocator expression. 21897 if (D.Allocator->isTypeDependent()) { 21898 AllocatorExpr = D.Allocator; 21899 } else { 21900 // Traits were specified - need to assign new allocator to the specified 21901 // allocator, so it must be an lvalue. 21902 AllocatorExpr = D.Allocator->IgnoreParenImpCasts(); 21903 auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr); 21904 bool IsPredefinedAllocator = false; 21905 if (DRE) 21906 IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl()); 21907 if (!DRE || 21908 !(Context.hasSameUnqualifiedType( 21909 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) || 21910 Context.typesAreCompatible(AllocatorExpr->getType(), 21911 DSAStack->getOMPAllocatorHandleT(), 21912 /*CompareUnqualified=*/true)) || 21913 (!IsPredefinedAllocator && 21914 (AllocatorExpr->getType().isConstant(Context) || 21915 !AllocatorExpr->isLValue()))) { 21916 Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected) 21917 << "omp_allocator_handle_t" << (DRE ? 1 : 0) 21918 << AllocatorExpr->getType() << D.Allocator->getSourceRange(); 21919 continue; 21920 } 21921 // OpenMP [2.12.5, target Construct] 21922 // Predefined allocators appearing in a uses_allocators clause cannot have 21923 // traits specified. 21924 if (IsPredefinedAllocator && D.AllocatorTraits) { 21925 Diag(D.AllocatorTraits->getExprLoc(), 21926 diag::err_omp_predefined_allocator_with_traits) 21927 << D.AllocatorTraits->getSourceRange(); 21928 Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator) 21929 << cast<NamedDecl>(DRE->getDecl())->getName() 21930 << D.Allocator->getSourceRange(); 21931 continue; 21932 } 21933 // OpenMP [2.12.5, target Construct] 21934 // Non-predefined allocators appearing in a uses_allocators clause must 21935 // have traits specified. 21936 if (!IsPredefinedAllocator && !D.AllocatorTraits) { 21937 Diag(D.Allocator->getExprLoc(), 21938 diag::err_omp_nonpredefined_allocator_without_traits); 21939 continue; 21940 } 21941 // No allocator traits - just convert it to rvalue. 21942 if (!D.AllocatorTraits) 21943 AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get(); 21944 DSAStack->addUsesAllocatorsDecl( 21945 DRE->getDecl(), 21946 IsPredefinedAllocator 21947 ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator 21948 : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator); 21949 } 21950 Expr *AllocatorTraitsExpr = nullptr; 21951 if (D.AllocatorTraits) { 21952 if (D.AllocatorTraits->isTypeDependent()) { 21953 AllocatorTraitsExpr = D.AllocatorTraits; 21954 } else { 21955 // OpenMP [2.12.5, target Construct] 21956 // Arrays that contain allocator traits that appear in a uses_allocators 21957 // clause must be constant arrays, have constant values and be defined 21958 // in the same scope as the construct in which the clause appears. 21959 AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts(); 21960 // Check that traits expr is a constant array. 21961 QualType TraitTy; 21962 if (const ArrayType *Ty = 21963 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe()) 21964 if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty)) 21965 TraitTy = ConstArrayTy->getElementType(); 21966 if (TraitTy.isNull() || 21967 !(Context.hasSameUnqualifiedType(TraitTy, 21968 DSAStack->getOMPAlloctraitT()) || 21969 Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(), 21970 /*CompareUnqualified=*/true))) { 21971 Diag(D.AllocatorTraits->getExprLoc(), 21972 diag::err_omp_expected_array_alloctraits) 21973 << AllocatorTraitsExpr->getType(); 21974 continue; 21975 } 21976 // Do not map by default allocator traits if it is a standalone 21977 // variable. 21978 if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr)) 21979 DSAStack->addUsesAllocatorsDecl( 21980 DRE->getDecl(), 21981 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait); 21982 } 21983 } 21984 OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back(); 21985 NewD.Allocator = AllocatorExpr; 21986 NewD.AllocatorTraits = AllocatorTraitsExpr; 21987 NewD.LParenLoc = D.LParenLoc; 21988 NewD.RParenLoc = D.RParenLoc; 21989 } 21990 return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc, 21991 NewData); 21992 } 21993 21994 OMPClause *Sema::ActOnOpenMPAffinityClause( 21995 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 21996 SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) { 21997 SmallVector<Expr *, 8> Vars; 21998 for (Expr *RefExpr : Locators) { 21999 assert(RefExpr && "NULL expr in OpenMP shared clause."); 22000 if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) { 22001 // It will be analyzed later. 22002 Vars.push_back(RefExpr); 22003 continue; 22004 } 22005 22006 SourceLocation ELoc = RefExpr->getExprLoc(); 22007 Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts(); 22008 22009 if (!SimpleExpr->isLValue()) { 22010 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 22011 << 1 << 0 << RefExpr->getSourceRange(); 22012 continue; 22013 } 22014 22015 ExprResult Res; 22016 { 22017 Sema::TentativeAnalysisScope Trap(*this); 22018 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr); 22019 } 22020 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) && 22021 !isa<OMPArrayShapingExpr>(SimpleExpr)) { 22022 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 22023 << 1 << 0 << RefExpr->getSourceRange(); 22024 continue; 22025 } 22026 Vars.push_back(SimpleExpr); 22027 } 22028 22029 return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 22030 EndLoc, Modifier, Vars); 22031 } 22032 22033 OMPClause *Sema::ActOnOpenMPBindClause(OpenMPBindClauseKind Kind, 22034 SourceLocation KindLoc, 22035 SourceLocation StartLoc, 22036 SourceLocation LParenLoc, 22037 SourceLocation EndLoc) { 22038 if (Kind == OMPC_BIND_unknown) { 22039 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 22040 << getListOfPossibleValues(OMPC_bind, /*First=*/0, 22041 /*Last=*/unsigned(OMPC_BIND_unknown)) 22042 << getOpenMPClauseName(OMPC_bind); 22043 return nullptr; 22044 } 22045 22046 return OMPBindClause::Create(Context, Kind, KindLoc, StartLoc, LParenLoc, 22047 EndLoc); 22048 } 22049