1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// \file 9 /// This file implements semantic analysis for OpenMP directives and 10 /// clauses. 11 /// 12 //===----------------------------------------------------------------------===// 13 14 #include "TreeTransform.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/AST/DeclCXX.h" 20 #include "clang/AST/DeclOpenMP.h" 21 #include "clang/AST/OpenMPClause.h" 22 #include "clang/AST/StmtCXX.h" 23 #include "clang/AST/StmtOpenMP.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/AST/TypeOrdering.h" 26 #include "clang/Basic/DiagnosticSema.h" 27 #include "clang/Basic/OpenMPKinds.h" 28 #include "clang/Basic/PartialDiagnostic.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/Sema/Initialization.h" 31 #include "clang/Sema/Lookup.h" 32 #include "clang/Sema/Scope.h" 33 #include "clang/Sema/ScopeInfo.h" 34 #include "clang/Sema/SemaInternal.h" 35 #include "llvm/ADT/IndexedMap.h" 36 #include "llvm/ADT/PointerEmbeddedInt.h" 37 #include "llvm/ADT/STLExtras.h" 38 #include "llvm/ADT/StringExtras.h" 39 #include "llvm/Frontend/OpenMP/OMPConstants.h" 40 #include <set> 41 42 using namespace clang; 43 using namespace llvm::omp; 44 45 //===----------------------------------------------------------------------===// 46 // Stack of data-sharing attributes for variables 47 //===----------------------------------------------------------------------===// 48 49 static const Expr *checkMapClauseExpressionBase( 50 Sema &SemaRef, Expr *E, 51 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 52 OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose); 53 54 namespace { 55 /// Default data sharing attributes, which can be applied to directive. 56 enum DefaultDataSharingAttributes { 57 DSA_unspecified = 0, /// Data sharing attribute not specified. 58 DSA_none = 1 << 0, /// Default data sharing attribute 'none'. 59 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'. 60 DSA_firstprivate = 1 << 2, /// Default data sharing attribute 'firstprivate'. 61 }; 62 63 /// Stack for tracking declarations used in OpenMP directives and 64 /// clauses and their data-sharing attributes. 65 class DSAStackTy { 66 public: 67 struct DSAVarData { 68 OpenMPDirectiveKind DKind = OMPD_unknown; 69 OpenMPClauseKind CKind = OMPC_unknown; 70 unsigned Modifier = 0; 71 const Expr *RefExpr = nullptr; 72 DeclRefExpr *PrivateCopy = nullptr; 73 SourceLocation ImplicitDSALoc; 74 bool AppliedToPointee = false; 75 DSAVarData() = default; 76 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 77 const Expr *RefExpr, DeclRefExpr *PrivateCopy, 78 SourceLocation ImplicitDSALoc, unsigned Modifier, 79 bool AppliedToPointee) 80 : DKind(DKind), CKind(CKind), Modifier(Modifier), RefExpr(RefExpr), 81 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc), 82 AppliedToPointee(AppliedToPointee) {} 83 }; 84 using OperatorOffsetTy = 85 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>; 86 using DoacrossDependMapTy = 87 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>; 88 /// Kind of the declaration used in the uses_allocators clauses. 89 enum class UsesAllocatorsDeclKind { 90 /// Predefined allocator 91 PredefinedAllocator, 92 /// User-defined allocator 93 UserDefinedAllocator, 94 /// The declaration that represent allocator trait 95 AllocatorTrait, 96 }; 97 98 private: 99 struct DSAInfo { 100 OpenMPClauseKind Attributes = OMPC_unknown; 101 unsigned Modifier = 0; 102 /// Pointer to a reference expression and a flag which shows that the 103 /// variable is marked as lastprivate(true) or not (false). 104 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr; 105 DeclRefExpr *PrivateCopy = nullptr; 106 /// true if the attribute is applied to the pointee, not the variable 107 /// itself. 108 bool AppliedToPointee = false; 109 }; 110 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>; 111 using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>; 112 using LCDeclInfo = std::pair<unsigned, VarDecl *>; 113 using LoopControlVariablesMapTy = 114 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>; 115 /// Struct that associates a component with the clause kind where they are 116 /// found. 117 struct MappedExprComponentTy { 118 OMPClauseMappableExprCommon::MappableExprComponentLists Components; 119 OpenMPClauseKind Kind = OMPC_unknown; 120 }; 121 using MappedExprComponentsTy = 122 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>; 123 using CriticalsWithHintsTy = 124 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>; 125 struct ReductionData { 126 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>; 127 SourceRange ReductionRange; 128 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp; 129 ReductionData() = default; 130 void set(BinaryOperatorKind BO, SourceRange RR) { 131 ReductionRange = RR; 132 ReductionOp = BO; 133 } 134 void set(const Expr *RefExpr, SourceRange RR) { 135 ReductionRange = RR; 136 ReductionOp = RefExpr; 137 } 138 }; 139 using DeclReductionMapTy = 140 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>; 141 struct DefaultmapInfo { 142 OpenMPDefaultmapClauseModifier ImplicitBehavior = 143 OMPC_DEFAULTMAP_MODIFIER_unknown; 144 SourceLocation SLoc; 145 DefaultmapInfo() = default; 146 DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc) 147 : ImplicitBehavior(M), SLoc(Loc) {} 148 }; 149 150 struct SharingMapTy { 151 DeclSAMapTy SharingMap; 152 DeclReductionMapTy ReductionMap; 153 UsedRefMapTy AlignedMap; 154 UsedRefMapTy NontemporalMap; 155 MappedExprComponentsTy MappedExprComponents; 156 LoopControlVariablesMapTy LCVMap; 157 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 158 SourceLocation DefaultAttrLoc; 159 DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown]; 160 OpenMPDirectiveKind Directive = OMPD_unknown; 161 DeclarationNameInfo DirectiveName; 162 Scope *CurScope = nullptr; 163 DeclContext *Context = nullptr; 164 SourceLocation ConstructLoc; 165 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 166 /// get the data (loop counters etc.) about enclosing loop-based construct. 167 /// This data is required during codegen. 168 DoacrossDependMapTy DoacrossDepends; 169 /// First argument (Expr *) contains optional argument of the 170 /// 'ordered' clause, the second one is true if the regions has 'ordered' 171 /// clause, false otherwise. 172 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion; 173 unsigned AssociatedLoops = 1; 174 bool HasMutipleLoops = false; 175 const Decl *PossiblyLoopCounter = nullptr; 176 bool NowaitRegion = false; 177 bool CancelRegion = false; 178 bool LoopStart = false; 179 bool BodyComplete = false; 180 SourceLocation PrevScanLocation; 181 SourceLocation PrevOrderedLocation; 182 SourceLocation InnerTeamsRegionLoc; 183 /// Reference to the taskgroup task_reduction reference expression. 184 Expr *TaskgroupReductionRef = nullptr; 185 llvm::DenseSet<QualType> MappedClassesQualTypes; 186 SmallVector<Expr *, 4> InnerUsedAllocators; 187 llvm::DenseSet<CanonicalDeclPtr<Decl>> ImplicitTaskFirstprivates; 188 /// List of globals marked as declare target link in this target region 189 /// (isOpenMPTargetExecutionDirective(Directive) == true). 190 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls; 191 /// List of decls used in inclusive/exclusive clauses of the scan directive. 192 llvm::DenseSet<CanonicalDeclPtr<Decl>> UsedInScanDirective; 193 llvm::DenseMap<CanonicalDeclPtr<const Decl>, UsesAllocatorsDeclKind> 194 UsesAllocatorsDecls; 195 Expr *DeclareMapperVar = nullptr; 196 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 197 Scope *CurScope, SourceLocation Loc) 198 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 199 ConstructLoc(Loc) {} 200 SharingMapTy() = default; 201 }; 202 203 using StackTy = SmallVector<SharingMapTy, 4>; 204 205 /// Stack of used declaration and their data-sharing attributes. 206 DeclSAMapTy Threadprivates; 207 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr; 208 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack; 209 /// true, if check for DSA must be from parent directive, false, if 210 /// from current directive. 211 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 212 Sema &SemaRef; 213 bool ForceCapturing = false; 214 /// true if all the variables in the target executable directives must be 215 /// captured by reference. 216 bool ForceCaptureByReferenceInTargetExecutable = false; 217 CriticalsWithHintsTy Criticals; 218 unsigned IgnoredStackElements = 0; 219 220 /// Iterators over the stack iterate in order from innermost to outermost 221 /// directive. 222 using const_iterator = StackTy::const_reverse_iterator; 223 const_iterator begin() const { 224 return Stack.empty() ? const_iterator() 225 : Stack.back().first.rbegin() + IgnoredStackElements; 226 } 227 const_iterator end() const { 228 return Stack.empty() ? const_iterator() : Stack.back().first.rend(); 229 } 230 using iterator = StackTy::reverse_iterator; 231 iterator begin() { 232 return Stack.empty() ? iterator() 233 : Stack.back().first.rbegin() + IgnoredStackElements; 234 } 235 iterator end() { 236 return Stack.empty() ? iterator() : Stack.back().first.rend(); 237 } 238 239 // Convenience operations to get at the elements of the stack. 240 241 bool isStackEmpty() const { 242 return Stack.empty() || 243 Stack.back().second != CurrentNonCapturingFunctionScope || 244 Stack.back().first.size() <= IgnoredStackElements; 245 } 246 size_t getStackSize() const { 247 return isStackEmpty() ? 0 248 : Stack.back().first.size() - IgnoredStackElements; 249 } 250 251 SharingMapTy *getTopOfStackOrNull() { 252 size_t Size = getStackSize(); 253 if (Size == 0) 254 return nullptr; 255 return &Stack.back().first[Size - 1]; 256 } 257 const SharingMapTy *getTopOfStackOrNull() const { 258 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull(); 259 } 260 SharingMapTy &getTopOfStack() { 261 assert(!isStackEmpty() && "no current directive"); 262 return *getTopOfStackOrNull(); 263 } 264 const SharingMapTy &getTopOfStack() const { 265 return const_cast<DSAStackTy&>(*this).getTopOfStack(); 266 } 267 268 SharingMapTy *getSecondOnStackOrNull() { 269 size_t Size = getStackSize(); 270 if (Size <= 1) 271 return nullptr; 272 return &Stack.back().first[Size - 2]; 273 } 274 const SharingMapTy *getSecondOnStackOrNull() const { 275 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull(); 276 } 277 278 /// Get the stack element at a certain level (previously returned by 279 /// \c getNestingLevel). 280 /// 281 /// Note that nesting levels count from outermost to innermost, and this is 282 /// the reverse of our iteration order where new inner levels are pushed at 283 /// the front of the stack. 284 SharingMapTy &getStackElemAtLevel(unsigned Level) { 285 assert(Level < getStackSize() && "no such stack element"); 286 return Stack.back().first[Level]; 287 } 288 const SharingMapTy &getStackElemAtLevel(unsigned Level) const { 289 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level); 290 } 291 292 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const; 293 294 /// Checks if the variable is a local for OpenMP region. 295 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const; 296 297 /// Vector of previously declared requires directives 298 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls; 299 /// omp_allocator_handle_t type. 300 QualType OMPAllocatorHandleT; 301 /// omp_depend_t type. 302 QualType OMPDependT; 303 /// omp_event_handle_t type. 304 QualType OMPEventHandleT; 305 /// omp_alloctrait_t type. 306 QualType OMPAlloctraitT; 307 /// Expression for the predefined allocators. 308 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = { 309 nullptr}; 310 /// Vector of previously encountered target directives 311 SmallVector<SourceLocation, 2> TargetLocations; 312 SourceLocation AtomicLocation; 313 /// Vector of declare variant construct traits. 314 SmallVector<llvm::omp::TraitProperty, 8> ConstructTraits; 315 316 public: 317 explicit DSAStackTy(Sema &S) : SemaRef(S) {} 318 319 /// Sets omp_allocator_handle_t type. 320 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; } 321 /// Gets omp_allocator_handle_t type. 322 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; } 323 /// Sets omp_alloctrait_t type. 324 void setOMPAlloctraitT(QualType Ty) { OMPAlloctraitT = Ty; } 325 /// Gets omp_alloctrait_t type. 326 QualType getOMPAlloctraitT() const { return OMPAlloctraitT; } 327 /// Sets the given default allocator. 328 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, 329 Expr *Allocator) { 330 OMPPredefinedAllocators[AllocatorKind] = Allocator; 331 } 332 /// Returns the specified default allocator. 333 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const { 334 return OMPPredefinedAllocators[AllocatorKind]; 335 } 336 /// Sets omp_depend_t type. 337 void setOMPDependT(QualType Ty) { OMPDependT = Ty; } 338 /// Gets omp_depend_t type. 339 QualType getOMPDependT() const { return OMPDependT; } 340 341 /// Sets omp_event_handle_t type. 342 void setOMPEventHandleT(QualType Ty) { OMPEventHandleT = Ty; } 343 /// Gets omp_event_handle_t type. 344 QualType getOMPEventHandleT() const { return OMPEventHandleT; } 345 346 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 347 OpenMPClauseKind getClauseParsingMode() const { 348 assert(isClauseParsingMode() && "Must be in clause parsing mode."); 349 return ClauseKindMode; 350 } 351 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 352 353 bool isBodyComplete() const { 354 const SharingMapTy *Top = getTopOfStackOrNull(); 355 return Top && Top->BodyComplete; 356 } 357 void setBodyComplete() { 358 getTopOfStack().BodyComplete = true; 359 } 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 public: 396 ParentDirectiveScope(DSAStackTy &Self, bool Activate) 397 : Self(Self), Active(false) { 398 if (Activate) 399 enable(); 400 } 401 ~ParentDirectiveScope() { disable(); } 402 void disable() { 403 if (Active) { 404 --Self.IgnoredStackElements; 405 Active = false; 406 } 407 } 408 void enable() { 409 if (!Active) { 410 ++Self.IgnoredStackElements; 411 Active = true; 412 } 413 } 414 }; 415 416 /// Marks that we're started loop parsing. 417 void loopInit() { 418 assert(isOpenMPLoopDirective(getCurrentDirective()) && 419 "Expected loop-based directive."); 420 getTopOfStack().LoopStart = true; 421 } 422 /// Start capturing of the variables in the loop context. 423 void loopStart() { 424 assert(isOpenMPLoopDirective(getCurrentDirective()) && 425 "Expected loop-based directive."); 426 getTopOfStack().LoopStart = false; 427 } 428 /// true, if variables are captured, false otherwise. 429 bool isLoopStarted() const { 430 assert(isOpenMPLoopDirective(getCurrentDirective()) && 431 "Expected loop-based directive."); 432 return !getTopOfStack().LoopStart; 433 } 434 /// Marks (or clears) declaration as possibly loop counter. 435 void resetPossibleLoopCounter(const Decl *D = nullptr) { 436 getTopOfStack().PossiblyLoopCounter = 437 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) { 635 RequiresDecls.push_back(RD); 636 } 637 638 /// Checks if the defined 'requires' directive has specified type of clause. 639 template <typename ClauseType> 640 bool hasRequiresDeclWithClause() const { 641 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) { 642 return llvm::any_of(D->clauselists(), [](const OMPClause *C) { 643 return isa<ClauseType>(C); 644 }); 645 }); 646 } 647 648 /// Checks for a duplicate clause amongst previously declared requires 649 /// directives 650 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const { 651 bool IsDuplicate = false; 652 for (OMPClause *CNew : ClauseList) { 653 for (const OMPRequiresDecl *D : RequiresDecls) { 654 for (const OMPClause *CPrev : D->clauselists()) { 655 if (CNew->getClauseKind() == CPrev->getClauseKind()) { 656 SemaRef.Diag(CNew->getBeginLoc(), 657 diag::err_omp_requires_clause_redeclaration) 658 << getOpenMPClauseName(CNew->getClauseKind()); 659 SemaRef.Diag(CPrev->getBeginLoc(), 660 diag::note_omp_requires_previous_clause) 661 << getOpenMPClauseName(CPrev->getClauseKind()); 662 IsDuplicate = true; 663 } 664 } 665 } 666 } 667 return IsDuplicate; 668 } 669 670 /// Add location of previously encountered target to internal vector 671 void addTargetDirLocation(SourceLocation LocStart) { 672 TargetLocations.push_back(LocStart); 673 } 674 675 /// Add location for the first encountered atomicc directive. 676 void addAtomicDirectiveLoc(SourceLocation Loc) { 677 if (AtomicLocation.isInvalid()) 678 AtomicLocation = Loc; 679 } 680 681 /// Returns the location of the first encountered atomic directive in the 682 /// module. 683 SourceLocation getAtomicDirectiveLoc() const { 684 return AtomicLocation; 685 } 686 687 // Return previously encountered target region locations. 688 ArrayRef<SourceLocation> getEncounteredTargetLocs() const { 689 return TargetLocations; 690 } 691 692 /// Set default data sharing attribute to none. 693 void setDefaultDSANone(SourceLocation Loc) { 694 getTopOfStack().DefaultAttr = DSA_none; 695 getTopOfStack().DefaultAttrLoc = Loc; 696 } 697 /// Set default data sharing attribute to shared. 698 void setDefaultDSAShared(SourceLocation Loc) { 699 getTopOfStack().DefaultAttr = DSA_shared; 700 getTopOfStack().DefaultAttrLoc = Loc; 701 } 702 /// Set default data sharing attribute to firstprivate. 703 void setDefaultDSAFirstPrivate(SourceLocation Loc) { 704 getTopOfStack().DefaultAttr = DSA_firstprivate; 705 getTopOfStack().DefaultAttrLoc = Loc; 706 } 707 /// Set default data mapping attribute to Modifier:Kind 708 void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M, 709 OpenMPDefaultmapClauseKind Kind, 710 SourceLocation Loc) { 711 DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind]; 712 DMI.ImplicitBehavior = M; 713 DMI.SLoc = Loc; 714 } 715 /// Check whether the implicit-behavior has been set in defaultmap 716 bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) { 717 if (VariableCategory == OMPC_DEFAULTMAP_unknown) 718 return getTopOfStack() 719 .DefaultmapMap[OMPC_DEFAULTMAP_aggregate] 720 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown || 721 getTopOfStack() 722 .DefaultmapMap[OMPC_DEFAULTMAP_scalar] 723 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown || 724 getTopOfStack() 725 .DefaultmapMap[OMPC_DEFAULTMAP_pointer] 726 .ImplicitBehavior != OMPC_DEFAULTMAP_MODIFIER_unknown; 727 return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior != 728 OMPC_DEFAULTMAP_MODIFIER_unknown; 729 } 730 731 ArrayRef<llvm::omp::TraitProperty> getConstructTraits() { 732 return ConstructTraits; 733 } 734 void handleConstructTrait(ArrayRef<llvm::omp::TraitProperty> Traits, 735 bool ScopeEntry) { 736 if (ScopeEntry) 737 ConstructTraits.append(Traits.begin(), Traits.end()); 738 else 739 for (llvm::omp::TraitProperty Trait : llvm::reverse(Traits)) { 740 llvm::omp::TraitProperty Top = ConstructTraits.pop_back_val(); 741 assert(Top == Trait && "Something left a trait on the stack!"); 742 (void)Trait; 743 (void)Top; 744 } 745 } 746 747 DefaultDataSharingAttributes getDefaultDSA(unsigned Level) const { 748 return getStackSize() <= Level ? DSA_unspecified 749 : getStackElemAtLevel(Level).DefaultAttr; 750 } 751 DefaultDataSharingAttributes getDefaultDSA() const { 752 return isStackEmpty() ? DSA_unspecified 753 : getTopOfStack().DefaultAttr; 754 } 755 SourceLocation getDefaultDSALocation() const { 756 return isStackEmpty() ? SourceLocation() 757 : getTopOfStack().DefaultAttrLoc; 758 } 759 OpenMPDefaultmapClauseModifier 760 getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const { 761 return isStackEmpty() 762 ? OMPC_DEFAULTMAP_MODIFIER_unknown 763 : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior; 764 } 765 OpenMPDefaultmapClauseModifier 766 getDefaultmapModifierAtLevel(unsigned Level, 767 OpenMPDefaultmapClauseKind Kind) const { 768 return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior; 769 } 770 bool isDefaultmapCapturedByRef(unsigned Level, 771 OpenMPDefaultmapClauseKind Kind) const { 772 OpenMPDefaultmapClauseModifier M = 773 getDefaultmapModifierAtLevel(Level, Kind); 774 if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) { 775 return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) || 776 (M == OMPC_DEFAULTMAP_MODIFIER_to) || 777 (M == OMPC_DEFAULTMAP_MODIFIER_from) || 778 (M == OMPC_DEFAULTMAP_MODIFIER_tofrom); 779 } 780 return true; 781 } 782 static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M, 783 OpenMPDefaultmapClauseKind Kind) { 784 switch (Kind) { 785 case OMPC_DEFAULTMAP_scalar: 786 case OMPC_DEFAULTMAP_pointer: 787 return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) || 788 (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) || 789 (M == OMPC_DEFAULTMAP_MODIFIER_default); 790 case OMPC_DEFAULTMAP_aggregate: 791 return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate; 792 default: 793 break; 794 } 795 llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum"); 796 } 797 bool mustBeFirstprivateAtLevel(unsigned Level, 798 OpenMPDefaultmapClauseKind Kind) const { 799 OpenMPDefaultmapClauseModifier M = 800 getDefaultmapModifierAtLevel(Level, Kind); 801 return mustBeFirstprivateBase(M, Kind); 802 } 803 bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const { 804 OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind); 805 return mustBeFirstprivateBase(M, Kind); 806 } 807 808 /// Checks if the specified variable is a threadprivate. 809 bool isThreadPrivate(VarDecl *D) { 810 const DSAVarData DVar = getTopDSA(D, false); 811 return isOpenMPThreadPrivate(DVar.CKind); 812 } 813 814 /// Marks current region as ordered (it has an 'ordered' clause). 815 void setOrderedRegion(bool IsOrdered, const Expr *Param, 816 OMPOrderedClause *Clause) { 817 if (IsOrdered) 818 getTopOfStack().OrderedRegion.emplace(Param, Clause); 819 else 820 getTopOfStack().OrderedRegion.reset(); 821 } 822 /// Returns true, if region is ordered (has associated 'ordered' clause), 823 /// false - otherwise. 824 bool isOrderedRegion() const { 825 if (const SharingMapTy *Top = getTopOfStackOrNull()) 826 return Top->OrderedRegion.hasValue(); 827 return false; 828 } 829 /// Returns optional parameter for the ordered region. 830 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const { 831 if (const SharingMapTy *Top = getTopOfStackOrNull()) 832 if (Top->OrderedRegion.hasValue()) 833 return Top->OrderedRegion.getValue(); 834 return std::make_pair(nullptr, nullptr); 835 } 836 /// Returns true, if parent region is ordered (has associated 837 /// 'ordered' clause), false - otherwise. 838 bool isParentOrderedRegion() const { 839 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 840 return Parent->OrderedRegion.hasValue(); 841 return false; 842 } 843 /// Returns optional parameter for the ordered region. 844 std::pair<const Expr *, OMPOrderedClause *> 845 getParentOrderedRegionParam() const { 846 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 847 if (Parent->OrderedRegion.hasValue()) 848 return Parent->OrderedRegion.getValue(); 849 return std::make_pair(nullptr, nullptr); 850 } 851 /// Marks current region as nowait (it has a 'nowait' clause). 852 void setNowaitRegion(bool IsNowait = true) { 853 getTopOfStack().NowaitRegion = IsNowait; 854 } 855 /// Returns true, if parent region is nowait (has associated 856 /// 'nowait' clause), false - otherwise. 857 bool isParentNowaitRegion() const { 858 if (const SharingMapTy *Parent = getSecondOnStackOrNull()) 859 return Parent->NowaitRegion; 860 return false; 861 } 862 /// Marks parent region as cancel region. 863 void setParentCancelRegion(bool Cancel = true) { 864 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 865 Parent->CancelRegion |= Cancel; 866 } 867 /// Return true if current region has inner cancel construct. 868 bool isCancelRegion() const { 869 const SharingMapTy *Top = getTopOfStackOrNull(); 870 return Top ? Top->CancelRegion : false; 871 } 872 873 /// Mark that parent region already has scan directive. 874 void setParentHasScanDirective(SourceLocation Loc) { 875 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 876 Parent->PrevScanLocation = Loc; 877 } 878 /// Return true if current region has inner cancel construct. 879 bool doesParentHasScanDirective() const { 880 const SharingMapTy *Top = getSecondOnStackOrNull(); 881 return Top ? Top->PrevScanLocation.isValid() : false; 882 } 883 /// Return true if current region has inner cancel construct. 884 SourceLocation getParentScanDirectiveLoc() const { 885 const SharingMapTy *Top = getSecondOnStackOrNull(); 886 return Top ? Top->PrevScanLocation : SourceLocation(); 887 } 888 /// Mark that parent region already has ordered directive. 889 void setParentHasOrderedDirective(SourceLocation Loc) { 890 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 891 Parent->PrevOrderedLocation = Loc; 892 } 893 /// Return true if current region has inner ordered construct. 894 bool doesParentHasOrderedDirective() const { 895 const SharingMapTy *Top = getSecondOnStackOrNull(); 896 return Top ? Top->PrevOrderedLocation.isValid() : false; 897 } 898 /// Returns the location of the previously specified ordered directive. 899 SourceLocation getParentOrderedDirectiveLoc() const { 900 const SharingMapTy *Top = getSecondOnStackOrNull(); 901 return Top ? Top->PrevOrderedLocation : SourceLocation(); 902 } 903 904 /// Set collapse value for the region. 905 void setAssociatedLoops(unsigned Val) { 906 getTopOfStack().AssociatedLoops = Val; 907 if (Val > 1) 908 getTopOfStack().HasMutipleLoops = true; 909 } 910 /// Return collapse value for region. 911 unsigned getAssociatedLoops() const { 912 const SharingMapTy *Top = getTopOfStackOrNull(); 913 return Top ? Top->AssociatedLoops : 0; 914 } 915 /// Returns true if the construct is associated with multiple loops. 916 bool hasMutipleLoops() const { 917 const SharingMapTy *Top = getTopOfStackOrNull(); 918 return Top ? Top->HasMutipleLoops : false; 919 } 920 921 /// Marks current target region as one with closely nested teams 922 /// region. 923 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 924 if (SharingMapTy *Parent = getSecondOnStackOrNull()) 925 Parent->InnerTeamsRegionLoc = TeamsRegionLoc; 926 } 927 /// Returns true, if current region has closely nested teams region. 928 bool hasInnerTeamsRegion() const { 929 return getInnerTeamsRegionLoc().isValid(); 930 } 931 /// Returns location of the nested teams region (if any). 932 SourceLocation getInnerTeamsRegionLoc() const { 933 const SharingMapTy *Top = getTopOfStackOrNull(); 934 return Top ? Top->InnerTeamsRegionLoc : SourceLocation(); 935 } 936 937 Scope *getCurScope() const { 938 const SharingMapTy *Top = getTopOfStackOrNull(); 939 return Top ? Top->CurScope : nullptr; 940 } 941 void setContext(DeclContext *DC) { getTopOfStack().Context = DC; } 942 SourceLocation getConstructLoc() const { 943 const SharingMapTy *Top = getTopOfStackOrNull(); 944 return Top ? Top->ConstructLoc : SourceLocation(); 945 } 946 947 /// Do the check specified in \a Check to all component lists and return true 948 /// if any issue is found. 949 bool checkMappableExprComponentListsForDecl( 950 const ValueDecl *VD, bool CurrentRegionOnly, 951 const llvm::function_ref< 952 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 953 OpenMPClauseKind)> 954 Check) const { 955 if (isStackEmpty()) 956 return false; 957 auto SI = begin(); 958 auto SE = end(); 959 960 if (SI == SE) 961 return false; 962 963 if (CurrentRegionOnly) 964 SE = std::next(SI); 965 else 966 std::advance(SI, 1); 967 968 for (; SI != SE; ++SI) { 969 auto MI = SI->MappedExprComponents.find(VD); 970 if (MI != SI->MappedExprComponents.end()) 971 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 972 MI->second.Components) 973 if (Check(L, MI->second.Kind)) 974 return true; 975 } 976 return false; 977 } 978 979 /// Do the check specified in \a Check to all component lists at a given level 980 /// and return true if any issue is found. 981 bool checkMappableExprComponentListsForDeclAtLevel( 982 const ValueDecl *VD, unsigned Level, 983 const llvm::function_ref< 984 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 985 OpenMPClauseKind)> 986 Check) const { 987 if (getStackSize() <= Level) 988 return false; 989 990 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 991 auto MI = StackElem.MappedExprComponents.find(VD); 992 if (MI != StackElem.MappedExprComponents.end()) 993 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 994 MI->second.Components) 995 if (Check(L, MI->second.Kind)) 996 return true; 997 return false; 998 } 999 1000 /// Create a new mappable expression component list associated with a given 1001 /// declaration and initialize it with the provided list of components. 1002 void addMappableExpressionComponents( 1003 const ValueDecl *VD, 1004 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 1005 OpenMPClauseKind WhereFoundClauseKind) { 1006 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD]; 1007 // Create new entry and append the new components there. 1008 MEC.Components.resize(MEC.Components.size() + 1); 1009 MEC.Components.back().append(Components.begin(), Components.end()); 1010 MEC.Kind = WhereFoundClauseKind; 1011 } 1012 1013 unsigned getNestingLevel() const { 1014 assert(!isStackEmpty()); 1015 return getStackSize() - 1; 1016 } 1017 void addDoacrossDependClause(OMPDependClause *C, 1018 const OperatorOffsetTy &OpsOffs) { 1019 SharingMapTy *Parent = getSecondOnStackOrNull(); 1020 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive)); 1021 Parent->DoacrossDepends.try_emplace(C, OpsOffs); 1022 } 1023 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 1024 getDoacrossDependClauses() const { 1025 const SharingMapTy &StackElem = getTopOfStack(); 1026 if (isOpenMPWorksharingDirective(StackElem.Directive)) { 1027 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends; 1028 return llvm::make_range(Ref.begin(), Ref.end()); 1029 } 1030 return llvm::make_range(StackElem.DoacrossDepends.end(), 1031 StackElem.DoacrossDepends.end()); 1032 } 1033 1034 // Store types of classes which have been explicitly mapped 1035 void addMappedClassesQualTypes(QualType QT) { 1036 SharingMapTy &StackElem = getTopOfStack(); 1037 StackElem.MappedClassesQualTypes.insert(QT); 1038 } 1039 1040 // Return set of mapped classes types 1041 bool isClassPreviouslyMapped(QualType QT) const { 1042 const SharingMapTy &StackElem = getTopOfStack(); 1043 return StackElem.MappedClassesQualTypes.contains(QT); 1044 } 1045 1046 /// Adds global declare target to the parent target region. 1047 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) { 1048 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 1049 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link && 1050 "Expected declare target link global."); 1051 for (auto &Elem : *this) { 1052 if (isOpenMPTargetExecutionDirective(Elem.Directive)) { 1053 Elem.DeclareTargetLinkVarDecls.push_back(E); 1054 return; 1055 } 1056 } 1057 } 1058 1059 /// Returns the list of globals with declare target link if current directive 1060 /// is target. 1061 ArrayRef<DeclRefExpr *> getLinkGlobals() const { 1062 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) && 1063 "Expected target executable directive."); 1064 return getTopOfStack().DeclareTargetLinkVarDecls; 1065 } 1066 1067 /// Adds list of allocators expressions. 1068 void addInnerAllocatorExpr(Expr *E) { 1069 getTopOfStack().InnerUsedAllocators.push_back(E); 1070 } 1071 /// Return list of used allocators. 1072 ArrayRef<Expr *> getInnerAllocators() const { 1073 return getTopOfStack().InnerUsedAllocators; 1074 } 1075 /// Marks the declaration as implicitly firstprivate nin the task-based 1076 /// regions. 1077 void addImplicitTaskFirstprivate(unsigned Level, Decl *D) { 1078 getStackElemAtLevel(Level).ImplicitTaskFirstprivates.insert(D); 1079 } 1080 /// Checks if the decl is implicitly firstprivate in the task-based region. 1081 bool isImplicitTaskFirstprivate(Decl *D) const { 1082 return getTopOfStack().ImplicitTaskFirstprivates.contains(D); 1083 } 1084 1085 /// Marks decl as used in uses_allocators clause as the allocator. 1086 void addUsesAllocatorsDecl(const Decl *D, UsesAllocatorsDeclKind Kind) { 1087 getTopOfStack().UsesAllocatorsDecls.try_emplace(D, Kind); 1088 } 1089 /// Checks if specified decl is used in uses allocator clause as the 1090 /// allocator. 1091 Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(unsigned Level, 1092 const Decl *D) const { 1093 const SharingMapTy &StackElem = getTopOfStack(); 1094 auto I = StackElem.UsesAllocatorsDecls.find(D); 1095 if (I == StackElem.UsesAllocatorsDecls.end()) 1096 return None; 1097 return I->getSecond(); 1098 } 1099 Optional<UsesAllocatorsDeclKind> isUsesAllocatorsDecl(const Decl *D) const { 1100 const SharingMapTy &StackElem = getTopOfStack(); 1101 auto I = StackElem.UsesAllocatorsDecls.find(D); 1102 if (I == StackElem.UsesAllocatorsDecls.end()) 1103 return None; 1104 return I->getSecond(); 1105 } 1106 1107 void addDeclareMapperVarRef(Expr *Ref) { 1108 SharingMapTy &StackElem = getTopOfStack(); 1109 StackElem.DeclareMapperVar = Ref; 1110 } 1111 const Expr *getDeclareMapperVarRef() const { 1112 const SharingMapTy *Top = getTopOfStackOrNull(); 1113 return Top ? Top->DeclareMapperVar : nullptr; 1114 } 1115 }; 1116 1117 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) { 1118 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind); 1119 } 1120 1121 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) { 1122 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || 1123 DKind == OMPD_unknown; 1124 } 1125 1126 } // namespace 1127 1128 static const Expr *getExprAsWritten(const Expr *E) { 1129 if (const auto *FE = dyn_cast<FullExpr>(E)) 1130 E = FE->getSubExpr(); 1131 1132 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 1133 E = MTE->getSubExpr(); 1134 1135 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 1136 E = Binder->getSubExpr(); 1137 1138 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 1139 E = ICE->getSubExprAsWritten(); 1140 return E->IgnoreParens(); 1141 } 1142 1143 static Expr *getExprAsWritten(Expr *E) { 1144 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E))); 1145 } 1146 1147 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) { 1148 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) 1149 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 1150 D = ME->getMemberDecl(); 1151 const auto *VD = dyn_cast<VarDecl>(D); 1152 const auto *FD = dyn_cast<FieldDecl>(D); 1153 if (VD != nullptr) { 1154 VD = VD->getCanonicalDecl(); 1155 D = VD; 1156 } else { 1157 assert(FD); 1158 FD = FD->getCanonicalDecl(); 1159 D = FD; 1160 } 1161 return D; 1162 } 1163 1164 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 1165 return const_cast<ValueDecl *>( 1166 getCanonicalDecl(const_cast<const ValueDecl *>(D))); 1167 } 1168 1169 DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter, 1170 ValueDecl *D) const { 1171 D = getCanonicalDecl(D); 1172 auto *VD = dyn_cast<VarDecl>(D); 1173 const auto *FD = dyn_cast<FieldDecl>(D); 1174 DSAVarData DVar; 1175 if (Iter == end()) { 1176 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1177 // in a region but not in construct] 1178 // File-scope or namespace-scope variables referenced in called routines 1179 // in the region are shared unless they appear in a threadprivate 1180 // directive. 1181 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD)) 1182 DVar.CKind = OMPC_shared; 1183 1184 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 1185 // in a region but not in construct] 1186 // Variables with static storage duration that are declared in called 1187 // routines in the region are shared. 1188 if (VD && VD->hasGlobalStorage()) 1189 DVar.CKind = OMPC_shared; 1190 1191 // Non-static data members are shared by default. 1192 if (FD) 1193 DVar.CKind = OMPC_shared; 1194 1195 return DVar; 1196 } 1197 1198 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1199 // in a Construct, C/C++, predetermined, p.1] 1200 // Variables with automatic storage duration that are declared in a scope 1201 // inside the construct are private. 1202 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 1203 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 1204 DVar.CKind = OMPC_private; 1205 return DVar; 1206 } 1207 1208 DVar.DKind = Iter->Directive; 1209 // Explicitly specified attributes and local variables with predetermined 1210 // attributes. 1211 if (Iter->SharingMap.count(D)) { 1212 const DSAInfo &Data = Iter->SharingMap.lookup(D); 1213 DVar.RefExpr = Data.RefExpr.getPointer(); 1214 DVar.PrivateCopy = Data.PrivateCopy; 1215 DVar.CKind = Data.Attributes; 1216 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1217 DVar.Modifier = Data.Modifier; 1218 DVar.AppliedToPointee = Data.AppliedToPointee; 1219 return DVar; 1220 } 1221 1222 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1223 // in a Construct, C/C++, implicitly determined, p.1] 1224 // In a parallel or task construct, the data-sharing attributes of these 1225 // variables are determined by the default clause, if present. 1226 switch (Iter->DefaultAttr) { 1227 case DSA_shared: 1228 DVar.CKind = OMPC_shared; 1229 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1230 return DVar; 1231 case DSA_none: 1232 return DVar; 1233 case DSA_firstprivate: 1234 if (VD->getStorageDuration() == SD_Static && 1235 VD->getDeclContext()->isFileContext()) { 1236 DVar.CKind = OMPC_unknown; 1237 } else { 1238 DVar.CKind = OMPC_firstprivate; 1239 } 1240 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1241 return DVar; 1242 case DSA_unspecified: 1243 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1244 // in a Construct, implicitly determined, p.2] 1245 // In a parallel construct, if no default clause is present, these 1246 // variables are shared. 1247 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 1248 if ((isOpenMPParallelDirective(DVar.DKind) && 1249 !isOpenMPTaskLoopDirective(DVar.DKind)) || 1250 isOpenMPTeamsDirective(DVar.DKind)) { 1251 DVar.CKind = OMPC_shared; 1252 return DVar; 1253 } 1254 1255 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1256 // in a Construct, implicitly determined, p.4] 1257 // In a task construct, if no default clause is present, a variable that in 1258 // the enclosing context is determined to be shared by all implicit tasks 1259 // bound to the current team is shared. 1260 if (isOpenMPTaskingDirective(DVar.DKind)) { 1261 DSAVarData DVarTemp; 1262 const_iterator I = Iter, E = end(); 1263 do { 1264 ++I; 1265 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 1266 // Referenced in a Construct, implicitly determined, p.6] 1267 // In a task construct, if no default clause is present, a variable 1268 // whose data-sharing attribute is not determined by the rules above is 1269 // firstprivate. 1270 DVarTemp = getDSA(I, D); 1271 if (DVarTemp.CKind != OMPC_shared) { 1272 DVar.RefExpr = nullptr; 1273 DVar.CKind = OMPC_firstprivate; 1274 return DVar; 1275 } 1276 } while (I != E && !isImplicitTaskingRegion(I->Directive)); 1277 DVar.CKind = 1278 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 1279 return DVar; 1280 } 1281 } 1282 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1283 // in a Construct, implicitly determined, p.3] 1284 // For constructs other than task, if no default clause is present, these 1285 // variables inherit their data-sharing attributes from the enclosing 1286 // context. 1287 return getDSA(++Iter, D); 1288 } 1289 1290 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D, 1291 const Expr *NewDE) { 1292 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 1293 D = getCanonicalDecl(D); 1294 SharingMapTy &StackElem = getTopOfStack(); 1295 auto It = StackElem.AlignedMap.find(D); 1296 if (It == StackElem.AlignedMap.end()) { 1297 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 1298 StackElem.AlignedMap[D] = NewDE; 1299 return nullptr; 1300 } 1301 assert(It->second && "Unexpected nullptr expr in the aligned map"); 1302 return It->second; 1303 } 1304 1305 const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D, 1306 const Expr *NewDE) { 1307 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 1308 D = getCanonicalDecl(D); 1309 SharingMapTy &StackElem = getTopOfStack(); 1310 auto It = StackElem.NontemporalMap.find(D); 1311 if (It == StackElem.NontemporalMap.end()) { 1312 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 1313 StackElem.NontemporalMap[D] = NewDE; 1314 return nullptr; 1315 } 1316 assert(It->second && "Unexpected nullptr expr in the aligned map"); 1317 return It->second; 1318 } 1319 1320 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) { 1321 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1322 D = getCanonicalDecl(D); 1323 SharingMapTy &StackElem = getTopOfStack(); 1324 StackElem.LCVMap.try_emplace( 1325 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)); 1326 } 1327 1328 const DSAStackTy::LCDeclInfo 1329 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const { 1330 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1331 D = getCanonicalDecl(D); 1332 const SharingMapTy &StackElem = getTopOfStack(); 1333 auto It = StackElem.LCVMap.find(D); 1334 if (It != StackElem.LCVMap.end()) 1335 return It->second; 1336 return {0, nullptr}; 1337 } 1338 1339 const DSAStackTy::LCDeclInfo 1340 DSAStackTy::isLoopControlVariable(const ValueDecl *D, unsigned Level) const { 1341 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1342 D = getCanonicalDecl(D); 1343 for (unsigned I = Level + 1; I > 0; --I) { 1344 const SharingMapTy &StackElem = getStackElemAtLevel(I - 1); 1345 auto It = StackElem.LCVMap.find(D); 1346 if (It != StackElem.LCVMap.end()) 1347 return It->second; 1348 } 1349 return {0, nullptr}; 1350 } 1351 1352 const DSAStackTy::LCDeclInfo 1353 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const { 1354 const SharingMapTy *Parent = getSecondOnStackOrNull(); 1355 assert(Parent && "Data-sharing attributes stack is empty"); 1356 D = getCanonicalDecl(D); 1357 auto It = Parent->LCVMap.find(D); 1358 if (It != Parent->LCVMap.end()) 1359 return It->second; 1360 return {0, nullptr}; 1361 } 1362 1363 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const { 1364 const SharingMapTy *Parent = getSecondOnStackOrNull(); 1365 assert(Parent && "Data-sharing attributes stack is empty"); 1366 if (Parent->LCVMap.size() < I) 1367 return nullptr; 1368 for (const auto &Pair : Parent->LCVMap) 1369 if (Pair.second.first == I) 1370 return Pair.first; 1371 return nullptr; 1372 } 1373 1374 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 1375 DeclRefExpr *PrivateCopy, unsigned Modifier, 1376 bool AppliedToPointee) { 1377 D = getCanonicalDecl(D); 1378 if (A == OMPC_threadprivate) { 1379 DSAInfo &Data = Threadprivates[D]; 1380 Data.Attributes = A; 1381 Data.RefExpr.setPointer(E); 1382 Data.PrivateCopy = nullptr; 1383 Data.Modifier = Modifier; 1384 } else { 1385 DSAInfo &Data = getTopOfStack().SharingMap[D]; 1386 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 1387 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 1388 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 1389 (isLoopControlVariable(D).first && A == OMPC_private)); 1390 Data.Modifier = Modifier; 1391 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 1392 Data.RefExpr.setInt(/*IntVal=*/true); 1393 return; 1394 } 1395 const bool IsLastprivate = 1396 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 1397 Data.Attributes = A; 1398 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 1399 Data.PrivateCopy = PrivateCopy; 1400 Data.AppliedToPointee = AppliedToPointee; 1401 if (PrivateCopy) { 1402 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()]; 1403 Data.Modifier = Modifier; 1404 Data.Attributes = A; 1405 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 1406 Data.PrivateCopy = nullptr; 1407 Data.AppliedToPointee = AppliedToPointee; 1408 } 1409 } 1410 } 1411 1412 /// Build a variable declaration for OpenMP loop iteration variable. 1413 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 1414 StringRef Name, const AttrVec *Attrs = nullptr, 1415 DeclRefExpr *OrigRef = nullptr) { 1416 DeclContext *DC = SemaRef.CurContext; 1417 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 1418 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 1419 auto *Decl = 1420 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 1421 if (Attrs) { 1422 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 1423 I != E; ++I) 1424 Decl->addAttr(*I); 1425 } 1426 Decl->setImplicit(); 1427 if (OrigRef) { 1428 Decl->addAttr( 1429 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef)); 1430 } 1431 return Decl; 1432 } 1433 1434 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 1435 SourceLocation Loc, 1436 bool RefersToCapture = false) { 1437 D->setReferenced(); 1438 D->markUsed(S.Context); 1439 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 1440 SourceLocation(), D, RefersToCapture, Loc, Ty, 1441 VK_LValue); 1442 } 1443 1444 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 1445 BinaryOperatorKind BOK) { 1446 D = getCanonicalDecl(D); 1447 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1448 assert( 1449 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && 1450 "Additional reduction info may be specified only for reduction items."); 1451 ReductionData &ReductionData = getTopOfStack().ReductionMap[D]; 1452 assert(ReductionData.ReductionRange.isInvalid() && 1453 (getTopOfStack().Directive == OMPD_taskgroup || 1454 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 1455 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 1456 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 1457 "Additional reduction info may be specified only once for reduction " 1458 "items."); 1459 ReductionData.set(BOK, SR); 1460 Expr *&TaskgroupReductionRef = 1461 getTopOfStack().TaskgroupReductionRef; 1462 if (!TaskgroupReductionRef) { 1463 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1464 SemaRef.Context.VoidPtrTy, ".task_red."); 1465 TaskgroupReductionRef = 1466 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1467 } 1468 } 1469 1470 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 1471 const Expr *ReductionRef) { 1472 D = getCanonicalDecl(D); 1473 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 1474 assert( 1475 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction && 1476 "Additional reduction info may be specified only for reduction items."); 1477 ReductionData &ReductionData = getTopOfStack().ReductionMap[D]; 1478 assert(ReductionData.ReductionRange.isInvalid() && 1479 (getTopOfStack().Directive == OMPD_taskgroup || 1480 ((isOpenMPParallelDirective(getTopOfStack().Directive) || 1481 isOpenMPWorksharingDirective(getTopOfStack().Directive)) && 1482 !isOpenMPSimdDirective(getTopOfStack().Directive))) && 1483 "Additional reduction info may be specified only once for reduction " 1484 "items."); 1485 ReductionData.set(ReductionRef, SR); 1486 Expr *&TaskgroupReductionRef = 1487 getTopOfStack().TaskgroupReductionRef; 1488 if (!TaskgroupReductionRef) { 1489 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1490 SemaRef.Context.VoidPtrTy, ".task_red."); 1491 TaskgroupReductionRef = 1492 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1493 } 1494 } 1495 1496 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1497 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK, 1498 Expr *&TaskgroupDescriptor) const { 1499 D = getCanonicalDecl(D); 1500 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1501 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) { 1502 const DSAInfo &Data = I->SharingMap.lookup(D); 1503 if (Data.Attributes != OMPC_reduction || 1504 Data.Modifier != OMPC_REDUCTION_task) 1505 continue; 1506 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1507 if (!ReductionData.ReductionOp || 1508 ReductionData.ReductionOp.is<const Expr *>()) 1509 return DSAVarData(); 1510 SR = ReductionData.ReductionRange; 1511 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>(); 1512 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1513 "expression for the descriptor is not " 1514 "set."); 1515 TaskgroupDescriptor = I->TaskgroupReductionRef; 1516 return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(), 1517 Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task, 1518 /*AppliedToPointee=*/false); 1519 } 1520 return DSAVarData(); 1521 } 1522 1523 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1524 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef, 1525 Expr *&TaskgroupDescriptor) const { 1526 D = getCanonicalDecl(D); 1527 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1528 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) { 1529 const DSAInfo &Data = I->SharingMap.lookup(D); 1530 if (Data.Attributes != OMPC_reduction || 1531 Data.Modifier != OMPC_REDUCTION_task) 1532 continue; 1533 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1534 if (!ReductionData.ReductionOp || 1535 !ReductionData.ReductionOp.is<const Expr *>()) 1536 return DSAVarData(); 1537 SR = ReductionData.ReductionRange; 1538 ReductionRef = ReductionData.ReductionOp.get<const Expr *>(); 1539 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1540 "expression for the descriptor is not " 1541 "set."); 1542 TaskgroupDescriptor = I->TaskgroupReductionRef; 1543 return DSAVarData(I->Directive, OMPC_reduction, Data.RefExpr.getPointer(), 1544 Data.PrivateCopy, I->DefaultAttrLoc, OMPC_REDUCTION_task, 1545 /*AppliedToPointee=*/false); 1546 } 1547 return DSAVarData(); 1548 } 1549 1550 bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const { 1551 D = D->getCanonicalDecl(); 1552 for (const_iterator E = end(); I != E; ++I) { 1553 if (isImplicitOrExplicitTaskingRegion(I->Directive) || 1554 isOpenMPTargetExecutionDirective(I->Directive)) { 1555 if (I->CurScope) { 1556 Scope *TopScope = I->CurScope->getParent(); 1557 Scope *CurScope = getCurScope(); 1558 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D)) 1559 CurScope = CurScope->getParent(); 1560 return CurScope != TopScope; 1561 } 1562 for (DeclContext *DC = D->getDeclContext(); DC; DC = DC->getParent()) 1563 if (I->Context == DC) 1564 return true; 1565 return false; 1566 } 1567 } 1568 return false; 1569 } 1570 1571 static bool isConstNotMutableType(Sema &SemaRef, QualType Type, 1572 bool AcceptIfMutable = true, 1573 bool *IsClassType = nullptr) { 1574 ASTContext &Context = SemaRef.getASTContext(); 1575 Type = Type.getNonReferenceType().getCanonicalType(); 1576 bool IsConstant = Type.isConstant(Context); 1577 Type = Context.getBaseElementType(Type); 1578 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus 1579 ? Type->getAsCXXRecordDecl() 1580 : nullptr; 1581 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 1582 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate()) 1583 RD = CTD->getTemplatedDecl(); 1584 if (IsClassType) 1585 *IsClassType = RD; 1586 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD && 1587 RD->hasDefinition() && RD->hasMutableFields()); 1588 } 1589 1590 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D, 1591 QualType Type, OpenMPClauseKind CKind, 1592 SourceLocation ELoc, 1593 bool AcceptIfMutable = true, 1594 bool ListItemNotVar = false) { 1595 ASTContext &Context = SemaRef.getASTContext(); 1596 bool IsClassType; 1597 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) { 1598 unsigned Diag = ListItemNotVar 1599 ? diag::err_omp_const_list_item 1600 : IsClassType ? diag::err_omp_const_not_mutable_variable 1601 : diag::err_omp_const_variable; 1602 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind); 1603 if (!ListItemNotVar && D) { 1604 const VarDecl *VD = dyn_cast<VarDecl>(D); 1605 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 1606 VarDecl::DeclarationOnly; 1607 SemaRef.Diag(D->getLocation(), 1608 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1609 << D; 1610 } 1611 return true; 1612 } 1613 return false; 1614 } 1615 1616 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, 1617 bool FromParent) { 1618 D = getCanonicalDecl(D); 1619 DSAVarData DVar; 1620 1621 auto *VD = dyn_cast<VarDecl>(D); 1622 auto TI = Threadprivates.find(D); 1623 if (TI != Threadprivates.end()) { 1624 DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); 1625 DVar.CKind = OMPC_threadprivate; 1626 DVar.Modifier = TI->getSecond().Modifier; 1627 return DVar; 1628 } 1629 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 1630 DVar.RefExpr = buildDeclRefExpr( 1631 SemaRef, VD, D->getType().getNonReferenceType(), 1632 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation()); 1633 DVar.CKind = OMPC_threadprivate; 1634 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1635 return DVar; 1636 } 1637 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1638 // in a Construct, C/C++, predetermined, p.1] 1639 // Variables appearing in threadprivate directives are threadprivate. 1640 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 1641 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1642 SemaRef.getLangOpts().OpenMPUseTLS && 1643 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 1644 (VD && VD->getStorageClass() == SC_Register && 1645 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 1646 DVar.RefExpr = buildDeclRefExpr( 1647 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation()); 1648 DVar.CKind = OMPC_threadprivate; 1649 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1650 return DVar; 1651 } 1652 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD && 1653 VD->isLocalVarDeclOrParm() && !isStackEmpty() && 1654 !isLoopControlVariable(D).first) { 1655 const_iterator IterTarget = 1656 std::find_if(begin(), end(), [](const SharingMapTy &Data) { 1657 return isOpenMPTargetExecutionDirective(Data.Directive); 1658 }); 1659 if (IterTarget != end()) { 1660 const_iterator ParentIterTarget = IterTarget + 1; 1661 for (const_iterator Iter = begin(); 1662 Iter != ParentIterTarget; ++Iter) { 1663 if (isOpenMPLocal(VD, Iter)) { 1664 DVar.RefExpr = 1665 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1666 D->getLocation()); 1667 DVar.CKind = OMPC_threadprivate; 1668 return DVar; 1669 } 1670 } 1671 if (!isClauseParsingMode() || IterTarget != begin()) { 1672 auto DSAIter = IterTarget->SharingMap.find(D); 1673 if (DSAIter != IterTarget->SharingMap.end() && 1674 isOpenMPPrivate(DSAIter->getSecond().Attributes)) { 1675 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer(); 1676 DVar.CKind = OMPC_threadprivate; 1677 return DVar; 1678 } 1679 const_iterator End = end(); 1680 if (!SemaRef.isOpenMPCapturedByRef( 1681 D, std::distance(ParentIterTarget, End), 1682 /*OpenMPCaptureLevel=*/0)) { 1683 DVar.RefExpr = 1684 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1685 IterTarget->ConstructLoc); 1686 DVar.CKind = OMPC_threadprivate; 1687 return DVar; 1688 } 1689 } 1690 } 1691 } 1692 1693 if (isStackEmpty()) 1694 // Not in OpenMP execution region and top scope was already checked. 1695 return DVar; 1696 1697 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1698 // in a Construct, C/C++, predetermined, p.4] 1699 // Static data members are shared. 1700 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1701 // in a Construct, C/C++, predetermined, p.7] 1702 // Variables with static storage duration that are declared in a scope 1703 // inside the construct are shared. 1704 if (VD && VD->isStaticDataMember()) { 1705 // Check for explicitly specified attributes. 1706 const_iterator I = begin(); 1707 const_iterator EndI = end(); 1708 if (FromParent && I != EndI) 1709 ++I; 1710 if (I != EndI) { 1711 auto It = I->SharingMap.find(D); 1712 if (It != I->SharingMap.end()) { 1713 const DSAInfo &Data = It->getSecond(); 1714 DVar.RefExpr = Data.RefExpr.getPointer(); 1715 DVar.PrivateCopy = Data.PrivateCopy; 1716 DVar.CKind = Data.Attributes; 1717 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1718 DVar.DKind = I->Directive; 1719 DVar.Modifier = Data.Modifier; 1720 DVar.AppliedToPointee = Data.AppliedToPointee; 1721 return DVar; 1722 } 1723 } 1724 1725 DVar.CKind = OMPC_shared; 1726 return DVar; 1727 } 1728 1729 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; }; 1730 // The predetermined shared attribute for const-qualified types having no 1731 // mutable members was removed after OpenMP 3.1. 1732 if (SemaRef.LangOpts.OpenMP <= 31) { 1733 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1734 // in a Construct, C/C++, predetermined, p.6] 1735 // Variables with const qualified type having no mutable member are 1736 // shared. 1737 if (isConstNotMutableType(SemaRef, D->getType())) { 1738 // Variables with const-qualified type having no mutable member may be 1739 // listed in a firstprivate clause, even if they are static data members. 1740 DSAVarData DVarTemp = hasInnermostDSA( 1741 D, 1742 [](OpenMPClauseKind C, bool) { 1743 return C == OMPC_firstprivate || C == OMPC_shared; 1744 }, 1745 MatchesAlways, FromParent); 1746 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 1747 return DVarTemp; 1748 1749 DVar.CKind = OMPC_shared; 1750 return DVar; 1751 } 1752 } 1753 1754 // Explicitly specified attributes and local variables with predetermined 1755 // attributes. 1756 const_iterator I = begin(); 1757 const_iterator EndI = end(); 1758 if (FromParent && I != EndI) 1759 ++I; 1760 if (I == EndI) 1761 return DVar; 1762 auto It = I->SharingMap.find(D); 1763 if (It != I->SharingMap.end()) { 1764 const DSAInfo &Data = It->getSecond(); 1765 DVar.RefExpr = Data.RefExpr.getPointer(); 1766 DVar.PrivateCopy = Data.PrivateCopy; 1767 DVar.CKind = Data.Attributes; 1768 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1769 DVar.DKind = I->Directive; 1770 DVar.Modifier = Data.Modifier; 1771 DVar.AppliedToPointee = Data.AppliedToPointee; 1772 } 1773 1774 return DVar; 1775 } 1776 1777 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1778 bool FromParent) const { 1779 if (isStackEmpty()) { 1780 const_iterator I; 1781 return getDSA(I, D); 1782 } 1783 D = getCanonicalDecl(D); 1784 const_iterator StartI = begin(); 1785 const_iterator EndI = end(); 1786 if (FromParent && StartI != EndI) 1787 ++StartI; 1788 return getDSA(StartI, D); 1789 } 1790 1791 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1792 unsigned Level) const { 1793 if (getStackSize() <= Level) 1794 return DSAVarData(); 1795 D = getCanonicalDecl(D); 1796 const_iterator StartI = std::next(begin(), getStackSize() - 1 - Level); 1797 return getDSA(StartI, D); 1798 } 1799 1800 const DSAStackTy::DSAVarData 1801 DSAStackTy::hasDSA(ValueDecl *D, 1802 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1803 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1804 bool FromParent) const { 1805 if (isStackEmpty()) 1806 return {}; 1807 D = getCanonicalDecl(D); 1808 const_iterator I = begin(); 1809 const_iterator EndI = end(); 1810 if (FromParent && I != EndI) 1811 ++I; 1812 for (; I != EndI; ++I) { 1813 if (!DPred(I->Directive) && 1814 !isImplicitOrExplicitTaskingRegion(I->Directive)) 1815 continue; 1816 const_iterator NewI = I; 1817 DSAVarData DVar = getDSA(NewI, D); 1818 if (I == NewI && CPred(DVar.CKind, DVar.AppliedToPointee)) 1819 return DVar; 1820 } 1821 return {}; 1822 } 1823 1824 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 1825 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1826 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1827 bool FromParent) const { 1828 if (isStackEmpty()) 1829 return {}; 1830 D = getCanonicalDecl(D); 1831 const_iterator StartI = begin(); 1832 const_iterator EndI = end(); 1833 if (FromParent && StartI != EndI) 1834 ++StartI; 1835 if (StartI == EndI || !DPred(StartI->Directive)) 1836 return {}; 1837 const_iterator NewI = StartI; 1838 DSAVarData DVar = getDSA(NewI, D); 1839 return (NewI == StartI && CPred(DVar.CKind, DVar.AppliedToPointee)) 1840 ? DVar 1841 : DSAVarData(); 1842 } 1843 1844 bool DSAStackTy::hasExplicitDSA( 1845 const ValueDecl *D, 1846 const llvm::function_ref<bool(OpenMPClauseKind, bool)> CPred, 1847 unsigned Level, bool NotLastprivate) const { 1848 if (getStackSize() <= Level) 1849 return false; 1850 D = getCanonicalDecl(D); 1851 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 1852 auto I = StackElem.SharingMap.find(D); 1853 if (I != StackElem.SharingMap.end() && I->getSecond().RefExpr.getPointer() && 1854 CPred(I->getSecond().Attributes, I->getSecond().AppliedToPointee) && 1855 (!NotLastprivate || !I->getSecond().RefExpr.getInt())) 1856 return true; 1857 // Check predetermined rules for the loop control variables. 1858 auto LI = StackElem.LCVMap.find(D); 1859 if (LI != StackElem.LCVMap.end()) 1860 return CPred(OMPC_private, /*AppliedToPointee=*/false); 1861 return false; 1862 } 1863 1864 bool DSAStackTy::hasExplicitDirective( 1865 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1866 unsigned Level) const { 1867 if (getStackSize() <= Level) 1868 return false; 1869 const SharingMapTy &StackElem = getStackElemAtLevel(Level); 1870 return DPred(StackElem.Directive); 1871 } 1872 1873 bool DSAStackTy::hasDirective( 1874 const llvm::function_ref<bool(OpenMPDirectiveKind, 1875 const DeclarationNameInfo &, SourceLocation)> 1876 DPred, 1877 bool FromParent) const { 1878 // We look only in the enclosing region. 1879 size_t Skip = FromParent ? 2 : 1; 1880 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end(); 1881 I != E; ++I) { 1882 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 1883 return true; 1884 } 1885 return false; 1886 } 1887 1888 void Sema::InitDataSharingAttributesStack() { 1889 VarDataSharingAttributesStack = new DSAStackTy(*this); 1890 } 1891 1892 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 1893 1894 void Sema::pushOpenMPFunctionRegion() { 1895 DSAStack->pushFunction(); 1896 } 1897 1898 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 1899 DSAStack->popFunction(OldFSI); 1900 } 1901 1902 static bool isOpenMPDeviceDelayedContext(Sema &S) { 1903 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && 1904 "Expected OpenMP device compilation."); 1905 return !S.isInOpenMPTargetExecutionDirective(); 1906 } 1907 1908 namespace { 1909 /// Status of the function emission on the host/device. 1910 enum class FunctionEmissionStatus { 1911 Emitted, 1912 Discarded, 1913 Unknown, 1914 }; 1915 } // anonymous namespace 1916 1917 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc, 1918 unsigned DiagID, 1919 FunctionDecl *FD) { 1920 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 1921 "Expected OpenMP device compilation."); 1922 1923 SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop; 1924 if (FD) { 1925 FunctionEmissionStatus FES = getEmissionStatus(FD); 1926 switch (FES) { 1927 case FunctionEmissionStatus::Emitted: 1928 Kind = SemaDiagnosticBuilder::K_Immediate; 1929 break; 1930 case FunctionEmissionStatus::Unknown: 1931 // TODO: We should always delay diagnostics here in case a target 1932 // region is in a function we do not emit. However, as the 1933 // current diagnostics are associated with the function containing 1934 // the target region and we do not emit that one, we would miss out 1935 // on diagnostics for the target region itself. We need to anchor 1936 // the diagnostics with the new generated function *or* ensure we 1937 // emit diagnostics associated with the surrounding function. 1938 Kind = isOpenMPDeviceDelayedContext(*this) 1939 ? SemaDiagnosticBuilder::K_Deferred 1940 : SemaDiagnosticBuilder::K_Immediate; 1941 break; 1942 case FunctionEmissionStatus::TemplateDiscarded: 1943 case FunctionEmissionStatus::OMPDiscarded: 1944 Kind = SemaDiagnosticBuilder::K_Nop; 1945 break; 1946 case FunctionEmissionStatus::CUDADiscarded: 1947 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation"); 1948 break; 1949 } 1950 } 1951 1952 return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this); 1953 } 1954 1955 Sema::SemaDiagnosticBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc, 1956 unsigned DiagID, 1957 FunctionDecl *FD) { 1958 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice && 1959 "Expected OpenMP host compilation."); 1960 1961 SemaDiagnosticBuilder::Kind Kind = SemaDiagnosticBuilder::K_Nop; 1962 if (FD) { 1963 FunctionEmissionStatus FES = getEmissionStatus(FD); 1964 switch (FES) { 1965 case FunctionEmissionStatus::Emitted: 1966 Kind = SemaDiagnosticBuilder::K_Immediate; 1967 break; 1968 case FunctionEmissionStatus::Unknown: 1969 Kind = SemaDiagnosticBuilder::K_Deferred; 1970 break; 1971 case FunctionEmissionStatus::TemplateDiscarded: 1972 case FunctionEmissionStatus::OMPDiscarded: 1973 case FunctionEmissionStatus::CUDADiscarded: 1974 Kind = SemaDiagnosticBuilder::K_Nop; 1975 break; 1976 } 1977 } 1978 1979 return SemaDiagnosticBuilder(Kind, Loc, DiagID, FD, *this); 1980 } 1981 1982 static OpenMPDefaultmapClauseKind 1983 getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) { 1984 if (LO.OpenMP <= 45) { 1985 if (VD->getType().getNonReferenceType()->isScalarType()) 1986 return OMPC_DEFAULTMAP_scalar; 1987 return OMPC_DEFAULTMAP_aggregate; 1988 } 1989 if (VD->getType().getNonReferenceType()->isAnyPointerType()) 1990 return OMPC_DEFAULTMAP_pointer; 1991 if (VD->getType().getNonReferenceType()->isScalarType()) 1992 return OMPC_DEFAULTMAP_scalar; 1993 return OMPC_DEFAULTMAP_aggregate; 1994 } 1995 1996 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level, 1997 unsigned OpenMPCaptureLevel) const { 1998 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1999 2000 ASTContext &Ctx = getASTContext(); 2001 bool IsByRef = true; 2002 2003 // Find the directive that is associated with the provided scope. 2004 D = cast<ValueDecl>(D->getCanonicalDecl()); 2005 QualType Ty = D->getType(); 2006 2007 bool IsVariableUsedInMapClause = false; 2008 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 2009 // This table summarizes how a given variable should be passed to the device 2010 // given its type and the clauses where it appears. This table is based on 2011 // the description in OpenMP 4.5 [2.10.4, target Construct] and 2012 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 2013 // 2014 // ========================================================================= 2015 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 2016 // | |(tofrom:scalar)| | pvt | | | | 2017 // ========================================================================= 2018 // | scl | | | | - | | bycopy| 2019 // | scl | | - | x | - | - | bycopy| 2020 // | scl | | x | - | - | - | null | 2021 // | scl | x | | | - | | byref | 2022 // | scl | x | - | x | - | - | bycopy| 2023 // | scl | x | x | - | - | - | null | 2024 // | scl | | - | - | - | x | byref | 2025 // | scl | x | - | - | - | x | byref | 2026 // 2027 // | agg | n.a. | | | - | | byref | 2028 // | agg | n.a. | - | x | - | - | byref | 2029 // | agg | n.a. | x | - | - | - | null | 2030 // | agg | n.a. | - | - | - | x | byref | 2031 // | agg | n.a. | - | - | - | x[] | byref | 2032 // 2033 // | ptr | n.a. | | | - | | bycopy| 2034 // | ptr | n.a. | - | x | - | - | bycopy| 2035 // | ptr | n.a. | x | - | - | - | null | 2036 // | ptr | n.a. | - | - | - | x | byref | 2037 // | ptr | n.a. | - | - | - | x[] | bycopy| 2038 // | ptr | n.a. | - | - | x | | bycopy| 2039 // | ptr | n.a. | - | - | x | x | bycopy| 2040 // | ptr | n.a. | - | - | x | x[] | bycopy| 2041 // ========================================================================= 2042 // Legend: 2043 // scl - scalar 2044 // ptr - pointer 2045 // agg - aggregate 2046 // x - applies 2047 // - - invalid in this combination 2048 // [] - mapped with an array section 2049 // byref - should be mapped by reference 2050 // byval - should be mapped by value 2051 // null - initialize a local variable to null on the device 2052 // 2053 // Observations: 2054 // - All scalar declarations that show up in a map clause have to be passed 2055 // by reference, because they may have been mapped in the enclosing data 2056 // environment. 2057 // - If the scalar value does not fit the size of uintptr, it has to be 2058 // passed by reference, regardless the result in the table above. 2059 // - For pointers mapped by value that have either an implicit map or an 2060 // array section, the runtime library may pass the NULL value to the 2061 // device instead of the value passed to it by the compiler. 2062 2063 if (Ty->isReferenceType()) 2064 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 2065 2066 // Locate map clauses and see if the variable being captured is referred to 2067 // in any of those clauses. Here we only care about variables, not fields, 2068 // because fields are part of aggregates. 2069 bool IsVariableAssociatedWithSection = false; 2070 2071 DSAStack->checkMappableExprComponentListsForDeclAtLevel( 2072 D, Level, 2073 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D]( 2074 OMPClauseMappableExprCommon::MappableExprComponentListRef 2075 MapExprComponents, 2076 OpenMPClauseKind WhereFoundClauseKind) { 2077 // Only the map clause information influences how a variable is 2078 // captured. E.g. is_device_ptr does not require changing the default 2079 // behavior. 2080 if (WhereFoundClauseKind != OMPC_map) 2081 return false; 2082 2083 auto EI = MapExprComponents.rbegin(); 2084 auto EE = MapExprComponents.rend(); 2085 2086 assert(EI != EE && "Invalid map expression!"); 2087 2088 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 2089 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 2090 2091 ++EI; 2092 if (EI == EE) 2093 return false; 2094 2095 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 2096 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 2097 isa<MemberExpr>(EI->getAssociatedExpression()) || 2098 isa<OMPArrayShapingExpr>(EI->getAssociatedExpression())) { 2099 IsVariableAssociatedWithSection = true; 2100 // There is nothing more we need to know about this variable. 2101 return true; 2102 } 2103 2104 // Keep looking for more map info. 2105 return false; 2106 }); 2107 2108 if (IsVariableUsedInMapClause) { 2109 // If variable is identified in a map clause it is always captured by 2110 // reference except if it is a pointer that is dereferenced somehow. 2111 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 2112 } else { 2113 // By default, all the data that has a scalar type is mapped by copy 2114 // (except for reduction variables). 2115 // Defaultmap scalar is mutual exclusive to defaultmap pointer 2116 IsByRef = (DSAStack->isForceCaptureByReferenceInTargetExecutable() && 2117 !Ty->isAnyPointerType()) || 2118 !Ty->isScalarType() || 2119 DSAStack->isDefaultmapCapturedByRef( 2120 Level, getVariableCategoryFromDecl(LangOpts, D)) || 2121 DSAStack->hasExplicitDSA( 2122 D, 2123 [](OpenMPClauseKind K, bool AppliedToPointee) { 2124 return K == OMPC_reduction && !AppliedToPointee; 2125 }, 2126 Level); 2127 } 2128 } 2129 2130 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 2131 IsByRef = 2132 ((IsVariableUsedInMapClause && 2133 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) == 2134 OMPD_target) || 2135 !(DSAStack->hasExplicitDSA( 2136 D, 2137 [](OpenMPClauseKind K, bool AppliedToPointee) -> bool { 2138 return K == OMPC_firstprivate || 2139 (K == OMPC_reduction && AppliedToPointee); 2140 }, 2141 Level, /*NotLastprivate=*/true) || 2142 DSAStack->isUsesAllocatorsDecl(Level, D))) && 2143 // If the variable is artificial and must be captured by value - try to 2144 // capture by value. 2145 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() && 2146 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()) && 2147 // If the variable is implicitly firstprivate and scalar - capture by 2148 // copy 2149 !(DSAStack->getDefaultDSA() == DSA_firstprivate && 2150 !DSAStack->hasExplicitDSA( 2151 D, [](OpenMPClauseKind K, bool) { return K != OMPC_unknown; }, 2152 Level) && 2153 !DSAStack->isLoopControlVariable(D, Level).first); 2154 } 2155 2156 // When passing data by copy, we need to make sure it fits the uintptr size 2157 // and alignment, because the runtime library only deals with uintptr types. 2158 // If it does not fit the uintptr size, we need to pass the data by reference 2159 // instead. 2160 if (!IsByRef && 2161 (Ctx.getTypeSizeInChars(Ty) > 2162 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 2163 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 2164 IsByRef = true; 2165 } 2166 2167 return IsByRef; 2168 } 2169 2170 unsigned Sema::getOpenMPNestingLevel() const { 2171 assert(getLangOpts().OpenMP); 2172 return DSAStack->getNestingLevel(); 2173 } 2174 2175 bool Sema::isInOpenMPTargetExecutionDirective() const { 2176 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) && 2177 !DSAStack->isClauseParsingMode()) || 2178 DSAStack->hasDirective( 2179 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 2180 SourceLocation) -> bool { 2181 return isOpenMPTargetExecutionDirective(K); 2182 }, 2183 false); 2184 } 2185 2186 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo, 2187 unsigned StopAt) { 2188 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2189 D = getCanonicalDecl(D); 2190 2191 auto *VD = dyn_cast<VarDecl>(D); 2192 // Do not capture constexpr variables. 2193 if (VD && VD->isConstexpr()) 2194 return nullptr; 2195 2196 // If we want to determine whether the variable should be captured from the 2197 // perspective of the current capturing scope, and we've already left all the 2198 // capturing scopes of the top directive on the stack, check from the 2199 // perspective of its parent directive (if any) instead. 2200 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII( 2201 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete()); 2202 2203 // If we are attempting to capture a global variable in a directive with 2204 // 'target' we return true so that this global is also mapped to the device. 2205 // 2206 if (VD && !VD->hasLocalStorage() && 2207 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) { 2208 if (isInOpenMPTargetExecutionDirective()) { 2209 DSAStackTy::DSAVarData DVarTop = 2210 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 2211 if (DVarTop.CKind != OMPC_unknown && DVarTop.RefExpr) 2212 return VD; 2213 // If the declaration is enclosed in a 'declare target' directive, 2214 // then it should not be captured. 2215 // 2216 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 2217 return nullptr; 2218 CapturedRegionScopeInfo *CSI = nullptr; 2219 for (FunctionScopeInfo *FSI : llvm::drop_begin( 2220 llvm::reverse(FunctionScopes), 2221 CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) { 2222 if (!isa<CapturingScopeInfo>(FSI)) 2223 return nullptr; 2224 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI)) 2225 if (RSI->CapRegionKind == CR_OpenMP) { 2226 CSI = RSI; 2227 break; 2228 } 2229 } 2230 assert(CSI && "Failed to find CapturedRegionScopeInfo"); 2231 SmallVector<OpenMPDirectiveKind, 4> Regions; 2232 getOpenMPCaptureRegions(Regions, 2233 DSAStack->getDirective(CSI->OpenMPLevel)); 2234 if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task) 2235 return VD; 2236 } 2237 if (isInOpenMPDeclareTargetContext()) { 2238 // Try to mark variable as declare target if it is used in capturing 2239 // regions. 2240 if (LangOpts.OpenMP <= 45 && 2241 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 2242 checkDeclIsAllowedInOpenMPTarget(nullptr, VD); 2243 return nullptr; 2244 } 2245 } 2246 2247 if (CheckScopeInfo) { 2248 bool OpenMPFound = false; 2249 for (unsigned I = StopAt + 1; I > 0; --I) { 2250 FunctionScopeInfo *FSI = FunctionScopes[I - 1]; 2251 if(!isa<CapturingScopeInfo>(FSI)) 2252 return nullptr; 2253 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI)) 2254 if (RSI->CapRegionKind == CR_OpenMP) { 2255 OpenMPFound = true; 2256 break; 2257 } 2258 } 2259 if (!OpenMPFound) 2260 return nullptr; 2261 } 2262 2263 if (DSAStack->getCurrentDirective() != OMPD_unknown && 2264 (!DSAStack->isClauseParsingMode() || 2265 DSAStack->getParentDirective() != OMPD_unknown)) { 2266 auto &&Info = DSAStack->isLoopControlVariable(D); 2267 if (Info.first || 2268 (VD && VD->hasLocalStorage() && 2269 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) || 2270 (VD && DSAStack->isForceVarCapturing())) 2271 return VD ? VD : Info.second; 2272 DSAStackTy::DSAVarData DVarTop = 2273 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 2274 if (DVarTop.CKind != OMPC_unknown && isOpenMPPrivate(DVarTop.CKind) && 2275 (!VD || VD->hasLocalStorage() || !DVarTop.AppliedToPointee)) 2276 return VD ? VD : cast<VarDecl>(DVarTop.PrivateCopy->getDecl()); 2277 // Threadprivate variables must not be captured. 2278 if (isOpenMPThreadPrivate(DVarTop.CKind)) 2279 return nullptr; 2280 // The variable is not private or it is the variable in the directive with 2281 // default(none) clause and not used in any clause. 2282 DSAStackTy::DSAVarData DVarPrivate = DSAStack->hasDSA( 2283 D, 2284 [](OpenMPClauseKind C, bool AppliedToPointee) { 2285 return isOpenMPPrivate(C) && !AppliedToPointee; 2286 }, 2287 [](OpenMPDirectiveKind) { return true; }, 2288 DSAStack->isClauseParsingMode()); 2289 // Global shared must not be captured. 2290 if (VD && !VD->hasLocalStorage() && DVarPrivate.CKind == OMPC_unknown && 2291 ((DSAStack->getDefaultDSA() != DSA_none && 2292 DSAStack->getDefaultDSA() != DSA_firstprivate) || 2293 DVarTop.CKind == OMPC_shared)) 2294 return nullptr; 2295 if (DVarPrivate.CKind != OMPC_unknown || 2296 (VD && (DSAStack->getDefaultDSA() == DSA_none || 2297 DSAStack->getDefaultDSA() == DSA_firstprivate))) 2298 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 2299 } 2300 return nullptr; 2301 } 2302 2303 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 2304 unsigned Level) const { 2305 FunctionScopesIndex -= getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 2306 } 2307 2308 void Sema::startOpenMPLoop() { 2309 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 2310 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) 2311 DSAStack->loopInit(); 2312 } 2313 2314 void Sema::startOpenMPCXXRangeFor() { 2315 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 2316 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 2317 DSAStack->resetPossibleLoopCounter(); 2318 DSAStack->loopStart(); 2319 } 2320 } 2321 2322 OpenMPClauseKind Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level, 2323 unsigned CapLevel) const { 2324 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2325 if (DSAStack->hasExplicitDirective( 2326 [](OpenMPDirectiveKind K) { return isOpenMPTaskingDirective(K); }, 2327 Level)) { 2328 bool IsTriviallyCopyable = 2329 D->getType().getNonReferenceType().isTriviallyCopyableType(Context) && 2330 !D->getType() 2331 .getNonReferenceType() 2332 .getCanonicalType() 2333 ->getAsCXXRecordDecl(); 2334 OpenMPDirectiveKind DKind = DSAStack->getDirective(Level); 2335 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2336 getOpenMPCaptureRegions(CaptureRegions, DKind); 2337 if (isOpenMPTaskingDirective(CaptureRegions[CapLevel]) && 2338 (IsTriviallyCopyable || 2339 !isOpenMPTaskLoopDirective(CaptureRegions[CapLevel]))) { 2340 if (DSAStack->hasExplicitDSA( 2341 D, 2342 [](OpenMPClauseKind K, bool) { return K == OMPC_firstprivate; }, 2343 Level, /*NotLastprivate=*/true)) 2344 return OMPC_firstprivate; 2345 DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level); 2346 if (DVar.CKind != OMPC_shared && 2347 !DSAStack->isLoopControlVariable(D, Level).first && !DVar.RefExpr) { 2348 DSAStack->addImplicitTaskFirstprivate(Level, D); 2349 return OMPC_firstprivate; 2350 } 2351 } 2352 } 2353 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 2354 if (DSAStack->getAssociatedLoops() > 0 && 2355 !DSAStack->isLoopStarted()) { 2356 DSAStack->resetPossibleLoopCounter(D); 2357 DSAStack->loopStart(); 2358 return OMPC_private; 2359 } 2360 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() || 2361 DSAStack->isLoopControlVariable(D).first) && 2362 !DSAStack->hasExplicitDSA( 2363 D, [](OpenMPClauseKind K, bool) { return K != OMPC_private; }, 2364 Level) && 2365 !isOpenMPSimdDirective(DSAStack->getCurrentDirective())) 2366 return OMPC_private; 2367 } 2368 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2369 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) && 2370 DSAStack->isForceVarCapturing() && 2371 !DSAStack->hasExplicitDSA( 2372 D, [](OpenMPClauseKind K, bool) { return K == OMPC_copyin; }, 2373 Level)) 2374 return OMPC_private; 2375 } 2376 // User-defined allocators are private since they must be defined in the 2377 // context of target region. 2378 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level) && 2379 DSAStack->isUsesAllocatorsDecl(Level, D).getValueOr( 2380 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait) == 2381 DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator) 2382 return OMPC_private; 2383 return (DSAStack->hasExplicitDSA( 2384 D, [](OpenMPClauseKind K, bool) { return K == OMPC_private; }, 2385 Level) || 2386 (DSAStack->isClauseParsingMode() && 2387 DSAStack->getClauseParsingMode() == OMPC_private) || 2388 // Consider taskgroup reduction descriptor variable a private 2389 // to avoid possible capture in the region. 2390 (DSAStack->hasExplicitDirective( 2391 [](OpenMPDirectiveKind K) { 2392 return K == OMPD_taskgroup || 2393 ((isOpenMPParallelDirective(K) || 2394 isOpenMPWorksharingDirective(K)) && 2395 !isOpenMPSimdDirective(K)); 2396 }, 2397 Level) && 2398 DSAStack->isTaskgroupReductionRef(D, Level))) 2399 ? OMPC_private 2400 : OMPC_unknown; 2401 } 2402 2403 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, 2404 unsigned Level) { 2405 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2406 D = getCanonicalDecl(D); 2407 OpenMPClauseKind OMPC = OMPC_unknown; 2408 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) { 2409 const unsigned NewLevel = I - 1; 2410 if (DSAStack->hasExplicitDSA( 2411 D, 2412 [&OMPC](const OpenMPClauseKind K, bool AppliedToPointee) { 2413 if (isOpenMPPrivate(K) && !AppliedToPointee) { 2414 OMPC = K; 2415 return true; 2416 } 2417 return false; 2418 }, 2419 NewLevel)) 2420 break; 2421 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel( 2422 D, NewLevel, 2423 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 2424 OpenMPClauseKind) { return true; })) { 2425 OMPC = OMPC_map; 2426 break; 2427 } 2428 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 2429 NewLevel)) { 2430 OMPC = OMPC_map; 2431 if (DSAStack->mustBeFirstprivateAtLevel( 2432 NewLevel, getVariableCategoryFromDecl(LangOpts, D))) 2433 OMPC = OMPC_firstprivate; 2434 break; 2435 } 2436 } 2437 if (OMPC != OMPC_unknown) 2438 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, unsigned(OMPC))); 2439 } 2440 2441 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level, 2442 unsigned CaptureLevel) const { 2443 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2444 // Return true if the current level is no longer enclosed in a target region. 2445 2446 SmallVector<OpenMPDirectiveKind, 4> Regions; 2447 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level)); 2448 const auto *VD = dyn_cast<VarDecl>(D); 2449 return VD && !VD->hasLocalStorage() && 2450 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 2451 Level) && 2452 Regions[CaptureLevel] != OMPD_task; 2453 } 2454 2455 bool Sema::isOpenMPGlobalCapturedDecl(ValueDecl *D, unsigned Level, 2456 unsigned CaptureLevel) const { 2457 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 2458 // Return true if the current level is no longer enclosed in a target region. 2459 2460 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2461 if (!VD->hasLocalStorage()) { 2462 if (isInOpenMPTargetExecutionDirective()) 2463 return true; 2464 DSAStackTy::DSAVarData TopDVar = 2465 DSAStack->getTopDSA(D, /*FromParent=*/false); 2466 unsigned NumLevels = 2467 getOpenMPCaptureLevels(DSAStack->getDirective(Level)); 2468 if (Level == 0) 2469 return (NumLevels == CaptureLevel + 1) && TopDVar.CKind != OMPC_shared; 2470 do { 2471 --Level; 2472 DSAStackTy::DSAVarData DVar = DSAStack->getImplicitDSA(D, Level); 2473 if (DVar.CKind != OMPC_shared) 2474 return true; 2475 } while (Level > 0); 2476 } 2477 } 2478 return true; 2479 } 2480 2481 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 2482 2483 void Sema::ActOnOpenMPBeginDeclareVariant(SourceLocation Loc, 2484 OMPTraitInfo &TI) { 2485 OMPDeclareVariantScopes.push_back(OMPDeclareVariantScope(TI)); 2486 } 2487 2488 void Sema::ActOnOpenMPEndDeclareVariant() { 2489 assert(isInOpenMPDeclareVariantScope() && 2490 "Not in OpenMP declare variant scope!"); 2491 2492 OMPDeclareVariantScopes.pop_back(); 2493 } 2494 2495 void Sema::finalizeOpenMPDelayedAnalysis(const FunctionDecl *Caller, 2496 const FunctionDecl *Callee, 2497 SourceLocation Loc) { 2498 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode."); 2499 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy = 2500 OMPDeclareTargetDeclAttr::getDeviceType(Caller->getMostRecentDecl()); 2501 // Ignore host functions during device analyzis. 2502 if (LangOpts.OpenMPIsDevice && 2503 (!DevTy || *DevTy == OMPDeclareTargetDeclAttr::DT_Host)) 2504 return; 2505 // Ignore nohost functions during host analyzis. 2506 if (!LangOpts.OpenMPIsDevice && DevTy && 2507 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) 2508 return; 2509 const FunctionDecl *FD = Callee->getMostRecentDecl(); 2510 DevTy = OMPDeclareTargetDeclAttr::getDeviceType(FD); 2511 if (LangOpts.OpenMPIsDevice && DevTy && 2512 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) { 2513 // Diagnose host function called during device codegen. 2514 StringRef HostDevTy = 2515 getOpenMPSimpleClauseTypeName(OMPC_device_type, OMPC_DEVICE_TYPE_host); 2516 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0; 2517 Diag(*OMPDeclareTargetDeclAttr::getLocation(FD), 2518 diag::note_omp_marked_device_type_here) 2519 << HostDevTy; 2520 return; 2521 } 2522 if (!LangOpts.OpenMPIsDevice && DevTy && 2523 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) { 2524 // Diagnose nohost function called during host codegen. 2525 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName( 2526 OMPC_device_type, OMPC_DEVICE_TYPE_nohost); 2527 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1; 2528 Diag(*OMPDeclareTargetDeclAttr::getLocation(FD), 2529 diag::note_omp_marked_device_type_here) 2530 << NoHostDevTy; 2531 } 2532 } 2533 2534 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 2535 const DeclarationNameInfo &DirName, 2536 Scope *CurScope, SourceLocation Loc) { 2537 DSAStack->push(DKind, DirName, CurScope, Loc); 2538 PushExpressionEvaluationContext( 2539 ExpressionEvaluationContext::PotentiallyEvaluated); 2540 } 2541 2542 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 2543 DSAStack->setClauseParsingMode(K); 2544 } 2545 2546 void Sema::EndOpenMPClause() { 2547 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 2548 CleanupVarDeclMarking(); 2549 } 2550 2551 static std::pair<ValueDecl *, bool> 2552 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 2553 SourceRange &ERange, bool AllowArraySection = false); 2554 2555 /// Check consistency of the reduction clauses. 2556 static void checkReductionClauses(Sema &S, DSAStackTy *Stack, 2557 ArrayRef<OMPClause *> Clauses) { 2558 bool InscanFound = false; 2559 SourceLocation InscanLoc; 2560 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions. 2561 // A reduction clause without the inscan reduction-modifier may not appear on 2562 // a construct on which a reduction clause with the inscan reduction-modifier 2563 // appears. 2564 for (OMPClause *C : Clauses) { 2565 if (C->getClauseKind() != OMPC_reduction) 2566 continue; 2567 auto *RC = cast<OMPReductionClause>(C); 2568 if (RC->getModifier() == OMPC_REDUCTION_inscan) { 2569 InscanFound = true; 2570 InscanLoc = RC->getModifierLoc(); 2571 continue; 2572 } 2573 if (RC->getModifier() == OMPC_REDUCTION_task) { 2574 // OpenMP 5.0, 2.19.5.4 reduction Clause. 2575 // A reduction clause with the task reduction-modifier may only appear on 2576 // a parallel construct, a worksharing construct or a combined or 2577 // composite construct for which any of the aforementioned constructs is a 2578 // constituent construct and simd or loop are not constituent constructs. 2579 OpenMPDirectiveKind CurDir = Stack->getCurrentDirective(); 2580 if (!(isOpenMPParallelDirective(CurDir) || 2581 isOpenMPWorksharingDirective(CurDir)) || 2582 isOpenMPSimdDirective(CurDir)) 2583 S.Diag(RC->getModifierLoc(), 2584 diag::err_omp_reduction_task_not_parallel_or_worksharing); 2585 continue; 2586 } 2587 } 2588 if (InscanFound) { 2589 for (OMPClause *C : Clauses) { 2590 if (C->getClauseKind() != OMPC_reduction) 2591 continue; 2592 auto *RC = cast<OMPReductionClause>(C); 2593 if (RC->getModifier() != OMPC_REDUCTION_inscan) { 2594 S.Diag(RC->getModifier() == OMPC_REDUCTION_unknown 2595 ? RC->getBeginLoc() 2596 : RC->getModifierLoc(), 2597 diag::err_omp_inscan_reduction_expected); 2598 S.Diag(InscanLoc, diag::note_omp_previous_inscan_reduction); 2599 continue; 2600 } 2601 for (Expr *Ref : RC->varlists()) { 2602 assert(Ref && "NULL expr in OpenMP nontemporal clause."); 2603 SourceLocation ELoc; 2604 SourceRange ERange; 2605 Expr *SimpleRefExpr = Ref; 2606 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 2607 /*AllowArraySection=*/true); 2608 ValueDecl *D = Res.first; 2609 if (!D) 2610 continue; 2611 if (!Stack->isUsedInScanDirective(getCanonicalDecl(D))) { 2612 S.Diag(Ref->getExprLoc(), 2613 diag::err_omp_reduction_not_inclusive_exclusive) 2614 << Ref->getSourceRange(); 2615 } 2616 } 2617 } 2618 } 2619 } 2620 2621 static void checkAllocateClauses(Sema &S, DSAStackTy *Stack, 2622 ArrayRef<OMPClause *> Clauses); 2623 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 2624 bool WithInit); 2625 2626 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 2627 const ValueDecl *D, 2628 const DSAStackTy::DSAVarData &DVar, 2629 bool IsLoopIterVar = false); 2630 2631 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 2632 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 2633 // A variable of class type (or array thereof) that appears in a lastprivate 2634 // clause requires an accessible, unambiguous default constructor for the 2635 // class type, unless the list item is also specified in a firstprivate 2636 // clause. 2637 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 2638 for (OMPClause *C : D->clauses()) { 2639 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 2640 SmallVector<Expr *, 8> PrivateCopies; 2641 for (Expr *DE : Clause->varlists()) { 2642 if (DE->isValueDependent() || DE->isTypeDependent()) { 2643 PrivateCopies.push_back(nullptr); 2644 continue; 2645 } 2646 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 2647 auto *VD = cast<VarDecl>(DRE->getDecl()); 2648 QualType Type = VD->getType().getNonReferenceType(); 2649 const DSAStackTy::DSAVarData DVar = 2650 DSAStack->getTopDSA(VD, /*FromParent=*/false); 2651 if (DVar.CKind == OMPC_lastprivate) { 2652 // Generate helper private variable and initialize it with the 2653 // default value. The address of the original variable is replaced 2654 // by the address of the new private variable in CodeGen. This new 2655 // variable is not added to IdResolver, so the code in the OpenMP 2656 // region uses original variable for proper diagnostics. 2657 VarDecl *VDPrivate = buildVarDecl( 2658 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 2659 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE); 2660 ActOnUninitializedDecl(VDPrivate); 2661 if (VDPrivate->isInvalidDecl()) { 2662 PrivateCopies.push_back(nullptr); 2663 continue; 2664 } 2665 PrivateCopies.push_back(buildDeclRefExpr( 2666 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 2667 } else { 2668 // The variable is also a firstprivate, so initialization sequence 2669 // for private copy is generated already. 2670 PrivateCopies.push_back(nullptr); 2671 } 2672 } 2673 Clause->setPrivateCopies(PrivateCopies); 2674 continue; 2675 } 2676 // Finalize nontemporal clause by handling private copies, if any. 2677 if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) { 2678 SmallVector<Expr *, 8> PrivateRefs; 2679 for (Expr *RefExpr : Clause->varlists()) { 2680 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 2681 SourceLocation ELoc; 2682 SourceRange ERange; 2683 Expr *SimpleRefExpr = RefExpr; 2684 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 2685 if (Res.second) 2686 // It will be analyzed later. 2687 PrivateRefs.push_back(RefExpr); 2688 ValueDecl *D = Res.first; 2689 if (!D) 2690 continue; 2691 2692 const DSAStackTy::DSAVarData DVar = 2693 DSAStack->getTopDSA(D, /*FromParent=*/false); 2694 PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy 2695 : SimpleRefExpr); 2696 } 2697 Clause->setPrivateRefs(PrivateRefs); 2698 continue; 2699 } 2700 if (auto *Clause = dyn_cast<OMPUsesAllocatorsClause>(C)) { 2701 for (unsigned I = 0, E = Clause->getNumberOfAllocators(); I < E; ++I) { 2702 OMPUsesAllocatorsClause::Data D = Clause->getAllocatorData(I); 2703 auto *DRE = dyn_cast<DeclRefExpr>(D.Allocator->IgnoreParenImpCasts()); 2704 if (!DRE) 2705 continue; 2706 ValueDecl *VD = DRE->getDecl(); 2707 if (!VD || !isa<VarDecl>(VD)) 2708 continue; 2709 DSAStackTy::DSAVarData DVar = 2710 DSAStack->getTopDSA(VD, /*FromParent=*/false); 2711 // OpenMP [2.12.5, target Construct] 2712 // Memory allocators that appear in a uses_allocators clause cannot 2713 // appear in other data-sharing attribute clauses or data-mapping 2714 // attribute clauses in the same construct. 2715 Expr *MapExpr = nullptr; 2716 if (DVar.RefExpr || 2717 DSAStack->checkMappableExprComponentListsForDecl( 2718 VD, /*CurrentRegionOnly=*/true, 2719 [VD, &MapExpr]( 2720 OMPClauseMappableExprCommon::MappableExprComponentListRef 2721 MapExprComponents, 2722 OpenMPClauseKind C) { 2723 auto MI = MapExprComponents.rbegin(); 2724 auto ME = MapExprComponents.rend(); 2725 if (MI != ME && 2726 MI->getAssociatedDeclaration()->getCanonicalDecl() == 2727 VD->getCanonicalDecl()) { 2728 MapExpr = MI->getAssociatedExpression(); 2729 return true; 2730 } 2731 return false; 2732 })) { 2733 Diag(D.Allocator->getExprLoc(), 2734 diag::err_omp_allocator_used_in_clauses) 2735 << D.Allocator->getSourceRange(); 2736 if (DVar.RefExpr) 2737 reportOriginalDsa(*this, DSAStack, VD, DVar); 2738 else 2739 Diag(MapExpr->getExprLoc(), diag::note_used_here) 2740 << MapExpr->getSourceRange(); 2741 } 2742 } 2743 continue; 2744 } 2745 } 2746 // Check allocate clauses. 2747 if (!CurContext->isDependentContext()) 2748 checkAllocateClauses(*this, DSAStack, D->clauses()); 2749 checkReductionClauses(*this, DSAStack, D->clauses()); 2750 } 2751 2752 DSAStack->pop(); 2753 DiscardCleanupsInEvaluationContext(); 2754 PopExpressionEvaluationContext(); 2755 } 2756 2757 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 2758 Expr *NumIterations, Sema &SemaRef, 2759 Scope *S, DSAStackTy *Stack); 2760 2761 namespace { 2762 2763 class VarDeclFilterCCC final : public CorrectionCandidateCallback { 2764 private: 2765 Sema &SemaRef; 2766 2767 public: 2768 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 2769 bool ValidateCandidate(const TypoCorrection &Candidate) override { 2770 NamedDecl *ND = Candidate.getCorrectionDecl(); 2771 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 2772 return VD->hasGlobalStorage() && 2773 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 2774 SemaRef.getCurScope()); 2775 } 2776 return false; 2777 } 2778 2779 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2780 return std::make_unique<VarDeclFilterCCC>(*this); 2781 } 2782 2783 }; 2784 2785 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback { 2786 private: 2787 Sema &SemaRef; 2788 2789 public: 2790 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 2791 bool ValidateCandidate(const TypoCorrection &Candidate) override { 2792 NamedDecl *ND = Candidate.getCorrectionDecl(); 2793 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) || 2794 isa<FunctionDecl>(ND))) { 2795 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 2796 SemaRef.getCurScope()); 2797 } 2798 return false; 2799 } 2800 2801 std::unique_ptr<CorrectionCandidateCallback> clone() override { 2802 return std::make_unique<VarOrFuncDeclFilterCCC>(*this); 2803 } 2804 }; 2805 2806 } // namespace 2807 2808 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 2809 CXXScopeSpec &ScopeSpec, 2810 const DeclarationNameInfo &Id, 2811 OpenMPDirectiveKind Kind) { 2812 LookupResult Lookup(*this, Id, LookupOrdinaryName); 2813 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 2814 2815 if (Lookup.isAmbiguous()) 2816 return ExprError(); 2817 2818 VarDecl *VD; 2819 if (!Lookup.isSingleResult()) { 2820 VarDeclFilterCCC CCC(*this); 2821 if (TypoCorrection Corrected = 2822 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC, 2823 CTK_ErrorRecovery)) { 2824 diagnoseTypo(Corrected, 2825 PDiag(Lookup.empty() 2826 ? diag::err_undeclared_var_use_suggest 2827 : diag::err_omp_expected_var_arg_suggest) 2828 << Id.getName()); 2829 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 2830 } else { 2831 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 2832 : diag::err_omp_expected_var_arg) 2833 << Id.getName(); 2834 return ExprError(); 2835 } 2836 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) { 2837 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 2838 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 2839 return ExprError(); 2840 } 2841 Lookup.suppressDiagnostics(); 2842 2843 // OpenMP [2.9.2, Syntax, C/C++] 2844 // Variables must be file-scope, namespace-scope, or static block-scope. 2845 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) { 2846 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 2847 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal(); 2848 bool IsDecl = 2849 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2850 Diag(VD->getLocation(), 2851 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2852 << VD; 2853 return ExprError(); 2854 } 2855 2856 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 2857 NamedDecl *ND = CanonicalVD; 2858 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 2859 // A threadprivate directive for file-scope variables must appear outside 2860 // any definition or declaration. 2861 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 2862 !getCurLexicalContext()->isTranslationUnit()) { 2863 Diag(Id.getLoc(), diag::err_omp_var_scope) 2864 << getOpenMPDirectiveName(Kind) << VD; 2865 bool IsDecl = 2866 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2867 Diag(VD->getLocation(), 2868 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2869 << VD; 2870 return ExprError(); 2871 } 2872 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 2873 // A threadprivate directive for static class member variables must appear 2874 // in the class definition, in the same scope in which the member 2875 // variables are declared. 2876 if (CanonicalVD->isStaticDataMember() && 2877 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 2878 Diag(Id.getLoc(), diag::err_omp_var_scope) 2879 << getOpenMPDirectiveName(Kind) << VD; 2880 bool IsDecl = 2881 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2882 Diag(VD->getLocation(), 2883 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2884 << VD; 2885 return ExprError(); 2886 } 2887 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 2888 // A threadprivate directive for namespace-scope variables must appear 2889 // outside any definition or declaration other than the namespace 2890 // definition itself. 2891 if (CanonicalVD->getDeclContext()->isNamespace() && 2892 (!getCurLexicalContext()->isFileContext() || 2893 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 2894 Diag(Id.getLoc(), diag::err_omp_var_scope) 2895 << getOpenMPDirectiveName(Kind) << VD; 2896 bool IsDecl = 2897 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2898 Diag(VD->getLocation(), 2899 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2900 << VD; 2901 return ExprError(); 2902 } 2903 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 2904 // A threadprivate directive for static block-scope variables must appear 2905 // in the scope of the variable and not in a nested scope. 2906 if (CanonicalVD->isLocalVarDecl() && CurScope && 2907 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 2908 Diag(Id.getLoc(), diag::err_omp_var_scope) 2909 << getOpenMPDirectiveName(Kind) << VD; 2910 bool IsDecl = 2911 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2912 Diag(VD->getLocation(), 2913 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2914 << VD; 2915 return ExprError(); 2916 } 2917 2918 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 2919 // A threadprivate directive must lexically precede all references to any 2920 // of the variables in its list. 2921 if (Kind == OMPD_threadprivate && VD->isUsed() && 2922 !DSAStack->isThreadPrivate(VD)) { 2923 Diag(Id.getLoc(), diag::err_omp_var_used) 2924 << getOpenMPDirectiveName(Kind) << VD; 2925 return ExprError(); 2926 } 2927 2928 QualType ExprType = VD->getType().getNonReferenceType(); 2929 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 2930 SourceLocation(), VD, 2931 /*RefersToEnclosingVariableOrCapture=*/false, 2932 Id.getLoc(), ExprType, VK_LValue); 2933 } 2934 2935 Sema::DeclGroupPtrTy 2936 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 2937 ArrayRef<Expr *> VarList) { 2938 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 2939 CurContext->addDecl(D); 2940 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2941 } 2942 return nullptr; 2943 } 2944 2945 namespace { 2946 class LocalVarRefChecker final 2947 : public ConstStmtVisitor<LocalVarRefChecker, bool> { 2948 Sema &SemaRef; 2949 2950 public: 2951 bool VisitDeclRefExpr(const DeclRefExpr *E) { 2952 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 2953 if (VD->hasLocalStorage()) { 2954 SemaRef.Diag(E->getBeginLoc(), 2955 diag::err_omp_local_var_in_threadprivate_init) 2956 << E->getSourceRange(); 2957 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 2958 << VD << VD->getSourceRange(); 2959 return true; 2960 } 2961 } 2962 return false; 2963 } 2964 bool VisitStmt(const Stmt *S) { 2965 for (const Stmt *Child : S->children()) { 2966 if (Child && Visit(Child)) 2967 return true; 2968 } 2969 return false; 2970 } 2971 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 2972 }; 2973 } // namespace 2974 2975 OMPThreadPrivateDecl * 2976 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 2977 SmallVector<Expr *, 8> Vars; 2978 for (Expr *RefExpr : VarList) { 2979 auto *DE = cast<DeclRefExpr>(RefExpr); 2980 auto *VD = cast<VarDecl>(DE->getDecl()); 2981 SourceLocation ILoc = DE->getExprLoc(); 2982 2983 // Mark variable as used. 2984 VD->setReferenced(); 2985 VD->markUsed(Context); 2986 2987 QualType QType = VD->getType(); 2988 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 2989 // It will be analyzed later. 2990 Vars.push_back(DE); 2991 continue; 2992 } 2993 2994 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2995 // A threadprivate variable must not have an incomplete type. 2996 if (RequireCompleteType(ILoc, VD->getType(), 2997 diag::err_omp_threadprivate_incomplete_type)) { 2998 continue; 2999 } 3000 3001 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 3002 // A threadprivate variable must not have a reference type. 3003 if (VD->getType()->isReferenceType()) { 3004 Diag(ILoc, diag::err_omp_ref_type_arg) 3005 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 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 this is a TLS variable. If TLS is not being supported, produce 3015 // the corresponding diagnostic. 3016 if ((VD->getTLSKind() != VarDecl::TLS_None && 3017 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 3018 getLangOpts().OpenMPUseTLS && 3019 getASTContext().getTargetInfo().isTLSSupported())) || 3020 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 3021 !VD->isLocalVarDecl())) { 3022 Diag(ILoc, diag::err_omp_var_thread_local) 3023 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 3024 bool IsDecl = 3025 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 3026 Diag(VD->getLocation(), 3027 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 3028 << VD; 3029 continue; 3030 } 3031 3032 // Check if initial value of threadprivate variable reference variable with 3033 // local storage (it is not supported by runtime). 3034 if (const Expr *Init = VD->getAnyInitializer()) { 3035 LocalVarRefChecker Checker(*this); 3036 if (Checker.Visit(Init)) 3037 continue; 3038 } 3039 3040 Vars.push_back(RefExpr); 3041 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 3042 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 3043 Context, SourceRange(Loc, Loc))); 3044 if (ASTMutationListener *ML = Context.getASTMutationListener()) 3045 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 3046 } 3047 OMPThreadPrivateDecl *D = nullptr; 3048 if (!Vars.empty()) { 3049 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 3050 Vars); 3051 D->setAccess(AS_public); 3052 } 3053 return D; 3054 } 3055 3056 static OMPAllocateDeclAttr::AllocatorTypeTy 3057 getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) { 3058 if (!Allocator) 3059 return OMPAllocateDeclAttr::OMPNullMemAlloc; 3060 if (Allocator->isTypeDependent() || Allocator->isValueDependent() || 3061 Allocator->isInstantiationDependent() || 3062 Allocator->containsUnexpandedParameterPack()) 3063 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; 3064 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; 3065 const Expr *AE = Allocator->IgnoreParenImpCasts(); 3066 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 3067 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 3068 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind); 3069 llvm::FoldingSetNodeID AEId, DAEId; 3070 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true); 3071 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true); 3072 if (AEId == DAEId) { 3073 AllocatorKindRes = AllocatorKind; 3074 break; 3075 } 3076 } 3077 return AllocatorKindRes; 3078 } 3079 3080 static bool checkPreviousOMPAllocateAttribute( 3081 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD, 3082 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) { 3083 if (!VD->hasAttr<OMPAllocateDeclAttr>()) 3084 return false; 3085 const auto *A = VD->getAttr<OMPAllocateDeclAttr>(); 3086 Expr *PrevAllocator = A->getAllocator(); 3087 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind = 3088 getAllocatorKind(S, Stack, PrevAllocator); 3089 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind; 3090 if (AllocatorsMatch && 3091 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc && 3092 Allocator && PrevAllocator) { 3093 const Expr *AE = Allocator->IgnoreParenImpCasts(); 3094 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts(); 3095 llvm::FoldingSetNodeID AEId, PAEId; 3096 AE->Profile(AEId, S.Context, /*Canonical=*/true); 3097 PAE->Profile(PAEId, S.Context, /*Canonical=*/true); 3098 AllocatorsMatch = AEId == PAEId; 3099 } 3100 if (!AllocatorsMatch) { 3101 SmallString<256> AllocatorBuffer; 3102 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer); 3103 if (Allocator) 3104 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy()); 3105 SmallString<256> PrevAllocatorBuffer; 3106 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer); 3107 if (PrevAllocator) 3108 PrevAllocator->printPretty(PrevAllocatorStream, nullptr, 3109 S.getPrintingPolicy()); 3110 3111 SourceLocation AllocatorLoc = 3112 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc(); 3113 SourceRange AllocatorRange = 3114 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange(); 3115 SourceLocation PrevAllocatorLoc = 3116 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation(); 3117 SourceRange PrevAllocatorRange = 3118 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange(); 3119 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator) 3120 << (Allocator ? 1 : 0) << AllocatorStream.str() 3121 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str() 3122 << AllocatorRange; 3123 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator) 3124 << PrevAllocatorRange; 3125 return true; 3126 } 3127 return false; 3128 } 3129 3130 static void 3131 applyOMPAllocateAttribute(Sema &S, VarDecl *VD, 3132 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, 3133 Expr *Allocator, Expr *Alignment, SourceRange SR) { 3134 if (VD->hasAttr<OMPAllocateDeclAttr>()) 3135 return; 3136 if (Alignment && 3137 (Alignment->isTypeDependent() || Alignment->isValueDependent() || 3138 Alignment->isInstantiationDependent() || 3139 Alignment->containsUnexpandedParameterPack())) 3140 // Apply later when we have a usable value. 3141 return; 3142 if (Allocator && 3143 (Allocator->isTypeDependent() || Allocator->isValueDependent() || 3144 Allocator->isInstantiationDependent() || 3145 Allocator->containsUnexpandedParameterPack())) 3146 return; 3147 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind, 3148 Allocator, Alignment, SR); 3149 VD->addAttr(A); 3150 if (ASTMutationListener *ML = S.Context.getASTMutationListener()) 3151 ML->DeclarationMarkedOpenMPAllocate(VD, A); 3152 } 3153 3154 Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective( 3155 SourceLocation Loc, ArrayRef<Expr *> VarList, 3156 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) { 3157 assert(Clauses.size() <= 2 && "Expected at most two clauses."); 3158 Expr *Alignment = nullptr; 3159 Expr *Allocator = nullptr; 3160 if (Clauses.empty()) { 3161 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions. 3162 // allocate directives that appear in a target region must specify an 3163 // allocator clause unless a requires directive with the dynamic_allocators 3164 // clause is present in the same compilation unit. 3165 if (LangOpts.OpenMPIsDevice && 3166 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>()) 3167 targetDiag(Loc, diag::err_expected_allocator_clause); 3168 } else { 3169 for (const OMPClause *C : Clauses) 3170 if (const auto *AC = dyn_cast<OMPAllocatorClause>(C)) 3171 Allocator = AC->getAllocator(); 3172 else if (const auto *AC = dyn_cast<OMPAlignClause>(C)) 3173 Alignment = AC->getAlignment(); 3174 else 3175 llvm_unreachable("Unexpected clause on allocate directive"); 3176 } 3177 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind = 3178 getAllocatorKind(*this, DSAStack, Allocator); 3179 SmallVector<Expr *, 8> Vars; 3180 for (Expr *RefExpr : VarList) { 3181 auto *DE = cast<DeclRefExpr>(RefExpr); 3182 auto *VD = cast<VarDecl>(DE->getDecl()); 3183 3184 // Check if this is a TLS variable or global register. 3185 if (VD->getTLSKind() != VarDecl::TLS_None || 3186 VD->hasAttr<OMPThreadPrivateDeclAttr>() || 3187 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 3188 !VD->isLocalVarDecl())) 3189 continue; 3190 3191 // If the used several times in the allocate directive, the same allocator 3192 // must be used. 3193 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD, 3194 AllocatorKind, Allocator)) 3195 continue; 3196 3197 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++ 3198 // If a list item has a static storage type, the allocator expression in the 3199 // allocator clause must be a constant expression that evaluates to one of 3200 // the predefined memory allocator values. 3201 if (Allocator && VD->hasGlobalStorage()) { 3202 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) { 3203 Diag(Allocator->getExprLoc(), 3204 diag::err_omp_expected_predefined_allocator) 3205 << Allocator->getSourceRange(); 3206 bool IsDecl = VD->isThisDeclarationADefinition(Context) == 3207 VarDecl::DeclarationOnly; 3208 Diag(VD->getLocation(), 3209 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 3210 << VD; 3211 continue; 3212 } 3213 } 3214 3215 Vars.push_back(RefExpr); 3216 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator, Alignment, 3217 DE->getSourceRange()); 3218 } 3219 if (Vars.empty()) 3220 return nullptr; 3221 if (!Owner) 3222 Owner = getCurLexicalContext(); 3223 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses); 3224 D->setAccess(AS_public); 3225 Owner->addDecl(D); 3226 return DeclGroupPtrTy::make(DeclGroupRef(D)); 3227 } 3228 3229 Sema::DeclGroupPtrTy 3230 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc, 3231 ArrayRef<OMPClause *> ClauseList) { 3232 OMPRequiresDecl *D = nullptr; 3233 if (!CurContext->isFileContext()) { 3234 Diag(Loc, diag::err_omp_invalid_scope) << "requires"; 3235 } else { 3236 D = CheckOMPRequiresDecl(Loc, ClauseList); 3237 if (D) { 3238 CurContext->addDecl(D); 3239 DSAStack->addRequiresDecl(D); 3240 } 3241 } 3242 return DeclGroupPtrTy::make(DeclGroupRef(D)); 3243 } 3244 3245 void Sema::ActOnOpenMPAssumesDirective(SourceLocation Loc, 3246 OpenMPDirectiveKind DKind, 3247 ArrayRef<std::string> Assumptions, 3248 bool SkippedClauses) { 3249 if (!SkippedClauses && Assumptions.empty()) 3250 Diag(Loc, diag::err_omp_no_clause_for_directive) 3251 << llvm::omp::getAllAssumeClauseOptions() 3252 << llvm::omp::getOpenMPDirectiveName(DKind); 3253 3254 auto *AA = AssumptionAttr::Create(Context, llvm::join(Assumptions, ","), Loc); 3255 if (DKind == llvm::omp::Directive::OMPD_begin_assumes) { 3256 OMPAssumeScoped.push_back(AA); 3257 return; 3258 } 3259 3260 // Global assumes without assumption clauses are ignored. 3261 if (Assumptions.empty()) 3262 return; 3263 3264 assert(DKind == llvm::omp::Directive::OMPD_assumes && 3265 "Unexpected omp assumption directive!"); 3266 OMPAssumeGlobal.push_back(AA); 3267 3268 // The OMPAssumeGlobal scope above will take care of new declarations but 3269 // we also want to apply the assumption to existing ones, e.g., to 3270 // declarations in included headers. To this end, we traverse all existing 3271 // declaration contexts and annotate function declarations here. 3272 SmallVector<DeclContext *, 8> DeclContexts; 3273 auto *Ctx = CurContext; 3274 while (Ctx->getLexicalParent()) 3275 Ctx = Ctx->getLexicalParent(); 3276 DeclContexts.push_back(Ctx); 3277 while (!DeclContexts.empty()) { 3278 DeclContext *DC = DeclContexts.pop_back_val(); 3279 for (auto *SubDC : DC->decls()) { 3280 if (SubDC->isInvalidDecl()) 3281 continue; 3282 if (auto *CTD = dyn_cast<ClassTemplateDecl>(SubDC)) { 3283 DeclContexts.push_back(CTD->getTemplatedDecl()); 3284 for (auto *S : CTD->specializations()) 3285 DeclContexts.push_back(S); 3286 continue; 3287 } 3288 if (auto *DC = dyn_cast<DeclContext>(SubDC)) 3289 DeclContexts.push_back(DC); 3290 if (auto *F = dyn_cast<FunctionDecl>(SubDC)) { 3291 F->addAttr(AA); 3292 continue; 3293 } 3294 } 3295 } 3296 } 3297 3298 void Sema::ActOnOpenMPEndAssumesDirective() { 3299 assert(isInOpenMPAssumeScope() && "Not in OpenMP assumes scope!"); 3300 OMPAssumeScoped.pop_back(); 3301 } 3302 3303 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc, 3304 ArrayRef<OMPClause *> ClauseList) { 3305 /// For target specific clauses, the requires directive cannot be 3306 /// specified after the handling of any of the target regions in the 3307 /// current compilation unit. 3308 ArrayRef<SourceLocation> TargetLocations = 3309 DSAStack->getEncounteredTargetLocs(); 3310 SourceLocation AtomicLoc = DSAStack->getAtomicDirectiveLoc(); 3311 if (!TargetLocations.empty() || !AtomicLoc.isInvalid()) { 3312 for (const OMPClause *CNew : ClauseList) { 3313 // Check if any of the requires clauses affect target regions. 3314 if (isa<OMPUnifiedSharedMemoryClause>(CNew) || 3315 isa<OMPUnifiedAddressClause>(CNew) || 3316 isa<OMPReverseOffloadClause>(CNew) || 3317 isa<OMPDynamicAllocatorsClause>(CNew)) { 3318 Diag(Loc, diag::err_omp_directive_before_requires) 3319 << "target" << getOpenMPClauseName(CNew->getClauseKind()); 3320 for (SourceLocation TargetLoc : TargetLocations) { 3321 Diag(TargetLoc, diag::note_omp_requires_encountered_directive) 3322 << "target"; 3323 } 3324 } else if (!AtomicLoc.isInvalid() && 3325 isa<OMPAtomicDefaultMemOrderClause>(CNew)) { 3326 Diag(Loc, diag::err_omp_directive_before_requires) 3327 << "atomic" << getOpenMPClauseName(CNew->getClauseKind()); 3328 Diag(AtomicLoc, diag::note_omp_requires_encountered_directive) 3329 << "atomic"; 3330 } 3331 } 3332 } 3333 3334 if (!DSAStack->hasDuplicateRequiresClause(ClauseList)) 3335 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc, 3336 ClauseList); 3337 return nullptr; 3338 } 3339 3340 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 3341 const ValueDecl *D, 3342 const DSAStackTy::DSAVarData &DVar, 3343 bool IsLoopIterVar) { 3344 if (DVar.RefExpr) { 3345 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 3346 << getOpenMPClauseName(DVar.CKind); 3347 return; 3348 } 3349 enum { 3350 PDSA_StaticMemberShared, 3351 PDSA_StaticLocalVarShared, 3352 PDSA_LoopIterVarPrivate, 3353 PDSA_LoopIterVarLinear, 3354 PDSA_LoopIterVarLastprivate, 3355 PDSA_ConstVarShared, 3356 PDSA_GlobalVarShared, 3357 PDSA_TaskVarFirstprivate, 3358 PDSA_LocalVarPrivate, 3359 PDSA_Implicit 3360 } Reason = PDSA_Implicit; 3361 bool ReportHint = false; 3362 auto ReportLoc = D->getLocation(); 3363 auto *VD = dyn_cast<VarDecl>(D); 3364 if (IsLoopIterVar) { 3365 if (DVar.CKind == OMPC_private) 3366 Reason = PDSA_LoopIterVarPrivate; 3367 else if (DVar.CKind == OMPC_lastprivate) 3368 Reason = PDSA_LoopIterVarLastprivate; 3369 else 3370 Reason = PDSA_LoopIterVarLinear; 3371 } else if (isOpenMPTaskingDirective(DVar.DKind) && 3372 DVar.CKind == OMPC_firstprivate) { 3373 Reason = PDSA_TaskVarFirstprivate; 3374 ReportLoc = DVar.ImplicitDSALoc; 3375 } else if (VD && VD->isStaticLocal()) 3376 Reason = PDSA_StaticLocalVarShared; 3377 else if (VD && VD->isStaticDataMember()) 3378 Reason = PDSA_StaticMemberShared; 3379 else if (VD && VD->isFileVarDecl()) 3380 Reason = PDSA_GlobalVarShared; 3381 else if (D->getType().isConstant(SemaRef.getASTContext())) 3382 Reason = PDSA_ConstVarShared; 3383 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 3384 ReportHint = true; 3385 Reason = PDSA_LocalVarPrivate; 3386 } 3387 if (Reason != PDSA_Implicit) { 3388 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 3389 << Reason << ReportHint 3390 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 3391 } else if (DVar.ImplicitDSALoc.isValid()) { 3392 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 3393 << getOpenMPClauseName(DVar.CKind); 3394 } 3395 } 3396 3397 static OpenMPMapClauseKind 3398 getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M, 3399 bool IsAggregateOrDeclareTarget) { 3400 OpenMPMapClauseKind Kind = OMPC_MAP_unknown; 3401 switch (M) { 3402 case OMPC_DEFAULTMAP_MODIFIER_alloc: 3403 Kind = OMPC_MAP_alloc; 3404 break; 3405 case OMPC_DEFAULTMAP_MODIFIER_to: 3406 Kind = OMPC_MAP_to; 3407 break; 3408 case OMPC_DEFAULTMAP_MODIFIER_from: 3409 Kind = OMPC_MAP_from; 3410 break; 3411 case OMPC_DEFAULTMAP_MODIFIER_tofrom: 3412 Kind = OMPC_MAP_tofrom; 3413 break; 3414 case OMPC_DEFAULTMAP_MODIFIER_present: 3415 // OpenMP 5.1 [2.21.7.3] defaultmap clause, Description] 3416 // If implicit-behavior is present, each variable referenced in the 3417 // construct in the category specified by variable-category is treated as if 3418 // it had been listed in a map clause with the map-type of alloc and 3419 // map-type-modifier of present. 3420 Kind = OMPC_MAP_alloc; 3421 break; 3422 case OMPC_DEFAULTMAP_MODIFIER_firstprivate: 3423 case OMPC_DEFAULTMAP_MODIFIER_last: 3424 llvm_unreachable("Unexpected defaultmap implicit behavior"); 3425 case OMPC_DEFAULTMAP_MODIFIER_none: 3426 case OMPC_DEFAULTMAP_MODIFIER_default: 3427 case OMPC_DEFAULTMAP_MODIFIER_unknown: 3428 // IsAggregateOrDeclareTarget could be true if: 3429 // 1. the implicit behavior for aggregate is tofrom 3430 // 2. it's a declare target link 3431 if (IsAggregateOrDeclareTarget) { 3432 Kind = OMPC_MAP_tofrom; 3433 break; 3434 } 3435 llvm_unreachable("Unexpected defaultmap implicit behavior"); 3436 } 3437 assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known"); 3438 return Kind; 3439 } 3440 3441 namespace { 3442 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> { 3443 DSAStackTy *Stack; 3444 Sema &SemaRef; 3445 bool ErrorFound = false; 3446 bool TryCaptureCXXThisMembers = false; 3447 CapturedStmt *CS = nullptr; 3448 const static unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1; 3449 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate; 3450 llvm::SmallVector<Expr *, 4> ImplicitMap[DefaultmapKindNum][OMPC_MAP_delete]; 3451 llvm::SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> 3452 ImplicitMapModifier[DefaultmapKindNum]; 3453 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA; 3454 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations; 3455 3456 void VisitSubCaptures(OMPExecutableDirective *S) { 3457 // Check implicitly captured variables. 3458 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt()) 3459 return; 3460 if (S->getDirectiveKind() == OMPD_atomic || 3461 S->getDirectiveKind() == OMPD_critical || 3462 S->getDirectiveKind() == OMPD_section || 3463 S->getDirectiveKind() == OMPD_master || 3464 S->getDirectiveKind() == OMPD_masked || 3465 isOpenMPLoopTransformationDirective(S->getDirectiveKind())) { 3466 Visit(S->getAssociatedStmt()); 3467 return; 3468 } 3469 visitSubCaptures(S->getInnermostCapturedStmt()); 3470 // Try to capture inner this->member references to generate correct mappings 3471 // and diagnostics. 3472 if (TryCaptureCXXThisMembers || 3473 (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 3474 llvm::any_of(S->getInnermostCapturedStmt()->captures(), 3475 [](const CapturedStmt::Capture &C) { 3476 return C.capturesThis(); 3477 }))) { 3478 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers; 3479 TryCaptureCXXThisMembers = true; 3480 Visit(S->getInnermostCapturedStmt()->getCapturedStmt()); 3481 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers; 3482 } 3483 // In tasks firstprivates are not captured anymore, need to analyze them 3484 // explicitly. 3485 if (isOpenMPTaskingDirective(S->getDirectiveKind()) && 3486 !isOpenMPTaskLoopDirective(S->getDirectiveKind())) { 3487 for (OMPClause *C : S->clauses()) 3488 if (auto *FC = dyn_cast<OMPFirstprivateClause>(C)) { 3489 for (Expr *Ref : FC->varlists()) 3490 Visit(Ref); 3491 } 3492 } 3493 } 3494 3495 public: 3496 void VisitDeclRefExpr(DeclRefExpr *E) { 3497 if (TryCaptureCXXThisMembers || E->isTypeDependent() || 3498 E->isValueDependent() || E->containsUnexpandedParameterPack() || 3499 E->isInstantiationDependent()) 3500 return; 3501 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 3502 // Check the datasharing rules for the expressions in the clauses. 3503 if (!CS) { 3504 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD)) 3505 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) { 3506 Visit(CED->getInit()); 3507 return; 3508 } 3509 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD)) 3510 // Do not analyze internal variables and do not enclose them into 3511 // implicit clauses. 3512 return; 3513 VD = VD->getCanonicalDecl(); 3514 // Skip internally declared variables. 3515 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD) && 3516 !Stack->isImplicitTaskFirstprivate(VD)) 3517 return; 3518 // Skip allocators in uses_allocators clauses. 3519 if (Stack->isUsesAllocatorsDecl(VD).hasValue()) 3520 return; 3521 3522 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 3523 // Check if the variable has explicit DSA set and stop analysis if it so. 3524 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second) 3525 return; 3526 3527 // Skip internally declared static variables. 3528 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 3529 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 3530 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) && 3531 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || 3532 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link) && 3533 !Stack->isImplicitTaskFirstprivate(VD)) 3534 return; 3535 3536 SourceLocation ELoc = E->getExprLoc(); 3537 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 3538 // The default(none) clause requires that each variable that is referenced 3539 // in the construct, and does not have a predetermined data-sharing 3540 // attribute, must have its data-sharing attribute explicitly determined 3541 // by being listed in a data-sharing attribute clause. 3542 if (DVar.CKind == OMPC_unknown && 3543 (Stack->getDefaultDSA() == DSA_none || 3544 Stack->getDefaultDSA() == DSA_firstprivate) && 3545 isImplicitOrExplicitTaskingRegion(DKind) && 3546 VarsWithInheritedDSA.count(VD) == 0) { 3547 bool InheritedDSA = Stack->getDefaultDSA() == DSA_none; 3548 if (!InheritedDSA && Stack->getDefaultDSA() == DSA_firstprivate) { 3549 DSAStackTy::DSAVarData DVar = 3550 Stack->getImplicitDSA(VD, /*FromParent=*/false); 3551 InheritedDSA = DVar.CKind == OMPC_unknown; 3552 } 3553 if (InheritedDSA) 3554 VarsWithInheritedDSA[VD] = E; 3555 return; 3556 } 3557 3558 // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description] 3559 // If implicit-behavior is none, each variable referenced in the 3560 // construct that does not have a predetermined data-sharing attribute 3561 // and does not appear in a to or link clause on a declare target 3562 // directive must be listed in a data-mapping attribute clause, a 3563 // data-haring attribute clause (including a data-sharing attribute 3564 // clause on a combined construct where target. is one of the 3565 // constituent constructs), or an is_device_ptr clause. 3566 OpenMPDefaultmapClauseKind ClauseKind = 3567 getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD); 3568 if (SemaRef.getLangOpts().OpenMP >= 50) { 3569 bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) == 3570 OMPC_DEFAULTMAP_MODIFIER_none; 3571 if (DVar.CKind == OMPC_unknown && IsModifierNone && 3572 VarsWithInheritedDSA.count(VD) == 0 && !Res) { 3573 // Only check for data-mapping attribute and is_device_ptr here 3574 // since we have already make sure that the declaration does not 3575 // have a data-sharing attribute above 3576 if (!Stack->checkMappableExprComponentListsForDecl( 3577 VD, /*CurrentRegionOnly=*/true, 3578 [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef 3579 MapExprComponents, 3580 OpenMPClauseKind) { 3581 auto MI = MapExprComponents.rbegin(); 3582 auto ME = MapExprComponents.rend(); 3583 return MI != ME && MI->getAssociatedDeclaration() == VD; 3584 })) { 3585 VarsWithInheritedDSA[VD] = E; 3586 return; 3587 } 3588 } 3589 } 3590 if (SemaRef.getLangOpts().OpenMP > 50) { 3591 bool IsModifierPresent = Stack->getDefaultmapModifier(ClauseKind) == 3592 OMPC_DEFAULTMAP_MODIFIER_present; 3593 if (IsModifierPresent) { 3594 if (llvm::find(ImplicitMapModifier[ClauseKind], 3595 OMPC_MAP_MODIFIER_present) == 3596 std::end(ImplicitMapModifier[ClauseKind])) { 3597 ImplicitMapModifier[ClauseKind].push_back( 3598 OMPC_MAP_MODIFIER_present); 3599 } 3600 } 3601 } 3602 3603 if (isOpenMPTargetExecutionDirective(DKind) && 3604 !Stack->isLoopControlVariable(VD).first) { 3605 if (!Stack->checkMappableExprComponentListsForDecl( 3606 VD, /*CurrentRegionOnly=*/true, 3607 [this](OMPClauseMappableExprCommon::MappableExprComponentListRef 3608 StackComponents, 3609 OpenMPClauseKind) { 3610 if (SemaRef.LangOpts.OpenMP >= 50) 3611 return !StackComponents.empty(); 3612 // Variable is used if it has been marked as an array, array 3613 // section, array shaping or the variable iself. 3614 return StackComponents.size() == 1 || 3615 std::all_of( 3616 std::next(StackComponents.rbegin()), 3617 StackComponents.rend(), 3618 [](const OMPClauseMappableExprCommon:: 3619 MappableComponent &MC) { 3620 return MC.getAssociatedDeclaration() == 3621 nullptr && 3622 (isa<OMPArraySectionExpr>( 3623 MC.getAssociatedExpression()) || 3624 isa<OMPArrayShapingExpr>( 3625 MC.getAssociatedExpression()) || 3626 isa<ArraySubscriptExpr>( 3627 MC.getAssociatedExpression())); 3628 }); 3629 })) { 3630 bool IsFirstprivate = false; 3631 // By default lambdas are captured as firstprivates. 3632 if (const auto *RD = 3633 VD->getType().getNonReferenceType()->getAsCXXRecordDecl()) 3634 IsFirstprivate = RD->isLambda(); 3635 IsFirstprivate = 3636 IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res); 3637 if (IsFirstprivate) { 3638 ImplicitFirstprivate.emplace_back(E); 3639 } else { 3640 OpenMPDefaultmapClauseModifier M = 3641 Stack->getDefaultmapModifier(ClauseKind); 3642 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier( 3643 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res); 3644 ImplicitMap[ClauseKind][Kind].emplace_back(E); 3645 } 3646 return; 3647 } 3648 } 3649 3650 // OpenMP [2.9.3.6, Restrictions, p.2] 3651 // A list item that appears in a reduction clause of the innermost 3652 // enclosing worksharing or parallel construct may not be accessed in an 3653 // explicit task. 3654 DVar = Stack->hasInnermostDSA( 3655 VD, 3656 [](OpenMPClauseKind C, bool AppliedToPointee) { 3657 return C == OMPC_reduction && !AppliedToPointee; 3658 }, 3659 [](OpenMPDirectiveKind K) { 3660 return isOpenMPParallelDirective(K) || 3661 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 3662 }, 3663 /*FromParent=*/true); 3664 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 3665 ErrorFound = true; 3666 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 3667 reportOriginalDsa(SemaRef, Stack, VD, DVar); 3668 return; 3669 } 3670 3671 // Define implicit data-sharing attributes for task. 3672 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false); 3673 if (((isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared) || 3674 (Stack->getDefaultDSA() == DSA_firstprivate && 3675 DVar.CKind == OMPC_firstprivate && !DVar.RefExpr)) && 3676 !Stack->isLoopControlVariable(VD).first) { 3677 ImplicitFirstprivate.push_back(E); 3678 return; 3679 } 3680 3681 // Store implicitly used globals with declare target link for parent 3682 // target. 3683 if (!isOpenMPTargetExecutionDirective(DKind) && Res && 3684 *Res == OMPDeclareTargetDeclAttr::MT_Link) { 3685 Stack->addToParentTargetRegionLinkGlobals(E); 3686 return; 3687 } 3688 } 3689 } 3690 void VisitMemberExpr(MemberExpr *E) { 3691 if (E->isTypeDependent() || E->isValueDependent() || 3692 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 3693 return; 3694 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 3695 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 3696 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParenCasts())) { 3697 if (!FD) 3698 return; 3699 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false); 3700 // Check if the variable has explicit DSA set and stop analysis if it 3701 // so. 3702 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second) 3703 return; 3704 3705 if (isOpenMPTargetExecutionDirective(DKind) && 3706 !Stack->isLoopControlVariable(FD).first && 3707 !Stack->checkMappableExprComponentListsForDecl( 3708 FD, /*CurrentRegionOnly=*/true, 3709 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 3710 StackComponents, 3711 OpenMPClauseKind) { 3712 return isa<CXXThisExpr>( 3713 cast<MemberExpr>( 3714 StackComponents.back().getAssociatedExpression()) 3715 ->getBase() 3716 ->IgnoreParens()); 3717 })) { 3718 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 3719 // A bit-field cannot appear in a map clause. 3720 // 3721 if (FD->isBitField()) 3722 return; 3723 3724 // Check to see if the member expression is referencing a class that 3725 // has already been explicitly mapped 3726 if (Stack->isClassPreviouslyMapped(TE->getType())) 3727 return; 3728 3729 OpenMPDefaultmapClauseModifier Modifier = 3730 Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate); 3731 OpenMPDefaultmapClauseKind ClauseKind = 3732 getVariableCategoryFromDecl(SemaRef.getLangOpts(), FD); 3733 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier( 3734 Modifier, /*IsAggregateOrDeclareTarget*/ true); 3735 ImplicitMap[ClauseKind][Kind].emplace_back(E); 3736 return; 3737 } 3738 3739 SourceLocation ELoc = E->getExprLoc(); 3740 // OpenMP [2.9.3.6, Restrictions, p.2] 3741 // A list item that appears in a reduction clause of the innermost 3742 // enclosing worksharing or parallel construct may not be accessed in 3743 // an explicit task. 3744 DVar = Stack->hasInnermostDSA( 3745 FD, 3746 [](OpenMPClauseKind C, bool AppliedToPointee) { 3747 return C == OMPC_reduction && !AppliedToPointee; 3748 }, 3749 [](OpenMPDirectiveKind K) { 3750 return isOpenMPParallelDirective(K) || 3751 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 3752 }, 3753 /*FromParent=*/true); 3754 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 3755 ErrorFound = true; 3756 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 3757 reportOriginalDsa(SemaRef, Stack, FD, DVar); 3758 return; 3759 } 3760 3761 // Define implicit data-sharing attributes for task. 3762 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false); 3763 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 3764 !Stack->isLoopControlVariable(FD).first) { 3765 // Check if there is a captured expression for the current field in the 3766 // region. Do not mark it as firstprivate unless there is no captured 3767 // expression. 3768 // TODO: try to make it firstprivate. 3769 if (DVar.CKind != OMPC_unknown) 3770 ImplicitFirstprivate.push_back(E); 3771 } 3772 return; 3773 } 3774 if (isOpenMPTargetExecutionDirective(DKind)) { 3775 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 3776 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map, 3777 Stack->getCurrentDirective(), 3778 /*NoDiagnose=*/true)) 3779 return; 3780 const auto *VD = cast<ValueDecl>( 3781 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl()); 3782 if (!Stack->checkMappableExprComponentListsForDecl( 3783 VD, /*CurrentRegionOnly=*/true, 3784 [&CurComponents]( 3785 OMPClauseMappableExprCommon::MappableExprComponentListRef 3786 StackComponents, 3787 OpenMPClauseKind) { 3788 auto CCI = CurComponents.rbegin(); 3789 auto CCE = CurComponents.rend(); 3790 for (const auto &SC : llvm::reverse(StackComponents)) { 3791 // Do both expressions have the same kind? 3792 if (CCI->getAssociatedExpression()->getStmtClass() != 3793 SC.getAssociatedExpression()->getStmtClass()) 3794 if (!((isa<OMPArraySectionExpr>( 3795 SC.getAssociatedExpression()) || 3796 isa<OMPArrayShapingExpr>( 3797 SC.getAssociatedExpression())) && 3798 isa<ArraySubscriptExpr>( 3799 CCI->getAssociatedExpression()))) 3800 return false; 3801 3802 const Decl *CCD = CCI->getAssociatedDeclaration(); 3803 const Decl *SCD = SC.getAssociatedDeclaration(); 3804 CCD = CCD ? CCD->getCanonicalDecl() : nullptr; 3805 SCD = SCD ? SCD->getCanonicalDecl() : nullptr; 3806 if (SCD != CCD) 3807 return false; 3808 std::advance(CCI, 1); 3809 if (CCI == CCE) 3810 break; 3811 } 3812 return true; 3813 })) { 3814 Visit(E->getBase()); 3815 } 3816 } else if (!TryCaptureCXXThisMembers) { 3817 Visit(E->getBase()); 3818 } 3819 } 3820 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 3821 for (OMPClause *C : S->clauses()) { 3822 // Skip analysis of arguments of implicitly defined firstprivate clause 3823 // for task|target directives. 3824 // Skip analysis of arguments of implicitly defined map clause for target 3825 // directives. 3826 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) && 3827 C->isImplicit() && 3828 !isOpenMPTaskingDirective(Stack->getCurrentDirective()))) { 3829 for (Stmt *CC : C->children()) { 3830 if (CC) 3831 Visit(CC); 3832 } 3833 } 3834 } 3835 // Check implicitly captured variables. 3836 VisitSubCaptures(S); 3837 } 3838 3839 void VisitOMPLoopTransformationDirective(OMPLoopTransformationDirective *S) { 3840 // Loop transformation directives do not introduce data sharing 3841 VisitStmt(S); 3842 } 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) << IsArrayExpr 5093 << 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>> 5138 DeclToCopy; 5139 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) { 5140 return isOpenMPPrivate(C->getClauseKind()); 5141 }); 5142 for (OMPClause *Cl : PrivateRange) { 5143 MutableArrayRef<Expr *>::iterator I, It, Et; 5144 if (Cl->getClauseKind() == OMPC_private) { 5145 auto *PC = cast<OMPPrivateClause>(Cl); 5146 I = PC->private_copies().begin(); 5147 It = PC->varlist_begin(); 5148 Et = PC->varlist_end(); 5149 } else if (Cl->getClauseKind() == OMPC_firstprivate) { 5150 auto *PC = cast<OMPFirstprivateClause>(Cl); 5151 I = PC->private_copies().begin(); 5152 It = PC->varlist_begin(); 5153 Et = PC->varlist_end(); 5154 } else if (Cl->getClauseKind() == OMPC_lastprivate) { 5155 auto *PC = cast<OMPLastprivateClause>(Cl); 5156 I = PC->private_copies().begin(); 5157 It = PC->varlist_begin(); 5158 Et = PC->varlist_end(); 5159 } else if (Cl->getClauseKind() == OMPC_linear) { 5160 auto *PC = cast<OMPLinearClause>(Cl); 5161 I = PC->privates().begin(); 5162 It = PC->varlist_begin(); 5163 Et = PC->varlist_end(); 5164 } else if (Cl->getClauseKind() == OMPC_reduction) { 5165 auto *PC = cast<OMPReductionClause>(Cl); 5166 I = PC->privates().begin(); 5167 It = PC->varlist_begin(); 5168 Et = PC->varlist_end(); 5169 } else if (Cl->getClauseKind() == OMPC_task_reduction) { 5170 auto *PC = cast<OMPTaskReductionClause>(Cl); 5171 I = PC->privates().begin(); 5172 It = PC->varlist_begin(); 5173 Et = PC->varlist_end(); 5174 } else if (Cl->getClauseKind() == OMPC_in_reduction) { 5175 auto *PC = cast<OMPInReductionClause>(Cl); 5176 I = PC->privates().begin(); 5177 It = PC->varlist_begin(); 5178 Et = PC->varlist_end(); 5179 } else { 5180 llvm_unreachable("Expected private clause."); 5181 } 5182 for (Expr *E : llvm::make_range(It, Et)) { 5183 if (!*I) { 5184 ++I; 5185 continue; 5186 } 5187 SourceLocation ELoc; 5188 SourceRange ERange; 5189 Expr *SimpleRefExpr = E; 5190 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 5191 /*AllowArraySection=*/true); 5192 DeclToCopy.try_emplace(Res.first, 5193 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl())); 5194 ++I; 5195 } 5196 } 5197 for (OMPClause *C : AllocateRange) { 5198 auto *AC = cast<OMPAllocateClause>(C); 5199 if (S.getLangOpts().OpenMP >= 50 && 5200 !Stack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>() && 5201 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 5202 AC->getAllocator()) { 5203 Expr *Allocator = AC->getAllocator(); 5204 // OpenMP, 2.12.5 target Construct 5205 // Memory allocators that do not appear in a uses_allocators clause cannot 5206 // appear as an allocator in an allocate clause or be used in the target 5207 // region unless a requires directive with the dynamic_allocators clause 5208 // is present in the same compilation unit. 5209 AllocatorChecker Checker(Stack); 5210 if (Checker.Visit(Allocator)) 5211 S.Diag(Allocator->getExprLoc(), 5212 diag::err_omp_allocator_not_in_uses_allocators) 5213 << Allocator->getSourceRange(); 5214 } 5215 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind = 5216 getAllocatorKind(S, Stack, AC->getAllocator()); 5217 // OpenMP, 2.11.4 allocate Clause, Restrictions. 5218 // For task, taskloop or target directives, allocation requests to memory 5219 // allocators with the trait access set to thread result in unspecified 5220 // behavior. 5221 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc && 5222 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 5223 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) { 5224 S.Diag(AC->getAllocator()->getExprLoc(), 5225 diag::warn_omp_allocate_thread_on_task_target_directive) 5226 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 5227 } 5228 for (Expr *E : AC->varlists()) { 5229 SourceLocation ELoc; 5230 SourceRange ERange; 5231 Expr *SimpleRefExpr = E; 5232 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange); 5233 ValueDecl *VD = Res.first; 5234 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false); 5235 if (!isOpenMPPrivate(Data.CKind)) { 5236 S.Diag(E->getExprLoc(), 5237 diag::err_omp_expected_private_copy_for_allocate); 5238 continue; 5239 } 5240 VarDecl *PrivateVD = DeclToCopy[VD]; 5241 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD, 5242 AllocatorKind, AC->getAllocator())) 5243 continue; 5244 // Placeholder until allocate clause supports align modifier. 5245 Expr *Alignment = nullptr; 5246 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(), 5247 Alignment, E->getSourceRange()); 5248 } 5249 } 5250 } 5251 5252 namespace { 5253 /// Rewrite statements and expressions for Sema \p Actions CurContext. 5254 /// 5255 /// Used to wrap already parsed statements/expressions into a new CapturedStmt 5256 /// context. DeclRefExpr used inside the new context are changed to refer to the 5257 /// captured variable instead. 5258 class CaptureVars : public TreeTransform<CaptureVars> { 5259 using BaseTransform = TreeTransform<CaptureVars>; 5260 5261 public: 5262 CaptureVars(Sema &Actions) : BaseTransform(Actions) {} 5263 5264 bool AlwaysRebuild() { return true; } 5265 }; 5266 } // namespace 5267 5268 static VarDecl *precomputeExpr(Sema &Actions, 5269 SmallVectorImpl<Stmt *> &BodyStmts, Expr *E, 5270 StringRef Name) { 5271 Expr *NewE = AssertSuccess(CaptureVars(Actions).TransformExpr(E)); 5272 VarDecl *NewVar = buildVarDecl(Actions, {}, NewE->getType(), Name, nullptr, 5273 dyn_cast<DeclRefExpr>(E->IgnoreImplicit())); 5274 auto *NewDeclStmt = cast<DeclStmt>(AssertSuccess( 5275 Actions.ActOnDeclStmt(Actions.ConvertDeclToDeclGroup(NewVar), {}, {}))); 5276 Actions.AddInitializerToDecl(NewDeclStmt->getSingleDecl(), NewE, false); 5277 BodyStmts.push_back(NewDeclStmt); 5278 return NewVar; 5279 } 5280 5281 /// Create a closure that computes the number of iterations of a loop. 5282 /// 5283 /// \param Actions The Sema object. 5284 /// \param LogicalTy Type for the logical iteration number. 5285 /// \param Rel Comparison operator of the loop condition. 5286 /// \param StartExpr Value of the loop counter at the first iteration. 5287 /// \param StopExpr Expression the loop counter is compared against in the loop 5288 /// condition. \param StepExpr Amount of increment after each iteration. 5289 /// 5290 /// \return Closure (CapturedStmt) of the distance calculation. 5291 static CapturedStmt *buildDistanceFunc(Sema &Actions, QualType LogicalTy, 5292 BinaryOperator::Opcode Rel, 5293 Expr *StartExpr, Expr *StopExpr, 5294 Expr *StepExpr) { 5295 ASTContext &Ctx = Actions.getASTContext(); 5296 TypeSourceInfo *LogicalTSI = Ctx.getTrivialTypeSourceInfo(LogicalTy); 5297 5298 // Captured regions currently don't support return values, we use an 5299 // out-parameter instead. All inputs are implicit captures. 5300 // TODO: Instead of capturing each DeclRefExpr occurring in 5301 // StartExpr/StopExpr/Step, these could also be passed as a value capture. 5302 QualType ResultTy = Ctx.getLValueReferenceType(LogicalTy); 5303 Sema::CapturedParamNameType Params[] = {{"Distance", ResultTy}, 5304 {StringRef(), QualType()}}; 5305 Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params); 5306 5307 Stmt *Body; 5308 { 5309 Sema::CompoundScopeRAII CompoundScope(Actions); 5310 CapturedDecl *CS = cast<CapturedDecl>(Actions.CurContext); 5311 5312 // Get the LValue expression for the result. 5313 ImplicitParamDecl *DistParam = CS->getParam(0); 5314 DeclRefExpr *DistRef = Actions.BuildDeclRefExpr( 5315 DistParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr); 5316 5317 SmallVector<Stmt *, 4> BodyStmts; 5318 5319 // Capture all referenced variable references. 5320 // TODO: Instead of computing NewStart/NewStop/NewStep inside the 5321 // CapturedStmt, we could compute them before and capture the result, to be 5322 // used jointly with the LoopVar function. 5323 VarDecl *NewStart = precomputeExpr(Actions, BodyStmts, StartExpr, ".start"); 5324 VarDecl *NewStop = precomputeExpr(Actions, BodyStmts, StopExpr, ".stop"); 5325 VarDecl *NewStep = precomputeExpr(Actions, BodyStmts, StepExpr, ".step"); 5326 auto BuildVarRef = [&](VarDecl *VD) { 5327 return buildDeclRefExpr(Actions, VD, VD->getType(), {}); 5328 }; 5329 5330 IntegerLiteral *Zero = IntegerLiteral::Create( 5331 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 0), LogicalTy, {}); 5332 Expr *Dist; 5333 if (Rel == BO_NE) { 5334 // When using a != comparison, the increment can be +1 or -1. This can be 5335 // dynamic at runtime, so we need to check for the direction. 5336 Expr *IsNegStep = AssertSuccess( 5337 Actions.BuildBinOp(nullptr, {}, BO_LT, BuildVarRef(NewStep), Zero)); 5338 5339 // Positive increment. 5340 Expr *ForwardRange = AssertSuccess(Actions.BuildBinOp( 5341 nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart))); 5342 ForwardRange = AssertSuccess( 5343 Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, ForwardRange)); 5344 Expr *ForwardDist = AssertSuccess(Actions.BuildBinOp( 5345 nullptr, {}, BO_Div, ForwardRange, BuildVarRef(NewStep))); 5346 5347 // Negative increment. 5348 Expr *BackwardRange = AssertSuccess(Actions.BuildBinOp( 5349 nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop))); 5350 BackwardRange = AssertSuccess( 5351 Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, BackwardRange)); 5352 Expr *NegIncAmount = AssertSuccess( 5353 Actions.BuildUnaryOp(nullptr, {}, UO_Minus, BuildVarRef(NewStep))); 5354 Expr *BackwardDist = AssertSuccess( 5355 Actions.BuildBinOp(nullptr, {}, BO_Div, BackwardRange, NegIncAmount)); 5356 5357 // Use the appropriate case. 5358 Dist = AssertSuccess(Actions.ActOnConditionalOp( 5359 {}, {}, IsNegStep, BackwardDist, ForwardDist)); 5360 } else { 5361 assert((Rel == BO_LT || Rel == BO_LE || Rel == BO_GE || Rel == BO_GT) && 5362 "Expected one of these relational operators"); 5363 5364 // We can derive the direction from any other comparison operator. It is 5365 // non well-formed OpenMP if Step increments/decrements in the other 5366 // directions. Whether at least the first iteration passes the loop 5367 // condition. 5368 Expr *HasAnyIteration = AssertSuccess(Actions.BuildBinOp( 5369 nullptr, {}, Rel, BuildVarRef(NewStart), BuildVarRef(NewStop))); 5370 5371 // Compute the range between first and last counter value. 5372 Expr *Range; 5373 if (Rel == BO_GE || Rel == BO_GT) 5374 Range = AssertSuccess(Actions.BuildBinOp( 5375 nullptr, {}, BO_Sub, BuildVarRef(NewStart), BuildVarRef(NewStop))); 5376 else 5377 Range = AssertSuccess(Actions.BuildBinOp( 5378 nullptr, {}, BO_Sub, BuildVarRef(NewStop), BuildVarRef(NewStart))); 5379 5380 // Ensure unsigned range space. 5381 Range = 5382 AssertSuccess(Actions.BuildCStyleCastExpr({}, LogicalTSI, {}, Range)); 5383 5384 if (Rel == BO_LE || Rel == BO_GE) { 5385 // Add one to the range if the relational operator is inclusive. 5386 Range = AssertSuccess(Actions.BuildBinOp( 5387 nullptr, {}, BO_Add, Range, 5388 Actions.ActOnIntegerConstant(SourceLocation(), 1).get())); 5389 } 5390 5391 // Divide by the absolute step amount. 5392 Expr *Divisor = BuildVarRef(NewStep); 5393 if (Rel == BO_GE || Rel == BO_GT) 5394 Divisor = 5395 AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Minus, Divisor)); 5396 Dist = AssertSuccess( 5397 Actions.BuildBinOp(nullptr, {}, BO_Div, Range, Divisor)); 5398 5399 // If there is not at least one iteration, the range contains garbage. Fix 5400 // to zero in this case. 5401 Dist = AssertSuccess( 5402 Actions.ActOnConditionalOp({}, {}, HasAnyIteration, Dist, Zero)); 5403 } 5404 5405 // Assign the result to the out-parameter. 5406 Stmt *ResultAssign = AssertSuccess(Actions.BuildBinOp( 5407 Actions.getCurScope(), {}, BO_Assign, DistRef, Dist)); 5408 BodyStmts.push_back(ResultAssign); 5409 5410 Body = AssertSuccess(Actions.ActOnCompoundStmt({}, {}, BodyStmts, false)); 5411 } 5412 5413 return cast<CapturedStmt>( 5414 AssertSuccess(Actions.ActOnCapturedRegionEnd(Body))); 5415 } 5416 5417 /// Create a closure that computes the loop variable from the logical iteration 5418 /// number. 5419 /// 5420 /// \param Actions The Sema object. 5421 /// \param LoopVarTy Type for the loop variable used for result value. 5422 /// \param LogicalTy Type for the logical iteration number. 5423 /// \param StartExpr Value of the loop counter at the first iteration. 5424 /// \param Step Amount of increment after each iteration. 5425 /// \param Deref Whether the loop variable is a dereference of the loop 5426 /// counter variable. 5427 /// 5428 /// \return Closure (CapturedStmt) of the loop value calculation. 5429 static CapturedStmt *buildLoopVarFunc(Sema &Actions, QualType LoopVarTy, 5430 QualType LogicalTy, 5431 DeclRefExpr *StartExpr, Expr *Step, 5432 bool Deref) { 5433 ASTContext &Ctx = Actions.getASTContext(); 5434 5435 // Pass the result as an out-parameter. Passing as return value would require 5436 // the OpenMPIRBuilder to know additional C/C++ semantics, such as how to 5437 // invoke a copy constructor. 5438 QualType TargetParamTy = Ctx.getLValueReferenceType(LoopVarTy); 5439 Sema::CapturedParamNameType Params[] = {{"LoopVar", TargetParamTy}, 5440 {"Logical", LogicalTy}, 5441 {StringRef(), QualType()}}; 5442 Actions.ActOnCapturedRegionStart({}, nullptr, CR_Default, Params); 5443 5444 // Capture the initial iterator which represents the LoopVar value at the 5445 // zero's logical iteration. Since the original ForStmt/CXXForRangeStmt update 5446 // it in every iteration, capture it by value before it is modified. 5447 VarDecl *StartVar = cast<VarDecl>(StartExpr->getDecl()); 5448 bool Invalid = Actions.tryCaptureVariable(StartVar, {}, 5449 Sema::TryCapture_ExplicitByVal, {}); 5450 (void)Invalid; 5451 assert(!Invalid && "Expecting capture-by-value to work."); 5452 5453 Expr *Body; 5454 { 5455 Sema::CompoundScopeRAII CompoundScope(Actions); 5456 auto *CS = cast<CapturedDecl>(Actions.CurContext); 5457 5458 ImplicitParamDecl *TargetParam = CS->getParam(0); 5459 DeclRefExpr *TargetRef = Actions.BuildDeclRefExpr( 5460 TargetParam, LoopVarTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr); 5461 ImplicitParamDecl *IndvarParam = CS->getParam(1); 5462 DeclRefExpr *LogicalRef = Actions.BuildDeclRefExpr( 5463 IndvarParam, LogicalTy, VK_LValue, {}, nullptr, nullptr, {}, nullptr); 5464 5465 // Capture the Start expression. 5466 CaptureVars Recap(Actions); 5467 Expr *NewStart = AssertSuccess(Recap.TransformExpr(StartExpr)); 5468 Expr *NewStep = AssertSuccess(Recap.TransformExpr(Step)); 5469 5470 Expr *Skip = AssertSuccess( 5471 Actions.BuildBinOp(nullptr, {}, BO_Mul, NewStep, LogicalRef)); 5472 // TODO: Explicitly cast to the iterator's difference_type instead of 5473 // relying on implicit conversion. 5474 Expr *Advanced = 5475 AssertSuccess(Actions.BuildBinOp(nullptr, {}, BO_Add, NewStart, Skip)); 5476 5477 if (Deref) { 5478 // For range-based for-loops convert the loop counter value to a concrete 5479 // loop variable value by dereferencing the iterator. 5480 Advanced = 5481 AssertSuccess(Actions.BuildUnaryOp(nullptr, {}, UO_Deref, Advanced)); 5482 } 5483 5484 // Assign the result to the output parameter. 5485 Body = AssertSuccess(Actions.BuildBinOp(Actions.getCurScope(), {}, 5486 BO_Assign, TargetRef, Advanced)); 5487 } 5488 return cast<CapturedStmt>( 5489 AssertSuccess(Actions.ActOnCapturedRegionEnd(Body))); 5490 } 5491 5492 StmtResult Sema::ActOnOpenMPCanonicalLoop(Stmt *AStmt) { 5493 ASTContext &Ctx = getASTContext(); 5494 5495 // Extract the common elements of ForStmt and CXXForRangeStmt: 5496 // Loop variable, repeat condition, increment 5497 Expr *Cond, *Inc; 5498 VarDecl *LIVDecl, *LUVDecl; 5499 if (auto *For = dyn_cast<ForStmt>(AStmt)) { 5500 Stmt *Init = For->getInit(); 5501 if (auto *LCVarDeclStmt = dyn_cast<DeclStmt>(Init)) { 5502 // For statement declares loop variable. 5503 LIVDecl = cast<VarDecl>(LCVarDeclStmt->getSingleDecl()); 5504 } else if (auto *LCAssign = dyn_cast<BinaryOperator>(Init)) { 5505 // For statement reuses variable. 5506 assert(LCAssign->getOpcode() == BO_Assign && 5507 "init part must be a loop variable assignment"); 5508 auto *CounterRef = cast<DeclRefExpr>(LCAssign->getLHS()); 5509 LIVDecl = cast<VarDecl>(CounterRef->getDecl()); 5510 } else 5511 llvm_unreachable("Cannot determine loop variable"); 5512 LUVDecl = LIVDecl; 5513 5514 Cond = For->getCond(); 5515 Inc = For->getInc(); 5516 } else if (auto *RangeFor = dyn_cast<CXXForRangeStmt>(AStmt)) { 5517 DeclStmt *BeginStmt = RangeFor->getBeginStmt(); 5518 LIVDecl = cast<VarDecl>(BeginStmt->getSingleDecl()); 5519 LUVDecl = RangeFor->getLoopVariable(); 5520 5521 Cond = RangeFor->getCond(); 5522 Inc = RangeFor->getInc(); 5523 } else 5524 llvm_unreachable("unhandled kind of loop"); 5525 5526 QualType CounterTy = LIVDecl->getType(); 5527 QualType LVTy = LUVDecl->getType(); 5528 5529 // Analyze the loop condition. 5530 Expr *LHS, *RHS; 5531 BinaryOperator::Opcode CondRel; 5532 Cond = Cond->IgnoreImplicit(); 5533 if (auto *CondBinExpr = dyn_cast<BinaryOperator>(Cond)) { 5534 LHS = CondBinExpr->getLHS(); 5535 RHS = CondBinExpr->getRHS(); 5536 CondRel = CondBinExpr->getOpcode(); 5537 } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Cond)) { 5538 assert(CondCXXOp->getNumArgs() == 2 && "Comparison should have 2 operands"); 5539 LHS = CondCXXOp->getArg(0); 5540 RHS = CondCXXOp->getArg(1); 5541 switch (CondCXXOp->getOperator()) { 5542 case OO_ExclaimEqual: 5543 CondRel = BO_NE; 5544 break; 5545 case OO_Less: 5546 CondRel = BO_LT; 5547 break; 5548 case OO_LessEqual: 5549 CondRel = BO_LE; 5550 break; 5551 case OO_Greater: 5552 CondRel = BO_GT; 5553 break; 5554 case OO_GreaterEqual: 5555 CondRel = BO_GE; 5556 break; 5557 default: 5558 llvm_unreachable("unexpected iterator operator"); 5559 } 5560 } else 5561 llvm_unreachable("unexpected loop condition"); 5562 5563 // Normalize such that the loop counter is on the LHS. 5564 if (!isa<DeclRefExpr>(LHS->IgnoreImplicit()) || 5565 cast<DeclRefExpr>(LHS->IgnoreImplicit())->getDecl() != LIVDecl) { 5566 std::swap(LHS, RHS); 5567 CondRel = BinaryOperator::reverseComparisonOp(CondRel); 5568 } 5569 auto *CounterRef = cast<DeclRefExpr>(LHS->IgnoreImplicit()); 5570 5571 // Decide the bit width for the logical iteration counter. By default use the 5572 // unsigned ptrdiff_t integer size (for iterators and pointers). 5573 // TODO: For iterators, use iterator::difference_type, 5574 // std::iterator_traits<>::difference_type or decltype(it - end). 5575 QualType LogicalTy = Ctx.getUnsignedPointerDiffType(); 5576 if (CounterTy->isIntegerType()) { 5577 unsigned BitWidth = Ctx.getIntWidth(CounterTy); 5578 LogicalTy = Ctx.getIntTypeForBitwidth(BitWidth, false); 5579 } 5580 5581 // Analyze the loop increment. 5582 Expr *Step; 5583 if (auto *IncUn = dyn_cast<UnaryOperator>(Inc)) { 5584 int Direction; 5585 switch (IncUn->getOpcode()) { 5586 case UO_PreInc: 5587 case UO_PostInc: 5588 Direction = 1; 5589 break; 5590 case UO_PreDec: 5591 case UO_PostDec: 5592 Direction = -1; 5593 break; 5594 default: 5595 llvm_unreachable("unhandled unary increment operator"); 5596 } 5597 Step = IntegerLiteral::Create( 5598 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), Direction), LogicalTy, {}); 5599 } else if (auto *IncBin = dyn_cast<BinaryOperator>(Inc)) { 5600 if (IncBin->getOpcode() == BO_AddAssign) { 5601 Step = IncBin->getRHS(); 5602 } else if (IncBin->getOpcode() == BO_SubAssign) { 5603 Step = 5604 AssertSuccess(BuildUnaryOp(nullptr, {}, UO_Minus, IncBin->getRHS())); 5605 } else 5606 llvm_unreachable("unhandled binary increment operator"); 5607 } else if (auto *CondCXXOp = dyn_cast<CXXOperatorCallExpr>(Inc)) { 5608 switch (CondCXXOp->getOperator()) { 5609 case OO_PlusPlus: 5610 Step = IntegerLiteral::Create( 5611 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), 1), LogicalTy, {}); 5612 break; 5613 case OO_MinusMinus: 5614 Step = IntegerLiteral::Create( 5615 Ctx, llvm::APInt(Ctx.getIntWidth(LogicalTy), -1), LogicalTy, {}); 5616 break; 5617 case OO_PlusEqual: 5618 Step = CondCXXOp->getArg(1); 5619 break; 5620 case OO_MinusEqual: 5621 Step = AssertSuccess( 5622 BuildUnaryOp(nullptr, {}, UO_Minus, CondCXXOp->getArg(1))); 5623 break; 5624 default: 5625 llvm_unreachable("unhandled overloaded increment operator"); 5626 } 5627 } else 5628 llvm_unreachable("unknown increment expression"); 5629 5630 CapturedStmt *DistanceFunc = 5631 buildDistanceFunc(*this, LogicalTy, CondRel, LHS, RHS, Step); 5632 CapturedStmt *LoopVarFunc = buildLoopVarFunc( 5633 *this, LVTy, LogicalTy, CounterRef, Step, isa<CXXForRangeStmt>(AStmt)); 5634 DeclRefExpr *LVRef = BuildDeclRefExpr(LUVDecl, LUVDecl->getType(), VK_LValue, 5635 {}, nullptr, nullptr, {}, nullptr); 5636 return OMPCanonicalLoop::create(getASTContext(), AStmt, DistanceFunc, 5637 LoopVarFunc, LVRef); 5638 } 5639 5640 StmtResult Sema::ActOnOpenMPLoopnest(Stmt *AStmt) { 5641 // Handle a literal loop. 5642 if (isa<ForStmt>(AStmt) || isa<CXXForRangeStmt>(AStmt)) 5643 return ActOnOpenMPCanonicalLoop(AStmt); 5644 5645 // If not a literal loop, it must be the result of a loop transformation. 5646 OMPExecutableDirective *LoopTransform = cast<OMPExecutableDirective>(AStmt); 5647 assert( 5648 isOpenMPLoopTransformationDirective(LoopTransform->getDirectiveKind()) && 5649 "Loop transformation directive expected"); 5650 return LoopTransform; 5651 } 5652 5653 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S, 5654 CXXScopeSpec &MapperIdScopeSpec, 5655 const DeclarationNameInfo &MapperId, 5656 QualType Type, 5657 Expr *UnresolvedMapper); 5658 5659 /// Perform DFS through the structure/class data members trying to find 5660 /// member(s) with user-defined 'default' mapper and generate implicit map 5661 /// clauses for such members with the found 'default' mapper. 5662 static void 5663 processImplicitMapsWithDefaultMappers(Sema &S, DSAStackTy *Stack, 5664 SmallVectorImpl<OMPClause *> &Clauses) { 5665 // Check for the deault mapper for data members. 5666 if (S.getLangOpts().OpenMP < 50) 5667 return; 5668 SmallVector<OMPClause *, 4> ImplicitMaps; 5669 for (int Cnt = 0, EndCnt = Clauses.size(); Cnt < EndCnt; ++Cnt) { 5670 auto *C = dyn_cast<OMPMapClause>(Clauses[Cnt]); 5671 if (!C) 5672 continue; 5673 SmallVector<Expr *, 4> SubExprs; 5674 auto *MI = C->mapperlist_begin(); 5675 for (auto I = C->varlist_begin(), End = C->varlist_end(); I != End; 5676 ++I, ++MI) { 5677 // Expression is mapped using mapper - skip it. 5678 if (*MI) 5679 continue; 5680 Expr *E = *I; 5681 // Expression is dependent - skip it, build the mapper when it gets 5682 // instantiated. 5683 if (E->isTypeDependent() || E->isValueDependent() || 5684 E->containsUnexpandedParameterPack()) 5685 continue; 5686 // Array section - need to check for the mapping of the array section 5687 // element. 5688 QualType CanonType = E->getType().getCanonicalType(); 5689 if (CanonType->isSpecificBuiltinType(BuiltinType::OMPArraySection)) { 5690 const auto *OASE = cast<OMPArraySectionExpr>(E->IgnoreParenImpCasts()); 5691 QualType BaseType = 5692 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 5693 QualType ElemType; 5694 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 5695 ElemType = ATy->getElementType(); 5696 else 5697 ElemType = BaseType->getPointeeType(); 5698 CanonType = ElemType; 5699 } 5700 5701 // DFS over data members in structures/classes. 5702 SmallVector<std::pair<QualType, FieldDecl *>, 4> Types( 5703 1, {CanonType, nullptr}); 5704 llvm::DenseMap<const Type *, Expr *> Visited; 5705 SmallVector<std::pair<FieldDecl *, unsigned>, 4> ParentChain( 5706 1, {nullptr, 1}); 5707 while (!Types.empty()) { 5708 QualType BaseType; 5709 FieldDecl *CurFD; 5710 std::tie(BaseType, CurFD) = Types.pop_back_val(); 5711 while (ParentChain.back().second == 0) 5712 ParentChain.pop_back(); 5713 --ParentChain.back().second; 5714 if (BaseType.isNull()) 5715 continue; 5716 // Only structs/classes are allowed to have mappers. 5717 const RecordDecl *RD = BaseType.getCanonicalType()->getAsRecordDecl(); 5718 if (!RD) 5719 continue; 5720 auto It = Visited.find(BaseType.getTypePtr()); 5721 if (It == Visited.end()) { 5722 // Try to find the associated user-defined mapper. 5723 CXXScopeSpec MapperIdScopeSpec; 5724 DeclarationNameInfo DefaultMapperId; 5725 DefaultMapperId.setName(S.Context.DeclarationNames.getIdentifier( 5726 &S.Context.Idents.get("default"))); 5727 DefaultMapperId.setLoc(E->getExprLoc()); 5728 ExprResult ER = buildUserDefinedMapperRef( 5729 S, Stack->getCurScope(), MapperIdScopeSpec, DefaultMapperId, 5730 BaseType, /*UnresolvedMapper=*/nullptr); 5731 if (ER.isInvalid()) 5732 continue; 5733 It = Visited.try_emplace(BaseType.getTypePtr(), ER.get()).first; 5734 } 5735 // Found default mapper. 5736 if (It->second) { 5737 auto *OE = new (S.Context) OpaqueValueExpr(E->getExprLoc(), CanonType, 5738 VK_LValue, OK_Ordinary, E); 5739 OE->setIsUnique(/*V=*/true); 5740 Expr *BaseExpr = OE; 5741 for (const auto &P : ParentChain) { 5742 if (P.first) { 5743 BaseExpr = S.BuildMemberExpr( 5744 BaseExpr, /*IsArrow=*/false, E->getExprLoc(), 5745 NestedNameSpecifierLoc(), SourceLocation(), P.first, 5746 DeclAccessPair::make(P.first, P.first->getAccess()), 5747 /*HadMultipleCandidates=*/false, DeclarationNameInfo(), 5748 P.first->getType(), VK_LValue, OK_Ordinary); 5749 BaseExpr = S.DefaultLvalueConversion(BaseExpr).get(); 5750 } 5751 } 5752 if (CurFD) 5753 BaseExpr = S.BuildMemberExpr( 5754 BaseExpr, /*IsArrow=*/false, E->getExprLoc(), 5755 NestedNameSpecifierLoc(), SourceLocation(), CurFD, 5756 DeclAccessPair::make(CurFD, CurFD->getAccess()), 5757 /*HadMultipleCandidates=*/false, DeclarationNameInfo(), 5758 CurFD->getType(), VK_LValue, OK_Ordinary); 5759 SubExprs.push_back(BaseExpr); 5760 continue; 5761 } 5762 // Check for the "default" mapper for data members. 5763 bool FirstIter = true; 5764 for (FieldDecl *FD : RD->fields()) { 5765 if (!FD) 5766 continue; 5767 QualType FieldTy = FD->getType(); 5768 if (FieldTy.isNull() || 5769 !(FieldTy->isStructureOrClassType() || FieldTy->isUnionType())) 5770 continue; 5771 if (FirstIter) { 5772 FirstIter = false; 5773 ParentChain.emplace_back(CurFD, 1); 5774 } else { 5775 ++ParentChain.back().second; 5776 } 5777 Types.emplace_back(FieldTy, FD); 5778 } 5779 } 5780 } 5781 if (SubExprs.empty()) 5782 continue; 5783 CXXScopeSpec MapperIdScopeSpec; 5784 DeclarationNameInfo MapperId; 5785 if (OMPClause *NewClause = S.ActOnOpenMPMapClause( 5786 C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(), 5787 MapperIdScopeSpec, MapperId, C->getMapType(), 5788 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(), 5789 SubExprs, OMPVarListLocTy())) 5790 Clauses.push_back(NewClause); 5791 } 5792 } 5793 5794 StmtResult Sema::ActOnOpenMPExecutableDirective( 5795 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 5796 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 5797 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 5798 StmtResult Res = StmtError(); 5799 OpenMPBindClauseKind BindKind = OMPC_BIND_unknown; 5800 if (const OMPBindClause *BC = 5801 OMPExecutableDirective::getSingleClause<OMPBindClause>(Clauses)) 5802 BindKind = BC->getBindKind(); 5803 // First check CancelRegion which is then used in checkNestingOfRegions. 5804 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 5805 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 5806 BindKind, StartLoc)) 5807 return StmtError(); 5808 5809 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 5810 VarsWithInheritedDSAType VarsWithInheritedDSA; 5811 bool ErrorFound = false; 5812 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 5813 if (AStmt && !CurContext->isDependentContext() && Kind != OMPD_atomic && 5814 Kind != OMPD_critical && Kind != OMPD_section && Kind != OMPD_master && 5815 Kind != OMPD_masked && !isOpenMPLoopTransformationDirective(Kind)) { 5816 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5817 5818 // Check default data sharing attributes for referenced variables. 5819 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 5820 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 5821 Stmt *S = AStmt; 5822 while (--ThisCaptureLevel >= 0) 5823 S = cast<CapturedStmt>(S)->getCapturedStmt(); 5824 DSAChecker.Visit(S); 5825 if (!isOpenMPTargetDataManagementDirective(Kind) && 5826 !isOpenMPTaskingDirective(Kind)) { 5827 // Visit subcaptures to generate implicit clauses for captured vars. 5828 auto *CS = cast<CapturedStmt>(AStmt); 5829 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 5830 getOpenMPCaptureRegions(CaptureRegions, Kind); 5831 // Ignore outer tasking regions for target directives. 5832 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task) 5833 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 5834 DSAChecker.visitSubCaptures(CS); 5835 } 5836 if (DSAChecker.isErrorFound()) 5837 return StmtError(); 5838 // Generate list of implicitly defined firstprivate variables. 5839 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 5840 5841 SmallVector<Expr *, 4> ImplicitFirstprivates( 5842 DSAChecker.getImplicitFirstprivate().begin(), 5843 DSAChecker.getImplicitFirstprivate().end()); 5844 const unsigned DefaultmapKindNum = OMPC_DEFAULTMAP_pointer + 1; 5845 SmallVector<Expr *, 4> ImplicitMaps[DefaultmapKindNum][OMPC_MAP_delete]; 5846 SmallVector<OpenMPMapModifierKind, NumberOfOMPMapClauseModifiers> 5847 ImplicitMapModifiers[DefaultmapKindNum]; 5848 SmallVector<SourceLocation, NumberOfOMPMapClauseModifiers> 5849 ImplicitMapModifiersLoc[DefaultmapKindNum]; 5850 // Get the original location of present modifier from Defaultmap clause. 5851 SourceLocation PresentModifierLocs[DefaultmapKindNum]; 5852 for (OMPClause *C : Clauses) { 5853 if (auto *DMC = dyn_cast<OMPDefaultmapClause>(C)) 5854 if (DMC->getDefaultmapModifier() == OMPC_DEFAULTMAP_MODIFIER_present) 5855 PresentModifierLocs[DMC->getDefaultmapKind()] = 5856 DMC->getDefaultmapModifierLoc(); 5857 } 5858 for (unsigned VC = 0; VC < DefaultmapKindNum; ++VC) { 5859 auto Kind = static_cast<OpenMPDefaultmapClauseKind>(VC); 5860 for (unsigned I = 0; I < OMPC_MAP_delete; ++I) { 5861 ArrayRef<Expr *> ImplicitMap = DSAChecker.getImplicitMap( 5862 Kind, static_cast<OpenMPMapClauseKind>(I)); 5863 ImplicitMaps[VC][I].append(ImplicitMap.begin(), ImplicitMap.end()); 5864 } 5865 ArrayRef<OpenMPMapModifierKind> ImplicitModifier = 5866 DSAChecker.getImplicitMapModifier(Kind); 5867 ImplicitMapModifiers[VC].append(ImplicitModifier.begin(), 5868 ImplicitModifier.end()); 5869 std::fill_n(std::back_inserter(ImplicitMapModifiersLoc[VC]), 5870 ImplicitModifier.size(), PresentModifierLocs[VC]); 5871 } 5872 // Mark taskgroup task_reduction descriptors as implicitly firstprivate. 5873 for (OMPClause *C : Clauses) { 5874 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) { 5875 for (Expr *E : IRC->taskgroup_descriptors()) 5876 if (E) 5877 ImplicitFirstprivates.emplace_back(E); 5878 } 5879 // OpenMP 5.0, 2.10.1 task Construct 5880 // [detach clause]... The event-handle will be considered as if it was 5881 // specified on a firstprivate clause. 5882 if (auto *DC = dyn_cast<OMPDetachClause>(C)) 5883 ImplicitFirstprivates.push_back(DC->getEventHandler()); 5884 } 5885 if (!ImplicitFirstprivates.empty()) { 5886 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 5887 ImplicitFirstprivates, SourceLocation(), SourceLocation(), 5888 SourceLocation())) { 5889 ClausesWithImplicit.push_back(Implicit); 5890 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 5891 ImplicitFirstprivates.size(); 5892 } else { 5893 ErrorFound = true; 5894 } 5895 } 5896 // OpenMP 5.0 [2.19.7] 5897 // If a list item appears in a reduction, lastprivate or linear 5898 // clause on a combined target construct then it is treated as 5899 // if it also appears in a map clause with a map-type of tofrom 5900 if (getLangOpts().OpenMP >= 50 && Kind != OMPD_target && 5901 isOpenMPTargetExecutionDirective(Kind)) { 5902 SmallVector<Expr *, 4> ImplicitExprs; 5903 for (OMPClause *C : Clauses) { 5904 if (auto *RC = dyn_cast<OMPReductionClause>(C)) 5905 for (Expr *E : RC->varlists()) 5906 if (!isa<DeclRefExpr>(E->IgnoreParenImpCasts())) 5907 ImplicitExprs.emplace_back(E); 5908 } 5909 if (!ImplicitExprs.empty()) { 5910 ArrayRef<Expr *> Exprs = ImplicitExprs; 5911 CXXScopeSpec MapperIdScopeSpec; 5912 DeclarationNameInfo MapperId; 5913 if (OMPClause *Implicit = ActOnOpenMPMapClause( 5914 OMPC_MAP_MODIFIER_unknown, SourceLocation(), MapperIdScopeSpec, 5915 MapperId, OMPC_MAP_tofrom, 5916 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(), 5917 Exprs, OMPVarListLocTy(), /*NoDiagnose=*/true)) 5918 ClausesWithImplicit.emplace_back(Implicit); 5919 } 5920 } 5921 for (unsigned I = 0, E = DefaultmapKindNum; I < E; ++I) { 5922 int ClauseKindCnt = -1; 5923 for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps[I]) { 5924 ++ClauseKindCnt; 5925 if (ImplicitMap.empty()) 5926 continue; 5927 CXXScopeSpec MapperIdScopeSpec; 5928 DeclarationNameInfo MapperId; 5929 auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt); 5930 if (OMPClause *Implicit = ActOnOpenMPMapClause( 5931 ImplicitMapModifiers[I], ImplicitMapModifiersLoc[I], 5932 MapperIdScopeSpec, MapperId, Kind, /*IsMapTypeImplicit=*/true, 5933 SourceLocation(), SourceLocation(), ImplicitMap, 5934 OMPVarListLocTy())) { 5935 ClausesWithImplicit.emplace_back(Implicit); 5936 ErrorFound |= cast<OMPMapClause>(Implicit)->varlist_size() != 5937 ImplicitMap.size(); 5938 } else { 5939 ErrorFound = true; 5940 } 5941 } 5942 } 5943 // Build expressions for implicit maps of data members with 'default' 5944 // mappers. 5945 if (LangOpts.OpenMP >= 50) 5946 processImplicitMapsWithDefaultMappers(*this, DSAStack, 5947 ClausesWithImplicit); 5948 } 5949 5950 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 5951 switch (Kind) { 5952 case OMPD_parallel: 5953 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 5954 EndLoc); 5955 AllowedNameModifiers.push_back(OMPD_parallel); 5956 break; 5957 case OMPD_simd: 5958 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 5959 VarsWithInheritedDSA); 5960 if (LangOpts.OpenMP >= 50) 5961 AllowedNameModifiers.push_back(OMPD_simd); 5962 break; 5963 case OMPD_tile: 5964 Res = 5965 ActOnOpenMPTileDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 5966 break; 5967 case OMPD_unroll: 5968 Res = ActOnOpenMPUnrollDirective(ClausesWithImplicit, AStmt, StartLoc, 5969 EndLoc); 5970 break; 5971 case OMPD_for: 5972 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 5973 VarsWithInheritedDSA); 5974 break; 5975 case OMPD_for_simd: 5976 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 5977 EndLoc, VarsWithInheritedDSA); 5978 if (LangOpts.OpenMP >= 50) 5979 AllowedNameModifiers.push_back(OMPD_simd); 5980 break; 5981 case OMPD_sections: 5982 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 5983 EndLoc); 5984 break; 5985 case OMPD_section: 5986 assert(ClausesWithImplicit.empty() && 5987 "No clauses are allowed for 'omp section' directive"); 5988 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 5989 break; 5990 case OMPD_single: 5991 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 5992 EndLoc); 5993 break; 5994 case OMPD_master: 5995 assert(ClausesWithImplicit.empty() && 5996 "No clauses are allowed for 'omp master' directive"); 5997 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 5998 break; 5999 case OMPD_masked: 6000 Res = ActOnOpenMPMaskedDirective(ClausesWithImplicit, AStmt, StartLoc, 6001 EndLoc); 6002 break; 6003 case OMPD_critical: 6004 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 6005 StartLoc, EndLoc); 6006 break; 6007 case OMPD_parallel_for: 6008 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 6009 EndLoc, VarsWithInheritedDSA); 6010 AllowedNameModifiers.push_back(OMPD_parallel); 6011 break; 6012 case OMPD_parallel_for_simd: 6013 Res = ActOnOpenMPParallelForSimdDirective( 6014 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6015 AllowedNameModifiers.push_back(OMPD_parallel); 6016 if (LangOpts.OpenMP >= 50) 6017 AllowedNameModifiers.push_back(OMPD_simd); 6018 break; 6019 case OMPD_parallel_master: 6020 Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt, 6021 StartLoc, EndLoc); 6022 AllowedNameModifiers.push_back(OMPD_parallel); 6023 break; 6024 case OMPD_parallel_sections: 6025 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 6026 StartLoc, EndLoc); 6027 AllowedNameModifiers.push_back(OMPD_parallel); 6028 break; 6029 case OMPD_task: 6030 Res = 6031 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 6032 AllowedNameModifiers.push_back(OMPD_task); 6033 break; 6034 case OMPD_taskyield: 6035 assert(ClausesWithImplicit.empty() && 6036 "No clauses are allowed for 'omp taskyield' directive"); 6037 assert(AStmt == nullptr && 6038 "No associated statement allowed for 'omp taskyield' directive"); 6039 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 6040 break; 6041 case OMPD_barrier: 6042 assert(ClausesWithImplicit.empty() && 6043 "No clauses are allowed for 'omp barrier' directive"); 6044 assert(AStmt == nullptr && 6045 "No associated statement allowed for 'omp barrier' directive"); 6046 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 6047 break; 6048 case OMPD_taskwait: 6049 assert(AStmt == nullptr && 6050 "No associated statement allowed for 'omp taskwait' directive"); 6051 Res = ActOnOpenMPTaskwaitDirective(ClausesWithImplicit, StartLoc, EndLoc); 6052 break; 6053 case OMPD_taskgroup: 6054 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, 6055 EndLoc); 6056 break; 6057 case OMPD_flush: 6058 assert(AStmt == nullptr && 6059 "No associated statement allowed for 'omp flush' directive"); 6060 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 6061 break; 6062 case OMPD_depobj: 6063 assert(AStmt == nullptr && 6064 "No associated statement allowed for 'omp depobj' directive"); 6065 Res = ActOnOpenMPDepobjDirective(ClausesWithImplicit, StartLoc, EndLoc); 6066 break; 6067 case OMPD_scan: 6068 assert(AStmt == nullptr && 6069 "No associated statement allowed for 'omp scan' directive"); 6070 Res = ActOnOpenMPScanDirective(ClausesWithImplicit, StartLoc, EndLoc); 6071 break; 6072 case OMPD_ordered: 6073 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 6074 EndLoc); 6075 break; 6076 case OMPD_atomic: 6077 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 6078 EndLoc); 6079 break; 6080 case OMPD_teams: 6081 Res = 6082 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 6083 break; 6084 case OMPD_target: 6085 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 6086 EndLoc); 6087 AllowedNameModifiers.push_back(OMPD_target); 6088 break; 6089 case OMPD_target_parallel: 6090 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 6091 StartLoc, EndLoc); 6092 AllowedNameModifiers.push_back(OMPD_target); 6093 AllowedNameModifiers.push_back(OMPD_parallel); 6094 break; 6095 case OMPD_target_parallel_for: 6096 Res = ActOnOpenMPTargetParallelForDirective( 6097 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6098 AllowedNameModifiers.push_back(OMPD_target); 6099 AllowedNameModifiers.push_back(OMPD_parallel); 6100 break; 6101 case OMPD_cancellation_point: 6102 assert(ClausesWithImplicit.empty() && 6103 "No clauses are allowed for 'omp cancellation point' directive"); 6104 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 6105 "cancellation point' directive"); 6106 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 6107 break; 6108 case OMPD_cancel: 6109 assert(AStmt == nullptr && 6110 "No associated statement allowed for 'omp cancel' directive"); 6111 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 6112 CancelRegion); 6113 AllowedNameModifiers.push_back(OMPD_cancel); 6114 break; 6115 case OMPD_target_data: 6116 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 6117 EndLoc); 6118 AllowedNameModifiers.push_back(OMPD_target_data); 6119 break; 6120 case OMPD_target_enter_data: 6121 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 6122 EndLoc, AStmt); 6123 AllowedNameModifiers.push_back(OMPD_target_enter_data); 6124 break; 6125 case OMPD_target_exit_data: 6126 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 6127 EndLoc, AStmt); 6128 AllowedNameModifiers.push_back(OMPD_target_exit_data); 6129 break; 6130 case OMPD_taskloop: 6131 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 6132 EndLoc, VarsWithInheritedDSA); 6133 AllowedNameModifiers.push_back(OMPD_taskloop); 6134 break; 6135 case OMPD_taskloop_simd: 6136 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 6137 EndLoc, VarsWithInheritedDSA); 6138 AllowedNameModifiers.push_back(OMPD_taskloop); 6139 if (LangOpts.OpenMP >= 50) 6140 AllowedNameModifiers.push_back(OMPD_simd); 6141 break; 6142 case OMPD_master_taskloop: 6143 Res = ActOnOpenMPMasterTaskLoopDirective( 6144 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6145 AllowedNameModifiers.push_back(OMPD_taskloop); 6146 break; 6147 case OMPD_master_taskloop_simd: 6148 Res = ActOnOpenMPMasterTaskLoopSimdDirective( 6149 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6150 AllowedNameModifiers.push_back(OMPD_taskloop); 6151 if (LangOpts.OpenMP >= 50) 6152 AllowedNameModifiers.push_back(OMPD_simd); 6153 break; 6154 case OMPD_parallel_master_taskloop: 6155 Res = ActOnOpenMPParallelMasterTaskLoopDirective( 6156 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6157 AllowedNameModifiers.push_back(OMPD_taskloop); 6158 AllowedNameModifiers.push_back(OMPD_parallel); 6159 break; 6160 case OMPD_parallel_master_taskloop_simd: 6161 Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective( 6162 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6163 AllowedNameModifiers.push_back(OMPD_taskloop); 6164 AllowedNameModifiers.push_back(OMPD_parallel); 6165 if (LangOpts.OpenMP >= 50) 6166 AllowedNameModifiers.push_back(OMPD_simd); 6167 break; 6168 case OMPD_distribute: 6169 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 6170 EndLoc, VarsWithInheritedDSA); 6171 break; 6172 case OMPD_target_update: 6173 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, 6174 EndLoc, AStmt); 6175 AllowedNameModifiers.push_back(OMPD_target_update); 6176 break; 6177 case OMPD_distribute_parallel_for: 6178 Res = ActOnOpenMPDistributeParallelForDirective( 6179 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6180 AllowedNameModifiers.push_back(OMPD_parallel); 6181 break; 6182 case OMPD_distribute_parallel_for_simd: 6183 Res = ActOnOpenMPDistributeParallelForSimdDirective( 6184 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6185 AllowedNameModifiers.push_back(OMPD_parallel); 6186 if (LangOpts.OpenMP >= 50) 6187 AllowedNameModifiers.push_back(OMPD_simd); 6188 break; 6189 case OMPD_distribute_simd: 6190 Res = ActOnOpenMPDistributeSimdDirective( 6191 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6192 if (LangOpts.OpenMP >= 50) 6193 AllowedNameModifiers.push_back(OMPD_simd); 6194 break; 6195 case OMPD_target_parallel_for_simd: 6196 Res = ActOnOpenMPTargetParallelForSimdDirective( 6197 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6198 AllowedNameModifiers.push_back(OMPD_target); 6199 AllowedNameModifiers.push_back(OMPD_parallel); 6200 if (LangOpts.OpenMP >= 50) 6201 AllowedNameModifiers.push_back(OMPD_simd); 6202 break; 6203 case OMPD_target_simd: 6204 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 6205 EndLoc, VarsWithInheritedDSA); 6206 AllowedNameModifiers.push_back(OMPD_target); 6207 if (LangOpts.OpenMP >= 50) 6208 AllowedNameModifiers.push_back(OMPD_simd); 6209 break; 6210 case OMPD_teams_distribute: 6211 Res = ActOnOpenMPTeamsDistributeDirective( 6212 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6213 break; 6214 case OMPD_teams_distribute_simd: 6215 Res = ActOnOpenMPTeamsDistributeSimdDirective( 6216 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6217 if (LangOpts.OpenMP >= 50) 6218 AllowedNameModifiers.push_back(OMPD_simd); 6219 break; 6220 case OMPD_teams_distribute_parallel_for_simd: 6221 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 6222 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6223 AllowedNameModifiers.push_back(OMPD_parallel); 6224 if (LangOpts.OpenMP >= 50) 6225 AllowedNameModifiers.push_back(OMPD_simd); 6226 break; 6227 case OMPD_teams_distribute_parallel_for: 6228 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 6229 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6230 AllowedNameModifiers.push_back(OMPD_parallel); 6231 break; 6232 case OMPD_target_teams: 6233 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 6234 EndLoc); 6235 AllowedNameModifiers.push_back(OMPD_target); 6236 break; 6237 case OMPD_target_teams_distribute: 6238 Res = ActOnOpenMPTargetTeamsDistributeDirective( 6239 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6240 AllowedNameModifiers.push_back(OMPD_target); 6241 break; 6242 case OMPD_target_teams_distribute_parallel_for: 6243 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 6244 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6245 AllowedNameModifiers.push_back(OMPD_target); 6246 AllowedNameModifiers.push_back(OMPD_parallel); 6247 break; 6248 case OMPD_target_teams_distribute_parallel_for_simd: 6249 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 6250 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6251 AllowedNameModifiers.push_back(OMPD_target); 6252 AllowedNameModifiers.push_back(OMPD_parallel); 6253 if (LangOpts.OpenMP >= 50) 6254 AllowedNameModifiers.push_back(OMPD_simd); 6255 break; 6256 case OMPD_target_teams_distribute_simd: 6257 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 6258 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 6259 AllowedNameModifiers.push_back(OMPD_target); 6260 if (LangOpts.OpenMP >= 50) 6261 AllowedNameModifiers.push_back(OMPD_simd); 6262 break; 6263 case OMPD_interop: 6264 assert(AStmt == nullptr && 6265 "No associated statement allowed for 'omp interop' directive"); 6266 Res = ActOnOpenMPInteropDirective(ClausesWithImplicit, StartLoc, EndLoc); 6267 break; 6268 case OMPD_dispatch: 6269 Res = ActOnOpenMPDispatchDirective(ClausesWithImplicit, AStmt, StartLoc, 6270 EndLoc); 6271 break; 6272 case OMPD_loop: 6273 Res = ActOnOpenMPGenericLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 6274 EndLoc, VarsWithInheritedDSA); 6275 break; 6276 case OMPD_declare_target: 6277 case OMPD_end_declare_target: 6278 case OMPD_threadprivate: 6279 case OMPD_allocate: 6280 case OMPD_declare_reduction: 6281 case OMPD_declare_mapper: 6282 case OMPD_declare_simd: 6283 case OMPD_requires: 6284 case OMPD_declare_variant: 6285 case OMPD_begin_declare_variant: 6286 case OMPD_end_declare_variant: 6287 llvm_unreachable("OpenMP Directive is not allowed"); 6288 case OMPD_unknown: 6289 default: 6290 llvm_unreachable("Unknown OpenMP directive"); 6291 } 6292 6293 ErrorFound = Res.isInvalid() || ErrorFound; 6294 6295 // Check variables in the clauses if default(none) or 6296 // default(firstprivate) was specified. 6297 if (DSAStack->getDefaultDSA() == DSA_none || 6298 DSAStack->getDefaultDSA() == DSA_firstprivate) { 6299 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr); 6300 for (OMPClause *C : Clauses) { 6301 switch (C->getClauseKind()) { 6302 case OMPC_num_threads: 6303 case OMPC_dist_schedule: 6304 // Do not analyse if no parent teams directive. 6305 if (isOpenMPTeamsDirective(Kind)) 6306 break; 6307 continue; 6308 case OMPC_if: 6309 if (isOpenMPTeamsDirective(Kind) && 6310 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target) 6311 break; 6312 if (isOpenMPParallelDirective(Kind) && 6313 isOpenMPTaskLoopDirective(Kind) && 6314 cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel) 6315 break; 6316 continue; 6317 case OMPC_schedule: 6318 case OMPC_detach: 6319 break; 6320 case OMPC_grainsize: 6321 case OMPC_num_tasks: 6322 case OMPC_final: 6323 case OMPC_priority: 6324 case OMPC_novariants: 6325 case OMPC_nocontext: 6326 // Do not analyze if no parent parallel directive. 6327 if (isOpenMPParallelDirective(Kind)) 6328 break; 6329 continue; 6330 case OMPC_ordered: 6331 case OMPC_device: 6332 case OMPC_num_teams: 6333 case OMPC_thread_limit: 6334 case OMPC_hint: 6335 case OMPC_collapse: 6336 case OMPC_safelen: 6337 case OMPC_simdlen: 6338 case OMPC_sizes: 6339 case OMPC_default: 6340 case OMPC_proc_bind: 6341 case OMPC_private: 6342 case OMPC_firstprivate: 6343 case OMPC_lastprivate: 6344 case OMPC_shared: 6345 case OMPC_reduction: 6346 case OMPC_task_reduction: 6347 case OMPC_in_reduction: 6348 case OMPC_linear: 6349 case OMPC_aligned: 6350 case OMPC_copyin: 6351 case OMPC_copyprivate: 6352 case OMPC_nowait: 6353 case OMPC_untied: 6354 case OMPC_mergeable: 6355 case OMPC_allocate: 6356 case OMPC_read: 6357 case OMPC_write: 6358 case OMPC_update: 6359 case OMPC_capture: 6360 case OMPC_seq_cst: 6361 case OMPC_acq_rel: 6362 case OMPC_acquire: 6363 case OMPC_release: 6364 case OMPC_relaxed: 6365 case OMPC_depend: 6366 case OMPC_threads: 6367 case OMPC_simd: 6368 case OMPC_map: 6369 case OMPC_nogroup: 6370 case OMPC_defaultmap: 6371 case OMPC_to: 6372 case OMPC_from: 6373 case OMPC_use_device_ptr: 6374 case OMPC_use_device_addr: 6375 case OMPC_is_device_ptr: 6376 case OMPC_nontemporal: 6377 case OMPC_order: 6378 case OMPC_destroy: 6379 case OMPC_inclusive: 6380 case OMPC_exclusive: 6381 case OMPC_uses_allocators: 6382 case OMPC_affinity: 6383 case OMPC_bind: 6384 continue; 6385 case OMPC_allocator: 6386 case OMPC_flush: 6387 case OMPC_depobj: 6388 case OMPC_threadprivate: 6389 case OMPC_uniform: 6390 case OMPC_unknown: 6391 case OMPC_unified_address: 6392 case OMPC_unified_shared_memory: 6393 case OMPC_reverse_offload: 6394 case OMPC_dynamic_allocators: 6395 case OMPC_atomic_default_mem_order: 6396 case OMPC_device_type: 6397 case OMPC_match: 6398 case OMPC_when: 6399 default: 6400 llvm_unreachable("Unexpected clause"); 6401 } 6402 for (Stmt *CC : C->children()) { 6403 if (CC) 6404 DSAChecker.Visit(CC); 6405 } 6406 } 6407 for (const auto &P : DSAChecker.getVarsWithInheritedDSA()) 6408 VarsWithInheritedDSA[P.getFirst()] = P.getSecond(); 6409 } 6410 for (const auto &P : VarsWithInheritedDSA) { 6411 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst())) 6412 continue; 6413 ErrorFound = true; 6414 if (DSAStack->getDefaultDSA() == DSA_none || 6415 DSAStack->getDefaultDSA() == DSA_firstprivate) { 6416 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 6417 << P.first << P.second->getSourceRange(); 6418 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none); 6419 } else if (getLangOpts().OpenMP >= 50) { 6420 Diag(P.second->getExprLoc(), 6421 diag::err_omp_defaultmap_no_attr_for_variable) 6422 << P.first << P.second->getSourceRange(); 6423 Diag(DSAStack->getDefaultDSALocation(), 6424 diag::note_omp_defaultmap_attr_none); 6425 } 6426 } 6427 6428 if (!AllowedNameModifiers.empty()) 6429 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 6430 ErrorFound; 6431 6432 if (ErrorFound) 6433 return StmtError(); 6434 6435 if (!CurContext->isDependentContext() && 6436 isOpenMPTargetExecutionDirective(Kind) && 6437 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() || 6438 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() || 6439 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() || 6440 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) { 6441 // Register target to DSA Stack. 6442 DSAStack->addTargetDirLocation(StartLoc); 6443 } 6444 6445 return Res; 6446 } 6447 6448 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 6449 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 6450 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 6451 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 6452 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 6453 assert(Aligneds.size() == Alignments.size()); 6454 assert(Linears.size() == LinModifiers.size()); 6455 assert(Linears.size() == Steps.size()); 6456 if (!DG || DG.get().isNull()) 6457 return DeclGroupPtrTy(); 6458 6459 const int SimdId = 0; 6460 if (!DG.get().isSingleDecl()) { 6461 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant) 6462 << SimdId; 6463 return DG; 6464 } 6465 Decl *ADecl = DG.get().getSingleDecl(); 6466 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 6467 ADecl = FTD->getTemplatedDecl(); 6468 6469 auto *FD = dyn_cast<FunctionDecl>(ADecl); 6470 if (!FD) { 6471 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId; 6472 return DeclGroupPtrTy(); 6473 } 6474 6475 // OpenMP [2.8.2, declare simd construct, Description] 6476 // The parameter of the simdlen clause must be a constant positive integer 6477 // expression. 6478 ExprResult SL; 6479 if (Simdlen) 6480 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 6481 // OpenMP [2.8.2, declare simd construct, Description] 6482 // The special this pointer can be used as if was one of the arguments to the 6483 // function in any of the linear, aligned, or uniform clauses. 6484 // The uniform clause declares one or more arguments to have an invariant 6485 // value for all concurrent invocations of the function in the execution of a 6486 // single SIMD loop. 6487 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs; 6488 const Expr *UniformedLinearThis = nullptr; 6489 for (const Expr *E : Uniforms) { 6490 E = E->IgnoreParenImpCasts(); 6491 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 6492 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 6493 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 6494 FD->getParamDecl(PVD->getFunctionScopeIndex()) 6495 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 6496 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E); 6497 continue; 6498 } 6499 if (isa<CXXThisExpr>(E)) { 6500 UniformedLinearThis = E; 6501 continue; 6502 } 6503 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 6504 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 6505 } 6506 // OpenMP [2.8.2, declare simd construct, Description] 6507 // The aligned clause declares that the object to which each list item points 6508 // is aligned to the number of bytes expressed in the optional parameter of 6509 // the aligned clause. 6510 // The special this pointer can be used as if was one of the arguments to the 6511 // function in any of the linear, aligned, or uniform clauses. 6512 // The type of list items appearing in the aligned clause must be array, 6513 // pointer, reference to array, or reference to pointer. 6514 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs; 6515 const Expr *AlignedThis = nullptr; 6516 for (const Expr *E : Aligneds) { 6517 E = E->IgnoreParenImpCasts(); 6518 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 6519 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 6520 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 6521 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 6522 FD->getParamDecl(PVD->getFunctionScopeIndex()) 6523 ->getCanonicalDecl() == CanonPVD) { 6524 // OpenMP [2.8.1, simd construct, Restrictions] 6525 // A list-item cannot appear in more than one aligned clause. 6526 if (AlignedArgs.count(CanonPVD) > 0) { 6527 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice) 6528 << 1 << getOpenMPClauseName(OMPC_aligned) 6529 << E->getSourceRange(); 6530 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 6531 diag::note_omp_explicit_dsa) 6532 << getOpenMPClauseName(OMPC_aligned); 6533 continue; 6534 } 6535 AlignedArgs[CanonPVD] = E; 6536 QualType QTy = PVD->getType() 6537 .getNonReferenceType() 6538 .getUnqualifiedType() 6539 .getCanonicalType(); 6540 const Type *Ty = QTy.getTypePtrOrNull(); 6541 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 6542 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 6543 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 6544 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 6545 } 6546 continue; 6547 } 6548 } 6549 if (isa<CXXThisExpr>(E)) { 6550 if (AlignedThis) { 6551 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice) 6552 << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange(); 6553 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 6554 << getOpenMPClauseName(OMPC_aligned); 6555 } 6556 AlignedThis = E; 6557 continue; 6558 } 6559 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 6560 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 6561 } 6562 // The optional parameter of the aligned clause, alignment, must be a constant 6563 // positive integer expression. If no optional parameter is specified, 6564 // implementation-defined default alignments for SIMD instructions on the 6565 // target platforms are assumed. 6566 SmallVector<const Expr *, 4> NewAligns; 6567 for (Expr *E : Alignments) { 6568 ExprResult Align; 6569 if (E) 6570 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 6571 NewAligns.push_back(Align.get()); 6572 } 6573 // OpenMP [2.8.2, declare simd construct, Description] 6574 // The linear clause declares one or more list items to be private to a SIMD 6575 // lane and to have a linear relationship with respect to the iteration space 6576 // of a loop. 6577 // The special this pointer can be used as if was one of the arguments to the 6578 // function in any of the linear, aligned, or uniform clauses. 6579 // When a linear-step expression is specified in a linear clause it must be 6580 // either a constant integer expression or an integer-typed parameter that is 6581 // specified in a uniform clause on the directive. 6582 llvm::DenseMap<const Decl *, const Expr *> LinearArgs; 6583 const bool IsUniformedThis = UniformedLinearThis != nullptr; 6584 auto MI = LinModifiers.begin(); 6585 for (const Expr *E : Linears) { 6586 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 6587 ++MI; 6588 E = E->IgnoreParenImpCasts(); 6589 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 6590 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 6591 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 6592 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 6593 FD->getParamDecl(PVD->getFunctionScopeIndex()) 6594 ->getCanonicalDecl() == CanonPVD) { 6595 // OpenMP [2.15.3.7, linear Clause, Restrictions] 6596 // A list-item cannot appear in more than one linear clause. 6597 if (LinearArgs.count(CanonPVD) > 0) { 6598 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 6599 << getOpenMPClauseName(OMPC_linear) 6600 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 6601 Diag(LinearArgs[CanonPVD]->getExprLoc(), 6602 diag::note_omp_explicit_dsa) 6603 << getOpenMPClauseName(OMPC_linear); 6604 continue; 6605 } 6606 // Each argument can appear in at most one uniform or linear clause. 6607 if (UniformedArgs.count(CanonPVD) > 0) { 6608 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 6609 << getOpenMPClauseName(OMPC_linear) 6610 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 6611 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 6612 diag::note_omp_explicit_dsa) 6613 << getOpenMPClauseName(OMPC_uniform); 6614 continue; 6615 } 6616 LinearArgs[CanonPVD] = E; 6617 if (E->isValueDependent() || E->isTypeDependent() || 6618 E->isInstantiationDependent() || 6619 E->containsUnexpandedParameterPack()) 6620 continue; 6621 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 6622 PVD->getOriginalType(), 6623 /*IsDeclareSimd=*/true); 6624 continue; 6625 } 6626 } 6627 if (isa<CXXThisExpr>(E)) { 6628 if (UniformedLinearThis) { 6629 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 6630 << getOpenMPClauseName(OMPC_linear) 6631 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 6632 << E->getSourceRange(); 6633 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 6634 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 6635 : OMPC_linear); 6636 continue; 6637 } 6638 UniformedLinearThis = E; 6639 if (E->isValueDependent() || E->isTypeDependent() || 6640 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 6641 continue; 6642 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 6643 E->getType(), /*IsDeclareSimd=*/true); 6644 continue; 6645 } 6646 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 6647 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 6648 } 6649 Expr *Step = nullptr; 6650 Expr *NewStep = nullptr; 6651 SmallVector<Expr *, 4> NewSteps; 6652 for (Expr *E : Steps) { 6653 // Skip the same step expression, it was checked already. 6654 if (Step == E || !E) { 6655 NewSteps.push_back(E ? NewStep : nullptr); 6656 continue; 6657 } 6658 Step = E; 6659 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step)) 6660 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 6661 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 6662 if (UniformedArgs.count(CanonPVD) == 0) { 6663 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 6664 << Step->getSourceRange(); 6665 } else if (E->isValueDependent() || E->isTypeDependent() || 6666 E->isInstantiationDependent() || 6667 E->containsUnexpandedParameterPack() || 6668 CanonPVD->getType()->hasIntegerRepresentation()) { 6669 NewSteps.push_back(Step); 6670 } else { 6671 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 6672 << Step->getSourceRange(); 6673 } 6674 continue; 6675 } 6676 NewStep = Step; 6677 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 6678 !Step->isInstantiationDependent() && 6679 !Step->containsUnexpandedParameterPack()) { 6680 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 6681 .get(); 6682 if (NewStep) 6683 NewStep = 6684 VerifyIntegerConstantExpression(NewStep, /*FIXME*/ AllowFold).get(); 6685 } 6686 NewSteps.push_back(NewStep); 6687 } 6688 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 6689 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 6690 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 6691 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 6692 const_cast<Expr **>(Linears.data()), Linears.size(), 6693 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 6694 NewSteps.data(), NewSteps.size(), SR); 6695 ADecl->addAttr(NewAttr); 6696 return DG; 6697 } 6698 6699 static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto, 6700 QualType NewType) { 6701 assert(NewType->isFunctionProtoType() && 6702 "Expected function type with prototype."); 6703 assert(FD->getType()->isFunctionNoProtoType() && 6704 "Expected function with type with no prototype."); 6705 assert(FDWithProto->getType()->isFunctionProtoType() && 6706 "Expected function with prototype."); 6707 // Synthesize parameters with the same types. 6708 FD->setType(NewType); 6709 SmallVector<ParmVarDecl *, 16> Params; 6710 for (const ParmVarDecl *P : FDWithProto->parameters()) { 6711 auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(), 6712 SourceLocation(), nullptr, P->getType(), 6713 /*TInfo=*/nullptr, SC_None, nullptr); 6714 Param->setScopeInfo(0, Params.size()); 6715 Param->setImplicit(); 6716 Params.push_back(Param); 6717 } 6718 6719 FD->setParams(Params); 6720 } 6721 6722 void Sema::ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D) { 6723 if (D->isInvalidDecl()) 6724 return; 6725 FunctionDecl *FD = nullptr; 6726 if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D)) 6727 FD = UTemplDecl->getTemplatedDecl(); 6728 else 6729 FD = cast<FunctionDecl>(D); 6730 assert(FD && "Expected a function declaration!"); 6731 6732 // If we are instantiating templates we do *not* apply scoped assumptions but 6733 // only global ones. We apply scoped assumption to the template definition 6734 // though. 6735 if (!inTemplateInstantiation()) { 6736 for (AssumptionAttr *AA : OMPAssumeScoped) 6737 FD->addAttr(AA); 6738 } 6739 for (AssumptionAttr *AA : OMPAssumeGlobal) 6740 FD->addAttr(AA); 6741 } 6742 6743 Sema::OMPDeclareVariantScope::OMPDeclareVariantScope(OMPTraitInfo &TI) 6744 : TI(&TI), NameSuffix(TI.getMangledName()) {} 6745 6746 void Sema::ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope( 6747 Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, 6748 SmallVectorImpl<FunctionDecl *> &Bases) { 6749 if (!D.getIdentifier()) 6750 return; 6751 6752 OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back(); 6753 6754 // Template specialization is an extension, check if we do it. 6755 bool IsTemplated = !TemplateParamLists.empty(); 6756 if (IsTemplated & 6757 !DVScope.TI->isExtensionActive( 6758 llvm::omp::TraitProperty::implementation_extension_allow_templates)) 6759 return; 6760 6761 IdentifierInfo *BaseII = D.getIdentifier(); 6762 LookupResult Lookup(*this, DeclarationName(BaseII), D.getIdentifierLoc(), 6763 LookupOrdinaryName); 6764 LookupParsedName(Lookup, S, &D.getCXXScopeSpec()); 6765 6766 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 6767 QualType FType = TInfo->getType(); 6768 6769 bool IsConstexpr = 6770 D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr; 6771 bool IsConsteval = 6772 D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Consteval; 6773 6774 for (auto *Candidate : Lookup) { 6775 auto *CandidateDecl = Candidate->getUnderlyingDecl(); 6776 FunctionDecl *UDecl = nullptr; 6777 if (IsTemplated && isa<FunctionTemplateDecl>(CandidateDecl)) { 6778 auto *FTD = cast<FunctionTemplateDecl>(CandidateDecl); 6779 if (FTD->getTemplateParameters()->size() == TemplateParamLists.size()) 6780 UDecl = FTD->getTemplatedDecl(); 6781 } else if (!IsTemplated) 6782 UDecl = dyn_cast<FunctionDecl>(CandidateDecl); 6783 if (!UDecl) 6784 continue; 6785 6786 // Don't specialize constexpr/consteval functions with 6787 // non-constexpr/consteval functions. 6788 if (UDecl->isConstexpr() && !IsConstexpr) 6789 continue; 6790 if (UDecl->isConsteval() && !IsConsteval) 6791 continue; 6792 6793 QualType UDeclTy = UDecl->getType(); 6794 if (!UDeclTy->isDependentType()) { 6795 QualType NewType = Context.mergeFunctionTypes( 6796 FType, UDeclTy, /* OfBlockPointer */ false, 6797 /* Unqualified */ false, /* AllowCXX */ true); 6798 if (NewType.isNull()) 6799 continue; 6800 } 6801 6802 // Found a base! 6803 Bases.push_back(UDecl); 6804 } 6805 6806 bool UseImplicitBase = !DVScope.TI->isExtensionActive( 6807 llvm::omp::TraitProperty::implementation_extension_disable_implicit_base); 6808 // If no base was found we create a declaration that we use as base. 6809 if (Bases.empty() && UseImplicitBase) { 6810 D.setFunctionDefinitionKind(FunctionDefinitionKind::Declaration); 6811 Decl *BaseD = HandleDeclarator(S, D, TemplateParamLists); 6812 BaseD->setImplicit(true); 6813 if (auto *BaseTemplD = dyn_cast<FunctionTemplateDecl>(BaseD)) 6814 Bases.push_back(BaseTemplD->getTemplatedDecl()); 6815 else 6816 Bases.push_back(cast<FunctionDecl>(BaseD)); 6817 } 6818 6819 std::string MangledName; 6820 MangledName += D.getIdentifier()->getName(); 6821 MangledName += getOpenMPVariantManglingSeparatorStr(); 6822 MangledName += DVScope.NameSuffix; 6823 IdentifierInfo &VariantII = Context.Idents.get(MangledName); 6824 6825 VariantII.setMangledOpenMPVariantName(true); 6826 D.SetIdentifier(&VariantII, D.getBeginLoc()); 6827 } 6828 6829 void Sema::ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope( 6830 Decl *D, SmallVectorImpl<FunctionDecl *> &Bases) { 6831 // Do not mark function as is used to prevent its emission if this is the 6832 // only place where it is used. 6833 EnterExpressionEvaluationContext Unevaluated( 6834 *this, Sema::ExpressionEvaluationContext::Unevaluated); 6835 6836 FunctionDecl *FD = nullptr; 6837 if (auto *UTemplDecl = dyn_cast<FunctionTemplateDecl>(D)) 6838 FD = UTemplDecl->getTemplatedDecl(); 6839 else 6840 FD = cast<FunctionDecl>(D); 6841 auto *VariantFuncRef = DeclRefExpr::Create( 6842 Context, NestedNameSpecifierLoc(), SourceLocation(), FD, 6843 /* RefersToEnclosingVariableOrCapture */ false, 6844 /* NameLoc */ FD->getLocation(), FD->getType(), 6845 ExprValueKind::VK_PRValue); 6846 6847 OMPDeclareVariantScope &DVScope = OMPDeclareVariantScopes.back(); 6848 auto *OMPDeclareVariantA = OMPDeclareVariantAttr::CreateImplicit( 6849 Context, VariantFuncRef, DVScope.TI, 6850 /*NothingArgs=*/nullptr, /*NothingArgsSize=*/0, 6851 /*NeedDevicePtrArgs=*/nullptr, /*NeedDevicePtrArgsSize=*/0, 6852 /*AppendArgs=*/nullptr, /*AppendArgsSize=*/0); 6853 for (FunctionDecl *BaseFD : Bases) 6854 BaseFD->addAttr(OMPDeclareVariantA); 6855 } 6856 6857 ExprResult Sema::ActOnOpenMPCall(ExprResult Call, Scope *Scope, 6858 SourceLocation LParenLoc, 6859 MultiExprArg ArgExprs, 6860 SourceLocation RParenLoc, Expr *ExecConfig) { 6861 // The common case is a regular call we do not want to specialize at all. Try 6862 // to make that case fast by bailing early. 6863 CallExpr *CE = dyn_cast<CallExpr>(Call.get()); 6864 if (!CE) 6865 return Call; 6866 6867 FunctionDecl *CalleeFnDecl = CE->getDirectCallee(); 6868 if (!CalleeFnDecl) 6869 return Call; 6870 6871 if (!CalleeFnDecl->hasAttr<OMPDeclareVariantAttr>()) 6872 return Call; 6873 6874 ASTContext &Context = getASTContext(); 6875 std::function<void(StringRef)> DiagUnknownTrait = [this, 6876 CE](StringRef ISATrait) { 6877 // TODO Track the selector locations in a way that is accessible here to 6878 // improve the diagnostic location. 6879 Diag(CE->getBeginLoc(), diag::warn_unknown_declare_variant_isa_trait) 6880 << ISATrait; 6881 }; 6882 TargetOMPContext OMPCtx(Context, std::move(DiagUnknownTrait), 6883 getCurFunctionDecl(), DSAStack->getConstructTraits()); 6884 6885 QualType CalleeFnType = CalleeFnDecl->getType(); 6886 6887 SmallVector<Expr *, 4> Exprs; 6888 SmallVector<VariantMatchInfo, 4> VMIs; 6889 while (CalleeFnDecl) { 6890 for (OMPDeclareVariantAttr *A : 6891 CalleeFnDecl->specific_attrs<OMPDeclareVariantAttr>()) { 6892 Expr *VariantRef = A->getVariantFuncRef(); 6893 6894 VariantMatchInfo VMI; 6895 OMPTraitInfo &TI = A->getTraitInfo(); 6896 TI.getAsVariantMatchInfo(Context, VMI); 6897 if (!isVariantApplicableInContext(VMI, OMPCtx, 6898 /* DeviceSetOnly */ false)) 6899 continue; 6900 6901 VMIs.push_back(VMI); 6902 Exprs.push_back(VariantRef); 6903 } 6904 6905 CalleeFnDecl = CalleeFnDecl->getPreviousDecl(); 6906 } 6907 6908 ExprResult NewCall; 6909 do { 6910 int BestIdx = getBestVariantMatchForContext(VMIs, OMPCtx); 6911 if (BestIdx < 0) 6912 return Call; 6913 Expr *BestExpr = cast<DeclRefExpr>(Exprs[BestIdx]); 6914 Decl *BestDecl = cast<DeclRefExpr>(BestExpr)->getDecl(); 6915 6916 { 6917 // Try to build a (member) call expression for the current best applicable 6918 // variant expression. We allow this to fail in which case we continue 6919 // with the next best variant expression. The fail case is part of the 6920 // implementation defined behavior in the OpenMP standard when it talks 6921 // about what differences in the function prototypes: "Any differences 6922 // that the specific OpenMP context requires in the prototype of the 6923 // variant from the base function prototype are implementation defined." 6924 // This wording is there to allow the specialized variant to have a 6925 // different type than the base function. This is intended and OK but if 6926 // we cannot create a call the difference is not in the "implementation 6927 // defined range" we allow. 6928 Sema::TentativeAnalysisScope Trap(*this); 6929 6930 if (auto *SpecializedMethod = dyn_cast<CXXMethodDecl>(BestDecl)) { 6931 auto *MemberCall = dyn_cast<CXXMemberCallExpr>(CE); 6932 BestExpr = MemberExpr::CreateImplicit( 6933 Context, MemberCall->getImplicitObjectArgument(), 6934 /* IsArrow */ false, SpecializedMethod, Context.BoundMemberTy, 6935 MemberCall->getValueKind(), MemberCall->getObjectKind()); 6936 } 6937 NewCall = BuildCallExpr(Scope, BestExpr, LParenLoc, ArgExprs, RParenLoc, 6938 ExecConfig); 6939 if (NewCall.isUsable()) { 6940 if (CallExpr *NCE = dyn_cast<CallExpr>(NewCall.get())) { 6941 FunctionDecl *NewCalleeFnDecl = NCE->getDirectCallee(); 6942 QualType NewType = Context.mergeFunctionTypes( 6943 CalleeFnType, NewCalleeFnDecl->getType(), 6944 /* OfBlockPointer */ false, 6945 /* Unqualified */ false, /* AllowCXX */ true); 6946 if (!NewType.isNull()) 6947 break; 6948 // Don't use the call if the function type was not compatible. 6949 NewCall = nullptr; 6950 } 6951 } 6952 } 6953 6954 VMIs.erase(VMIs.begin() + BestIdx); 6955 Exprs.erase(Exprs.begin() + BestIdx); 6956 } while (!VMIs.empty()); 6957 6958 if (!NewCall.isUsable()) 6959 return Call; 6960 return PseudoObjectExpr::Create(Context, CE, {NewCall.get()}, 0); 6961 } 6962 6963 Optional<std::pair<FunctionDecl *, Expr *>> 6964 Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG, 6965 Expr *VariantRef, OMPTraitInfo &TI, 6966 unsigned NumAppendArgs, 6967 SourceRange SR) { 6968 if (!DG || DG.get().isNull()) 6969 return None; 6970 6971 const int VariantId = 1; 6972 // Must be applied only to single decl. 6973 if (!DG.get().isSingleDecl()) { 6974 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant) 6975 << VariantId << SR; 6976 return None; 6977 } 6978 Decl *ADecl = DG.get().getSingleDecl(); 6979 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 6980 ADecl = FTD->getTemplatedDecl(); 6981 6982 // Decl must be a function. 6983 auto *FD = dyn_cast<FunctionDecl>(ADecl); 6984 if (!FD) { 6985 Diag(ADecl->getLocation(), diag::err_omp_function_expected) 6986 << VariantId << SR; 6987 return None; 6988 } 6989 6990 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) { 6991 return FD->hasAttrs() && 6992 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() || 6993 FD->hasAttr<TargetAttr>()); 6994 }; 6995 // OpenMP is not compatible with CPU-specific attributes. 6996 if (HasMultiVersionAttributes(FD)) { 6997 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes) 6998 << SR; 6999 return None; 7000 } 7001 7002 // Allow #pragma omp declare variant only if the function is not used. 7003 if (FD->isUsed(false)) 7004 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used) 7005 << FD->getLocation(); 7006 7007 // Check if the function was emitted already. 7008 const FunctionDecl *Definition; 7009 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) && 7010 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition))) 7011 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted) 7012 << FD->getLocation(); 7013 7014 // The VariantRef must point to function. 7015 if (!VariantRef) { 7016 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId; 7017 return None; 7018 } 7019 7020 auto ShouldDelayChecks = [](Expr *&E, bool) { 7021 return E && (E->isTypeDependent() || E->isValueDependent() || 7022 E->containsUnexpandedParameterPack() || 7023 E->isInstantiationDependent()); 7024 }; 7025 // Do not check templates, wait until instantiation. 7026 if (FD->isDependentContext() || ShouldDelayChecks(VariantRef, false) || 7027 TI.anyScoreOrCondition(ShouldDelayChecks)) 7028 return std::make_pair(FD, VariantRef); 7029 7030 // Deal with non-constant score and user condition expressions. 7031 auto HandleNonConstantScoresAndConditions = [this](Expr *&E, 7032 bool IsScore) -> bool { 7033 if (!E || E->isIntegerConstantExpr(Context)) 7034 return false; 7035 7036 if (IsScore) { 7037 // We warn on non-constant scores and pretend they were not present. 7038 Diag(E->getExprLoc(), diag::warn_omp_declare_variant_score_not_constant) 7039 << E; 7040 E = nullptr; 7041 } else { 7042 // We could replace a non-constant user condition with "false" but we 7043 // will soon need to handle these anyway for the dynamic version of 7044 // OpenMP context selectors. 7045 Diag(E->getExprLoc(), 7046 diag::err_omp_declare_variant_user_condition_not_constant) 7047 << E; 7048 } 7049 return true; 7050 }; 7051 if (TI.anyScoreOrCondition(HandleNonConstantScoresAndConditions)) 7052 return None; 7053 7054 QualType AdjustedFnType = FD->getType(); 7055 if (NumAppendArgs) { 7056 if (isa<FunctionNoProtoType>(FD->getType())) { 7057 Diag(FD->getLocation(), diag::err_omp_declare_variant_prototype_required) 7058 << SR; 7059 return None; 7060 } 7061 // Adjust the function type to account for an extra omp_interop_t for each 7062 // specified in the append_args clause. 7063 const TypeDecl *TD = nullptr; 7064 LookupResult Result(*this, &Context.Idents.get("omp_interop_t"), 7065 SR.getBegin(), Sema::LookupOrdinaryName); 7066 if (LookupName(Result, getCurScope())) { 7067 NamedDecl *ND = Result.getFoundDecl(); 7068 TD = dyn_cast_or_null<TypeDecl>(ND); 7069 } 7070 if (!TD) { 7071 Diag(SR.getBegin(), diag::err_omp_interop_type_not_found) << SR; 7072 return None; 7073 } 7074 QualType InteropType = QualType(TD->getTypeForDecl(), 0); 7075 auto *PTy = cast<FunctionProtoType>(FD->getType()); 7076 if (PTy->isVariadic()) { 7077 Diag(FD->getLocation(), diag::err_omp_append_args_with_varargs) << SR; 7078 return None; 7079 } 7080 llvm::SmallVector<QualType, 8> Params; 7081 Params.append(PTy->param_type_begin(), PTy->param_type_end()); 7082 Params.insert(Params.end(), NumAppendArgs, InteropType); 7083 AdjustedFnType = Context.getFunctionType(PTy->getReturnType(), Params, 7084 PTy->getExtProtoInfo()); 7085 } 7086 7087 // Convert VariantRef expression to the type of the original function to 7088 // resolve possible conflicts. 7089 ExprResult VariantRefCast = VariantRef; 7090 if (LangOpts.CPlusPlus) { 7091 QualType FnPtrType; 7092 auto *Method = dyn_cast<CXXMethodDecl>(FD); 7093 if (Method && !Method->isStatic()) { 7094 const Type *ClassType = 7095 Context.getTypeDeclType(Method->getParent()).getTypePtr(); 7096 FnPtrType = Context.getMemberPointerType(AdjustedFnType, ClassType); 7097 ExprResult ER; 7098 { 7099 // Build adrr_of unary op to correctly handle type checks for member 7100 // functions. 7101 Sema::TentativeAnalysisScope Trap(*this); 7102 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf, 7103 VariantRef); 7104 } 7105 if (!ER.isUsable()) { 7106 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7107 << VariantId << VariantRef->getSourceRange(); 7108 return None; 7109 } 7110 VariantRef = ER.get(); 7111 } else { 7112 FnPtrType = Context.getPointerType(AdjustedFnType); 7113 } 7114 QualType VarianPtrType = Context.getPointerType(VariantRef->getType()); 7115 if (VarianPtrType.getUnqualifiedType() != FnPtrType.getUnqualifiedType()) { 7116 ImplicitConversionSequence ICS = TryImplicitConversion( 7117 VariantRef, FnPtrType.getUnqualifiedType(), 7118 /*SuppressUserConversions=*/false, AllowedExplicit::None, 7119 /*InOverloadResolution=*/false, 7120 /*CStyle=*/false, 7121 /*AllowObjCWritebackConversion=*/false); 7122 if (ICS.isFailure()) { 7123 Diag(VariantRef->getExprLoc(), 7124 diag::err_omp_declare_variant_incompat_types) 7125 << VariantRef->getType() 7126 << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType()) 7127 << (NumAppendArgs ? 1 : 0) << VariantRef->getSourceRange(); 7128 return None; 7129 } 7130 VariantRefCast = PerformImplicitConversion( 7131 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting); 7132 if (!VariantRefCast.isUsable()) 7133 return None; 7134 } 7135 // Drop previously built artificial addr_of unary op for member functions. 7136 if (Method && !Method->isStatic()) { 7137 Expr *PossibleAddrOfVariantRef = VariantRefCast.get(); 7138 if (auto *UO = dyn_cast<UnaryOperator>( 7139 PossibleAddrOfVariantRef->IgnoreImplicit())) 7140 VariantRefCast = UO->getSubExpr(); 7141 } 7142 } 7143 7144 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get()); 7145 if (!ER.isUsable() || 7146 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) { 7147 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7148 << VariantId << VariantRef->getSourceRange(); 7149 return None; 7150 } 7151 7152 // The VariantRef must point to function. 7153 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts()); 7154 if (!DRE) { 7155 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7156 << VariantId << VariantRef->getSourceRange(); 7157 return None; 7158 } 7159 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl()); 7160 if (!NewFD) { 7161 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected) 7162 << VariantId << VariantRef->getSourceRange(); 7163 return None; 7164 } 7165 7166 // Check if function types are compatible in C. 7167 if (!LangOpts.CPlusPlus) { 7168 QualType NewType = 7169 Context.mergeFunctionTypes(AdjustedFnType, NewFD->getType()); 7170 if (NewType.isNull()) { 7171 Diag(VariantRef->getExprLoc(), 7172 diag::err_omp_declare_variant_incompat_types) 7173 << NewFD->getType() << FD->getType() << (NumAppendArgs ? 1 : 0) 7174 << VariantRef->getSourceRange(); 7175 return None; 7176 } 7177 if (NewType->isFunctionProtoType()) { 7178 if (FD->getType()->isFunctionNoProtoType()) 7179 setPrototype(*this, FD, NewFD, NewType); 7180 else if (NewFD->getType()->isFunctionNoProtoType()) 7181 setPrototype(*this, NewFD, FD, NewType); 7182 } 7183 } 7184 7185 // Check if variant function is not marked with declare variant directive. 7186 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) { 7187 Diag(VariantRef->getExprLoc(), 7188 diag::warn_omp_declare_variant_marked_as_declare_variant) 7189 << VariantRef->getSourceRange(); 7190 SourceRange SR = 7191 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange(); 7192 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR; 7193 return None; 7194 } 7195 7196 enum DoesntSupport { 7197 VirtFuncs = 1, 7198 Constructors = 3, 7199 Destructors = 4, 7200 DeletedFuncs = 5, 7201 DefaultedFuncs = 6, 7202 ConstexprFuncs = 7, 7203 ConstevalFuncs = 8, 7204 }; 7205 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) { 7206 if (CXXFD->isVirtual()) { 7207 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7208 << VirtFuncs; 7209 return None; 7210 } 7211 7212 if (isa<CXXConstructorDecl>(FD)) { 7213 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7214 << Constructors; 7215 return None; 7216 } 7217 7218 if (isa<CXXDestructorDecl>(FD)) { 7219 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7220 << Destructors; 7221 return None; 7222 } 7223 } 7224 7225 if (FD->isDeleted()) { 7226 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7227 << DeletedFuncs; 7228 return None; 7229 } 7230 7231 if (FD->isDefaulted()) { 7232 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7233 << DefaultedFuncs; 7234 return None; 7235 } 7236 7237 if (FD->isConstexpr()) { 7238 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support) 7239 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs); 7240 return None; 7241 } 7242 7243 // Check general compatibility. 7244 if (areMultiversionVariantFunctionsCompatible( 7245 FD, NewFD, PartialDiagnostic::NullDiagnostic(), 7246 PartialDiagnosticAt(SourceLocation(), 7247 PartialDiagnostic::NullDiagnostic()), 7248 PartialDiagnosticAt( 7249 VariantRef->getExprLoc(), 7250 PDiag(diag::err_omp_declare_variant_doesnt_support)), 7251 PartialDiagnosticAt(VariantRef->getExprLoc(), 7252 PDiag(diag::err_omp_declare_variant_diff) 7253 << FD->getLocation()), 7254 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false, 7255 /*CLinkageMayDiffer=*/true)) 7256 return None; 7257 return std::make_pair(FD, cast<Expr>(DRE)); 7258 } 7259 7260 void Sema::ActOnOpenMPDeclareVariantDirective( 7261 FunctionDecl *FD, Expr *VariantRef, OMPTraitInfo &TI, 7262 ArrayRef<Expr *> AdjustArgsNothing, 7263 ArrayRef<Expr *> AdjustArgsNeedDevicePtr, 7264 ArrayRef<OMPDeclareVariantAttr::InteropType> AppendArgs, 7265 SourceLocation AdjustArgsLoc, SourceLocation AppendArgsLoc, 7266 SourceRange SR) { 7267 7268 // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions] 7269 // An adjust_args clause or append_args clause can only be specified if the 7270 // dispatch selector of the construct selector set appears in the match 7271 // clause. 7272 7273 SmallVector<Expr *, 8> AllAdjustArgs; 7274 llvm::append_range(AllAdjustArgs, AdjustArgsNothing); 7275 llvm::append_range(AllAdjustArgs, AdjustArgsNeedDevicePtr); 7276 7277 if (!AllAdjustArgs.empty() || !AppendArgs.empty()) { 7278 VariantMatchInfo VMI; 7279 TI.getAsVariantMatchInfo(Context, VMI); 7280 if (!llvm::is_contained( 7281 VMI.ConstructTraits, 7282 llvm::omp::TraitProperty::construct_dispatch_dispatch)) { 7283 if (!AllAdjustArgs.empty()) 7284 Diag(AdjustArgsLoc, diag::err_omp_clause_requires_dispatch_construct) 7285 << getOpenMPClauseName(OMPC_adjust_args); 7286 if (!AppendArgs.empty()) 7287 Diag(AppendArgsLoc, diag::err_omp_clause_requires_dispatch_construct) 7288 << getOpenMPClauseName(OMPC_append_args); 7289 return; 7290 } 7291 } 7292 7293 // OpenMP 5.1 [2.3.5, declare variant directive, Restrictions] 7294 // Each argument can only appear in a single adjust_args clause for each 7295 // declare variant directive. 7296 llvm::SmallPtrSet<const VarDecl *, 4> AdjustVars; 7297 7298 for (Expr *E : AllAdjustArgs) { 7299 E = E->IgnoreParenImpCasts(); 7300 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) { 7301 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 7302 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 7303 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 7304 FD->getParamDecl(PVD->getFunctionScopeIndex()) 7305 ->getCanonicalDecl() == CanonPVD) { 7306 // It's a parameter of the function, check duplicates. 7307 if (!AdjustVars.insert(CanonPVD).second) { 7308 Diag(DRE->getLocation(), diag::err_omp_adjust_arg_multiple_clauses) 7309 << PVD; 7310 return; 7311 } 7312 continue; 7313 } 7314 } 7315 } 7316 // Anything that is not a function parameter is an error. 7317 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) << FD << 0; 7318 return; 7319 } 7320 7321 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit( 7322 Context, VariantRef, &TI, const_cast<Expr **>(AdjustArgsNothing.data()), 7323 AdjustArgsNothing.size(), 7324 const_cast<Expr **>(AdjustArgsNeedDevicePtr.data()), 7325 AdjustArgsNeedDevicePtr.size(), 7326 const_cast<OMPDeclareVariantAttr::InteropType *>(AppendArgs.data()), 7327 AppendArgs.size(), SR); 7328 FD->addAttr(NewAttr); 7329 } 7330 7331 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 7332 Stmt *AStmt, 7333 SourceLocation StartLoc, 7334 SourceLocation EndLoc) { 7335 if (!AStmt) 7336 return StmtError(); 7337 7338 auto *CS = cast<CapturedStmt>(AStmt); 7339 // 1.2.2 OpenMP Language Terminology 7340 // Structured block - An executable statement with a single entry at the 7341 // top and a single exit at the bottom. 7342 // The point of exit cannot be a branch out of the structured block. 7343 // longjmp() and throw() must not violate the entry/exit criteria. 7344 CS->getCapturedDecl()->setNothrow(); 7345 7346 setFunctionHasBranchProtectedScope(); 7347 7348 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 7349 DSAStack->getTaskgroupReductionRef(), 7350 DSAStack->isCancelRegion()); 7351 } 7352 7353 namespace { 7354 /// Iteration space of a single for loop. 7355 struct LoopIterationSpace final { 7356 /// True if the condition operator is the strict compare operator (<, > or 7357 /// !=). 7358 bool IsStrictCompare = false; 7359 /// Condition of the loop. 7360 Expr *PreCond = nullptr; 7361 /// This expression calculates the number of iterations in the loop. 7362 /// It is always possible to calculate it before starting the loop. 7363 Expr *NumIterations = nullptr; 7364 /// The loop counter variable. 7365 Expr *CounterVar = nullptr; 7366 /// Private loop counter variable. 7367 Expr *PrivateCounterVar = nullptr; 7368 /// This is initializer for the initial value of #CounterVar. 7369 Expr *CounterInit = nullptr; 7370 /// This is step for the #CounterVar used to generate its update: 7371 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 7372 Expr *CounterStep = nullptr; 7373 /// Should step be subtracted? 7374 bool Subtract = false; 7375 /// Source range of the loop init. 7376 SourceRange InitSrcRange; 7377 /// Source range of the loop condition. 7378 SourceRange CondSrcRange; 7379 /// Source range of the loop increment. 7380 SourceRange IncSrcRange; 7381 /// Minimum value that can have the loop control variable. Used to support 7382 /// non-rectangular loops. Applied only for LCV with the non-iterator types, 7383 /// since only such variables can be used in non-loop invariant expressions. 7384 Expr *MinValue = nullptr; 7385 /// Maximum value that can have the loop control variable. Used to support 7386 /// non-rectangular loops. Applied only for LCV with the non-iterator type, 7387 /// since only such variables can be used in non-loop invariant expressions. 7388 Expr *MaxValue = nullptr; 7389 /// true, if the lower bound depends on the outer loop control var. 7390 bool IsNonRectangularLB = false; 7391 /// true, if the upper bound depends on the outer loop control var. 7392 bool IsNonRectangularUB = false; 7393 /// Index of the loop this loop depends on and forms non-rectangular loop 7394 /// nest. 7395 unsigned LoopDependentIdx = 0; 7396 /// Final condition for the non-rectangular loop nest support. It is used to 7397 /// check that the number of iterations for this particular counter must be 7398 /// finished. 7399 Expr *FinalCondition = nullptr; 7400 }; 7401 7402 /// Helper class for checking canonical form of the OpenMP loops and 7403 /// extracting iteration space of each loop in the loop nest, that will be used 7404 /// for IR generation. 7405 class OpenMPIterationSpaceChecker { 7406 /// Reference to Sema. 7407 Sema &SemaRef; 7408 /// Does the loop associated directive support non-rectangular loops? 7409 bool SupportsNonRectangular; 7410 /// Data-sharing stack. 7411 DSAStackTy &Stack; 7412 /// A location for diagnostics (when there is no some better location). 7413 SourceLocation DefaultLoc; 7414 /// A location for diagnostics (when increment is not compatible). 7415 SourceLocation ConditionLoc; 7416 /// A source location for referring to loop init later. 7417 SourceRange InitSrcRange; 7418 /// A source location for referring to condition later. 7419 SourceRange ConditionSrcRange; 7420 /// A source location for referring to increment later. 7421 SourceRange IncrementSrcRange; 7422 /// Loop variable. 7423 ValueDecl *LCDecl = nullptr; 7424 /// Reference to loop variable. 7425 Expr *LCRef = nullptr; 7426 /// Lower bound (initializer for the var). 7427 Expr *LB = nullptr; 7428 /// Upper bound. 7429 Expr *UB = nullptr; 7430 /// Loop step (increment). 7431 Expr *Step = nullptr; 7432 /// This flag is true when condition is one of: 7433 /// Var < UB 7434 /// Var <= UB 7435 /// UB > Var 7436 /// UB >= Var 7437 /// This will have no value when the condition is != 7438 llvm::Optional<bool> TestIsLessOp; 7439 /// This flag is true when condition is strict ( < or > ). 7440 bool TestIsStrictOp = false; 7441 /// This flag is true when step is subtracted on each iteration. 7442 bool SubtractStep = false; 7443 /// The outer loop counter this loop depends on (if any). 7444 const ValueDecl *DepDecl = nullptr; 7445 /// Contains number of loop (starts from 1) on which loop counter init 7446 /// expression of this loop depends on. 7447 Optional<unsigned> InitDependOnLC; 7448 /// Contains number of loop (starts from 1) on which loop counter condition 7449 /// expression of this loop depends on. 7450 Optional<unsigned> CondDependOnLC; 7451 /// Checks if the provide statement depends on the loop counter. 7452 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer); 7453 /// Original condition required for checking of the exit condition for 7454 /// non-rectangular loop. 7455 Expr *Condition = nullptr; 7456 7457 public: 7458 OpenMPIterationSpaceChecker(Sema &SemaRef, bool SupportsNonRectangular, 7459 DSAStackTy &Stack, SourceLocation DefaultLoc) 7460 : SemaRef(SemaRef), SupportsNonRectangular(SupportsNonRectangular), 7461 Stack(Stack), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 7462 /// Check init-expr for canonical loop form and save loop counter 7463 /// variable - #Var and its initialization value - #LB. 7464 bool checkAndSetInit(Stmt *S, bool EmitDiags = true); 7465 /// Check test-expr for canonical form, save upper-bound (#UB), flags 7466 /// for less/greater and for strict/non-strict comparison. 7467 bool checkAndSetCond(Expr *S); 7468 /// Check incr-expr for canonical loop form and return true if it 7469 /// does not conform, otherwise save loop step (#Step). 7470 bool checkAndSetInc(Expr *S); 7471 /// Return the loop counter variable. 7472 ValueDecl *getLoopDecl() const { return LCDecl; } 7473 /// Return the reference expression to loop counter variable. 7474 Expr *getLoopDeclRefExpr() const { return LCRef; } 7475 /// Source range of the loop init. 7476 SourceRange getInitSrcRange() const { return InitSrcRange; } 7477 /// Source range of the loop condition. 7478 SourceRange getConditionSrcRange() const { return ConditionSrcRange; } 7479 /// Source range of the loop increment. 7480 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; } 7481 /// True if the step should be subtracted. 7482 bool shouldSubtractStep() const { return SubtractStep; } 7483 /// True, if the compare operator is strict (<, > or !=). 7484 bool isStrictTestOp() const { return TestIsStrictOp; } 7485 /// Build the expression to calculate the number of iterations. 7486 Expr *buildNumIterations( 7487 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType, 7488 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 7489 /// Build the precondition expression for the loops. 7490 Expr * 7491 buildPreCond(Scope *S, Expr *Cond, 7492 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 7493 /// Build reference expression to the counter be used for codegen. 7494 DeclRefExpr * 7495 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 7496 DSAStackTy &DSA) const; 7497 /// Build reference expression to the private counter be used for 7498 /// codegen. 7499 Expr *buildPrivateCounterVar() const; 7500 /// Build initialization of the counter be used for codegen. 7501 Expr *buildCounterInit() const; 7502 /// Build step of the counter be used for codegen. 7503 Expr *buildCounterStep() const; 7504 /// Build loop data with counter value for depend clauses in ordered 7505 /// directives. 7506 Expr * 7507 buildOrderedLoopData(Scope *S, Expr *Counter, 7508 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 7509 SourceLocation Loc, Expr *Inc = nullptr, 7510 OverloadedOperatorKind OOK = OO_Amp); 7511 /// Builds the minimum value for the loop counter. 7512 std::pair<Expr *, Expr *> buildMinMaxValues( 7513 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 7514 /// Builds final condition for the non-rectangular loops. 7515 Expr *buildFinalCondition(Scope *S) const; 7516 /// Return true if any expression is dependent. 7517 bool dependent() const; 7518 /// Returns true if the initializer forms non-rectangular loop. 7519 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); } 7520 /// Returns true if the condition forms non-rectangular loop. 7521 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); } 7522 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise. 7523 unsigned getLoopDependentIdx() const { 7524 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0)); 7525 } 7526 7527 private: 7528 /// Check the right-hand side of an assignment in the increment 7529 /// expression. 7530 bool checkAndSetIncRHS(Expr *RHS); 7531 /// Helper to set loop counter variable and its initializer. 7532 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB, 7533 bool EmitDiags); 7534 /// Helper to set upper bound. 7535 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp, 7536 SourceRange SR, SourceLocation SL); 7537 /// Helper to set loop increment. 7538 bool setStep(Expr *NewStep, bool Subtract); 7539 }; 7540 7541 bool OpenMPIterationSpaceChecker::dependent() const { 7542 if (!LCDecl) { 7543 assert(!LB && !UB && !Step); 7544 return false; 7545 } 7546 return LCDecl->getType()->isDependentType() || 7547 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 7548 (Step && Step->isValueDependent()); 7549 } 7550 7551 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl, 7552 Expr *NewLCRefExpr, 7553 Expr *NewLB, bool EmitDiags) { 7554 // State consistency checking to ensure correct usage. 7555 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 7556 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 7557 if (!NewLCDecl || !NewLB || NewLB->containsErrors()) 7558 return true; 7559 LCDecl = getCanonicalDecl(NewLCDecl); 7560 LCRef = NewLCRefExpr; 7561 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 7562 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 7563 if ((Ctor->isCopyOrMoveConstructor() || 7564 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 7565 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 7566 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 7567 LB = NewLB; 7568 if (EmitDiags) 7569 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true); 7570 return false; 7571 } 7572 7573 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, 7574 llvm::Optional<bool> LessOp, 7575 bool StrictOp, SourceRange SR, 7576 SourceLocation SL) { 7577 // State consistency checking to ensure correct usage. 7578 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 7579 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 7580 if (!NewUB || NewUB->containsErrors()) 7581 return true; 7582 UB = NewUB; 7583 if (LessOp) 7584 TestIsLessOp = LessOp; 7585 TestIsStrictOp = StrictOp; 7586 ConditionSrcRange = SR; 7587 ConditionLoc = SL; 7588 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false); 7589 return false; 7590 } 7591 7592 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) { 7593 // State consistency checking to ensure correct usage. 7594 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 7595 if (!NewStep || NewStep->containsErrors()) 7596 return true; 7597 if (!NewStep->isValueDependent()) { 7598 // Check that the step is integer expression. 7599 SourceLocation StepLoc = NewStep->getBeginLoc(); 7600 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( 7601 StepLoc, getExprAsWritten(NewStep)); 7602 if (Val.isInvalid()) 7603 return true; 7604 NewStep = Val.get(); 7605 7606 // OpenMP [2.6, Canonical Loop Form, Restrictions] 7607 // If test-expr is of form var relational-op b and relational-op is < or 7608 // <= then incr-expr must cause var to increase on each iteration of the 7609 // loop. If test-expr is of form var relational-op b and relational-op is 7610 // > or >= then incr-expr must cause var to decrease on each iteration of 7611 // the loop. 7612 // If test-expr is of form b relational-op var and relational-op is < or 7613 // <= then incr-expr must cause var to decrease on each iteration of the 7614 // loop. If test-expr is of form b relational-op var and relational-op is 7615 // > or >= then incr-expr must cause var to increase on each iteration of 7616 // the loop. 7617 Optional<llvm::APSInt> Result = 7618 NewStep->getIntegerConstantExpr(SemaRef.Context); 7619 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 7620 bool IsConstNeg = 7621 Result && Result->isSigned() && (Subtract != Result->isNegative()); 7622 bool IsConstPos = 7623 Result && Result->isSigned() && (Subtract == Result->isNegative()); 7624 bool IsConstZero = Result && !Result->getBoolValue(); 7625 7626 // != with increment is treated as <; != with decrement is treated as > 7627 if (!TestIsLessOp.hasValue()) 7628 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract); 7629 if (UB && (IsConstZero || 7630 (TestIsLessOp.getValue() ? 7631 (IsConstNeg || (IsUnsigned && Subtract)) : 7632 (IsConstPos || (IsUnsigned && !Subtract))))) { 7633 SemaRef.Diag(NewStep->getExprLoc(), 7634 diag::err_omp_loop_incr_not_compatible) 7635 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange(); 7636 SemaRef.Diag(ConditionLoc, 7637 diag::note_omp_loop_cond_requres_compatible_incr) 7638 << TestIsLessOp.getValue() << ConditionSrcRange; 7639 return true; 7640 } 7641 if (TestIsLessOp.getValue() == Subtract) { 7642 NewStep = 7643 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 7644 .get(); 7645 Subtract = !Subtract; 7646 } 7647 } 7648 7649 Step = NewStep; 7650 SubtractStep = Subtract; 7651 return false; 7652 } 7653 7654 namespace { 7655 /// Checker for the non-rectangular loops. Checks if the initializer or 7656 /// condition expression references loop counter variable. 7657 class LoopCounterRefChecker final 7658 : public ConstStmtVisitor<LoopCounterRefChecker, bool> { 7659 Sema &SemaRef; 7660 DSAStackTy &Stack; 7661 const ValueDecl *CurLCDecl = nullptr; 7662 const ValueDecl *DepDecl = nullptr; 7663 const ValueDecl *PrevDepDecl = nullptr; 7664 bool IsInitializer = true; 7665 bool SupportsNonRectangular; 7666 unsigned BaseLoopId = 0; 7667 bool checkDecl(const Expr *E, const ValueDecl *VD) { 7668 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) { 7669 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter) 7670 << (IsInitializer ? 0 : 1); 7671 return false; 7672 } 7673 const auto &&Data = Stack.isLoopControlVariable(VD); 7674 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions. 7675 // The type of the loop iterator on which we depend may not have a random 7676 // access iterator type. 7677 if (Data.first && VD->getType()->isRecordType()) { 7678 SmallString<128> Name; 7679 llvm::raw_svector_ostream OS(Name); 7680 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(), 7681 /*Qualified=*/true); 7682 SemaRef.Diag(E->getExprLoc(), 7683 diag::err_omp_wrong_dependency_iterator_type) 7684 << OS.str(); 7685 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD; 7686 return false; 7687 } 7688 if (Data.first && !SupportsNonRectangular) { 7689 SemaRef.Diag(E->getExprLoc(), diag::err_omp_invariant_dependency); 7690 return false; 7691 } 7692 if (Data.first && 7693 (DepDecl || (PrevDepDecl && 7694 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) { 7695 if (!DepDecl && PrevDepDecl) 7696 DepDecl = PrevDepDecl; 7697 SmallString<128> Name; 7698 llvm::raw_svector_ostream OS(Name); 7699 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(), 7700 /*Qualified=*/true); 7701 SemaRef.Diag(E->getExprLoc(), 7702 diag::err_omp_invariant_or_linear_dependency) 7703 << OS.str(); 7704 return false; 7705 } 7706 if (Data.first) { 7707 DepDecl = VD; 7708 BaseLoopId = Data.first; 7709 } 7710 return Data.first; 7711 } 7712 7713 public: 7714 bool VisitDeclRefExpr(const DeclRefExpr *E) { 7715 const ValueDecl *VD = E->getDecl(); 7716 if (isa<VarDecl>(VD)) 7717 return checkDecl(E, VD); 7718 return false; 7719 } 7720 bool VisitMemberExpr(const MemberExpr *E) { 7721 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 7722 const ValueDecl *VD = E->getMemberDecl(); 7723 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD)) 7724 return checkDecl(E, VD); 7725 } 7726 return false; 7727 } 7728 bool VisitStmt(const Stmt *S) { 7729 bool Res = false; 7730 for (const Stmt *Child : S->children()) 7731 Res = (Child && Visit(Child)) || Res; 7732 return Res; 7733 } 7734 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack, 7735 const ValueDecl *CurLCDecl, bool IsInitializer, 7736 const ValueDecl *PrevDepDecl = nullptr, 7737 bool SupportsNonRectangular = true) 7738 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl), 7739 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer), 7740 SupportsNonRectangular(SupportsNonRectangular) {} 7741 unsigned getBaseLoopId() const { 7742 assert(CurLCDecl && "Expected loop dependency."); 7743 return BaseLoopId; 7744 } 7745 const ValueDecl *getDepDecl() const { 7746 assert(CurLCDecl && "Expected loop dependency."); 7747 return DepDecl; 7748 } 7749 }; 7750 } // namespace 7751 7752 Optional<unsigned> 7753 OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S, 7754 bool IsInitializer) { 7755 // Check for the non-rectangular loops. 7756 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer, 7757 DepDecl, SupportsNonRectangular); 7758 if (LoopStmtChecker.Visit(S)) { 7759 DepDecl = LoopStmtChecker.getDepDecl(); 7760 return LoopStmtChecker.getBaseLoopId(); 7761 } 7762 return llvm::None; 7763 } 7764 7765 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) { 7766 // Check init-expr for canonical loop form and save loop counter 7767 // variable - #Var and its initialization value - #LB. 7768 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 7769 // var = lb 7770 // integer-type var = lb 7771 // random-access-iterator-type var = lb 7772 // pointer-type var = lb 7773 // 7774 if (!S) { 7775 if (EmitDiags) { 7776 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 7777 } 7778 return true; 7779 } 7780 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 7781 if (!ExprTemp->cleanupsHaveSideEffects()) 7782 S = ExprTemp->getSubExpr(); 7783 7784 InitSrcRange = S->getSourceRange(); 7785 if (Expr *E = dyn_cast<Expr>(S)) 7786 S = E->IgnoreParens(); 7787 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 7788 if (BO->getOpcode() == BO_Assign) { 7789 Expr *LHS = BO->getLHS()->IgnoreParens(); 7790 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 7791 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 7792 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 7793 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7794 EmitDiags); 7795 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags); 7796 } 7797 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 7798 if (ME->isArrow() && 7799 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7800 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7801 EmitDiags); 7802 } 7803 } 7804 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 7805 if (DS->isSingleDecl()) { 7806 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 7807 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 7808 // Accept non-canonical init form here but emit ext. warning. 7809 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 7810 SemaRef.Diag(S->getBeginLoc(), 7811 diag::ext_omp_loop_not_canonical_init) 7812 << S->getSourceRange(); 7813 return setLCDeclAndLB( 7814 Var, 7815 buildDeclRefExpr(SemaRef, Var, 7816 Var->getType().getNonReferenceType(), 7817 DS->getBeginLoc()), 7818 Var->getInit(), EmitDiags); 7819 } 7820 } 7821 } 7822 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 7823 if (CE->getOperator() == OO_Equal) { 7824 Expr *LHS = CE->getArg(0); 7825 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 7826 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 7827 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 7828 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7829 EmitDiags); 7830 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags); 7831 } 7832 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 7833 if (ME->isArrow() && 7834 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7835 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(), 7836 EmitDiags); 7837 } 7838 } 7839 } 7840 7841 if (dependent() || SemaRef.CurContext->isDependentContext()) 7842 return false; 7843 if (EmitDiags) { 7844 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init) 7845 << S->getSourceRange(); 7846 } 7847 return true; 7848 } 7849 7850 /// Ignore parenthesizes, implicit casts, copy constructor and return the 7851 /// variable (which may be the loop variable) if possible. 7852 static const ValueDecl *getInitLCDecl(const Expr *E) { 7853 if (!E) 7854 return nullptr; 7855 E = getExprAsWritten(E); 7856 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 7857 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 7858 if ((Ctor->isCopyOrMoveConstructor() || 7859 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 7860 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 7861 E = CE->getArg(0)->IgnoreParenImpCasts(); 7862 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 7863 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 7864 return getCanonicalDecl(VD); 7865 } 7866 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E)) 7867 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 7868 return getCanonicalDecl(ME->getMemberDecl()); 7869 return nullptr; 7870 } 7871 7872 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) { 7873 // Check test-expr for canonical form, save upper-bound UB, flags for 7874 // less/greater and for strict/non-strict comparison. 7875 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following: 7876 // var relational-op b 7877 // b relational-op var 7878 // 7879 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50; 7880 if (!S) { 7881 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) 7882 << (IneqCondIsCanonical ? 1 : 0) << LCDecl; 7883 return true; 7884 } 7885 Condition = S; 7886 S = getExprAsWritten(S); 7887 SourceLocation CondLoc = S->getBeginLoc(); 7888 auto &&CheckAndSetCond = [this, IneqCondIsCanonical]( 7889 BinaryOperatorKind Opcode, const Expr *LHS, 7890 const Expr *RHS, SourceRange SR, 7891 SourceLocation OpLoc) -> llvm::Optional<bool> { 7892 if (BinaryOperator::isRelationalOp(Opcode)) { 7893 if (getInitLCDecl(LHS) == LCDecl) 7894 return setUB(const_cast<Expr *>(RHS), 7895 (Opcode == BO_LT || Opcode == BO_LE), 7896 (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc); 7897 if (getInitLCDecl(RHS) == LCDecl) 7898 return setUB(const_cast<Expr *>(LHS), 7899 (Opcode == BO_GT || Opcode == BO_GE), 7900 (Opcode == BO_LT || Opcode == BO_GT), SR, OpLoc); 7901 } else if (IneqCondIsCanonical && Opcode == BO_NE) { 7902 return setUB(const_cast<Expr *>(getInitLCDecl(LHS) == LCDecl ? RHS : LHS), 7903 /*LessOp=*/llvm::None, 7904 /*StrictOp=*/true, SR, OpLoc); 7905 } 7906 return llvm::None; 7907 }; 7908 llvm::Optional<bool> Res; 7909 if (auto *RBO = dyn_cast<CXXRewrittenBinaryOperator>(S)) { 7910 CXXRewrittenBinaryOperator::DecomposedForm DF = RBO->getDecomposedForm(); 7911 Res = CheckAndSetCond(DF.Opcode, DF.LHS, DF.RHS, RBO->getSourceRange(), 7912 RBO->getOperatorLoc()); 7913 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 7914 Res = CheckAndSetCond(BO->getOpcode(), BO->getLHS(), BO->getRHS(), 7915 BO->getSourceRange(), BO->getOperatorLoc()); 7916 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 7917 if (CE->getNumArgs() == 2) { 7918 Res = CheckAndSetCond( 7919 BinaryOperator::getOverloadedOpcode(CE->getOperator()), CE->getArg(0), 7920 CE->getArg(1), CE->getSourceRange(), CE->getOperatorLoc()); 7921 } 7922 } 7923 if (Res.hasValue()) 7924 return *Res; 7925 if (dependent() || SemaRef.CurContext->isDependentContext()) 7926 return false; 7927 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 7928 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl; 7929 return true; 7930 } 7931 7932 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) { 7933 // RHS of canonical loop form increment can be: 7934 // var + incr 7935 // incr + var 7936 // var - incr 7937 // 7938 RHS = RHS->IgnoreParenImpCasts(); 7939 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 7940 if (BO->isAdditiveOp()) { 7941 bool IsAdd = BO->getOpcode() == BO_Add; 7942 if (getInitLCDecl(BO->getLHS()) == LCDecl) 7943 return setStep(BO->getRHS(), !IsAdd); 7944 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl) 7945 return setStep(BO->getLHS(), /*Subtract=*/false); 7946 } 7947 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 7948 bool IsAdd = CE->getOperator() == OO_Plus; 7949 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 7950 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 7951 return setStep(CE->getArg(1), !IsAdd); 7952 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl) 7953 return setStep(CE->getArg(0), /*Subtract=*/false); 7954 } 7955 } 7956 if (dependent() || SemaRef.CurContext->isDependentContext()) 7957 return false; 7958 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 7959 << RHS->getSourceRange() << LCDecl; 7960 return true; 7961 } 7962 7963 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) { 7964 // Check incr-expr for canonical loop form and return true if it 7965 // does not conform. 7966 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 7967 // ++var 7968 // var++ 7969 // --var 7970 // var-- 7971 // var += incr 7972 // var -= incr 7973 // var = var + incr 7974 // var = incr + var 7975 // var = var - incr 7976 // 7977 if (!S) { 7978 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 7979 return true; 7980 } 7981 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 7982 if (!ExprTemp->cleanupsHaveSideEffects()) 7983 S = ExprTemp->getSubExpr(); 7984 7985 IncrementSrcRange = S->getSourceRange(); 7986 S = S->IgnoreParens(); 7987 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 7988 if (UO->isIncrementDecrementOp() && 7989 getInitLCDecl(UO->getSubExpr()) == LCDecl) 7990 return setStep(SemaRef 7991 .ActOnIntegerConstant(UO->getBeginLoc(), 7992 (UO->isDecrementOp() ? -1 : 1)) 7993 .get(), 7994 /*Subtract=*/false); 7995 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 7996 switch (BO->getOpcode()) { 7997 case BO_AddAssign: 7998 case BO_SubAssign: 7999 if (getInitLCDecl(BO->getLHS()) == LCDecl) 8000 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 8001 break; 8002 case BO_Assign: 8003 if (getInitLCDecl(BO->getLHS()) == LCDecl) 8004 return checkAndSetIncRHS(BO->getRHS()); 8005 break; 8006 default: 8007 break; 8008 } 8009 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 8010 switch (CE->getOperator()) { 8011 case OO_PlusPlus: 8012 case OO_MinusMinus: 8013 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 8014 return setStep(SemaRef 8015 .ActOnIntegerConstant( 8016 CE->getBeginLoc(), 8017 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 8018 .get(), 8019 /*Subtract=*/false); 8020 break; 8021 case OO_PlusEqual: 8022 case OO_MinusEqual: 8023 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 8024 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 8025 break; 8026 case OO_Equal: 8027 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 8028 return checkAndSetIncRHS(CE->getArg(1)); 8029 break; 8030 default: 8031 break; 8032 } 8033 } 8034 if (dependent() || SemaRef.CurContext->isDependentContext()) 8035 return false; 8036 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 8037 << S->getSourceRange() << LCDecl; 8038 return true; 8039 } 8040 8041 static ExprResult 8042 tryBuildCapture(Sema &SemaRef, Expr *Capture, 8043 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8044 if (SemaRef.CurContext->isDependentContext() || Capture->containsErrors()) 8045 return Capture; 8046 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 8047 return SemaRef.PerformImplicitConversion( 8048 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 8049 /*AllowExplicit=*/true); 8050 auto I = Captures.find(Capture); 8051 if (I != Captures.end()) 8052 return buildCapture(SemaRef, Capture, I->second); 8053 DeclRefExpr *Ref = nullptr; 8054 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 8055 Captures[Capture] = Ref; 8056 return Res; 8057 } 8058 8059 /// Calculate number of iterations, transforming to unsigned, if number of 8060 /// iterations may be larger than the original type. 8061 static Expr * 8062 calculateNumIters(Sema &SemaRef, Scope *S, SourceLocation DefaultLoc, 8063 Expr *Lower, Expr *Upper, Expr *Step, QualType LCTy, 8064 bool TestIsStrictOp, bool RoundToStep, 8065 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8066 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 8067 if (!NewStep.isUsable()) 8068 return nullptr; 8069 llvm::APSInt LRes, SRes; 8070 bool IsLowerConst = false, IsStepConst = false; 8071 if (Optional<llvm::APSInt> Res = Lower->getIntegerConstantExpr(SemaRef.Context)) { 8072 LRes = *Res; 8073 IsLowerConst = true; 8074 } 8075 if (Optional<llvm::APSInt> Res = Step->getIntegerConstantExpr(SemaRef.Context)) { 8076 SRes = *Res; 8077 IsStepConst = true; 8078 } 8079 bool NoNeedToConvert = IsLowerConst && !RoundToStep && 8080 ((!TestIsStrictOp && LRes.isNonNegative()) || 8081 (TestIsStrictOp && LRes.isStrictlyPositive())); 8082 bool NeedToReorganize = false; 8083 // Check if any subexpressions in Lower -Step [+ 1] lead to overflow. 8084 if (!NoNeedToConvert && IsLowerConst && 8085 (TestIsStrictOp || (RoundToStep && IsStepConst))) { 8086 NoNeedToConvert = true; 8087 if (RoundToStep) { 8088 unsigned BW = LRes.getBitWidth() > SRes.getBitWidth() 8089 ? LRes.getBitWidth() 8090 : SRes.getBitWidth(); 8091 LRes = LRes.extend(BW + 1); 8092 LRes.setIsSigned(true); 8093 SRes = SRes.extend(BW + 1); 8094 SRes.setIsSigned(true); 8095 LRes -= SRes; 8096 NoNeedToConvert = LRes.trunc(BW).extend(BW + 1) == LRes; 8097 LRes = LRes.trunc(BW); 8098 } 8099 if (TestIsStrictOp) { 8100 unsigned BW = LRes.getBitWidth(); 8101 LRes = LRes.extend(BW + 1); 8102 LRes.setIsSigned(true); 8103 ++LRes; 8104 NoNeedToConvert = 8105 NoNeedToConvert && LRes.trunc(BW).extend(BW + 1) == LRes; 8106 // truncate to the original bitwidth. 8107 LRes = LRes.trunc(BW); 8108 } 8109 NeedToReorganize = NoNeedToConvert; 8110 } 8111 llvm::APSInt URes; 8112 bool IsUpperConst = false; 8113 if (Optional<llvm::APSInt> Res = Upper->getIntegerConstantExpr(SemaRef.Context)) { 8114 URes = *Res; 8115 IsUpperConst = true; 8116 } 8117 if (NoNeedToConvert && IsLowerConst && IsUpperConst && 8118 (!RoundToStep || IsStepConst)) { 8119 unsigned BW = LRes.getBitWidth() > URes.getBitWidth() ? LRes.getBitWidth() 8120 : URes.getBitWidth(); 8121 LRes = LRes.extend(BW + 1); 8122 LRes.setIsSigned(true); 8123 URes = URes.extend(BW + 1); 8124 URes.setIsSigned(true); 8125 URes -= LRes; 8126 NoNeedToConvert = URes.trunc(BW).extend(BW + 1) == URes; 8127 NeedToReorganize = NoNeedToConvert; 8128 } 8129 // If the boundaries are not constant or (Lower - Step [+ 1]) is not constant 8130 // or less than zero (Upper - (Lower - Step [+ 1]) may overflow) - promote to 8131 // unsigned. 8132 if ((!NoNeedToConvert || (LRes.isNegative() && !IsUpperConst)) && 8133 !LCTy->isDependentType() && LCTy->isIntegerType()) { 8134 QualType LowerTy = Lower->getType(); 8135 QualType UpperTy = Upper->getType(); 8136 uint64_t LowerSize = SemaRef.Context.getTypeSize(LowerTy); 8137 uint64_t UpperSize = SemaRef.Context.getTypeSize(UpperTy); 8138 if ((LowerSize <= UpperSize && UpperTy->hasSignedIntegerRepresentation()) || 8139 (LowerSize > UpperSize && LowerTy->hasSignedIntegerRepresentation())) { 8140 QualType CastType = SemaRef.Context.getIntTypeForBitwidth( 8141 LowerSize > UpperSize ? LowerSize : UpperSize, /*Signed=*/0); 8142 Upper = 8143 SemaRef 8144 .PerformImplicitConversion( 8145 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(), 8146 CastType, Sema::AA_Converting) 8147 .get(); 8148 Lower = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(); 8149 NewStep = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, NewStep.get()); 8150 } 8151 } 8152 if (!Lower || !Upper || NewStep.isInvalid()) 8153 return nullptr; 8154 8155 ExprResult Diff; 8156 // If need to reorganize, then calculate the form as Upper - (Lower - Step [+ 8157 // 1]). 8158 if (NeedToReorganize) { 8159 Diff = Lower; 8160 8161 if (RoundToStep) { 8162 // Lower - Step 8163 Diff = 8164 SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Diff.get(), NewStep.get()); 8165 if (!Diff.isUsable()) 8166 return nullptr; 8167 } 8168 8169 // Lower - Step [+ 1] 8170 if (TestIsStrictOp) 8171 Diff = SemaRef.BuildBinOp( 8172 S, DefaultLoc, BO_Add, Diff.get(), 8173 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 8174 if (!Diff.isUsable()) 8175 return nullptr; 8176 8177 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8178 if (!Diff.isUsable()) 8179 return nullptr; 8180 8181 // Upper - (Lower - Step [+ 1]). 8182 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get()); 8183 if (!Diff.isUsable()) 8184 return nullptr; 8185 } else { 8186 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 8187 8188 if (!Diff.isUsable() && LCTy->getAsCXXRecordDecl()) { 8189 // BuildBinOp already emitted error, this one is to point user to upper 8190 // and lower bound, and to tell what is passed to 'operator-'. 8191 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx) 8192 << Upper->getSourceRange() << Lower->getSourceRange(); 8193 return nullptr; 8194 } 8195 8196 if (!Diff.isUsable()) 8197 return nullptr; 8198 8199 // Upper - Lower [- 1] 8200 if (TestIsStrictOp) 8201 Diff = SemaRef.BuildBinOp( 8202 S, DefaultLoc, BO_Sub, Diff.get(), 8203 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 8204 if (!Diff.isUsable()) 8205 return nullptr; 8206 8207 if (RoundToStep) { 8208 // Upper - Lower [- 1] + Step 8209 Diff = 8210 SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 8211 if (!Diff.isUsable()) 8212 return nullptr; 8213 } 8214 } 8215 8216 // Parentheses (for dumping/debugging purposes only). 8217 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8218 if (!Diff.isUsable()) 8219 return nullptr; 8220 8221 // (Upper - Lower [- 1] + Step) / Step or (Upper - Lower) / Step 8222 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 8223 if (!Diff.isUsable()) 8224 return nullptr; 8225 8226 return Diff.get(); 8227 } 8228 8229 /// Build the expression to calculate the number of iterations. 8230 Expr *OpenMPIterationSpaceChecker::buildNumIterations( 8231 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType, 8232 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 8233 QualType VarType = LCDecl->getType().getNonReferenceType(); 8234 if (!VarType->isIntegerType() && !VarType->isPointerType() && 8235 !SemaRef.getLangOpts().CPlusPlus) 8236 return nullptr; 8237 Expr *LBVal = LB; 8238 Expr *UBVal = UB; 8239 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) : 8240 // max(LB(MinVal), LB(MaxVal)) 8241 if (InitDependOnLC) { 8242 const LoopIterationSpace &IS = ResultIterSpaces[*InitDependOnLC - 1]; 8243 if (!IS.MinValue || !IS.MaxValue) 8244 return nullptr; 8245 // OuterVar = Min 8246 ExprResult MinValue = 8247 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue); 8248 if (!MinValue.isUsable()) 8249 return nullptr; 8250 8251 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8252 IS.CounterVar, MinValue.get()); 8253 if (!LBMinVal.isUsable()) 8254 return nullptr; 8255 // OuterVar = Min, LBVal 8256 LBMinVal = 8257 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal); 8258 if (!LBMinVal.isUsable()) 8259 return nullptr; 8260 // (OuterVar = Min, LBVal) 8261 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get()); 8262 if (!LBMinVal.isUsable()) 8263 return nullptr; 8264 8265 // OuterVar = Max 8266 ExprResult MaxValue = 8267 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue); 8268 if (!MaxValue.isUsable()) 8269 return nullptr; 8270 8271 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8272 IS.CounterVar, MaxValue.get()); 8273 if (!LBMaxVal.isUsable()) 8274 return nullptr; 8275 // OuterVar = Max, LBVal 8276 LBMaxVal = 8277 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal); 8278 if (!LBMaxVal.isUsable()) 8279 return nullptr; 8280 // (OuterVar = Max, LBVal) 8281 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get()); 8282 if (!LBMaxVal.isUsable()) 8283 return nullptr; 8284 8285 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get(); 8286 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get(); 8287 if (!LBMin || !LBMax) 8288 return nullptr; 8289 // LB(MinVal) < LB(MaxVal) 8290 ExprResult MinLessMaxRes = 8291 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax); 8292 if (!MinLessMaxRes.isUsable()) 8293 return nullptr; 8294 Expr *MinLessMax = 8295 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get(); 8296 if (!MinLessMax) 8297 return nullptr; 8298 if (TestIsLessOp.getValue()) { 8299 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal), 8300 // LB(MaxVal)) 8301 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc, 8302 MinLessMax, LBMin, LBMax); 8303 if (!MinLB.isUsable()) 8304 return nullptr; 8305 LBVal = MinLB.get(); 8306 } else { 8307 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal), 8308 // LB(MaxVal)) 8309 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc, 8310 MinLessMax, LBMax, LBMin); 8311 if (!MaxLB.isUsable()) 8312 return nullptr; 8313 LBVal = MaxLB.get(); 8314 } 8315 } 8316 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) : 8317 // min(UB(MinVal), UB(MaxVal)) 8318 if (CondDependOnLC) { 8319 const LoopIterationSpace &IS = ResultIterSpaces[*CondDependOnLC - 1]; 8320 if (!IS.MinValue || !IS.MaxValue) 8321 return nullptr; 8322 // OuterVar = Min 8323 ExprResult MinValue = 8324 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue); 8325 if (!MinValue.isUsable()) 8326 return nullptr; 8327 8328 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8329 IS.CounterVar, MinValue.get()); 8330 if (!UBMinVal.isUsable()) 8331 return nullptr; 8332 // OuterVar = Min, UBVal 8333 UBMinVal = 8334 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal); 8335 if (!UBMinVal.isUsable()) 8336 return nullptr; 8337 // (OuterVar = Min, UBVal) 8338 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get()); 8339 if (!UBMinVal.isUsable()) 8340 return nullptr; 8341 8342 // OuterVar = Max 8343 ExprResult MaxValue = 8344 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue); 8345 if (!MaxValue.isUsable()) 8346 return nullptr; 8347 8348 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign, 8349 IS.CounterVar, MaxValue.get()); 8350 if (!UBMaxVal.isUsable()) 8351 return nullptr; 8352 // OuterVar = Max, UBVal 8353 UBMaxVal = 8354 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal); 8355 if (!UBMaxVal.isUsable()) 8356 return nullptr; 8357 // (OuterVar = Max, UBVal) 8358 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get()); 8359 if (!UBMaxVal.isUsable()) 8360 return nullptr; 8361 8362 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get(); 8363 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get(); 8364 if (!UBMin || !UBMax) 8365 return nullptr; 8366 // UB(MinVal) > UB(MaxVal) 8367 ExprResult MinGreaterMaxRes = 8368 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax); 8369 if (!MinGreaterMaxRes.isUsable()) 8370 return nullptr; 8371 Expr *MinGreaterMax = 8372 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get(); 8373 if (!MinGreaterMax) 8374 return nullptr; 8375 if (TestIsLessOp.getValue()) { 8376 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal), 8377 // UB(MaxVal)) 8378 ExprResult MaxUB = SemaRef.ActOnConditionalOp( 8379 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax); 8380 if (!MaxUB.isUsable()) 8381 return nullptr; 8382 UBVal = MaxUB.get(); 8383 } else { 8384 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal), 8385 // UB(MaxVal)) 8386 ExprResult MinUB = SemaRef.ActOnConditionalOp( 8387 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin); 8388 if (!MinUB.isUsable()) 8389 return nullptr; 8390 UBVal = MinUB.get(); 8391 } 8392 } 8393 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal; 8394 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal; 8395 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 8396 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 8397 if (!Upper || !Lower) 8398 return nullptr; 8399 8400 ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, 8401 Step, VarType, TestIsStrictOp, 8402 /*RoundToStep=*/true, Captures); 8403 if (!Diff.isUsable()) 8404 return nullptr; 8405 8406 // OpenMP runtime requires 32-bit or 64-bit loop variables. 8407 QualType Type = Diff.get()->getType(); 8408 ASTContext &C = SemaRef.Context; 8409 bool UseVarType = VarType->hasIntegerRepresentation() && 8410 C.getTypeSize(Type) > C.getTypeSize(VarType); 8411 if (!Type->isIntegerType() || UseVarType) { 8412 unsigned NewSize = 8413 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 8414 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 8415 : Type->hasSignedIntegerRepresentation(); 8416 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 8417 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 8418 Diff = SemaRef.PerformImplicitConversion( 8419 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 8420 if (!Diff.isUsable()) 8421 return nullptr; 8422 } 8423 } 8424 if (LimitedType) { 8425 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 8426 if (NewSize != C.getTypeSize(Type)) { 8427 if (NewSize < C.getTypeSize(Type)) { 8428 assert(NewSize == 64 && "incorrect loop var size"); 8429 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 8430 << InitSrcRange << ConditionSrcRange; 8431 } 8432 QualType NewType = C.getIntTypeForBitwidth( 8433 NewSize, Type->hasSignedIntegerRepresentation() || 8434 C.getTypeSize(Type) < NewSize); 8435 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 8436 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 8437 Sema::AA_Converting, true); 8438 if (!Diff.isUsable()) 8439 return nullptr; 8440 } 8441 } 8442 } 8443 8444 return Diff.get(); 8445 } 8446 8447 std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues( 8448 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 8449 // Do not build for iterators, they cannot be used in non-rectangular loop 8450 // nests. 8451 if (LCDecl->getType()->isRecordType()) 8452 return std::make_pair(nullptr, nullptr); 8453 // If we subtract, the min is in the condition, otherwise the min is in the 8454 // init value. 8455 Expr *MinExpr = nullptr; 8456 Expr *MaxExpr = nullptr; 8457 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB; 8458 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB; 8459 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue() 8460 : CondDependOnLC.hasValue(); 8461 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue() 8462 : InitDependOnLC.hasValue(); 8463 Expr *Lower = 8464 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get(); 8465 Expr *Upper = 8466 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get(); 8467 if (!Upper || !Lower) 8468 return std::make_pair(nullptr, nullptr); 8469 8470 if (TestIsLessOp.getValue()) 8471 MinExpr = Lower; 8472 else 8473 MaxExpr = Upper; 8474 8475 // Build minimum/maximum value based on number of iterations. 8476 QualType VarType = LCDecl->getType().getNonReferenceType(); 8477 8478 ExprResult Diff = calculateNumIters(SemaRef, S, DefaultLoc, Lower, Upper, 8479 Step, VarType, TestIsStrictOp, 8480 /*RoundToStep=*/false, Captures); 8481 if (!Diff.isUsable()) 8482 return std::make_pair(nullptr, nullptr); 8483 8484 // ((Upper - Lower [- 1]) / Step) * Step 8485 // Parentheses (for dumping/debugging purposes only). 8486 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8487 if (!Diff.isUsable()) 8488 return std::make_pair(nullptr, nullptr); 8489 8490 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 8491 if (!NewStep.isUsable()) 8492 return std::make_pair(nullptr, nullptr); 8493 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get()); 8494 if (!Diff.isUsable()) 8495 return std::make_pair(nullptr, nullptr); 8496 8497 // Parentheses (for dumping/debugging purposes only). 8498 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 8499 if (!Diff.isUsable()) 8500 return std::make_pair(nullptr, nullptr); 8501 8502 // Convert to the ptrdiff_t, if original type is pointer. 8503 if (VarType->isAnyPointerType() && 8504 !SemaRef.Context.hasSameType( 8505 Diff.get()->getType(), 8506 SemaRef.Context.getUnsignedPointerDiffType())) { 8507 Diff = SemaRef.PerformImplicitConversion( 8508 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(), 8509 Sema::AA_Converting, /*AllowExplicit=*/true); 8510 } 8511 if (!Diff.isUsable()) 8512 return std::make_pair(nullptr, nullptr); 8513 8514 if (TestIsLessOp.getValue()) { 8515 // MinExpr = Lower; 8516 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step) 8517 Diff = SemaRef.BuildBinOp( 8518 S, DefaultLoc, BO_Add, 8519 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Lower).get(), 8520 Diff.get()); 8521 if (!Diff.isUsable()) 8522 return std::make_pair(nullptr, nullptr); 8523 } else { 8524 // MaxExpr = Upper; 8525 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step) 8526 Diff = SemaRef.BuildBinOp( 8527 S, DefaultLoc, BO_Sub, 8528 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Upper).get(), 8529 Diff.get()); 8530 if (!Diff.isUsable()) 8531 return std::make_pair(nullptr, nullptr); 8532 } 8533 8534 // Convert to the original type. 8535 if (SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) 8536 Diff = SemaRef.PerformImplicitConversion(Diff.get(), VarType, 8537 Sema::AA_Converting, 8538 /*AllowExplicit=*/true); 8539 if (!Diff.isUsable()) 8540 return std::make_pair(nullptr, nullptr); 8541 8542 Sema::TentativeAnalysisScope Trap(SemaRef); 8543 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue=*/false); 8544 if (!Diff.isUsable()) 8545 return std::make_pair(nullptr, nullptr); 8546 8547 if (TestIsLessOp.getValue()) 8548 MaxExpr = Diff.get(); 8549 else 8550 MinExpr = Diff.get(); 8551 8552 return std::make_pair(MinExpr, MaxExpr); 8553 } 8554 8555 Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const { 8556 if (InitDependOnLC || CondDependOnLC) 8557 return Condition; 8558 return nullptr; 8559 } 8560 8561 Expr *OpenMPIterationSpaceChecker::buildPreCond( 8562 Scope *S, Expr *Cond, 8563 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 8564 // Do not build a precondition when the condition/initialization is dependent 8565 // to prevent pessimistic early loop exit. 8566 // TODO: this can be improved by calculating min/max values but not sure that 8567 // it will be very effective. 8568 if (CondDependOnLC || InitDependOnLC) 8569 return SemaRef.PerformImplicitConversion( 8570 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(), 8571 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 8572 /*AllowExplicit=*/true).get(); 8573 8574 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 8575 Sema::TentativeAnalysisScope Trap(SemaRef); 8576 8577 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures); 8578 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures); 8579 if (!NewLB.isUsable() || !NewUB.isUsable()) 8580 return nullptr; 8581 8582 ExprResult CondExpr = 8583 SemaRef.BuildBinOp(S, DefaultLoc, 8584 TestIsLessOp.getValue() ? 8585 (TestIsStrictOp ? BO_LT : BO_LE) : 8586 (TestIsStrictOp ? BO_GT : BO_GE), 8587 NewLB.get(), NewUB.get()); 8588 if (CondExpr.isUsable()) { 8589 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 8590 SemaRef.Context.BoolTy)) 8591 CondExpr = SemaRef.PerformImplicitConversion( 8592 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 8593 /*AllowExplicit=*/true); 8594 } 8595 8596 // Otherwise use original loop condition and evaluate it in runtime. 8597 return CondExpr.isUsable() ? CondExpr.get() : Cond; 8598 } 8599 8600 /// Build reference expression to the counter be used for codegen. 8601 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar( 8602 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 8603 DSAStackTy &DSA) const { 8604 auto *VD = dyn_cast<VarDecl>(LCDecl); 8605 if (!VD) { 8606 VD = SemaRef.isOpenMPCapturedDecl(LCDecl); 8607 DeclRefExpr *Ref = buildDeclRefExpr( 8608 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 8609 const DSAStackTy::DSAVarData Data = 8610 DSA.getTopDSA(LCDecl, /*FromParent=*/false); 8611 // If the loop control decl is explicitly marked as private, do not mark it 8612 // as captured again. 8613 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 8614 Captures.insert(std::make_pair(LCRef, Ref)); 8615 return Ref; 8616 } 8617 return cast<DeclRefExpr>(LCRef); 8618 } 8619 8620 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const { 8621 if (LCDecl && !LCDecl->isInvalidDecl()) { 8622 QualType Type = LCDecl->getType().getNonReferenceType(); 8623 VarDecl *PrivateVar = buildVarDecl( 8624 SemaRef, DefaultLoc, Type, LCDecl->getName(), 8625 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr, 8626 isa<VarDecl>(LCDecl) 8627 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc) 8628 : nullptr); 8629 if (PrivateVar->isInvalidDecl()) 8630 return nullptr; 8631 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 8632 } 8633 return nullptr; 8634 } 8635 8636 /// Build initialization of the counter to be used for codegen. 8637 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; } 8638 8639 /// Build step of the counter be used for codegen. 8640 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; } 8641 8642 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData( 8643 Scope *S, Expr *Counter, 8644 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc, 8645 Expr *Inc, OverloadedOperatorKind OOK) { 8646 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get(); 8647 if (!Cnt) 8648 return nullptr; 8649 if (Inc) { 8650 assert((OOK == OO_Plus || OOK == OO_Minus) && 8651 "Expected only + or - operations for depend clauses."); 8652 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub; 8653 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get(); 8654 if (!Cnt) 8655 return nullptr; 8656 } 8657 QualType VarType = LCDecl->getType().getNonReferenceType(); 8658 if (!VarType->isIntegerType() && !VarType->isPointerType() && 8659 !SemaRef.getLangOpts().CPlusPlus) 8660 return nullptr; 8661 // Upper - Lower 8662 Expr *Upper = TestIsLessOp.getValue() 8663 ? Cnt 8664 : tryBuildCapture(SemaRef, LB, Captures).get(); 8665 Expr *Lower = TestIsLessOp.getValue() 8666 ? tryBuildCapture(SemaRef, LB, Captures).get() 8667 : Cnt; 8668 if (!Upper || !Lower) 8669 return nullptr; 8670 8671 ExprResult Diff = calculateNumIters( 8672 SemaRef, S, DefaultLoc, Lower, Upper, Step, VarType, 8673 /*TestIsStrictOp=*/false, /*RoundToStep=*/false, Captures); 8674 if (!Diff.isUsable()) 8675 return nullptr; 8676 8677 return Diff.get(); 8678 } 8679 } // namespace 8680 8681 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 8682 assert(getLangOpts().OpenMP && "OpenMP is not active."); 8683 assert(Init && "Expected loop in canonical form."); 8684 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 8685 if (AssociatedLoops > 0 && 8686 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 8687 DSAStack->loopStart(); 8688 OpenMPIterationSpaceChecker ISC(*this, /*SupportsNonRectangular=*/true, 8689 *DSAStack, ForLoc); 8690 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) { 8691 if (ValueDecl *D = ISC.getLoopDecl()) { 8692 auto *VD = dyn_cast<VarDecl>(D); 8693 DeclRefExpr *PrivateRef = nullptr; 8694 if (!VD) { 8695 if (VarDecl *Private = isOpenMPCapturedDecl(D)) { 8696 VD = Private; 8697 } else { 8698 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(), 8699 /*WithInit=*/false); 8700 VD = cast<VarDecl>(PrivateRef->getDecl()); 8701 } 8702 } 8703 DSAStack->addLoopControlVariable(D, VD); 8704 const Decl *LD = DSAStack->getPossiblyLoopCunter(); 8705 if (LD != D->getCanonicalDecl()) { 8706 DSAStack->resetPossibleLoopCounter(); 8707 if (auto *Var = dyn_cast_or_null<VarDecl>(LD)) 8708 MarkDeclarationsReferencedInExpr( 8709 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var), 8710 Var->getType().getNonLValueExprType(Context), 8711 ForLoc, /*RefersToCapture=*/true)); 8712 } 8713 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 8714 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables 8715 // Referenced in a Construct, C/C++]. The loop iteration variable in the 8716 // associated for-loop of a simd construct with just one associated 8717 // for-loop may be listed in a linear clause with a constant-linear-step 8718 // that is the increment of the associated for-loop. The loop iteration 8719 // variable(s) in the associated for-loop(s) of a for or parallel for 8720 // construct may be listed in a private or lastprivate clause. 8721 DSAStackTy::DSAVarData DVar = 8722 DSAStack->getTopDSA(D, /*FromParent=*/false); 8723 // If LoopVarRefExpr is nullptr it means the corresponding loop variable 8724 // is declared in the loop and it is predetermined as a private. 8725 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr(); 8726 OpenMPClauseKind PredeterminedCKind = 8727 isOpenMPSimdDirective(DKind) 8728 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear) 8729 : OMPC_private; 8730 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 8731 DVar.CKind != PredeterminedCKind && DVar.RefExpr && 8732 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate && 8733 DVar.CKind != OMPC_private))) || 8734 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 8735 DKind == OMPD_master_taskloop || 8736 DKind == OMPD_parallel_master_taskloop || 8737 isOpenMPDistributeDirective(DKind)) && 8738 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 8739 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 8740 (DVar.CKind != OMPC_private || DVar.RefExpr)) { 8741 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa) 8742 << getOpenMPClauseName(DVar.CKind) 8743 << getOpenMPDirectiveName(DKind) 8744 << getOpenMPClauseName(PredeterminedCKind); 8745 if (DVar.RefExpr == nullptr) 8746 DVar.CKind = PredeterminedCKind; 8747 reportOriginalDsa(*this, DSAStack, D, DVar, 8748 /*IsLoopIterVar=*/true); 8749 } else if (LoopDeclRefExpr) { 8750 // Make the loop iteration variable private (for worksharing 8751 // constructs), linear (for simd directives with the only one 8752 // associated loop) or lastprivate (for simd directives with several 8753 // collapsed or ordered loops). 8754 if (DVar.CKind == OMPC_unknown) 8755 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind, 8756 PrivateRef); 8757 } 8758 } 8759 } 8760 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 8761 } 8762 } 8763 8764 /// Called on a for stmt to check and extract its iteration space 8765 /// for further processing (such as collapsing). 8766 static bool checkOpenMPIterationSpace( 8767 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 8768 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 8769 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr, 8770 Expr *OrderedLoopCountExpr, 8771 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 8772 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces, 8773 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8774 bool SupportsNonRectangular = !isOpenMPLoopTransformationDirective(DKind); 8775 // OpenMP [2.9.1, Canonical Loop Form] 8776 // for (init-expr; test-expr; incr-expr) structured-block 8777 // for (range-decl: range-expr) structured-block 8778 if (auto *CanonLoop = dyn_cast_or_null<OMPCanonicalLoop>(S)) 8779 S = CanonLoop->getLoopStmt(); 8780 auto *For = dyn_cast_or_null<ForStmt>(S); 8781 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S); 8782 // Ranged for is supported only in OpenMP 5.0. 8783 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) { 8784 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for) 8785 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 8786 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount 8787 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 8788 if (TotalNestedLoopCount > 1) { 8789 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 8790 SemaRef.Diag(DSA.getConstructLoc(), 8791 diag::note_omp_collapse_ordered_expr) 8792 << 2 << CollapseLoopCountExpr->getSourceRange() 8793 << OrderedLoopCountExpr->getSourceRange(); 8794 else if (CollapseLoopCountExpr) 8795 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 8796 diag::note_omp_collapse_ordered_expr) 8797 << 0 << CollapseLoopCountExpr->getSourceRange(); 8798 else 8799 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 8800 diag::note_omp_collapse_ordered_expr) 8801 << 1 << OrderedLoopCountExpr->getSourceRange(); 8802 } 8803 return true; 8804 } 8805 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) && 8806 "No loop body."); 8807 8808 OpenMPIterationSpaceChecker ISC(SemaRef, SupportsNonRectangular, DSA, 8809 For ? For->getForLoc() : CXXFor->getForLoc()); 8810 8811 // Check init. 8812 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt(); 8813 if (ISC.checkAndSetInit(Init)) 8814 return true; 8815 8816 bool HasErrors = false; 8817 8818 // Check loop variable's type. 8819 if (ValueDecl *LCDecl = ISC.getLoopDecl()) { 8820 // OpenMP [2.6, Canonical Loop Form] 8821 // Var is one of the following: 8822 // A variable of signed or unsigned integer type. 8823 // For C++, a variable of a random access iterator type. 8824 // For C, a variable of a pointer type. 8825 QualType VarType = LCDecl->getType().getNonReferenceType(); 8826 if (!VarType->isDependentType() && !VarType->isIntegerType() && 8827 !VarType->isPointerType() && 8828 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 8829 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type) 8830 << SemaRef.getLangOpts().CPlusPlus; 8831 HasErrors = true; 8832 } 8833 8834 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 8835 // a Construct 8836 // The loop iteration variable(s) in the associated for-loop(s) of a for or 8837 // parallel for construct is (are) private. 8838 // The loop iteration variable in the associated for-loop of a simd 8839 // construct with just one associated for-loop is linear with a 8840 // constant-linear-step that is the increment of the associated for-loop. 8841 // Exclude loop var from the list of variables with implicitly defined data 8842 // sharing attributes. 8843 VarsWithImplicitDSA.erase(LCDecl); 8844 8845 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 8846 8847 // Check test-expr. 8848 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond()); 8849 8850 // Check incr-expr. 8851 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc()); 8852 } 8853 8854 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 8855 return HasErrors; 8856 8857 // Build the loop's iteration space representation. 8858 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond( 8859 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures); 8860 ResultIterSpaces[CurrentNestedLoopCount].NumIterations = 8861 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces, 8862 (isOpenMPWorksharingDirective(DKind) || 8863 isOpenMPGenericLoopDirective(DKind) || 8864 isOpenMPTaskLoopDirective(DKind) || 8865 isOpenMPDistributeDirective(DKind) || 8866 isOpenMPLoopTransformationDirective(DKind)), 8867 Captures); 8868 ResultIterSpaces[CurrentNestedLoopCount].CounterVar = 8869 ISC.buildCounterVar(Captures, DSA); 8870 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar = 8871 ISC.buildPrivateCounterVar(); 8872 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit(); 8873 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep(); 8874 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange(); 8875 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange = 8876 ISC.getConditionSrcRange(); 8877 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange = 8878 ISC.getIncrementSrcRange(); 8879 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep(); 8880 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare = 8881 ISC.isStrictTestOp(); 8882 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue, 8883 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) = 8884 ISC.buildMinMaxValues(DSA.getCurScope(), Captures); 8885 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition = 8886 ISC.buildFinalCondition(DSA.getCurScope()); 8887 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB = 8888 ISC.doesInitDependOnLC(); 8889 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB = 8890 ISC.doesCondDependOnLC(); 8891 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx = 8892 ISC.getLoopDependentIdx(); 8893 8894 HasErrors |= 8895 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr || 8896 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr || 8897 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr || 8898 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr || 8899 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr || 8900 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr); 8901 if (!HasErrors && DSA.isOrderedRegion()) { 8902 if (DSA.getOrderedRegionParam().second->getNumForLoops()) { 8903 if (CurrentNestedLoopCount < 8904 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) { 8905 DSA.getOrderedRegionParam().second->setLoopNumIterations( 8906 CurrentNestedLoopCount, 8907 ResultIterSpaces[CurrentNestedLoopCount].NumIterations); 8908 DSA.getOrderedRegionParam().second->setLoopCounter( 8909 CurrentNestedLoopCount, 8910 ResultIterSpaces[CurrentNestedLoopCount].CounterVar); 8911 } 8912 } 8913 for (auto &Pair : DSA.getDoacrossDependClauses()) { 8914 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) { 8915 // Erroneous case - clause has some problems. 8916 continue; 8917 } 8918 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink && 8919 Pair.second.size() <= CurrentNestedLoopCount) { 8920 // Erroneous case - clause has some problems. 8921 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr); 8922 continue; 8923 } 8924 Expr *CntValue; 8925 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 8926 CntValue = ISC.buildOrderedLoopData( 8927 DSA.getCurScope(), 8928 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures, 8929 Pair.first->getDependencyLoc()); 8930 else 8931 CntValue = ISC.buildOrderedLoopData( 8932 DSA.getCurScope(), 8933 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures, 8934 Pair.first->getDependencyLoc(), 8935 Pair.second[CurrentNestedLoopCount].first, 8936 Pair.second[CurrentNestedLoopCount].second); 8937 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue); 8938 } 8939 } 8940 8941 return HasErrors; 8942 } 8943 8944 /// Build 'VarRef = Start. 8945 static ExprResult 8946 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 8947 ExprResult Start, bool IsNonRectangularLB, 8948 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 8949 // Build 'VarRef = Start. 8950 ExprResult NewStart = IsNonRectangularLB 8951 ? Start.get() 8952 : tryBuildCapture(SemaRef, Start.get(), Captures); 8953 if (!NewStart.isUsable()) 8954 return ExprError(); 8955 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 8956 VarRef.get()->getType())) { 8957 NewStart = SemaRef.PerformImplicitConversion( 8958 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 8959 /*AllowExplicit=*/true); 8960 if (!NewStart.isUsable()) 8961 return ExprError(); 8962 } 8963 8964 ExprResult Init = 8965 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 8966 return Init; 8967 } 8968 8969 /// Build 'VarRef = Start + Iter * Step'. 8970 static ExprResult buildCounterUpdate( 8971 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 8972 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract, 8973 bool IsNonRectangularLB, 8974 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) { 8975 // Add parentheses (for debugging purposes only). 8976 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 8977 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 8978 !Step.isUsable()) 8979 return ExprError(); 8980 8981 ExprResult NewStep = Step; 8982 if (Captures) 8983 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 8984 if (NewStep.isInvalid()) 8985 return ExprError(); 8986 ExprResult Update = 8987 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 8988 if (!Update.isUsable()) 8989 return ExprError(); 8990 8991 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 8992 // 'VarRef = Start (+|-) Iter * Step'. 8993 if (!Start.isUsable()) 8994 return ExprError(); 8995 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get()); 8996 if (!NewStart.isUsable()) 8997 return ExprError(); 8998 if (Captures && !IsNonRectangularLB) 8999 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 9000 if (NewStart.isInvalid()) 9001 return ExprError(); 9002 9003 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 9004 ExprResult SavedUpdate = Update; 9005 ExprResult UpdateVal; 9006 if (VarRef.get()->getType()->isOverloadableType() || 9007 NewStart.get()->getType()->isOverloadableType() || 9008 Update.get()->getType()->isOverloadableType()) { 9009 Sema::TentativeAnalysisScope Trap(SemaRef); 9010 9011 Update = 9012 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 9013 if (Update.isUsable()) { 9014 UpdateVal = 9015 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 9016 VarRef.get(), SavedUpdate.get()); 9017 if (UpdateVal.isUsable()) { 9018 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 9019 UpdateVal.get()); 9020 } 9021 } 9022 } 9023 9024 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 9025 if (!Update.isUsable() || !UpdateVal.isUsable()) { 9026 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 9027 NewStart.get(), SavedUpdate.get()); 9028 if (!Update.isUsable()) 9029 return ExprError(); 9030 9031 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 9032 VarRef.get()->getType())) { 9033 Update = SemaRef.PerformImplicitConversion( 9034 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 9035 if (!Update.isUsable()) 9036 return ExprError(); 9037 } 9038 9039 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 9040 } 9041 return Update; 9042 } 9043 9044 /// Convert integer expression \a E to make it have at least \a Bits 9045 /// bits. 9046 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 9047 if (E == nullptr) 9048 return ExprError(); 9049 ASTContext &C = SemaRef.Context; 9050 QualType OldType = E->getType(); 9051 unsigned HasBits = C.getTypeSize(OldType); 9052 if (HasBits >= Bits) 9053 return ExprResult(E); 9054 // OK to convert to signed, because new type has more bits than old. 9055 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 9056 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 9057 true); 9058 } 9059 9060 /// Check if the given expression \a E is a constant integer that fits 9061 /// into \a Bits bits. 9062 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) { 9063 if (E == nullptr) 9064 return false; 9065 if (Optional<llvm::APSInt> Result = 9066 E->getIntegerConstantExpr(SemaRef.Context)) 9067 return Signed ? Result->isSignedIntN(Bits) : Result->isIntN(Bits); 9068 return false; 9069 } 9070 9071 /// Build preinits statement for the given declarations. 9072 static Stmt *buildPreInits(ASTContext &Context, 9073 MutableArrayRef<Decl *> PreInits) { 9074 if (!PreInits.empty()) { 9075 return new (Context) DeclStmt( 9076 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 9077 SourceLocation(), SourceLocation()); 9078 } 9079 return nullptr; 9080 } 9081 9082 /// Build preinits statement for the given declarations. 9083 static Stmt * 9084 buildPreInits(ASTContext &Context, 9085 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 9086 if (!Captures.empty()) { 9087 SmallVector<Decl *, 16> PreInits; 9088 for (const auto &Pair : Captures) 9089 PreInits.push_back(Pair.second->getDecl()); 9090 return buildPreInits(Context, PreInits); 9091 } 9092 return nullptr; 9093 } 9094 9095 /// Build postupdate expression for the given list of postupdates expressions. 9096 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 9097 Expr *PostUpdate = nullptr; 9098 if (!PostUpdates.empty()) { 9099 for (Expr *E : PostUpdates) { 9100 Expr *ConvE = S.BuildCStyleCastExpr( 9101 E->getExprLoc(), 9102 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 9103 E->getExprLoc(), E) 9104 .get(); 9105 PostUpdate = PostUpdate 9106 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 9107 PostUpdate, ConvE) 9108 .get() 9109 : ConvE; 9110 } 9111 } 9112 return PostUpdate; 9113 } 9114 9115 /// Called on a for stmt to check itself and nested loops (if any). 9116 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 9117 /// number of collapsed loops otherwise. 9118 static unsigned 9119 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 9120 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 9121 DSAStackTy &DSA, 9122 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 9123 OMPLoopBasedDirective::HelperExprs &Built) { 9124 unsigned NestedLoopCount = 1; 9125 bool SupportsNonPerfectlyNested = (SemaRef.LangOpts.OpenMP >= 50) && 9126 !isOpenMPLoopTransformationDirective(DKind); 9127 9128 if (CollapseLoopCountExpr) { 9129 // Found 'collapse' clause - calculate collapse number. 9130 Expr::EvalResult Result; 9131 if (!CollapseLoopCountExpr->isValueDependent() && 9132 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 9133 NestedLoopCount = Result.Val.getInt().getLimitedValue(); 9134 } else { 9135 Built.clear(/*Size=*/1); 9136 return 1; 9137 } 9138 } 9139 unsigned OrderedLoopCount = 1; 9140 if (OrderedLoopCountExpr) { 9141 // Found 'ordered' clause - calculate collapse number. 9142 Expr::EvalResult EVResult; 9143 if (!OrderedLoopCountExpr->isValueDependent() && 9144 OrderedLoopCountExpr->EvaluateAsInt(EVResult, 9145 SemaRef.getASTContext())) { 9146 llvm::APSInt Result = EVResult.Val.getInt(); 9147 if (Result.getLimitedValue() < NestedLoopCount) { 9148 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 9149 diag::err_omp_wrong_ordered_loop_count) 9150 << OrderedLoopCountExpr->getSourceRange(); 9151 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 9152 diag::note_collapse_loop_count) 9153 << CollapseLoopCountExpr->getSourceRange(); 9154 } 9155 OrderedLoopCount = Result.getLimitedValue(); 9156 } else { 9157 Built.clear(/*Size=*/1); 9158 return 1; 9159 } 9160 } 9161 // This is helper routine for loop directives (e.g., 'for', 'simd', 9162 // 'for simd', etc.). 9163 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 9164 unsigned NumLoops = std::max(OrderedLoopCount, NestedLoopCount); 9165 SmallVector<LoopIterationSpace, 4> IterSpaces(NumLoops); 9166 if (!OMPLoopBasedDirective::doForAllLoops( 9167 AStmt->IgnoreContainers(!isOpenMPLoopTransformationDirective(DKind)), 9168 SupportsNonPerfectlyNested, NumLoops, 9169 [DKind, &SemaRef, &DSA, NumLoops, NestedLoopCount, 9170 CollapseLoopCountExpr, OrderedLoopCountExpr, &VarsWithImplicitDSA, 9171 &IterSpaces, &Captures](unsigned Cnt, Stmt *CurStmt) { 9172 if (checkOpenMPIterationSpace( 9173 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 9174 NumLoops, CollapseLoopCountExpr, OrderedLoopCountExpr, 9175 VarsWithImplicitDSA, IterSpaces, Captures)) 9176 return true; 9177 if (Cnt > 0 && Cnt >= NestedLoopCount && 9178 IterSpaces[Cnt].CounterVar) { 9179 // Handle initialization of captured loop iterator variables. 9180 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar); 9181 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) { 9182 Captures[DRE] = DRE; 9183 } 9184 } 9185 return false; 9186 }, 9187 [&SemaRef, &Captures](OMPLoopTransformationDirective *Transform) { 9188 Stmt *DependentPreInits = Transform->getPreInits(); 9189 if (!DependentPreInits) 9190 return; 9191 for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) { 9192 auto *D = cast<VarDecl>(C); 9193 DeclRefExpr *Ref = buildDeclRefExpr(SemaRef, D, D->getType(), 9194 Transform->getBeginLoc()); 9195 Captures[Ref] = Ref; 9196 } 9197 })) 9198 return 0; 9199 9200 Built.clear(/* size */ NestedLoopCount); 9201 9202 if (SemaRef.CurContext->isDependentContext()) 9203 return NestedLoopCount; 9204 9205 // An example of what is generated for the following code: 9206 // 9207 // #pragma omp simd collapse(2) ordered(2) 9208 // for (i = 0; i < NI; ++i) 9209 // for (k = 0; k < NK; ++k) 9210 // for (j = J0; j < NJ; j+=2) { 9211 // <loop body> 9212 // } 9213 // 9214 // We generate the code below. 9215 // Note: the loop body may be outlined in CodeGen. 9216 // Note: some counters may be C++ classes, operator- is used to find number of 9217 // iterations and operator+= to calculate counter value. 9218 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 9219 // or i64 is currently supported). 9220 // 9221 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 9222 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 9223 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 9224 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 9225 // // similar updates for vars in clauses (e.g. 'linear') 9226 // <loop body (using local i and j)> 9227 // } 9228 // i = NI; // assign final values of counters 9229 // j = NJ; 9230 // 9231 9232 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 9233 // the iteration counts of the collapsed for loops. 9234 // Precondition tests if there is at least one iteration (all conditions are 9235 // true). 9236 auto PreCond = ExprResult(IterSpaces[0].PreCond); 9237 Expr *N0 = IterSpaces[0].NumIterations; 9238 ExprResult LastIteration32 = 9239 widenIterationCount(/*Bits=*/32, 9240 SemaRef 9241 .PerformImplicitConversion( 9242 N0->IgnoreImpCasts(), N0->getType(), 9243 Sema::AA_Converting, /*AllowExplicit=*/true) 9244 .get(), 9245 SemaRef); 9246 ExprResult LastIteration64 = widenIterationCount( 9247 /*Bits=*/64, 9248 SemaRef 9249 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(), 9250 Sema::AA_Converting, 9251 /*AllowExplicit=*/true) 9252 .get(), 9253 SemaRef); 9254 9255 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 9256 return NestedLoopCount; 9257 9258 ASTContext &C = SemaRef.Context; 9259 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 9260 9261 Scope *CurScope = DSA.getCurScope(); 9262 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 9263 if (PreCond.isUsable()) { 9264 PreCond = 9265 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 9266 PreCond.get(), IterSpaces[Cnt].PreCond); 9267 } 9268 Expr *N = IterSpaces[Cnt].NumIterations; 9269 SourceLocation Loc = N->getExprLoc(); 9270 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 9271 if (LastIteration32.isUsable()) 9272 LastIteration32 = SemaRef.BuildBinOp( 9273 CurScope, Loc, BO_Mul, LastIteration32.get(), 9274 SemaRef 9275 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 9276 Sema::AA_Converting, 9277 /*AllowExplicit=*/true) 9278 .get()); 9279 if (LastIteration64.isUsable()) 9280 LastIteration64 = SemaRef.BuildBinOp( 9281 CurScope, Loc, BO_Mul, LastIteration64.get(), 9282 SemaRef 9283 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 9284 Sema::AA_Converting, 9285 /*AllowExplicit=*/true) 9286 .get()); 9287 } 9288 9289 // Choose either the 32-bit or 64-bit version. 9290 ExprResult LastIteration = LastIteration64; 9291 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse || 9292 (LastIteration32.isUsable() && 9293 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 9294 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 9295 fitsInto( 9296 /*Bits=*/32, 9297 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 9298 LastIteration64.get(), SemaRef)))) 9299 LastIteration = LastIteration32; 9300 QualType VType = LastIteration.get()->getType(); 9301 QualType RealVType = VType; 9302 QualType StrideVType = VType; 9303 if (isOpenMPTaskLoopDirective(DKind)) { 9304 VType = 9305 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 9306 StrideVType = 9307 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 9308 } 9309 9310 if (!LastIteration.isUsable()) 9311 return 0; 9312 9313 // Save the number of iterations. 9314 ExprResult NumIterations = LastIteration; 9315 { 9316 LastIteration = SemaRef.BuildBinOp( 9317 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 9318 LastIteration.get(), 9319 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 9320 if (!LastIteration.isUsable()) 9321 return 0; 9322 } 9323 9324 // Calculate the last iteration number beforehand instead of doing this on 9325 // each iteration. Do not do this if the number of iterations may be kfold-ed. 9326 bool IsConstant = LastIteration.get()->isIntegerConstantExpr(SemaRef.Context); 9327 ExprResult CalcLastIteration; 9328 if (!IsConstant) { 9329 ExprResult SaveRef = 9330 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 9331 LastIteration = SaveRef; 9332 9333 // Prepare SaveRef + 1. 9334 NumIterations = SemaRef.BuildBinOp( 9335 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 9336 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 9337 if (!NumIterations.isUsable()) 9338 return 0; 9339 } 9340 9341 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 9342 9343 // Build variables passed into runtime, necessary for worksharing directives. 9344 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 9345 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 9346 isOpenMPDistributeDirective(DKind) || 9347 isOpenMPGenericLoopDirective(DKind) || 9348 isOpenMPLoopTransformationDirective(DKind)) { 9349 // Lower bound variable, initialized with zero. 9350 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 9351 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 9352 SemaRef.AddInitializerToDecl(LBDecl, 9353 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 9354 /*DirectInit*/ false); 9355 9356 // Upper bound variable, initialized with last iteration number. 9357 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 9358 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 9359 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 9360 /*DirectInit*/ false); 9361 9362 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 9363 // This will be used to implement clause 'lastprivate'. 9364 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 9365 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 9366 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 9367 SemaRef.AddInitializerToDecl(ILDecl, 9368 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 9369 /*DirectInit*/ false); 9370 9371 // Stride variable returned by runtime (we initialize it to 1 by default). 9372 VarDecl *STDecl = 9373 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 9374 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 9375 SemaRef.AddInitializerToDecl(STDecl, 9376 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 9377 /*DirectInit*/ false); 9378 9379 // Build expression: UB = min(UB, LastIteration) 9380 // It is necessary for CodeGen of directives with static scheduling. 9381 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 9382 UB.get(), LastIteration.get()); 9383 ExprResult CondOp = SemaRef.ActOnConditionalOp( 9384 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(), 9385 LastIteration.get(), UB.get()); 9386 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 9387 CondOp.get()); 9388 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false); 9389 9390 // If we have a combined directive that combines 'distribute', 'for' or 9391 // 'simd' we need to be able to access the bounds of the schedule of the 9392 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 9393 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 9394 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9395 // Lower bound variable, initialized with zero. 9396 VarDecl *CombLBDecl = 9397 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 9398 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 9399 SemaRef.AddInitializerToDecl( 9400 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 9401 /*DirectInit*/ false); 9402 9403 // Upper bound variable, initialized with last iteration number. 9404 VarDecl *CombUBDecl = 9405 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 9406 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 9407 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 9408 /*DirectInit*/ false); 9409 9410 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 9411 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 9412 ExprResult CombCondOp = 9413 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 9414 LastIteration.get(), CombUB.get()); 9415 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 9416 CombCondOp.get()); 9417 CombEUB = 9418 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false); 9419 9420 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 9421 // We expect to have at least 2 more parameters than the 'parallel' 9422 // directive does - the lower and upper bounds of the previous schedule. 9423 assert(CD->getNumParams() >= 4 && 9424 "Unexpected number of parameters in loop combined directive"); 9425 9426 // Set the proper type for the bounds given what we learned from the 9427 // enclosed loops. 9428 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 9429 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 9430 9431 // Previous lower and upper bounds are obtained from the region 9432 // parameters. 9433 PrevLB = 9434 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 9435 PrevUB = 9436 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 9437 } 9438 } 9439 9440 // Build the iteration variable and its initialization before loop. 9441 ExprResult IV; 9442 ExprResult Init, CombInit; 9443 { 9444 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 9445 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 9446 Expr *RHS = (isOpenMPWorksharingDirective(DKind) || 9447 isOpenMPGenericLoopDirective(DKind) || 9448 isOpenMPTaskLoopDirective(DKind) || 9449 isOpenMPDistributeDirective(DKind) || 9450 isOpenMPLoopTransformationDirective(DKind)) 9451 ? LB.get() 9452 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 9453 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 9454 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false); 9455 9456 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9457 Expr *CombRHS = 9458 (isOpenMPWorksharingDirective(DKind) || 9459 isOpenMPGenericLoopDirective(DKind) || 9460 isOpenMPTaskLoopDirective(DKind) || 9461 isOpenMPDistributeDirective(DKind)) 9462 ? CombLB.get() 9463 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 9464 CombInit = 9465 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 9466 CombInit = 9467 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false); 9468 } 9469 } 9470 9471 bool UseStrictCompare = 9472 RealVType->hasUnsignedIntegerRepresentation() && 9473 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) { 9474 return LIS.IsStrictCompare; 9475 }); 9476 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for 9477 // unsigned IV)) for worksharing loops. 9478 SourceLocation CondLoc = AStmt->getBeginLoc(); 9479 Expr *BoundUB = UB.get(); 9480 if (UseStrictCompare) { 9481 BoundUB = 9482 SemaRef 9483 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB, 9484 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 9485 .get(); 9486 BoundUB = 9487 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get(); 9488 } 9489 ExprResult Cond = 9490 (isOpenMPWorksharingDirective(DKind) || 9491 isOpenMPGenericLoopDirective(DKind) || 9492 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind) || 9493 isOpenMPLoopTransformationDirective(DKind)) 9494 ? SemaRef.BuildBinOp(CurScope, CondLoc, 9495 UseStrictCompare ? BO_LT : BO_LE, IV.get(), 9496 BoundUB) 9497 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 9498 NumIterations.get()); 9499 ExprResult CombDistCond; 9500 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9501 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 9502 NumIterations.get()); 9503 } 9504 9505 ExprResult CombCond; 9506 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9507 Expr *BoundCombUB = CombUB.get(); 9508 if (UseStrictCompare) { 9509 BoundCombUB = 9510 SemaRef 9511 .BuildBinOp( 9512 CurScope, CondLoc, BO_Add, BoundCombUB, 9513 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 9514 .get(); 9515 BoundCombUB = 9516 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false) 9517 .get(); 9518 } 9519 CombCond = 9520 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 9521 IV.get(), BoundCombUB); 9522 } 9523 // Loop increment (IV = IV + 1) 9524 SourceLocation IncLoc = AStmt->getBeginLoc(); 9525 ExprResult Inc = 9526 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 9527 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 9528 if (!Inc.isUsable()) 9529 return 0; 9530 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 9531 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false); 9532 if (!Inc.isUsable()) 9533 return 0; 9534 9535 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 9536 // Used for directives with static scheduling. 9537 // In combined construct, add combined version that use CombLB and CombUB 9538 // base variables for the update 9539 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 9540 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 9541 isOpenMPGenericLoopDirective(DKind) || 9542 isOpenMPDistributeDirective(DKind) || 9543 isOpenMPLoopTransformationDirective(DKind)) { 9544 // LB + ST 9545 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 9546 if (!NextLB.isUsable()) 9547 return 0; 9548 // LB = LB + ST 9549 NextLB = 9550 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 9551 NextLB = 9552 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false); 9553 if (!NextLB.isUsable()) 9554 return 0; 9555 // UB + ST 9556 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 9557 if (!NextUB.isUsable()) 9558 return 0; 9559 // UB = UB + ST 9560 NextUB = 9561 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 9562 NextUB = 9563 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false); 9564 if (!NextUB.isUsable()) 9565 return 0; 9566 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9567 CombNextLB = 9568 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 9569 if (!NextLB.isUsable()) 9570 return 0; 9571 // LB = LB + ST 9572 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 9573 CombNextLB.get()); 9574 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(), 9575 /*DiscardedValue*/ false); 9576 if (!CombNextLB.isUsable()) 9577 return 0; 9578 // UB + ST 9579 CombNextUB = 9580 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 9581 if (!CombNextUB.isUsable()) 9582 return 0; 9583 // UB = UB + ST 9584 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 9585 CombNextUB.get()); 9586 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(), 9587 /*DiscardedValue*/ false); 9588 if (!CombNextUB.isUsable()) 9589 return 0; 9590 } 9591 } 9592 9593 // Create increment expression for distribute loop when combined in a same 9594 // directive with for as IV = IV + ST; ensure upper bound expression based 9595 // on PrevUB instead of NumIterations - used to implement 'for' when found 9596 // in combination with 'distribute', like in 'distribute parallel for' 9597 SourceLocation DistIncLoc = AStmt->getBeginLoc(); 9598 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond; 9599 if (isOpenMPLoopBoundSharingDirective(DKind)) { 9600 DistCond = SemaRef.BuildBinOp( 9601 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB); 9602 assert(DistCond.isUsable() && "distribute cond expr was not built"); 9603 9604 DistInc = 9605 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 9606 assert(DistInc.isUsable() && "distribute inc expr was not built"); 9607 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 9608 DistInc.get()); 9609 DistInc = 9610 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false); 9611 assert(DistInc.isUsable() && "distribute inc expr was not built"); 9612 9613 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 9614 // construct 9615 ExprResult NewPrevUB = PrevUB; 9616 SourceLocation DistEUBLoc = AStmt->getBeginLoc(); 9617 if (!SemaRef.Context.hasSameType(UB.get()->getType(), 9618 PrevUB.get()->getType())) { 9619 NewPrevUB = SemaRef.BuildCStyleCastExpr( 9620 DistEUBLoc, 9621 SemaRef.Context.getTrivialTypeSourceInfo(UB.get()->getType()), 9622 DistEUBLoc, NewPrevUB.get()); 9623 if (!NewPrevUB.isUsable()) 9624 return 0; 9625 } 9626 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, 9627 UB.get(), NewPrevUB.get()); 9628 ExprResult CondOp = SemaRef.ActOnConditionalOp( 9629 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), NewPrevUB.get(), UB.get()); 9630 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 9631 CondOp.get()); 9632 PrevEUB = 9633 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false); 9634 9635 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in 9636 // parallel for is in combination with a distribute directive with 9637 // schedule(static, 1) 9638 Expr *BoundPrevUB = PrevUB.get(); 9639 if (UseStrictCompare) { 9640 BoundPrevUB = 9641 SemaRef 9642 .BuildBinOp( 9643 CurScope, CondLoc, BO_Add, BoundPrevUB, 9644 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 9645 .get(); 9646 BoundPrevUB = 9647 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false) 9648 .get(); 9649 } 9650 ParForInDistCond = 9651 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 9652 IV.get(), BoundPrevUB); 9653 } 9654 9655 // Build updates and final values of the loop counters. 9656 bool HasErrors = false; 9657 Built.Counters.resize(NestedLoopCount); 9658 Built.Inits.resize(NestedLoopCount); 9659 Built.Updates.resize(NestedLoopCount); 9660 Built.Finals.resize(NestedLoopCount); 9661 Built.DependentCounters.resize(NestedLoopCount); 9662 Built.DependentInits.resize(NestedLoopCount); 9663 Built.FinalsConditions.resize(NestedLoopCount); 9664 { 9665 // We implement the following algorithm for obtaining the 9666 // original loop iteration variable values based on the 9667 // value of the collapsed loop iteration variable IV. 9668 // 9669 // Let n+1 be the number of collapsed loops in the nest. 9670 // Iteration variables (I0, I1, .... In) 9671 // Iteration counts (N0, N1, ... Nn) 9672 // 9673 // Acc = IV; 9674 // 9675 // To compute Ik for loop k, 0 <= k <= n, generate: 9676 // Prod = N(k+1) * N(k+2) * ... * Nn; 9677 // Ik = Acc / Prod; 9678 // Acc -= Ik * Prod; 9679 // 9680 ExprResult Acc = IV; 9681 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 9682 LoopIterationSpace &IS = IterSpaces[Cnt]; 9683 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 9684 ExprResult Iter; 9685 9686 // Compute prod 9687 ExprResult Prod = 9688 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 9689 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K) 9690 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(), 9691 IterSpaces[K].NumIterations); 9692 9693 // Iter = Acc / Prod 9694 // If there is at least one more inner loop to avoid 9695 // multiplication by 1. 9696 if (Cnt + 1 < NestedLoopCount) 9697 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, 9698 Acc.get(), Prod.get()); 9699 else 9700 Iter = Acc; 9701 if (!Iter.isUsable()) { 9702 HasErrors = true; 9703 break; 9704 } 9705 9706 // Update Acc: 9707 // Acc -= Iter * Prod 9708 // Check if there is at least one more inner loop to avoid 9709 // multiplication by 1. 9710 if (Cnt + 1 < NestedLoopCount) 9711 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, 9712 Iter.get(), Prod.get()); 9713 else 9714 Prod = Iter; 9715 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, 9716 Acc.get(), Prod.get()); 9717 9718 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 9719 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 9720 DeclRefExpr *CounterVar = buildDeclRefExpr( 9721 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(), 9722 /*RefersToCapture=*/true); 9723 ExprResult Init = 9724 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 9725 IS.CounterInit, IS.IsNonRectangularLB, Captures); 9726 if (!Init.isUsable()) { 9727 HasErrors = true; 9728 break; 9729 } 9730 ExprResult Update = buildCounterUpdate( 9731 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 9732 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures); 9733 if (!Update.isUsable()) { 9734 HasErrors = true; 9735 break; 9736 } 9737 9738 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 9739 ExprResult Final = 9740 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar, 9741 IS.CounterInit, IS.NumIterations, IS.CounterStep, 9742 IS.Subtract, IS.IsNonRectangularLB, &Captures); 9743 if (!Final.isUsable()) { 9744 HasErrors = true; 9745 break; 9746 } 9747 9748 if (!Update.isUsable() || !Final.isUsable()) { 9749 HasErrors = true; 9750 break; 9751 } 9752 // Save results 9753 Built.Counters[Cnt] = IS.CounterVar; 9754 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 9755 Built.Inits[Cnt] = Init.get(); 9756 Built.Updates[Cnt] = Update.get(); 9757 Built.Finals[Cnt] = Final.get(); 9758 Built.DependentCounters[Cnt] = nullptr; 9759 Built.DependentInits[Cnt] = nullptr; 9760 Built.FinalsConditions[Cnt] = nullptr; 9761 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) { 9762 Built.DependentCounters[Cnt] = 9763 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx]; 9764 Built.DependentInits[Cnt] = 9765 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx]; 9766 Built.FinalsConditions[Cnt] = IS.FinalCondition; 9767 } 9768 } 9769 } 9770 9771 if (HasErrors) 9772 return 0; 9773 9774 // Save results 9775 Built.IterationVarRef = IV.get(); 9776 Built.LastIteration = LastIteration.get(); 9777 Built.NumIterations = NumIterations.get(); 9778 Built.CalcLastIteration = SemaRef 9779 .ActOnFinishFullExpr(CalcLastIteration.get(), 9780 /*DiscardedValue=*/false) 9781 .get(); 9782 Built.PreCond = PreCond.get(); 9783 Built.PreInits = buildPreInits(C, Captures); 9784 Built.Cond = Cond.get(); 9785 Built.Init = Init.get(); 9786 Built.Inc = Inc.get(); 9787 Built.LB = LB.get(); 9788 Built.UB = UB.get(); 9789 Built.IL = IL.get(); 9790 Built.ST = ST.get(); 9791 Built.EUB = EUB.get(); 9792 Built.NLB = NextLB.get(); 9793 Built.NUB = NextUB.get(); 9794 Built.PrevLB = PrevLB.get(); 9795 Built.PrevUB = PrevUB.get(); 9796 Built.DistInc = DistInc.get(); 9797 Built.PrevEUB = PrevEUB.get(); 9798 Built.DistCombinedFields.LB = CombLB.get(); 9799 Built.DistCombinedFields.UB = CombUB.get(); 9800 Built.DistCombinedFields.EUB = CombEUB.get(); 9801 Built.DistCombinedFields.Init = CombInit.get(); 9802 Built.DistCombinedFields.Cond = CombCond.get(); 9803 Built.DistCombinedFields.NLB = CombNextLB.get(); 9804 Built.DistCombinedFields.NUB = CombNextUB.get(); 9805 Built.DistCombinedFields.DistCond = CombDistCond.get(); 9806 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get(); 9807 9808 return NestedLoopCount; 9809 } 9810 9811 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 9812 auto CollapseClauses = 9813 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 9814 if (CollapseClauses.begin() != CollapseClauses.end()) 9815 return (*CollapseClauses.begin())->getNumForLoops(); 9816 return nullptr; 9817 } 9818 9819 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 9820 auto OrderedClauses = 9821 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 9822 if (OrderedClauses.begin() != OrderedClauses.end()) 9823 return (*OrderedClauses.begin())->getNumForLoops(); 9824 return nullptr; 9825 } 9826 9827 static bool checkSimdlenSafelenSpecified(Sema &S, 9828 const ArrayRef<OMPClause *> Clauses) { 9829 const OMPSafelenClause *Safelen = nullptr; 9830 const OMPSimdlenClause *Simdlen = nullptr; 9831 9832 for (const OMPClause *Clause : Clauses) { 9833 if (Clause->getClauseKind() == OMPC_safelen) 9834 Safelen = cast<OMPSafelenClause>(Clause); 9835 else if (Clause->getClauseKind() == OMPC_simdlen) 9836 Simdlen = cast<OMPSimdlenClause>(Clause); 9837 if (Safelen && Simdlen) 9838 break; 9839 } 9840 9841 if (Simdlen && Safelen) { 9842 const Expr *SimdlenLength = Simdlen->getSimdlen(); 9843 const Expr *SafelenLength = Safelen->getSafelen(); 9844 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 9845 SimdlenLength->isInstantiationDependent() || 9846 SimdlenLength->containsUnexpandedParameterPack()) 9847 return false; 9848 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 9849 SafelenLength->isInstantiationDependent() || 9850 SafelenLength->containsUnexpandedParameterPack()) 9851 return false; 9852 Expr::EvalResult SimdlenResult, SafelenResult; 9853 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context); 9854 SafelenLength->EvaluateAsInt(SafelenResult, S.Context); 9855 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt(); 9856 llvm::APSInt SafelenRes = SafelenResult.Val.getInt(); 9857 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 9858 // If both simdlen and safelen clauses are specified, the value of the 9859 // simdlen parameter must be less than or equal to the value of the safelen 9860 // parameter. 9861 if (SimdlenRes > SafelenRes) { 9862 S.Diag(SimdlenLength->getExprLoc(), 9863 diag::err_omp_wrong_simdlen_safelen_values) 9864 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 9865 return true; 9866 } 9867 } 9868 return false; 9869 } 9870 9871 StmtResult 9872 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 9873 SourceLocation StartLoc, SourceLocation EndLoc, 9874 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9875 if (!AStmt) 9876 return StmtError(); 9877 9878 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9879 OMPLoopBasedDirective::HelperExprs B; 9880 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9881 // define the nested loops number. 9882 unsigned NestedLoopCount = checkOpenMPLoop( 9883 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 9884 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 9885 if (NestedLoopCount == 0) 9886 return StmtError(); 9887 9888 assert((CurContext->isDependentContext() || B.builtAll()) && 9889 "omp simd loop exprs were not built"); 9890 9891 if (!CurContext->isDependentContext()) { 9892 // Finalize the clauses that need pre-built expressions for CodeGen. 9893 for (OMPClause *C : Clauses) { 9894 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9895 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9896 B.NumIterations, *this, CurScope, 9897 DSAStack)) 9898 return StmtError(); 9899 } 9900 } 9901 9902 if (checkSimdlenSafelenSpecified(*this, Clauses)) 9903 return StmtError(); 9904 9905 setFunctionHasBranchProtectedScope(); 9906 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 9907 Clauses, AStmt, B); 9908 } 9909 9910 StmtResult 9911 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 9912 SourceLocation StartLoc, SourceLocation EndLoc, 9913 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9914 if (!AStmt) 9915 return StmtError(); 9916 9917 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9918 OMPLoopBasedDirective::HelperExprs B; 9919 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9920 // define the nested loops number. 9921 unsigned NestedLoopCount = checkOpenMPLoop( 9922 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 9923 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 9924 if (NestedLoopCount == 0) 9925 return StmtError(); 9926 9927 assert((CurContext->isDependentContext() || B.builtAll()) && 9928 "omp for loop exprs were not built"); 9929 9930 if (!CurContext->isDependentContext()) { 9931 // Finalize the clauses that need pre-built expressions for CodeGen. 9932 for (OMPClause *C : Clauses) { 9933 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9934 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9935 B.NumIterations, *this, CurScope, 9936 DSAStack)) 9937 return StmtError(); 9938 } 9939 } 9940 9941 setFunctionHasBranchProtectedScope(); 9942 return OMPForDirective::Create( 9943 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 9944 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 9945 } 9946 9947 StmtResult Sema::ActOnOpenMPForSimdDirective( 9948 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 9949 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 9950 if (!AStmt) 9951 return StmtError(); 9952 9953 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9954 OMPLoopBasedDirective::HelperExprs B; 9955 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 9956 // define the nested loops number. 9957 unsigned NestedLoopCount = 9958 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 9959 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 9960 VarsWithImplicitDSA, B); 9961 if (NestedLoopCount == 0) 9962 return StmtError(); 9963 9964 assert((CurContext->isDependentContext() || B.builtAll()) && 9965 "omp for simd loop exprs were not built"); 9966 9967 if (!CurContext->isDependentContext()) { 9968 // Finalize the clauses that need pre-built expressions for CodeGen. 9969 for (OMPClause *C : Clauses) { 9970 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 9971 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 9972 B.NumIterations, *this, CurScope, 9973 DSAStack)) 9974 return StmtError(); 9975 } 9976 } 9977 9978 if (checkSimdlenSafelenSpecified(*this, Clauses)) 9979 return StmtError(); 9980 9981 setFunctionHasBranchProtectedScope(); 9982 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 9983 Clauses, AStmt, B); 9984 } 9985 9986 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 9987 Stmt *AStmt, 9988 SourceLocation StartLoc, 9989 SourceLocation EndLoc) { 9990 if (!AStmt) 9991 return StmtError(); 9992 9993 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 9994 auto BaseStmt = AStmt; 9995 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 9996 BaseStmt = CS->getCapturedStmt(); 9997 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 9998 auto S = C->children(); 9999 if (S.begin() == S.end()) 10000 return StmtError(); 10001 // All associated statements must be '#pragma omp section' except for 10002 // the first one. 10003 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 10004 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 10005 if (SectionStmt) 10006 Diag(SectionStmt->getBeginLoc(), 10007 diag::err_omp_sections_substmt_not_section); 10008 return StmtError(); 10009 } 10010 cast<OMPSectionDirective>(SectionStmt) 10011 ->setHasCancel(DSAStack->isCancelRegion()); 10012 } 10013 } else { 10014 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt); 10015 return StmtError(); 10016 } 10017 10018 setFunctionHasBranchProtectedScope(); 10019 10020 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 10021 DSAStack->getTaskgroupReductionRef(), 10022 DSAStack->isCancelRegion()); 10023 } 10024 10025 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 10026 SourceLocation StartLoc, 10027 SourceLocation EndLoc) { 10028 if (!AStmt) 10029 return StmtError(); 10030 10031 setFunctionHasBranchProtectedScope(); 10032 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 10033 10034 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 10035 DSAStack->isCancelRegion()); 10036 } 10037 10038 static Expr *getDirectCallExpr(Expr *E) { 10039 E = E->IgnoreParenCasts()->IgnoreImplicit(); 10040 if (auto *CE = dyn_cast<CallExpr>(E)) 10041 if (CE->getDirectCallee()) 10042 return E; 10043 return nullptr; 10044 } 10045 10046 StmtResult Sema::ActOnOpenMPDispatchDirective(ArrayRef<OMPClause *> Clauses, 10047 Stmt *AStmt, 10048 SourceLocation StartLoc, 10049 SourceLocation EndLoc) { 10050 if (!AStmt) 10051 return StmtError(); 10052 10053 Stmt *S = cast<CapturedStmt>(AStmt)->getCapturedStmt(); 10054 10055 // 5.1 OpenMP 10056 // expression-stmt : an expression statement with one of the following forms: 10057 // expression = target-call ( [expression-list] ); 10058 // target-call ( [expression-list] ); 10059 10060 SourceLocation TargetCallLoc; 10061 10062 if (!CurContext->isDependentContext()) { 10063 Expr *TargetCall = nullptr; 10064 10065 auto *E = dyn_cast<Expr>(S); 10066 if (!E) { 10067 Diag(S->getBeginLoc(), diag::err_omp_dispatch_statement_call); 10068 return StmtError(); 10069 } 10070 10071 E = E->IgnoreParenCasts()->IgnoreImplicit(); 10072 10073 if (auto *BO = dyn_cast<BinaryOperator>(E)) { 10074 if (BO->getOpcode() == BO_Assign) 10075 TargetCall = getDirectCallExpr(BO->getRHS()); 10076 } else { 10077 if (auto *COCE = dyn_cast<CXXOperatorCallExpr>(E)) 10078 if (COCE->getOperator() == OO_Equal) 10079 TargetCall = getDirectCallExpr(COCE->getArg(1)); 10080 if (!TargetCall) 10081 TargetCall = getDirectCallExpr(E); 10082 } 10083 if (!TargetCall) { 10084 Diag(E->getBeginLoc(), diag::err_omp_dispatch_statement_call); 10085 return StmtError(); 10086 } 10087 TargetCallLoc = TargetCall->getExprLoc(); 10088 } 10089 10090 setFunctionHasBranchProtectedScope(); 10091 10092 return OMPDispatchDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 10093 TargetCallLoc); 10094 } 10095 10096 StmtResult Sema::ActOnOpenMPGenericLoopDirective( 10097 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10098 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10099 if (!AStmt) 10100 return StmtError(); 10101 10102 // OpenMP 5.1 [2.11.7, loop construct] 10103 // A list item may not appear in a lastprivate clause unless it is the 10104 // loop iteration variable of a loop that is associated with the construct. 10105 for (OMPClause *C : Clauses) { 10106 if (auto *LPC = dyn_cast<OMPLastprivateClause>(C)) { 10107 for (Expr *RefExpr : LPC->varlists()) { 10108 SourceLocation ELoc; 10109 SourceRange ERange; 10110 Expr *SimpleRefExpr = RefExpr; 10111 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 10112 if (ValueDecl *D = Res.first) { 10113 auto &&Info = DSAStack->isLoopControlVariable(D); 10114 if (!Info.first) { 10115 Diag(ELoc, diag::err_omp_lastprivate_loop_var_non_loop_iteration); 10116 return StmtError(); 10117 } 10118 } 10119 } 10120 } 10121 } 10122 10123 auto *CS = cast<CapturedStmt>(AStmt); 10124 // 1.2.2 OpenMP Language Terminology 10125 // Structured block - An executable statement with a single entry at the 10126 // top and a single exit at the bottom. 10127 // The point of exit cannot be a branch out of the structured block. 10128 // longjmp() and throw() must not violate the entry/exit criteria. 10129 CS->getCapturedDecl()->setNothrow(); 10130 10131 OMPLoopDirective::HelperExprs B; 10132 // In presence of clause 'collapse', it will define the nested loops number. 10133 unsigned NestedLoopCount = checkOpenMPLoop( 10134 OMPD_loop, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 10135 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 10136 if (NestedLoopCount == 0) 10137 return StmtError(); 10138 10139 assert((CurContext->isDependentContext() || B.builtAll()) && 10140 "omp loop exprs were not built"); 10141 10142 setFunctionHasBranchProtectedScope(); 10143 return OMPGenericLoopDirective::Create(Context, StartLoc, EndLoc, 10144 NestedLoopCount, Clauses, AStmt, B); 10145 } 10146 10147 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 10148 Stmt *AStmt, 10149 SourceLocation StartLoc, 10150 SourceLocation EndLoc) { 10151 if (!AStmt) 10152 return StmtError(); 10153 10154 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10155 10156 setFunctionHasBranchProtectedScope(); 10157 10158 // OpenMP [2.7.3, single Construct, Restrictions] 10159 // The copyprivate clause must not be used with the nowait clause. 10160 const OMPClause *Nowait = nullptr; 10161 const OMPClause *Copyprivate = nullptr; 10162 for (const OMPClause *Clause : Clauses) { 10163 if (Clause->getClauseKind() == OMPC_nowait) 10164 Nowait = Clause; 10165 else if (Clause->getClauseKind() == OMPC_copyprivate) 10166 Copyprivate = Clause; 10167 if (Copyprivate && Nowait) { 10168 Diag(Copyprivate->getBeginLoc(), 10169 diag::err_omp_single_copyprivate_with_nowait); 10170 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here); 10171 return StmtError(); 10172 } 10173 } 10174 10175 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10176 } 10177 10178 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 10179 SourceLocation StartLoc, 10180 SourceLocation EndLoc) { 10181 if (!AStmt) 10182 return StmtError(); 10183 10184 setFunctionHasBranchProtectedScope(); 10185 10186 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 10187 } 10188 10189 StmtResult Sema::ActOnOpenMPMaskedDirective(ArrayRef<OMPClause *> Clauses, 10190 Stmt *AStmt, 10191 SourceLocation StartLoc, 10192 SourceLocation EndLoc) { 10193 if (!AStmt) 10194 return StmtError(); 10195 10196 setFunctionHasBranchProtectedScope(); 10197 10198 return OMPMaskedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10199 } 10200 10201 StmtResult Sema::ActOnOpenMPCriticalDirective( 10202 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 10203 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 10204 if (!AStmt) 10205 return StmtError(); 10206 10207 bool ErrorFound = false; 10208 llvm::APSInt Hint; 10209 SourceLocation HintLoc; 10210 bool DependentHint = false; 10211 for (const OMPClause *C : Clauses) { 10212 if (C->getClauseKind() == OMPC_hint) { 10213 if (!DirName.getName()) { 10214 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name); 10215 ErrorFound = true; 10216 } 10217 Expr *E = cast<OMPHintClause>(C)->getHint(); 10218 if (E->isTypeDependent() || E->isValueDependent() || 10219 E->isInstantiationDependent()) { 10220 DependentHint = true; 10221 } else { 10222 Hint = E->EvaluateKnownConstInt(Context); 10223 HintLoc = C->getBeginLoc(); 10224 } 10225 } 10226 } 10227 if (ErrorFound) 10228 return StmtError(); 10229 const auto Pair = DSAStack->getCriticalWithHint(DirName); 10230 if (Pair.first && DirName.getName() && !DependentHint) { 10231 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 10232 Diag(StartLoc, diag::err_omp_critical_with_hint); 10233 if (HintLoc.isValid()) 10234 Diag(HintLoc, diag::note_omp_critical_hint_here) 10235 << 0 << toString(Hint, /*Radix=*/10, /*Signed=*/false); 10236 else 10237 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 10238 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 10239 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here) 10240 << 1 10241 << toString(C->getHint()->EvaluateKnownConstInt(Context), 10242 /*Radix=*/10, /*Signed=*/false); 10243 } else { 10244 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1; 10245 } 10246 } 10247 } 10248 10249 setFunctionHasBranchProtectedScope(); 10250 10251 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 10252 Clauses, AStmt); 10253 if (!Pair.first && DirName.getName() && !DependentHint) 10254 DSAStack->addCriticalWithHint(Dir, Hint); 10255 return Dir; 10256 } 10257 10258 StmtResult Sema::ActOnOpenMPParallelForDirective( 10259 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10260 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10261 if (!AStmt) 10262 return StmtError(); 10263 10264 auto *CS = cast<CapturedStmt>(AStmt); 10265 // 1.2.2 OpenMP Language Terminology 10266 // Structured block - An executable statement with a single entry at the 10267 // top and a single exit at the bottom. 10268 // The point of exit cannot be a branch out of the structured block. 10269 // longjmp() and throw() must not violate the entry/exit criteria. 10270 CS->getCapturedDecl()->setNothrow(); 10271 10272 OMPLoopBasedDirective::HelperExprs B; 10273 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10274 // define the nested loops number. 10275 unsigned NestedLoopCount = 10276 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 10277 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 10278 VarsWithImplicitDSA, B); 10279 if (NestedLoopCount == 0) 10280 return StmtError(); 10281 10282 assert((CurContext->isDependentContext() || B.builtAll()) && 10283 "omp parallel for loop exprs were not built"); 10284 10285 if (!CurContext->isDependentContext()) { 10286 // Finalize the clauses that need pre-built expressions for CodeGen. 10287 for (OMPClause *C : Clauses) { 10288 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10289 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10290 B.NumIterations, *this, CurScope, 10291 DSAStack)) 10292 return StmtError(); 10293 } 10294 } 10295 10296 setFunctionHasBranchProtectedScope(); 10297 return OMPParallelForDirective::Create( 10298 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 10299 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 10300 } 10301 10302 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 10303 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 10304 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 10305 if (!AStmt) 10306 return StmtError(); 10307 10308 auto *CS = cast<CapturedStmt>(AStmt); 10309 // 1.2.2 OpenMP Language Terminology 10310 // Structured block - An executable statement with a single entry at the 10311 // top and a single exit at the bottom. 10312 // The point of exit cannot be a branch out of the structured block. 10313 // longjmp() and throw() must not violate the entry/exit criteria. 10314 CS->getCapturedDecl()->setNothrow(); 10315 10316 OMPLoopBasedDirective::HelperExprs B; 10317 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 10318 // define the nested loops number. 10319 unsigned NestedLoopCount = 10320 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 10321 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 10322 VarsWithImplicitDSA, B); 10323 if (NestedLoopCount == 0) 10324 return StmtError(); 10325 10326 if (!CurContext->isDependentContext()) { 10327 // Finalize the clauses that need pre-built expressions for CodeGen. 10328 for (OMPClause *C : Clauses) { 10329 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 10330 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 10331 B.NumIterations, *this, CurScope, 10332 DSAStack)) 10333 return StmtError(); 10334 } 10335 } 10336 10337 if (checkSimdlenSafelenSpecified(*this, Clauses)) 10338 return StmtError(); 10339 10340 setFunctionHasBranchProtectedScope(); 10341 return OMPParallelForSimdDirective::Create( 10342 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 10343 } 10344 10345 StmtResult 10346 Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses, 10347 Stmt *AStmt, SourceLocation StartLoc, 10348 SourceLocation EndLoc) { 10349 if (!AStmt) 10350 return StmtError(); 10351 10352 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10353 auto *CS = cast<CapturedStmt>(AStmt); 10354 // 1.2.2 OpenMP Language Terminology 10355 // Structured block - An executable statement with a single entry at the 10356 // top and a single exit at the bottom. 10357 // The point of exit cannot be a branch out of the structured block. 10358 // longjmp() and throw() must not violate the entry/exit criteria. 10359 CS->getCapturedDecl()->setNothrow(); 10360 10361 setFunctionHasBranchProtectedScope(); 10362 10363 return OMPParallelMasterDirective::Create( 10364 Context, StartLoc, EndLoc, Clauses, AStmt, 10365 DSAStack->getTaskgroupReductionRef()); 10366 } 10367 10368 StmtResult 10369 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 10370 Stmt *AStmt, SourceLocation StartLoc, 10371 SourceLocation EndLoc) { 10372 if (!AStmt) 10373 return StmtError(); 10374 10375 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10376 auto BaseStmt = AStmt; 10377 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 10378 BaseStmt = CS->getCapturedStmt(); 10379 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 10380 auto S = C->children(); 10381 if (S.begin() == S.end()) 10382 return StmtError(); 10383 // All associated statements must be '#pragma omp section' except for 10384 // the first one. 10385 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 10386 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 10387 if (SectionStmt) 10388 Diag(SectionStmt->getBeginLoc(), 10389 diag::err_omp_parallel_sections_substmt_not_section); 10390 return StmtError(); 10391 } 10392 cast<OMPSectionDirective>(SectionStmt) 10393 ->setHasCancel(DSAStack->isCancelRegion()); 10394 } 10395 } else { 10396 Diag(AStmt->getBeginLoc(), 10397 diag::err_omp_parallel_sections_not_compound_stmt); 10398 return StmtError(); 10399 } 10400 10401 setFunctionHasBranchProtectedScope(); 10402 10403 return OMPParallelSectionsDirective::Create( 10404 Context, StartLoc, EndLoc, Clauses, AStmt, 10405 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 10406 } 10407 10408 /// Find and diagnose mutually exclusive clause kinds. 10409 static bool checkMutuallyExclusiveClauses( 10410 Sema &S, ArrayRef<OMPClause *> Clauses, 10411 ArrayRef<OpenMPClauseKind> MutuallyExclusiveClauses) { 10412 const OMPClause *PrevClause = nullptr; 10413 bool ErrorFound = false; 10414 for (const OMPClause *C : Clauses) { 10415 if (llvm::is_contained(MutuallyExclusiveClauses, C->getClauseKind())) { 10416 if (!PrevClause) { 10417 PrevClause = C; 10418 } else if (PrevClause->getClauseKind() != C->getClauseKind()) { 10419 S.Diag(C->getBeginLoc(), diag::err_omp_clauses_mutually_exclusive) 10420 << getOpenMPClauseName(C->getClauseKind()) 10421 << getOpenMPClauseName(PrevClause->getClauseKind()); 10422 S.Diag(PrevClause->getBeginLoc(), diag::note_omp_previous_clause) 10423 << getOpenMPClauseName(PrevClause->getClauseKind()); 10424 ErrorFound = true; 10425 } 10426 } 10427 } 10428 return ErrorFound; 10429 } 10430 10431 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 10432 Stmt *AStmt, SourceLocation StartLoc, 10433 SourceLocation EndLoc) { 10434 if (!AStmt) 10435 return StmtError(); 10436 10437 // OpenMP 5.0, 2.10.1 task Construct 10438 // If a detach clause appears on the directive, then a mergeable clause cannot 10439 // appear on the same directive. 10440 if (checkMutuallyExclusiveClauses(*this, Clauses, 10441 {OMPC_detach, OMPC_mergeable})) 10442 return StmtError(); 10443 10444 auto *CS = cast<CapturedStmt>(AStmt); 10445 // 1.2.2 OpenMP Language Terminology 10446 // Structured block - An executable statement with a single entry at the 10447 // top and a single exit at the bottom. 10448 // The point of exit cannot be a branch out of the structured block. 10449 // longjmp() and throw() must not violate the entry/exit criteria. 10450 CS->getCapturedDecl()->setNothrow(); 10451 10452 setFunctionHasBranchProtectedScope(); 10453 10454 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 10455 DSAStack->isCancelRegion()); 10456 } 10457 10458 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 10459 SourceLocation EndLoc) { 10460 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 10461 } 10462 10463 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 10464 SourceLocation EndLoc) { 10465 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 10466 } 10467 10468 StmtResult Sema::ActOnOpenMPTaskwaitDirective(ArrayRef<OMPClause *> Clauses, 10469 SourceLocation StartLoc, 10470 SourceLocation EndLoc) { 10471 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc, Clauses); 10472 } 10473 10474 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 10475 Stmt *AStmt, 10476 SourceLocation StartLoc, 10477 SourceLocation EndLoc) { 10478 if (!AStmt) 10479 return StmtError(); 10480 10481 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10482 10483 setFunctionHasBranchProtectedScope(); 10484 10485 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, 10486 AStmt, 10487 DSAStack->getTaskgroupReductionRef()); 10488 } 10489 10490 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 10491 SourceLocation StartLoc, 10492 SourceLocation EndLoc) { 10493 OMPFlushClause *FC = nullptr; 10494 OMPClause *OrderClause = nullptr; 10495 for (OMPClause *C : Clauses) { 10496 if (C->getClauseKind() == OMPC_flush) 10497 FC = cast<OMPFlushClause>(C); 10498 else 10499 OrderClause = C; 10500 } 10501 OpenMPClauseKind MemOrderKind = OMPC_unknown; 10502 SourceLocation MemOrderLoc; 10503 for (const OMPClause *C : Clauses) { 10504 if (C->getClauseKind() == OMPC_acq_rel || 10505 C->getClauseKind() == OMPC_acquire || 10506 C->getClauseKind() == OMPC_release) { 10507 if (MemOrderKind != OMPC_unknown) { 10508 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses) 10509 << getOpenMPDirectiveName(OMPD_flush) << 1 10510 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 10511 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 10512 << getOpenMPClauseName(MemOrderKind); 10513 } else { 10514 MemOrderKind = C->getClauseKind(); 10515 MemOrderLoc = C->getBeginLoc(); 10516 } 10517 } 10518 } 10519 if (FC && OrderClause) { 10520 Diag(FC->getLParenLoc(), diag::err_omp_flush_order_clause_and_list) 10521 << getOpenMPClauseName(OrderClause->getClauseKind()); 10522 Diag(OrderClause->getBeginLoc(), diag::note_omp_flush_order_clause_here) 10523 << getOpenMPClauseName(OrderClause->getClauseKind()); 10524 return StmtError(); 10525 } 10526 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 10527 } 10528 10529 StmtResult Sema::ActOnOpenMPDepobjDirective(ArrayRef<OMPClause *> Clauses, 10530 SourceLocation StartLoc, 10531 SourceLocation EndLoc) { 10532 if (Clauses.empty()) { 10533 Diag(StartLoc, diag::err_omp_depobj_expected); 10534 return StmtError(); 10535 } else if (Clauses[0]->getClauseKind() != OMPC_depobj) { 10536 Diag(Clauses[0]->getBeginLoc(), diag::err_omp_depobj_expected); 10537 return StmtError(); 10538 } 10539 // Only depobj expression and another single clause is allowed. 10540 if (Clauses.size() > 2) { 10541 Diag(Clauses[2]->getBeginLoc(), 10542 diag::err_omp_depobj_single_clause_expected); 10543 return StmtError(); 10544 } else if (Clauses.size() < 1) { 10545 Diag(Clauses[0]->getEndLoc(), diag::err_omp_depobj_single_clause_expected); 10546 return StmtError(); 10547 } 10548 return OMPDepobjDirective::Create(Context, StartLoc, EndLoc, Clauses); 10549 } 10550 10551 StmtResult Sema::ActOnOpenMPScanDirective(ArrayRef<OMPClause *> Clauses, 10552 SourceLocation StartLoc, 10553 SourceLocation EndLoc) { 10554 // Check that exactly one clause is specified. 10555 if (Clauses.size() != 1) { 10556 Diag(Clauses.empty() ? EndLoc : Clauses[1]->getBeginLoc(), 10557 diag::err_omp_scan_single_clause_expected); 10558 return StmtError(); 10559 } 10560 // Check that scan directive is used in the scopeof the OpenMP loop body. 10561 if (Scope *S = DSAStack->getCurScope()) { 10562 Scope *ParentS = S->getParent(); 10563 if (!ParentS || ParentS->getParent() != ParentS->getBreakParent() || 10564 !ParentS->getBreakParent()->isOpenMPLoopScope()) 10565 return StmtError(Diag(StartLoc, diag::err_omp_orphaned_device_directive) 10566 << getOpenMPDirectiveName(OMPD_scan) << 5); 10567 } 10568 // Check that only one instance of scan directives is used in the same outer 10569 // region. 10570 if (DSAStack->doesParentHasScanDirective()) { 10571 Diag(StartLoc, diag::err_omp_several_directives_in_region) << "scan"; 10572 Diag(DSAStack->getParentScanDirectiveLoc(), 10573 diag::note_omp_previous_directive) 10574 << "scan"; 10575 return StmtError(); 10576 } 10577 DSAStack->setParentHasScanDirective(StartLoc); 10578 return OMPScanDirective::Create(Context, StartLoc, EndLoc, Clauses); 10579 } 10580 10581 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 10582 Stmt *AStmt, 10583 SourceLocation StartLoc, 10584 SourceLocation EndLoc) { 10585 const OMPClause *DependFound = nullptr; 10586 const OMPClause *DependSourceClause = nullptr; 10587 const OMPClause *DependSinkClause = nullptr; 10588 bool ErrorFound = false; 10589 const OMPThreadsClause *TC = nullptr; 10590 const OMPSIMDClause *SC = nullptr; 10591 for (const OMPClause *C : Clauses) { 10592 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 10593 DependFound = C; 10594 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 10595 if (DependSourceClause) { 10596 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 10597 << getOpenMPDirectiveName(OMPD_ordered) 10598 << getOpenMPClauseName(OMPC_depend) << 2; 10599 ErrorFound = true; 10600 } else { 10601 DependSourceClause = C; 10602 } 10603 if (DependSinkClause) { 10604 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 10605 << 0; 10606 ErrorFound = true; 10607 } 10608 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 10609 if (DependSourceClause) { 10610 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 10611 << 1; 10612 ErrorFound = true; 10613 } 10614 DependSinkClause = C; 10615 } 10616 } else if (C->getClauseKind() == OMPC_threads) { 10617 TC = cast<OMPThreadsClause>(C); 10618 } else if (C->getClauseKind() == OMPC_simd) { 10619 SC = cast<OMPSIMDClause>(C); 10620 } 10621 } 10622 if (!ErrorFound && !SC && 10623 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 10624 // OpenMP [2.8.1,simd Construct, Restrictions] 10625 // An ordered construct with the simd clause is the only OpenMP construct 10626 // that can appear in the simd region. 10627 Diag(StartLoc, diag::err_omp_prohibited_region_simd) 10628 << (LangOpts.OpenMP >= 50 ? 1 : 0); 10629 ErrorFound = true; 10630 } else if (DependFound && (TC || SC)) { 10631 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd) 10632 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 10633 ErrorFound = true; 10634 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) { 10635 Diag(DependFound->getBeginLoc(), 10636 diag::err_omp_ordered_directive_without_param); 10637 ErrorFound = true; 10638 } else if (TC || Clauses.empty()) { 10639 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) { 10640 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc; 10641 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 10642 << (TC != nullptr); 10643 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1; 10644 ErrorFound = true; 10645 } 10646 } 10647 if ((!AStmt && !DependFound) || ErrorFound) 10648 return StmtError(); 10649 10650 // OpenMP 5.0, 2.17.9, ordered Construct, Restrictions. 10651 // During execution of an iteration of a worksharing-loop or a loop nest 10652 // within a worksharing-loop, simd, or worksharing-loop SIMD region, a thread 10653 // must not execute more than one ordered region corresponding to an ordered 10654 // construct without a depend clause. 10655 if (!DependFound) { 10656 if (DSAStack->doesParentHasOrderedDirective()) { 10657 Diag(StartLoc, diag::err_omp_several_directives_in_region) << "ordered"; 10658 Diag(DSAStack->getParentOrderedDirectiveLoc(), 10659 diag::note_omp_previous_directive) 10660 << "ordered"; 10661 return StmtError(); 10662 } 10663 DSAStack->setParentHasOrderedDirective(StartLoc); 10664 } 10665 10666 if (AStmt) { 10667 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 10668 10669 setFunctionHasBranchProtectedScope(); 10670 } 10671 10672 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 10673 } 10674 10675 namespace { 10676 /// Helper class for checking expression in 'omp atomic [update]' 10677 /// construct. 10678 class OpenMPAtomicUpdateChecker { 10679 /// Error results for atomic update expressions. 10680 enum ExprAnalysisErrorCode { 10681 /// A statement is not an expression statement. 10682 NotAnExpression, 10683 /// Expression is not builtin binary or unary operation. 10684 NotABinaryOrUnaryExpression, 10685 /// Unary operation is not post-/pre- increment/decrement operation. 10686 NotAnUnaryIncDecExpression, 10687 /// An expression is not of scalar type. 10688 NotAScalarType, 10689 /// A binary operation is not an assignment operation. 10690 NotAnAssignmentOp, 10691 /// RHS part of the binary operation is not a binary expression. 10692 NotABinaryExpression, 10693 /// RHS part is not additive/multiplicative/shift/biwise binary 10694 /// expression. 10695 NotABinaryOperator, 10696 /// RHS binary operation does not have reference to the updated LHS 10697 /// part. 10698 NotAnUpdateExpression, 10699 /// No errors is found. 10700 NoError 10701 }; 10702 /// Reference to Sema. 10703 Sema &SemaRef; 10704 /// A location for note diagnostics (when error is found). 10705 SourceLocation NoteLoc; 10706 /// 'x' lvalue part of the source atomic expression. 10707 Expr *X; 10708 /// 'expr' rvalue part of the source atomic expression. 10709 Expr *E; 10710 /// Helper expression of the form 10711 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 10712 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 10713 Expr *UpdateExpr; 10714 /// Is 'x' a LHS in a RHS part of full update expression. It is 10715 /// important for non-associative operations. 10716 bool IsXLHSInRHSPart; 10717 BinaryOperatorKind Op; 10718 SourceLocation OpLoc; 10719 /// true if the source expression is a postfix unary operation, false 10720 /// if it is a prefix unary operation. 10721 bool IsPostfixUpdate; 10722 10723 public: 10724 OpenMPAtomicUpdateChecker(Sema &SemaRef) 10725 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 10726 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 10727 /// Check specified statement that it is suitable for 'atomic update' 10728 /// constructs and extract 'x', 'expr' and Operation from the original 10729 /// expression. If DiagId and NoteId == 0, then only check is performed 10730 /// without error notification. 10731 /// \param DiagId Diagnostic which should be emitted if error is found. 10732 /// \param NoteId Diagnostic note for the main error message. 10733 /// \return true if statement is not an update expression, false otherwise. 10734 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 10735 /// Return the 'x' lvalue part of the source atomic expression. 10736 Expr *getX() const { return X; } 10737 /// Return the 'expr' rvalue part of the source atomic expression. 10738 Expr *getExpr() const { return E; } 10739 /// Return the update expression used in calculation of the updated 10740 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 10741 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 10742 Expr *getUpdateExpr() const { return UpdateExpr; } 10743 /// Return true if 'x' is LHS in RHS part of full update expression, 10744 /// false otherwise. 10745 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 10746 10747 /// true if the source expression is a postfix unary operation, false 10748 /// if it is a prefix unary operation. 10749 bool isPostfixUpdate() const { return IsPostfixUpdate; } 10750 10751 private: 10752 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 10753 unsigned NoteId = 0); 10754 }; 10755 } // namespace 10756 10757 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 10758 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 10759 ExprAnalysisErrorCode ErrorFound = NoError; 10760 SourceLocation ErrorLoc, NoteLoc; 10761 SourceRange ErrorRange, NoteRange; 10762 // Allowed constructs are: 10763 // x = x binop expr; 10764 // x = expr binop x; 10765 if (AtomicBinOp->getOpcode() == BO_Assign) { 10766 X = AtomicBinOp->getLHS(); 10767 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 10768 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 10769 if (AtomicInnerBinOp->isMultiplicativeOp() || 10770 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 10771 AtomicInnerBinOp->isBitwiseOp()) { 10772 Op = AtomicInnerBinOp->getOpcode(); 10773 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 10774 Expr *LHS = AtomicInnerBinOp->getLHS(); 10775 Expr *RHS = AtomicInnerBinOp->getRHS(); 10776 llvm::FoldingSetNodeID XId, LHSId, RHSId; 10777 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 10778 /*Canonical=*/true); 10779 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 10780 /*Canonical=*/true); 10781 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 10782 /*Canonical=*/true); 10783 if (XId == LHSId) { 10784 E = RHS; 10785 IsXLHSInRHSPart = true; 10786 } else if (XId == RHSId) { 10787 E = LHS; 10788 IsXLHSInRHSPart = false; 10789 } else { 10790 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 10791 ErrorRange = AtomicInnerBinOp->getSourceRange(); 10792 NoteLoc = X->getExprLoc(); 10793 NoteRange = X->getSourceRange(); 10794 ErrorFound = NotAnUpdateExpression; 10795 } 10796 } else { 10797 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 10798 ErrorRange = AtomicInnerBinOp->getSourceRange(); 10799 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 10800 NoteRange = SourceRange(NoteLoc, NoteLoc); 10801 ErrorFound = NotABinaryOperator; 10802 } 10803 } else { 10804 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 10805 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 10806 ErrorFound = NotABinaryExpression; 10807 } 10808 } else { 10809 ErrorLoc = AtomicBinOp->getExprLoc(); 10810 ErrorRange = AtomicBinOp->getSourceRange(); 10811 NoteLoc = AtomicBinOp->getOperatorLoc(); 10812 NoteRange = SourceRange(NoteLoc, NoteLoc); 10813 ErrorFound = NotAnAssignmentOp; 10814 } 10815 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 10816 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 10817 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 10818 return true; 10819 } 10820 if (SemaRef.CurContext->isDependentContext()) 10821 E = X = UpdateExpr = nullptr; 10822 return ErrorFound != NoError; 10823 } 10824 10825 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 10826 unsigned NoteId) { 10827 ExprAnalysisErrorCode ErrorFound = NoError; 10828 SourceLocation ErrorLoc, NoteLoc; 10829 SourceRange ErrorRange, NoteRange; 10830 // Allowed constructs are: 10831 // x++; 10832 // x--; 10833 // ++x; 10834 // --x; 10835 // x binop= expr; 10836 // x = x binop expr; 10837 // x = expr binop x; 10838 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 10839 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 10840 if (AtomicBody->getType()->isScalarType() || 10841 AtomicBody->isInstantiationDependent()) { 10842 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 10843 AtomicBody->IgnoreParenImpCasts())) { 10844 // Check for Compound Assignment Operation 10845 Op = BinaryOperator::getOpForCompoundAssignment( 10846 AtomicCompAssignOp->getOpcode()); 10847 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 10848 E = AtomicCompAssignOp->getRHS(); 10849 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 10850 IsXLHSInRHSPart = true; 10851 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 10852 AtomicBody->IgnoreParenImpCasts())) { 10853 // Check for Binary Operation 10854 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 10855 return true; 10856 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 10857 AtomicBody->IgnoreParenImpCasts())) { 10858 // Check for Unary Operation 10859 if (AtomicUnaryOp->isIncrementDecrementOp()) { 10860 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 10861 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 10862 OpLoc = AtomicUnaryOp->getOperatorLoc(); 10863 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 10864 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 10865 IsXLHSInRHSPart = true; 10866 } else { 10867 ErrorFound = NotAnUnaryIncDecExpression; 10868 ErrorLoc = AtomicUnaryOp->getExprLoc(); 10869 ErrorRange = AtomicUnaryOp->getSourceRange(); 10870 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 10871 NoteRange = SourceRange(NoteLoc, NoteLoc); 10872 } 10873 } else if (!AtomicBody->isInstantiationDependent()) { 10874 ErrorFound = NotABinaryOrUnaryExpression; 10875 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 10876 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 10877 } 10878 } else { 10879 ErrorFound = NotAScalarType; 10880 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc(); 10881 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 10882 } 10883 } else { 10884 ErrorFound = NotAnExpression; 10885 NoteLoc = ErrorLoc = S->getBeginLoc(); 10886 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 10887 } 10888 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 10889 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 10890 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 10891 return true; 10892 } 10893 if (SemaRef.CurContext->isDependentContext()) 10894 E = X = UpdateExpr = nullptr; 10895 if (ErrorFound == NoError && E && X) { 10896 // Build an update expression of form 'OpaqueValueExpr(x) binop 10897 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 10898 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 10899 auto *OVEX = new (SemaRef.getASTContext()) 10900 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_PRValue); 10901 auto *OVEExpr = new (SemaRef.getASTContext()) 10902 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_PRValue); 10903 ExprResult Update = 10904 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 10905 IsXLHSInRHSPart ? OVEExpr : OVEX); 10906 if (Update.isInvalid()) 10907 return true; 10908 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 10909 Sema::AA_Casting); 10910 if (Update.isInvalid()) 10911 return true; 10912 UpdateExpr = Update.get(); 10913 } 10914 return ErrorFound != NoError; 10915 } 10916 10917 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 10918 Stmt *AStmt, 10919 SourceLocation StartLoc, 10920 SourceLocation EndLoc) { 10921 // Register location of the first atomic directive. 10922 DSAStack->addAtomicDirectiveLoc(StartLoc); 10923 if (!AStmt) 10924 return StmtError(); 10925 10926 // 1.2.2 OpenMP Language Terminology 10927 // Structured block - An executable statement with a single entry at the 10928 // top and a single exit at the bottom. 10929 // The point of exit cannot be a branch out of the structured block. 10930 // longjmp() and throw() must not violate the entry/exit criteria. 10931 OpenMPClauseKind AtomicKind = OMPC_unknown; 10932 SourceLocation AtomicKindLoc; 10933 OpenMPClauseKind MemOrderKind = OMPC_unknown; 10934 SourceLocation MemOrderLoc; 10935 for (const OMPClause *C : Clauses) { 10936 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 10937 C->getClauseKind() == OMPC_update || 10938 C->getClauseKind() == OMPC_capture) { 10939 if (AtomicKind != OMPC_unknown) { 10940 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses) 10941 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 10942 Diag(AtomicKindLoc, diag::note_omp_previous_mem_order_clause) 10943 << getOpenMPClauseName(AtomicKind); 10944 } else { 10945 AtomicKind = C->getClauseKind(); 10946 AtomicKindLoc = C->getBeginLoc(); 10947 } 10948 } 10949 if (C->getClauseKind() == OMPC_seq_cst || 10950 C->getClauseKind() == OMPC_acq_rel || 10951 C->getClauseKind() == OMPC_acquire || 10952 C->getClauseKind() == OMPC_release || 10953 C->getClauseKind() == OMPC_relaxed) { 10954 if (MemOrderKind != OMPC_unknown) { 10955 Diag(C->getBeginLoc(), diag::err_omp_several_mem_order_clauses) 10956 << getOpenMPDirectiveName(OMPD_atomic) << 0 10957 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 10958 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 10959 << getOpenMPClauseName(MemOrderKind); 10960 } else { 10961 MemOrderKind = C->getClauseKind(); 10962 MemOrderLoc = C->getBeginLoc(); 10963 } 10964 } 10965 } 10966 // OpenMP 5.0, 2.17.7 atomic Construct, Restrictions 10967 // If atomic-clause is read then memory-order-clause must not be acq_rel or 10968 // release. 10969 // If atomic-clause is write then memory-order-clause must not be acq_rel or 10970 // acquire. 10971 // If atomic-clause is update or not present then memory-order-clause must not 10972 // be acq_rel or acquire. 10973 if ((AtomicKind == OMPC_read && 10974 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_release)) || 10975 ((AtomicKind == OMPC_write || AtomicKind == OMPC_update || 10976 AtomicKind == OMPC_unknown) && 10977 (MemOrderKind == OMPC_acq_rel || MemOrderKind == OMPC_acquire))) { 10978 SourceLocation Loc = AtomicKindLoc; 10979 if (AtomicKind == OMPC_unknown) 10980 Loc = StartLoc; 10981 Diag(Loc, diag::err_omp_atomic_incompatible_mem_order_clause) 10982 << getOpenMPClauseName(AtomicKind) 10983 << (AtomicKind == OMPC_unknown ? 1 : 0) 10984 << getOpenMPClauseName(MemOrderKind); 10985 Diag(MemOrderLoc, diag::note_omp_previous_mem_order_clause) 10986 << getOpenMPClauseName(MemOrderKind); 10987 } 10988 10989 Stmt *Body = AStmt; 10990 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 10991 Body = EWC->getSubExpr(); 10992 10993 Expr *X = nullptr; 10994 Expr *V = nullptr; 10995 Expr *E = nullptr; 10996 Expr *UE = nullptr; 10997 bool IsXLHSInRHSPart = false; 10998 bool IsPostfixUpdate = false; 10999 // OpenMP [2.12.6, atomic Construct] 11000 // In the next expressions: 11001 // * x and v (as applicable) are both l-value expressions with scalar type. 11002 // * During the execution of an atomic region, multiple syntactic 11003 // occurrences of x must designate the same storage location. 11004 // * Neither of v and expr (as applicable) may access the storage location 11005 // designated by x. 11006 // * Neither of x and expr (as applicable) may access the storage location 11007 // designated by v. 11008 // * expr is an expression with scalar type. 11009 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 11010 // * binop, binop=, ++, and -- are not overloaded operators. 11011 // * The expression x binop expr must be numerically equivalent to x binop 11012 // (expr). This requirement is satisfied if the operators in expr have 11013 // precedence greater than binop, or by using parentheses around expr or 11014 // subexpressions of expr. 11015 // * The expression expr binop x must be numerically equivalent to (expr) 11016 // binop x. This requirement is satisfied if the operators in expr have 11017 // precedence equal to or greater than binop, or by using parentheses around 11018 // expr or subexpressions of expr. 11019 // * For forms that allow multiple occurrences of x, the number of times 11020 // that x is evaluated is unspecified. 11021 if (AtomicKind == OMPC_read) { 11022 enum { 11023 NotAnExpression, 11024 NotAnAssignmentOp, 11025 NotAScalarType, 11026 NotAnLValue, 11027 NoError 11028 } ErrorFound = NoError; 11029 SourceLocation ErrorLoc, NoteLoc; 11030 SourceRange ErrorRange, NoteRange; 11031 // If clause is read: 11032 // v = x; 11033 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 11034 const auto *AtomicBinOp = 11035 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 11036 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 11037 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 11038 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 11039 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 11040 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 11041 if (!X->isLValue() || !V->isLValue()) { 11042 const Expr *NotLValueExpr = X->isLValue() ? V : X; 11043 ErrorFound = NotAnLValue; 11044 ErrorLoc = AtomicBinOp->getExprLoc(); 11045 ErrorRange = AtomicBinOp->getSourceRange(); 11046 NoteLoc = NotLValueExpr->getExprLoc(); 11047 NoteRange = NotLValueExpr->getSourceRange(); 11048 } 11049 } else if (!X->isInstantiationDependent() || 11050 !V->isInstantiationDependent()) { 11051 const Expr *NotScalarExpr = 11052 (X->isInstantiationDependent() || X->getType()->isScalarType()) 11053 ? V 11054 : X; 11055 ErrorFound = NotAScalarType; 11056 ErrorLoc = AtomicBinOp->getExprLoc(); 11057 ErrorRange = AtomicBinOp->getSourceRange(); 11058 NoteLoc = NotScalarExpr->getExprLoc(); 11059 NoteRange = NotScalarExpr->getSourceRange(); 11060 } 11061 } else if (!AtomicBody->isInstantiationDependent()) { 11062 ErrorFound = NotAnAssignmentOp; 11063 ErrorLoc = AtomicBody->getExprLoc(); 11064 ErrorRange = AtomicBody->getSourceRange(); 11065 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 11066 : AtomicBody->getExprLoc(); 11067 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 11068 : AtomicBody->getSourceRange(); 11069 } 11070 } else { 11071 ErrorFound = NotAnExpression; 11072 NoteLoc = ErrorLoc = Body->getBeginLoc(); 11073 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 11074 } 11075 if (ErrorFound != NoError) { 11076 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 11077 << ErrorRange; 11078 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 11079 << NoteRange; 11080 return StmtError(); 11081 } 11082 if (CurContext->isDependentContext()) 11083 V = X = nullptr; 11084 } else if (AtomicKind == OMPC_write) { 11085 enum { 11086 NotAnExpression, 11087 NotAnAssignmentOp, 11088 NotAScalarType, 11089 NotAnLValue, 11090 NoError 11091 } ErrorFound = NoError; 11092 SourceLocation ErrorLoc, NoteLoc; 11093 SourceRange ErrorRange, NoteRange; 11094 // If clause is write: 11095 // x = expr; 11096 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 11097 const auto *AtomicBinOp = 11098 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 11099 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 11100 X = AtomicBinOp->getLHS(); 11101 E = AtomicBinOp->getRHS(); 11102 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 11103 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 11104 if (!X->isLValue()) { 11105 ErrorFound = NotAnLValue; 11106 ErrorLoc = AtomicBinOp->getExprLoc(); 11107 ErrorRange = AtomicBinOp->getSourceRange(); 11108 NoteLoc = X->getExprLoc(); 11109 NoteRange = X->getSourceRange(); 11110 } 11111 } else if (!X->isInstantiationDependent() || 11112 !E->isInstantiationDependent()) { 11113 const Expr *NotScalarExpr = 11114 (X->isInstantiationDependent() || X->getType()->isScalarType()) 11115 ? E 11116 : X; 11117 ErrorFound = NotAScalarType; 11118 ErrorLoc = AtomicBinOp->getExprLoc(); 11119 ErrorRange = AtomicBinOp->getSourceRange(); 11120 NoteLoc = NotScalarExpr->getExprLoc(); 11121 NoteRange = NotScalarExpr->getSourceRange(); 11122 } 11123 } else if (!AtomicBody->isInstantiationDependent()) { 11124 ErrorFound = NotAnAssignmentOp; 11125 ErrorLoc = AtomicBody->getExprLoc(); 11126 ErrorRange = AtomicBody->getSourceRange(); 11127 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 11128 : AtomicBody->getExprLoc(); 11129 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 11130 : AtomicBody->getSourceRange(); 11131 } 11132 } else { 11133 ErrorFound = NotAnExpression; 11134 NoteLoc = ErrorLoc = Body->getBeginLoc(); 11135 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 11136 } 11137 if (ErrorFound != NoError) { 11138 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 11139 << ErrorRange; 11140 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 11141 << NoteRange; 11142 return StmtError(); 11143 } 11144 if (CurContext->isDependentContext()) 11145 E = X = nullptr; 11146 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 11147 // If clause is update: 11148 // x++; 11149 // x--; 11150 // ++x; 11151 // --x; 11152 // x binop= expr; 11153 // x = x binop expr; 11154 // x = expr binop x; 11155 OpenMPAtomicUpdateChecker Checker(*this); 11156 if (Checker.checkStatement( 11157 Body, (AtomicKind == OMPC_update) 11158 ? diag::err_omp_atomic_update_not_expression_statement 11159 : diag::err_omp_atomic_not_expression_statement, 11160 diag::note_omp_atomic_update)) 11161 return StmtError(); 11162 if (!CurContext->isDependentContext()) { 11163 E = Checker.getExpr(); 11164 X = Checker.getX(); 11165 UE = Checker.getUpdateExpr(); 11166 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 11167 } 11168 } else if (AtomicKind == OMPC_capture) { 11169 enum { 11170 NotAnAssignmentOp, 11171 NotACompoundStatement, 11172 NotTwoSubstatements, 11173 NotASpecificExpression, 11174 NoError 11175 } ErrorFound = NoError; 11176 SourceLocation ErrorLoc, NoteLoc; 11177 SourceRange ErrorRange, NoteRange; 11178 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 11179 // If clause is a capture: 11180 // v = x++; 11181 // v = x--; 11182 // v = ++x; 11183 // v = --x; 11184 // v = x binop= expr; 11185 // v = x = x binop expr; 11186 // v = x = expr binop x; 11187 const auto *AtomicBinOp = 11188 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 11189 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 11190 V = AtomicBinOp->getLHS(); 11191 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 11192 OpenMPAtomicUpdateChecker Checker(*this); 11193 if (Checker.checkStatement( 11194 Body, diag::err_omp_atomic_capture_not_expression_statement, 11195 diag::note_omp_atomic_update)) 11196 return StmtError(); 11197 E = Checker.getExpr(); 11198 X = Checker.getX(); 11199 UE = Checker.getUpdateExpr(); 11200 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 11201 IsPostfixUpdate = Checker.isPostfixUpdate(); 11202 } else if (!AtomicBody->isInstantiationDependent()) { 11203 ErrorLoc = AtomicBody->getExprLoc(); 11204 ErrorRange = AtomicBody->getSourceRange(); 11205 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 11206 : AtomicBody->getExprLoc(); 11207 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 11208 : AtomicBody->getSourceRange(); 11209 ErrorFound = NotAnAssignmentOp; 11210 } 11211 if (ErrorFound != NoError) { 11212 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 11213 << ErrorRange; 11214 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 11215 return StmtError(); 11216 } 11217 if (CurContext->isDependentContext()) 11218 UE = V = E = X = nullptr; 11219 } else { 11220 // If clause is a capture: 11221 // { v = x; x = expr; } 11222 // { v = x; x++; } 11223 // { v = x; x--; } 11224 // { v = x; ++x; } 11225 // { v = x; --x; } 11226 // { v = x; x binop= expr; } 11227 // { v = x; x = x binop expr; } 11228 // { v = x; x = expr binop x; } 11229 // { x++; v = x; } 11230 // { x--; v = x; } 11231 // { ++x; v = x; } 11232 // { --x; v = x; } 11233 // { x binop= expr; v = x; } 11234 // { x = x binop expr; v = x; } 11235 // { x = expr binop x; v = x; } 11236 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 11237 // Check that this is { expr1; expr2; } 11238 if (CS->size() == 2) { 11239 Stmt *First = CS->body_front(); 11240 Stmt *Second = CS->body_back(); 11241 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 11242 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 11243 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 11244 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 11245 // Need to find what subexpression is 'v' and what is 'x'. 11246 OpenMPAtomicUpdateChecker Checker(*this); 11247 bool IsUpdateExprFound = !Checker.checkStatement(Second); 11248 BinaryOperator *BinOp = nullptr; 11249 if (IsUpdateExprFound) { 11250 BinOp = dyn_cast<BinaryOperator>(First); 11251 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 11252 } 11253 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 11254 // { v = x; x++; } 11255 // { v = x; x--; } 11256 // { v = x; ++x; } 11257 // { v = x; --x; } 11258 // { v = x; x binop= expr; } 11259 // { v = x; x = x binop expr; } 11260 // { v = x; x = expr binop x; } 11261 // Check that the first expression has form v = x. 11262 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 11263 llvm::FoldingSetNodeID XId, PossibleXId; 11264 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 11265 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 11266 IsUpdateExprFound = XId == PossibleXId; 11267 if (IsUpdateExprFound) { 11268 V = BinOp->getLHS(); 11269 X = Checker.getX(); 11270 E = Checker.getExpr(); 11271 UE = Checker.getUpdateExpr(); 11272 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 11273 IsPostfixUpdate = true; 11274 } 11275 } 11276 if (!IsUpdateExprFound) { 11277 IsUpdateExprFound = !Checker.checkStatement(First); 11278 BinOp = nullptr; 11279 if (IsUpdateExprFound) { 11280 BinOp = dyn_cast<BinaryOperator>(Second); 11281 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 11282 } 11283 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 11284 // { x++; v = x; } 11285 // { x--; v = x; } 11286 // { ++x; v = x; } 11287 // { --x; v = x; } 11288 // { x binop= expr; v = x; } 11289 // { x = x binop expr; v = x; } 11290 // { x = expr binop x; v = x; } 11291 // Check that the second expression has form v = x. 11292 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 11293 llvm::FoldingSetNodeID XId, PossibleXId; 11294 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 11295 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 11296 IsUpdateExprFound = XId == PossibleXId; 11297 if (IsUpdateExprFound) { 11298 V = BinOp->getLHS(); 11299 X = Checker.getX(); 11300 E = Checker.getExpr(); 11301 UE = Checker.getUpdateExpr(); 11302 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 11303 IsPostfixUpdate = false; 11304 } 11305 } 11306 } 11307 if (!IsUpdateExprFound) { 11308 // { v = x; x = expr; } 11309 auto *FirstExpr = dyn_cast<Expr>(First); 11310 auto *SecondExpr = dyn_cast<Expr>(Second); 11311 if (!FirstExpr || !SecondExpr || 11312 !(FirstExpr->isInstantiationDependent() || 11313 SecondExpr->isInstantiationDependent())) { 11314 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 11315 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 11316 ErrorFound = NotAnAssignmentOp; 11317 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 11318 : First->getBeginLoc(); 11319 NoteRange = ErrorRange = FirstBinOp 11320 ? FirstBinOp->getSourceRange() 11321 : SourceRange(ErrorLoc, ErrorLoc); 11322 } else { 11323 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 11324 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 11325 ErrorFound = NotAnAssignmentOp; 11326 NoteLoc = ErrorLoc = SecondBinOp 11327 ? SecondBinOp->getOperatorLoc() 11328 : Second->getBeginLoc(); 11329 NoteRange = ErrorRange = 11330 SecondBinOp ? SecondBinOp->getSourceRange() 11331 : SourceRange(ErrorLoc, ErrorLoc); 11332 } else { 11333 Expr *PossibleXRHSInFirst = 11334 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 11335 Expr *PossibleXLHSInSecond = 11336 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 11337 llvm::FoldingSetNodeID X1Id, X2Id; 11338 PossibleXRHSInFirst->Profile(X1Id, Context, 11339 /*Canonical=*/true); 11340 PossibleXLHSInSecond->Profile(X2Id, Context, 11341 /*Canonical=*/true); 11342 IsUpdateExprFound = X1Id == X2Id; 11343 if (IsUpdateExprFound) { 11344 V = FirstBinOp->getLHS(); 11345 X = SecondBinOp->getLHS(); 11346 E = SecondBinOp->getRHS(); 11347 UE = nullptr; 11348 IsXLHSInRHSPart = false; 11349 IsPostfixUpdate = true; 11350 } else { 11351 ErrorFound = NotASpecificExpression; 11352 ErrorLoc = FirstBinOp->getExprLoc(); 11353 ErrorRange = FirstBinOp->getSourceRange(); 11354 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 11355 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 11356 } 11357 } 11358 } 11359 } 11360 } 11361 } else { 11362 NoteLoc = ErrorLoc = Body->getBeginLoc(); 11363 NoteRange = ErrorRange = 11364 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 11365 ErrorFound = NotTwoSubstatements; 11366 } 11367 } else { 11368 NoteLoc = ErrorLoc = Body->getBeginLoc(); 11369 NoteRange = ErrorRange = 11370 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 11371 ErrorFound = NotACompoundStatement; 11372 } 11373 if (ErrorFound != NoError) { 11374 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 11375 << ErrorRange; 11376 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 11377 return StmtError(); 11378 } 11379 if (CurContext->isDependentContext()) 11380 UE = V = E = X = nullptr; 11381 } 11382 } 11383 11384 setFunctionHasBranchProtectedScope(); 11385 11386 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 11387 X, V, E, UE, IsXLHSInRHSPart, 11388 IsPostfixUpdate); 11389 } 11390 11391 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 11392 Stmt *AStmt, 11393 SourceLocation StartLoc, 11394 SourceLocation EndLoc) { 11395 if (!AStmt) 11396 return StmtError(); 11397 11398 auto *CS = cast<CapturedStmt>(AStmt); 11399 // 1.2.2 OpenMP Language Terminology 11400 // Structured block - An executable statement with a single entry at the 11401 // top and a single exit at the bottom. 11402 // The point of exit cannot be a branch out of the structured block. 11403 // longjmp() and throw() must not violate the entry/exit criteria. 11404 CS->getCapturedDecl()->setNothrow(); 11405 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target); 11406 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11407 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11408 // 1.2.2 OpenMP Language Terminology 11409 // Structured block - An executable statement with a single entry at the 11410 // top and a single exit at the bottom. 11411 // The point of exit cannot be a branch out of the structured block. 11412 // longjmp() and throw() must not violate the entry/exit criteria. 11413 CS->getCapturedDecl()->setNothrow(); 11414 } 11415 11416 // OpenMP [2.16, Nesting of Regions] 11417 // If specified, a teams construct must be contained within a target 11418 // construct. That target construct must contain no statements or directives 11419 // outside of the teams construct. 11420 if (DSAStack->hasInnerTeamsRegion()) { 11421 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true); 11422 bool OMPTeamsFound = true; 11423 if (const auto *CS = dyn_cast<CompoundStmt>(S)) { 11424 auto I = CS->body_begin(); 11425 while (I != CS->body_end()) { 11426 const auto *OED = dyn_cast<OMPExecutableDirective>(*I); 11427 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) || 11428 OMPTeamsFound) { 11429 11430 OMPTeamsFound = false; 11431 break; 11432 } 11433 ++I; 11434 } 11435 assert(I != CS->body_end() && "Not found statement"); 11436 S = *I; 11437 } else { 11438 const auto *OED = dyn_cast<OMPExecutableDirective>(S); 11439 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 11440 } 11441 if (!OMPTeamsFound) { 11442 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 11443 Diag(DSAStack->getInnerTeamsRegionLoc(), 11444 diag::note_omp_nested_teams_construct_here); 11445 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here) 11446 << isa<OMPExecutableDirective>(S); 11447 return StmtError(); 11448 } 11449 } 11450 11451 setFunctionHasBranchProtectedScope(); 11452 11453 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 11454 } 11455 11456 StmtResult 11457 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 11458 Stmt *AStmt, SourceLocation StartLoc, 11459 SourceLocation EndLoc) { 11460 if (!AStmt) 11461 return StmtError(); 11462 11463 auto *CS = cast<CapturedStmt>(AStmt); 11464 // 1.2.2 OpenMP Language Terminology 11465 // Structured block - An executable statement with a single entry at the 11466 // top and a single exit at the bottom. 11467 // The point of exit cannot be a branch out of the structured block. 11468 // longjmp() and throw() must not violate the entry/exit criteria. 11469 CS->getCapturedDecl()->setNothrow(); 11470 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel); 11471 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11472 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11473 // 1.2.2 OpenMP Language Terminology 11474 // Structured block - An executable statement with a single entry at the 11475 // top and a single exit at the bottom. 11476 // The point of exit cannot be a branch out of the structured block. 11477 // longjmp() and throw() must not violate the entry/exit criteria. 11478 CS->getCapturedDecl()->setNothrow(); 11479 } 11480 11481 setFunctionHasBranchProtectedScope(); 11482 11483 return OMPTargetParallelDirective::Create( 11484 Context, StartLoc, EndLoc, Clauses, AStmt, 11485 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 11486 } 11487 11488 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 11489 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11490 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11491 if (!AStmt) 11492 return StmtError(); 11493 11494 auto *CS = cast<CapturedStmt>(AStmt); 11495 // 1.2.2 OpenMP Language Terminology 11496 // Structured block - An executable statement with a single entry at the 11497 // top and a single exit at the bottom. 11498 // The point of exit cannot be a branch out of the structured block. 11499 // longjmp() and throw() must not violate the entry/exit criteria. 11500 CS->getCapturedDecl()->setNothrow(); 11501 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 11502 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11503 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11504 // 1.2.2 OpenMP Language Terminology 11505 // Structured block - An executable statement with a single entry at the 11506 // top and a single exit at the bottom. 11507 // The point of exit cannot be a branch out of the structured block. 11508 // longjmp() and throw() must not violate the entry/exit criteria. 11509 CS->getCapturedDecl()->setNothrow(); 11510 } 11511 11512 OMPLoopBasedDirective::HelperExprs B; 11513 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11514 // define the nested loops number. 11515 unsigned NestedLoopCount = 11516 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 11517 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 11518 VarsWithImplicitDSA, B); 11519 if (NestedLoopCount == 0) 11520 return StmtError(); 11521 11522 assert((CurContext->isDependentContext() || B.builtAll()) && 11523 "omp target parallel for loop exprs were not built"); 11524 11525 if (!CurContext->isDependentContext()) { 11526 // Finalize the clauses that need pre-built expressions for CodeGen. 11527 for (OMPClause *C : Clauses) { 11528 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11529 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11530 B.NumIterations, *this, CurScope, 11531 DSAStack)) 11532 return StmtError(); 11533 } 11534 } 11535 11536 setFunctionHasBranchProtectedScope(); 11537 return OMPTargetParallelForDirective::Create( 11538 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 11539 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 11540 } 11541 11542 /// Check for existence of a map clause in the list of clauses. 11543 static bool hasClauses(ArrayRef<OMPClause *> Clauses, 11544 const OpenMPClauseKind K) { 11545 return llvm::any_of( 11546 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); 11547 } 11548 11549 template <typename... Params> 11550 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, 11551 const Params... ClauseTypes) { 11552 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); 11553 } 11554 11555 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 11556 Stmt *AStmt, 11557 SourceLocation StartLoc, 11558 SourceLocation EndLoc) { 11559 if (!AStmt) 11560 return StmtError(); 11561 11562 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11563 11564 // OpenMP [2.12.2, target data Construct, Restrictions] 11565 // At least one map, use_device_addr or use_device_ptr clause must appear on 11566 // the directive. 11567 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr) && 11568 (LangOpts.OpenMP < 50 || !hasClauses(Clauses, OMPC_use_device_addr))) { 11569 StringRef Expected; 11570 if (LangOpts.OpenMP < 50) 11571 Expected = "'map' or 'use_device_ptr'"; 11572 else 11573 Expected = "'map', 'use_device_ptr', or 'use_device_addr'"; 11574 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 11575 << Expected << getOpenMPDirectiveName(OMPD_target_data); 11576 return StmtError(); 11577 } 11578 11579 setFunctionHasBranchProtectedScope(); 11580 11581 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 11582 AStmt); 11583 } 11584 11585 StmtResult 11586 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 11587 SourceLocation StartLoc, 11588 SourceLocation EndLoc, Stmt *AStmt) { 11589 if (!AStmt) 11590 return StmtError(); 11591 11592 auto *CS = cast<CapturedStmt>(AStmt); 11593 // 1.2.2 OpenMP Language Terminology 11594 // Structured block - An executable statement with a single entry at the 11595 // top and a single exit at the bottom. 11596 // The point of exit cannot be a branch out of the structured block. 11597 // longjmp() and throw() must not violate the entry/exit criteria. 11598 CS->getCapturedDecl()->setNothrow(); 11599 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data); 11600 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11601 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11602 // 1.2.2 OpenMP Language Terminology 11603 // Structured block - An executable statement with a single entry at the 11604 // top and a single exit at the bottom. 11605 // The point of exit cannot be a branch out of the structured block. 11606 // longjmp() and throw() must not violate the entry/exit criteria. 11607 CS->getCapturedDecl()->setNothrow(); 11608 } 11609 11610 // OpenMP [2.10.2, Restrictions, p. 99] 11611 // At least one map clause must appear on the directive. 11612 if (!hasClauses(Clauses, OMPC_map)) { 11613 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 11614 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); 11615 return StmtError(); 11616 } 11617 11618 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 11619 AStmt); 11620 } 11621 11622 StmtResult 11623 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 11624 SourceLocation StartLoc, 11625 SourceLocation EndLoc, Stmt *AStmt) { 11626 if (!AStmt) 11627 return StmtError(); 11628 11629 auto *CS = cast<CapturedStmt>(AStmt); 11630 // 1.2.2 OpenMP Language Terminology 11631 // Structured block - An executable statement with a single entry at the 11632 // top and a single exit at the bottom. 11633 // The point of exit cannot be a branch out of the structured block. 11634 // longjmp() and throw() must not violate the entry/exit criteria. 11635 CS->getCapturedDecl()->setNothrow(); 11636 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data); 11637 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11638 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11639 // 1.2.2 OpenMP Language Terminology 11640 // Structured block - An executable statement with a single entry at the 11641 // top and a single exit at the bottom. 11642 // The point of exit cannot be a branch out of the structured block. 11643 // longjmp() and throw() must not violate the entry/exit criteria. 11644 CS->getCapturedDecl()->setNothrow(); 11645 } 11646 11647 // OpenMP [2.10.3, Restrictions, p. 102] 11648 // At least one map clause must appear on the directive. 11649 if (!hasClauses(Clauses, OMPC_map)) { 11650 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 11651 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data); 11652 return StmtError(); 11653 } 11654 11655 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 11656 AStmt); 11657 } 11658 11659 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 11660 SourceLocation StartLoc, 11661 SourceLocation EndLoc, 11662 Stmt *AStmt) { 11663 if (!AStmt) 11664 return StmtError(); 11665 11666 auto *CS = cast<CapturedStmt>(AStmt); 11667 // 1.2.2 OpenMP Language Terminology 11668 // Structured block - An executable statement with a single entry at the 11669 // top and a single exit at the bottom. 11670 // The point of exit cannot be a branch out of the structured block. 11671 // longjmp() and throw() must not violate the entry/exit criteria. 11672 CS->getCapturedDecl()->setNothrow(); 11673 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update); 11674 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11675 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11676 // 1.2.2 OpenMP Language Terminology 11677 // Structured block - An executable statement with a single entry at the 11678 // top and a single exit at the bottom. 11679 // The point of exit cannot be a branch out of the structured block. 11680 // longjmp() and throw() must not violate the entry/exit criteria. 11681 CS->getCapturedDecl()->setNothrow(); 11682 } 11683 11684 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { 11685 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 11686 return StmtError(); 11687 } 11688 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses, 11689 AStmt); 11690 } 11691 11692 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 11693 Stmt *AStmt, SourceLocation StartLoc, 11694 SourceLocation EndLoc) { 11695 if (!AStmt) 11696 return StmtError(); 11697 11698 auto *CS = cast<CapturedStmt>(AStmt); 11699 // 1.2.2 OpenMP Language Terminology 11700 // Structured block - An executable statement with a single entry at the 11701 // top and a single exit at the bottom. 11702 // The point of exit cannot be a branch out of the structured block. 11703 // longjmp() and throw() must not violate the entry/exit criteria. 11704 CS->getCapturedDecl()->setNothrow(); 11705 11706 setFunctionHasBranchProtectedScope(); 11707 11708 DSAStack->setParentTeamsRegionLoc(StartLoc); 11709 11710 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 11711 } 11712 11713 StmtResult 11714 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 11715 SourceLocation EndLoc, 11716 OpenMPDirectiveKind CancelRegion) { 11717 if (DSAStack->isParentNowaitRegion()) { 11718 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 11719 return StmtError(); 11720 } 11721 if (DSAStack->isParentOrderedRegion()) { 11722 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 11723 return StmtError(); 11724 } 11725 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 11726 CancelRegion); 11727 } 11728 11729 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 11730 SourceLocation StartLoc, 11731 SourceLocation EndLoc, 11732 OpenMPDirectiveKind CancelRegion) { 11733 if (DSAStack->isParentNowaitRegion()) { 11734 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 11735 return StmtError(); 11736 } 11737 if (DSAStack->isParentOrderedRegion()) { 11738 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 11739 return StmtError(); 11740 } 11741 DSAStack->setParentCancelRegion(/*Cancel=*/true); 11742 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 11743 CancelRegion); 11744 } 11745 11746 static bool checkReductionClauseWithNogroup(Sema &S, 11747 ArrayRef<OMPClause *> Clauses) { 11748 const OMPClause *ReductionClause = nullptr; 11749 const OMPClause *NogroupClause = nullptr; 11750 for (const OMPClause *C : Clauses) { 11751 if (C->getClauseKind() == OMPC_reduction) { 11752 ReductionClause = C; 11753 if (NogroupClause) 11754 break; 11755 continue; 11756 } 11757 if (C->getClauseKind() == OMPC_nogroup) { 11758 NogroupClause = C; 11759 if (ReductionClause) 11760 break; 11761 continue; 11762 } 11763 } 11764 if (ReductionClause && NogroupClause) { 11765 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup) 11766 << SourceRange(NogroupClause->getBeginLoc(), 11767 NogroupClause->getEndLoc()); 11768 return true; 11769 } 11770 return false; 11771 } 11772 11773 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 11774 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11775 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11776 if (!AStmt) 11777 return StmtError(); 11778 11779 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11780 OMPLoopBasedDirective::HelperExprs B; 11781 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11782 // define the nested loops number. 11783 unsigned NestedLoopCount = 11784 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 11785 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 11786 VarsWithImplicitDSA, B); 11787 if (NestedLoopCount == 0) 11788 return StmtError(); 11789 11790 assert((CurContext->isDependentContext() || B.builtAll()) && 11791 "omp for loop exprs were not built"); 11792 11793 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11794 // The grainsize clause and num_tasks clause are mutually exclusive and may 11795 // not appear on the same taskloop directive. 11796 if (checkMutuallyExclusiveClauses(*this, Clauses, 11797 {OMPC_grainsize, OMPC_num_tasks})) 11798 return StmtError(); 11799 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11800 // If a reduction clause is present on the taskloop directive, the nogroup 11801 // clause must not be specified. 11802 if (checkReductionClauseWithNogroup(*this, Clauses)) 11803 return StmtError(); 11804 11805 setFunctionHasBranchProtectedScope(); 11806 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 11807 NestedLoopCount, Clauses, AStmt, B, 11808 DSAStack->isCancelRegion()); 11809 } 11810 11811 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 11812 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11813 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11814 if (!AStmt) 11815 return StmtError(); 11816 11817 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11818 OMPLoopBasedDirective::HelperExprs B; 11819 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11820 // define the nested loops number. 11821 unsigned NestedLoopCount = 11822 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 11823 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 11824 VarsWithImplicitDSA, B); 11825 if (NestedLoopCount == 0) 11826 return StmtError(); 11827 11828 assert((CurContext->isDependentContext() || B.builtAll()) && 11829 "omp for loop exprs were not built"); 11830 11831 if (!CurContext->isDependentContext()) { 11832 // Finalize the clauses that need pre-built expressions for CodeGen. 11833 for (OMPClause *C : Clauses) { 11834 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11835 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11836 B.NumIterations, *this, CurScope, 11837 DSAStack)) 11838 return StmtError(); 11839 } 11840 } 11841 11842 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11843 // The grainsize clause and num_tasks clause are mutually exclusive and may 11844 // not appear on the same taskloop directive. 11845 if (checkMutuallyExclusiveClauses(*this, Clauses, 11846 {OMPC_grainsize, OMPC_num_tasks})) 11847 return StmtError(); 11848 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11849 // If a reduction clause is present on the taskloop directive, the nogroup 11850 // clause must not be specified. 11851 if (checkReductionClauseWithNogroup(*this, Clauses)) 11852 return StmtError(); 11853 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11854 return StmtError(); 11855 11856 setFunctionHasBranchProtectedScope(); 11857 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 11858 NestedLoopCount, Clauses, AStmt, B); 11859 } 11860 11861 StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective( 11862 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11863 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11864 if (!AStmt) 11865 return StmtError(); 11866 11867 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11868 OMPLoopBasedDirective::HelperExprs B; 11869 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11870 // define the nested loops number. 11871 unsigned NestedLoopCount = 11872 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses), 11873 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 11874 VarsWithImplicitDSA, B); 11875 if (NestedLoopCount == 0) 11876 return StmtError(); 11877 11878 assert((CurContext->isDependentContext() || B.builtAll()) && 11879 "omp for loop exprs were not built"); 11880 11881 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11882 // The grainsize clause and num_tasks clause are mutually exclusive and may 11883 // not appear on the same taskloop directive. 11884 if (checkMutuallyExclusiveClauses(*this, Clauses, 11885 {OMPC_grainsize, OMPC_num_tasks})) 11886 return StmtError(); 11887 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11888 // If a reduction clause is present on the taskloop directive, the nogroup 11889 // clause must not be specified. 11890 if (checkReductionClauseWithNogroup(*this, Clauses)) 11891 return StmtError(); 11892 11893 setFunctionHasBranchProtectedScope(); 11894 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc, 11895 NestedLoopCount, Clauses, AStmt, B, 11896 DSAStack->isCancelRegion()); 11897 } 11898 11899 StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective( 11900 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11901 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11902 if (!AStmt) 11903 return StmtError(); 11904 11905 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11906 OMPLoopBasedDirective::HelperExprs B; 11907 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11908 // define the nested loops number. 11909 unsigned NestedLoopCount = 11910 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses), 11911 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 11912 VarsWithImplicitDSA, B); 11913 if (NestedLoopCount == 0) 11914 return StmtError(); 11915 11916 assert((CurContext->isDependentContext() || B.builtAll()) && 11917 "omp for loop exprs were not built"); 11918 11919 if (!CurContext->isDependentContext()) { 11920 // Finalize the clauses that need pre-built expressions for CodeGen. 11921 for (OMPClause *C : Clauses) { 11922 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 11923 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 11924 B.NumIterations, *this, CurScope, 11925 DSAStack)) 11926 return StmtError(); 11927 } 11928 } 11929 11930 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11931 // The grainsize clause and num_tasks clause are mutually exclusive and may 11932 // not appear on the same taskloop directive. 11933 if (checkMutuallyExclusiveClauses(*this, Clauses, 11934 {OMPC_grainsize, OMPC_num_tasks})) 11935 return StmtError(); 11936 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11937 // If a reduction clause is present on the taskloop directive, the nogroup 11938 // clause must not be specified. 11939 if (checkReductionClauseWithNogroup(*this, Clauses)) 11940 return StmtError(); 11941 if (checkSimdlenSafelenSpecified(*this, Clauses)) 11942 return StmtError(); 11943 11944 setFunctionHasBranchProtectedScope(); 11945 return OMPMasterTaskLoopSimdDirective::Create( 11946 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 11947 } 11948 11949 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective( 11950 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 11951 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 11952 if (!AStmt) 11953 return StmtError(); 11954 11955 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 11956 auto *CS = cast<CapturedStmt>(AStmt); 11957 // 1.2.2 OpenMP Language Terminology 11958 // Structured block - An executable statement with a single entry at the 11959 // top and a single exit at the bottom. 11960 // The point of exit cannot be a branch out of the structured block. 11961 // longjmp() and throw() must not violate the entry/exit criteria. 11962 CS->getCapturedDecl()->setNothrow(); 11963 for (int ThisCaptureLevel = 11964 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop); 11965 ThisCaptureLevel > 1; --ThisCaptureLevel) { 11966 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 11967 // 1.2.2 OpenMP Language Terminology 11968 // Structured block - An executable statement with a single entry at the 11969 // top and a single exit at the bottom. 11970 // The point of exit cannot be a branch out of the structured block. 11971 // longjmp() and throw() must not violate the entry/exit criteria. 11972 CS->getCapturedDecl()->setNothrow(); 11973 } 11974 11975 OMPLoopBasedDirective::HelperExprs B; 11976 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 11977 // define the nested loops number. 11978 unsigned NestedLoopCount = checkOpenMPLoop( 11979 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses), 11980 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 11981 VarsWithImplicitDSA, B); 11982 if (NestedLoopCount == 0) 11983 return StmtError(); 11984 11985 assert((CurContext->isDependentContext() || B.builtAll()) && 11986 "omp for loop exprs were not built"); 11987 11988 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11989 // The grainsize clause and num_tasks clause are mutually exclusive and may 11990 // not appear on the same taskloop directive. 11991 if (checkMutuallyExclusiveClauses(*this, Clauses, 11992 {OMPC_grainsize, OMPC_num_tasks})) 11993 return StmtError(); 11994 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 11995 // If a reduction clause is present on the taskloop directive, the nogroup 11996 // clause must not be specified. 11997 if (checkReductionClauseWithNogroup(*this, Clauses)) 11998 return StmtError(); 11999 12000 setFunctionHasBranchProtectedScope(); 12001 return OMPParallelMasterTaskLoopDirective::Create( 12002 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 12003 DSAStack->isCancelRegion()); 12004 } 12005 12006 StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective( 12007 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12008 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12009 if (!AStmt) 12010 return StmtError(); 12011 12012 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 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 = 12021 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd); 12022 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12023 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12024 // 1.2.2 OpenMP Language Terminology 12025 // Structured block - An executable statement with a single entry at the 12026 // top and a single exit at the bottom. 12027 // The point of exit cannot be a branch out of the structured block. 12028 // longjmp() and throw() must not violate the entry/exit criteria. 12029 CS->getCapturedDecl()->setNothrow(); 12030 } 12031 12032 OMPLoopBasedDirective::HelperExprs B; 12033 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 12034 // define the nested loops number. 12035 unsigned NestedLoopCount = checkOpenMPLoop( 12036 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses), 12037 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack, 12038 VarsWithImplicitDSA, B); 12039 if (NestedLoopCount == 0) 12040 return StmtError(); 12041 12042 assert((CurContext->isDependentContext() || B.builtAll()) && 12043 "omp for loop exprs were not built"); 12044 12045 if (!CurContext->isDependentContext()) { 12046 // Finalize the clauses that need pre-built expressions for CodeGen. 12047 for (OMPClause *C : Clauses) { 12048 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12049 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12050 B.NumIterations, *this, CurScope, 12051 DSAStack)) 12052 return StmtError(); 12053 } 12054 } 12055 12056 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12057 // The grainsize clause and num_tasks clause are mutually exclusive and may 12058 // not appear on the same taskloop directive. 12059 if (checkMutuallyExclusiveClauses(*this, Clauses, 12060 {OMPC_grainsize, OMPC_num_tasks})) 12061 return StmtError(); 12062 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 12063 // If a reduction clause is present on the taskloop directive, the nogroup 12064 // clause must not be specified. 12065 if (checkReductionClauseWithNogroup(*this, Clauses)) 12066 return StmtError(); 12067 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12068 return StmtError(); 12069 12070 setFunctionHasBranchProtectedScope(); 12071 return OMPParallelMasterTaskLoopSimdDirective::Create( 12072 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12073 } 12074 12075 StmtResult Sema::ActOnOpenMPDistributeDirective( 12076 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12077 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12078 if (!AStmt) 12079 return StmtError(); 12080 12081 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 12082 OMPLoopBasedDirective::HelperExprs B; 12083 // In presence of clause 'collapse' with number of loops, it will 12084 // define the nested loops number. 12085 unsigned NestedLoopCount = 12086 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 12087 nullptr /*ordered not a clause on distribute*/, AStmt, 12088 *this, *DSAStack, VarsWithImplicitDSA, B); 12089 if (NestedLoopCount == 0) 12090 return StmtError(); 12091 12092 assert((CurContext->isDependentContext() || B.builtAll()) && 12093 "omp for loop exprs were not built"); 12094 12095 setFunctionHasBranchProtectedScope(); 12096 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 12097 NestedLoopCount, Clauses, AStmt, B); 12098 } 12099 12100 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 12101 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12102 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12103 if (!AStmt) 12104 return StmtError(); 12105 12106 auto *CS = cast<CapturedStmt>(AStmt); 12107 // 1.2.2 OpenMP Language Terminology 12108 // Structured block - An executable statement with a single entry at the 12109 // top and a single exit at the bottom. 12110 // The point of exit cannot be a branch out of the structured block. 12111 // longjmp() and throw() must not violate the entry/exit criteria. 12112 CS->getCapturedDecl()->setNothrow(); 12113 for (int ThisCaptureLevel = 12114 getOpenMPCaptureLevels(OMPD_distribute_parallel_for); 12115 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12116 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12117 // 1.2.2 OpenMP Language Terminology 12118 // Structured block - An executable statement with a single entry at the 12119 // top and a single exit at the bottom. 12120 // The point of exit cannot be a branch out of the structured block. 12121 // longjmp() and throw() must not violate the entry/exit criteria. 12122 CS->getCapturedDecl()->setNothrow(); 12123 } 12124 12125 OMPLoopBasedDirective::HelperExprs B; 12126 // In presence of clause 'collapse' with number of loops, it will 12127 // define the nested loops number. 12128 unsigned NestedLoopCount = checkOpenMPLoop( 12129 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 12130 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12131 VarsWithImplicitDSA, B); 12132 if (NestedLoopCount == 0) 12133 return StmtError(); 12134 12135 assert((CurContext->isDependentContext() || B.builtAll()) && 12136 "omp for loop exprs were not built"); 12137 12138 setFunctionHasBranchProtectedScope(); 12139 return OMPDistributeParallelForDirective::Create( 12140 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 12141 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 12142 } 12143 12144 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 12145 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12146 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12147 if (!AStmt) 12148 return StmtError(); 12149 12150 auto *CS = cast<CapturedStmt>(AStmt); 12151 // 1.2.2 OpenMP Language Terminology 12152 // Structured block - An executable statement with a single entry at the 12153 // top and a single exit at the bottom. 12154 // The point of exit cannot be a branch out of the structured block. 12155 // longjmp() and throw() must not violate the entry/exit criteria. 12156 CS->getCapturedDecl()->setNothrow(); 12157 for (int ThisCaptureLevel = 12158 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd); 12159 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12160 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12161 // 1.2.2 OpenMP Language Terminology 12162 // Structured block - An executable statement with a single entry at the 12163 // top and a single exit at the bottom. 12164 // The point of exit cannot be a branch out of the structured block. 12165 // longjmp() and throw() must not violate the entry/exit criteria. 12166 CS->getCapturedDecl()->setNothrow(); 12167 } 12168 12169 OMPLoopBasedDirective::HelperExprs B; 12170 // In presence of clause 'collapse' with number of loops, it will 12171 // define the nested loops number. 12172 unsigned NestedLoopCount = checkOpenMPLoop( 12173 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 12174 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12175 VarsWithImplicitDSA, B); 12176 if (NestedLoopCount == 0) 12177 return StmtError(); 12178 12179 assert((CurContext->isDependentContext() || B.builtAll()) && 12180 "omp for loop exprs were not built"); 12181 12182 if (!CurContext->isDependentContext()) { 12183 // Finalize the clauses that need pre-built expressions for CodeGen. 12184 for (OMPClause *C : Clauses) { 12185 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12186 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12187 B.NumIterations, *this, CurScope, 12188 DSAStack)) 12189 return StmtError(); 12190 } 12191 } 12192 12193 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12194 return StmtError(); 12195 12196 setFunctionHasBranchProtectedScope(); 12197 return OMPDistributeParallelForSimdDirective::Create( 12198 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12199 } 12200 12201 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 12202 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12203 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12204 if (!AStmt) 12205 return StmtError(); 12206 12207 auto *CS = cast<CapturedStmt>(AStmt); 12208 // 1.2.2 OpenMP Language Terminology 12209 // Structured block - An executable statement with a single entry at the 12210 // top and a single exit at the bottom. 12211 // The point of exit cannot be a branch out of the structured block. 12212 // longjmp() and throw() must not violate the entry/exit criteria. 12213 CS->getCapturedDecl()->setNothrow(); 12214 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd); 12215 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12216 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12217 // 1.2.2 OpenMP Language Terminology 12218 // Structured block - An executable statement with a single entry at the 12219 // top and a single exit at the bottom. 12220 // The point of exit cannot be a branch out of the structured block. 12221 // longjmp() and throw() must not violate the entry/exit criteria. 12222 CS->getCapturedDecl()->setNothrow(); 12223 } 12224 12225 OMPLoopBasedDirective::HelperExprs B; 12226 // In presence of clause 'collapse' with number of loops, it will 12227 // define the nested loops number. 12228 unsigned NestedLoopCount = 12229 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 12230 nullptr /*ordered not a clause on distribute*/, CS, *this, 12231 *DSAStack, VarsWithImplicitDSA, B); 12232 if (NestedLoopCount == 0) 12233 return StmtError(); 12234 12235 assert((CurContext->isDependentContext() || B.builtAll()) && 12236 "omp for loop exprs were not built"); 12237 12238 if (!CurContext->isDependentContext()) { 12239 // Finalize the clauses that need pre-built expressions for CodeGen. 12240 for (OMPClause *C : Clauses) { 12241 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12242 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12243 B.NumIterations, *this, CurScope, 12244 DSAStack)) 12245 return StmtError(); 12246 } 12247 } 12248 12249 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12250 return StmtError(); 12251 12252 setFunctionHasBranchProtectedScope(); 12253 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 12254 NestedLoopCount, Clauses, AStmt, B); 12255 } 12256 12257 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 12258 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12259 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12260 if (!AStmt) 12261 return StmtError(); 12262 12263 auto *CS = cast<CapturedStmt>(AStmt); 12264 // 1.2.2 OpenMP Language Terminology 12265 // Structured block - An executable statement with a single entry at the 12266 // top and a single exit at the bottom. 12267 // The point of exit cannot be a branch out of the structured block. 12268 // longjmp() and throw() must not violate the entry/exit criteria. 12269 CS->getCapturedDecl()->setNothrow(); 12270 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 12271 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12272 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12273 // 1.2.2 OpenMP Language Terminology 12274 // Structured block - An executable statement with a single entry at the 12275 // top and a single exit at the bottom. 12276 // The point of exit cannot be a branch out of the structured block. 12277 // longjmp() and throw() must not violate the entry/exit criteria. 12278 CS->getCapturedDecl()->setNothrow(); 12279 } 12280 12281 OMPLoopBasedDirective::HelperExprs B; 12282 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 12283 // define the nested loops number. 12284 unsigned NestedLoopCount = checkOpenMPLoop( 12285 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 12286 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 12287 VarsWithImplicitDSA, B); 12288 if (NestedLoopCount == 0) 12289 return StmtError(); 12290 12291 assert((CurContext->isDependentContext() || B.builtAll()) && 12292 "omp target parallel for simd loop exprs were not built"); 12293 12294 if (!CurContext->isDependentContext()) { 12295 // Finalize the clauses that need pre-built expressions for CodeGen. 12296 for (OMPClause *C : Clauses) { 12297 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12298 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12299 B.NumIterations, *this, CurScope, 12300 DSAStack)) 12301 return StmtError(); 12302 } 12303 } 12304 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12305 return StmtError(); 12306 12307 setFunctionHasBranchProtectedScope(); 12308 return OMPTargetParallelForSimdDirective::Create( 12309 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12310 } 12311 12312 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 12313 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12314 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12315 if (!AStmt) 12316 return StmtError(); 12317 12318 auto *CS = cast<CapturedStmt>(AStmt); 12319 // 1.2.2 OpenMP Language Terminology 12320 // Structured block - An executable statement with a single entry at the 12321 // top and a single exit at the bottom. 12322 // The point of exit cannot be a branch out of the structured block. 12323 // longjmp() and throw() must not violate the entry/exit criteria. 12324 CS->getCapturedDecl()->setNothrow(); 12325 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd); 12326 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12327 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12328 // 1.2.2 OpenMP Language Terminology 12329 // Structured block - An executable statement with a single entry at the 12330 // top and a single exit at the bottom. 12331 // The point of exit cannot be a branch out of the structured block. 12332 // longjmp() and throw() must not violate the entry/exit criteria. 12333 CS->getCapturedDecl()->setNothrow(); 12334 } 12335 12336 OMPLoopBasedDirective::HelperExprs B; 12337 // In presence of clause 'collapse' with number of loops, it will define the 12338 // nested loops number. 12339 unsigned NestedLoopCount = 12340 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 12341 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 12342 VarsWithImplicitDSA, B); 12343 if (NestedLoopCount == 0) 12344 return StmtError(); 12345 12346 assert((CurContext->isDependentContext() || B.builtAll()) && 12347 "omp target simd loop exprs were not built"); 12348 12349 if (!CurContext->isDependentContext()) { 12350 // Finalize the clauses that need pre-built expressions for CodeGen. 12351 for (OMPClause *C : Clauses) { 12352 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12353 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12354 B.NumIterations, *this, CurScope, 12355 DSAStack)) 12356 return StmtError(); 12357 } 12358 } 12359 12360 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12361 return StmtError(); 12362 12363 setFunctionHasBranchProtectedScope(); 12364 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 12365 NestedLoopCount, Clauses, AStmt, B); 12366 } 12367 12368 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 12369 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12370 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12371 if (!AStmt) 12372 return StmtError(); 12373 12374 auto *CS = cast<CapturedStmt>(AStmt); 12375 // 1.2.2 OpenMP Language Terminology 12376 // Structured block - An executable statement with a single entry at the 12377 // top and a single exit at the bottom. 12378 // The point of exit cannot be a branch out of the structured block. 12379 // longjmp() and throw() must not violate the entry/exit criteria. 12380 CS->getCapturedDecl()->setNothrow(); 12381 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute); 12382 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12383 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12384 // 1.2.2 OpenMP Language Terminology 12385 // Structured block - An executable statement with a single entry at the 12386 // top and a single exit at the bottom. 12387 // The point of exit cannot be a branch out of the structured block. 12388 // longjmp() and throw() must not violate the entry/exit criteria. 12389 CS->getCapturedDecl()->setNothrow(); 12390 } 12391 12392 OMPLoopBasedDirective::HelperExprs B; 12393 // In presence of clause 'collapse' with number of loops, it will 12394 // define the nested loops number. 12395 unsigned NestedLoopCount = 12396 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 12397 nullptr /*ordered not a clause on distribute*/, CS, *this, 12398 *DSAStack, VarsWithImplicitDSA, B); 12399 if (NestedLoopCount == 0) 12400 return StmtError(); 12401 12402 assert((CurContext->isDependentContext() || B.builtAll()) && 12403 "omp teams distribute loop exprs were not built"); 12404 12405 setFunctionHasBranchProtectedScope(); 12406 12407 DSAStack->setParentTeamsRegionLoc(StartLoc); 12408 12409 return OMPTeamsDistributeDirective::Create( 12410 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12411 } 12412 12413 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 12414 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12415 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12416 if (!AStmt) 12417 return StmtError(); 12418 12419 auto *CS = cast<CapturedStmt>(AStmt); 12420 // 1.2.2 OpenMP Language Terminology 12421 // Structured block - An executable statement with a single entry at the 12422 // top and a single exit at the bottom. 12423 // The point of exit cannot be a branch out of the structured block. 12424 // longjmp() and throw() must not violate the entry/exit criteria. 12425 CS->getCapturedDecl()->setNothrow(); 12426 for (int ThisCaptureLevel = 12427 getOpenMPCaptureLevels(OMPD_teams_distribute_simd); 12428 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12429 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12430 // 1.2.2 OpenMP Language Terminology 12431 // Structured block - An executable statement with a single entry at the 12432 // top and a single exit at the bottom. 12433 // The point of exit cannot be a branch out of the structured block. 12434 // longjmp() and throw() must not violate the entry/exit criteria. 12435 CS->getCapturedDecl()->setNothrow(); 12436 } 12437 12438 OMPLoopBasedDirective::HelperExprs B; 12439 // In presence of clause 'collapse' with number of loops, it will 12440 // define the nested loops number. 12441 unsigned NestedLoopCount = checkOpenMPLoop( 12442 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 12443 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12444 VarsWithImplicitDSA, B); 12445 12446 if (NestedLoopCount == 0) 12447 return StmtError(); 12448 12449 assert((CurContext->isDependentContext() || B.builtAll()) && 12450 "omp teams distribute simd loop exprs were not built"); 12451 12452 if (!CurContext->isDependentContext()) { 12453 // Finalize the clauses that need pre-built expressions for CodeGen. 12454 for (OMPClause *C : Clauses) { 12455 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12456 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12457 B.NumIterations, *this, CurScope, 12458 DSAStack)) 12459 return StmtError(); 12460 } 12461 } 12462 12463 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12464 return StmtError(); 12465 12466 setFunctionHasBranchProtectedScope(); 12467 12468 DSAStack->setParentTeamsRegionLoc(StartLoc); 12469 12470 return OMPTeamsDistributeSimdDirective::Create( 12471 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12472 } 12473 12474 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 12475 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12476 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12477 if (!AStmt) 12478 return StmtError(); 12479 12480 auto *CS = cast<CapturedStmt>(AStmt); 12481 // 1.2.2 OpenMP Language Terminology 12482 // Structured block - An executable statement with a single entry at the 12483 // top and a single exit at the bottom. 12484 // The point of exit cannot be a branch out of the structured block. 12485 // longjmp() and throw() must not violate the entry/exit criteria. 12486 CS->getCapturedDecl()->setNothrow(); 12487 12488 for (int ThisCaptureLevel = 12489 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd); 12490 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12491 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12492 // 1.2.2 OpenMP Language Terminology 12493 // Structured block - An executable statement with a single entry at the 12494 // top and a single exit at the bottom. 12495 // The point of exit cannot be a branch out of the structured block. 12496 // longjmp() and throw() must not violate the entry/exit criteria. 12497 CS->getCapturedDecl()->setNothrow(); 12498 } 12499 12500 OMPLoopBasedDirective::HelperExprs B; 12501 // In presence of clause 'collapse' with number of loops, it will 12502 // define the nested loops number. 12503 unsigned NestedLoopCount = checkOpenMPLoop( 12504 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 12505 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12506 VarsWithImplicitDSA, B); 12507 12508 if (NestedLoopCount == 0) 12509 return StmtError(); 12510 12511 assert((CurContext->isDependentContext() || B.builtAll()) && 12512 "omp for loop exprs were not built"); 12513 12514 if (!CurContext->isDependentContext()) { 12515 // Finalize the clauses that need pre-built expressions for CodeGen. 12516 for (OMPClause *C : Clauses) { 12517 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12518 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12519 B.NumIterations, *this, CurScope, 12520 DSAStack)) 12521 return StmtError(); 12522 } 12523 } 12524 12525 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12526 return StmtError(); 12527 12528 setFunctionHasBranchProtectedScope(); 12529 12530 DSAStack->setParentTeamsRegionLoc(StartLoc); 12531 12532 return OMPTeamsDistributeParallelForSimdDirective::Create( 12533 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12534 } 12535 12536 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 12537 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12538 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12539 if (!AStmt) 12540 return StmtError(); 12541 12542 auto *CS = cast<CapturedStmt>(AStmt); 12543 // 1.2.2 OpenMP Language Terminology 12544 // Structured block - An executable statement with a single entry at the 12545 // top and a single exit at the bottom. 12546 // The point of exit cannot be a branch out of the structured block. 12547 // longjmp() and throw() must not violate the entry/exit criteria. 12548 CS->getCapturedDecl()->setNothrow(); 12549 12550 for (int ThisCaptureLevel = 12551 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for); 12552 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12553 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12554 // 1.2.2 OpenMP Language Terminology 12555 // Structured block - An executable statement with a single entry at the 12556 // top and a single exit at the bottom. 12557 // The point of exit cannot be a branch out of the structured block. 12558 // longjmp() and throw() must not violate the entry/exit criteria. 12559 CS->getCapturedDecl()->setNothrow(); 12560 } 12561 12562 OMPLoopBasedDirective::HelperExprs B; 12563 // In presence of clause 'collapse' with number of loops, it will 12564 // define the nested loops number. 12565 unsigned NestedLoopCount = checkOpenMPLoop( 12566 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 12567 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12568 VarsWithImplicitDSA, B); 12569 12570 if (NestedLoopCount == 0) 12571 return StmtError(); 12572 12573 assert((CurContext->isDependentContext() || B.builtAll()) && 12574 "omp for loop exprs were not built"); 12575 12576 setFunctionHasBranchProtectedScope(); 12577 12578 DSAStack->setParentTeamsRegionLoc(StartLoc); 12579 12580 return OMPTeamsDistributeParallelForDirective::Create( 12581 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 12582 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 12583 } 12584 12585 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 12586 Stmt *AStmt, 12587 SourceLocation StartLoc, 12588 SourceLocation EndLoc) { 12589 if (!AStmt) 12590 return StmtError(); 12591 12592 auto *CS = cast<CapturedStmt>(AStmt); 12593 // 1.2.2 OpenMP Language Terminology 12594 // Structured block - An executable statement with a single entry at the 12595 // top and a single exit at the bottom. 12596 // The point of exit cannot be a branch out of the structured block. 12597 // longjmp() and throw() must not violate the entry/exit criteria. 12598 CS->getCapturedDecl()->setNothrow(); 12599 12600 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams); 12601 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12602 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12603 // 1.2.2 OpenMP Language Terminology 12604 // Structured block - An executable statement with a single entry at the 12605 // top and a single exit at the bottom. 12606 // The point of exit cannot be a branch out of the structured block. 12607 // longjmp() and throw() must not violate the entry/exit criteria. 12608 CS->getCapturedDecl()->setNothrow(); 12609 } 12610 setFunctionHasBranchProtectedScope(); 12611 12612 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 12613 AStmt); 12614 } 12615 12616 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 12617 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12618 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12619 if (!AStmt) 12620 return StmtError(); 12621 12622 auto *CS = cast<CapturedStmt>(AStmt); 12623 // 1.2.2 OpenMP Language Terminology 12624 // Structured block - An executable statement with a single entry at the 12625 // top and a single exit at the bottom. 12626 // The point of exit cannot be a branch out of the structured block. 12627 // longjmp() and throw() must not violate the entry/exit criteria. 12628 CS->getCapturedDecl()->setNothrow(); 12629 for (int ThisCaptureLevel = 12630 getOpenMPCaptureLevels(OMPD_target_teams_distribute); 12631 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12632 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12633 // 1.2.2 OpenMP Language Terminology 12634 // Structured block - An executable statement with a single entry at the 12635 // top and a single exit at the bottom. 12636 // The point of exit cannot be a branch out of the structured block. 12637 // longjmp() and throw() must not violate the entry/exit criteria. 12638 CS->getCapturedDecl()->setNothrow(); 12639 } 12640 12641 OMPLoopBasedDirective::HelperExprs B; 12642 // In presence of clause 'collapse' with number of loops, it will 12643 // define the nested loops number. 12644 unsigned NestedLoopCount = checkOpenMPLoop( 12645 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses), 12646 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12647 VarsWithImplicitDSA, B); 12648 if (NestedLoopCount == 0) 12649 return StmtError(); 12650 12651 assert((CurContext->isDependentContext() || B.builtAll()) && 12652 "omp target teams distribute loop exprs were not built"); 12653 12654 setFunctionHasBranchProtectedScope(); 12655 return OMPTargetTeamsDistributeDirective::Create( 12656 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12657 } 12658 12659 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 12660 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12661 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12662 if (!AStmt) 12663 return StmtError(); 12664 12665 auto *CS = cast<CapturedStmt>(AStmt); 12666 // 1.2.2 OpenMP Language Terminology 12667 // Structured block - An executable statement with a single entry at the 12668 // top and a single exit at the bottom. 12669 // The point of exit cannot be a branch out of the structured block. 12670 // longjmp() and throw() must not violate the entry/exit criteria. 12671 CS->getCapturedDecl()->setNothrow(); 12672 for (int ThisCaptureLevel = 12673 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for); 12674 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12675 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12676 // 1.2.2 OpenMP Language Terminology 12677 // Structured block - An executable statement with a single entry at the 12678 // top and a single exit at the bottom. 12679 // The point of exit cannot be a branch out of the structured block. 12680 // longjmp() and throw() must not violate the entry/exit criteria. 12681 CS->getCapturedDecl()->setNothrow(); 12682 } 12683 12684 OMPLoopBasedDirective::HelperExprs B; 12685 // In presence of clause 'collapse' with number of loops, it will 12686 // define the nested loops number. 12687 unsigned NestedLoopCount = checkOpenMPLoop( 12688 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 12689 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12690 VarsWithImplicitDSA, B); 12691 if (NestedLoopCount == 0) 12692 return StmtError(); 12693 12694 assert((CurContext->isDependentContext() || B.builtAll()) && 12695 "omp target teams distribute parallel for loop exprs were not built"); 12696 12697 if (!CurContext->isDependentContext()) { 12698 // Finalize the clauses that need pre-built expressions for CodeGen. 12699 for (OMPClause *C : Clauses) { 12700 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12701 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12702 B.NumIterations, *this, CurScope, 12703 DSAStack)) 12704 return StmtError(); 12705 } 12706 } 12707 12708 setFunctionHasBranchProtectedScope(); 12709 return OMPTargetTeamsDistributeParallelForDirective::Create( 12710 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 12711 DSAStack->getTaskgroupReductionRef(), DSAStack->isCancelRegion()); 12712 } 12713 12714 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 12715 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12716 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12717 if (!AStmt) 12718 return StmtError(); 12719 12720 auto *CS = cast<CapturedStmt>(AStmt); 12721 // 1.2.2 OpenMP Language Terminology 12722 // Structured block - An executable statement with a single entry at the 12723 // top and a single exit at the bottom. 12724 // The point of exit cannot be a branch out of the structured block. 12725 // longjmp() and throw() must not violate the entry/exit criteria. 12726 CS->getCapturedDecl()->setNothrow(); 12727 for (int ThisCaptureLevel = getOpenMPCaptureLevels( 12728 OMPD_target_teams_distribute_parallel_for_simd); 12729 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12730 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12731 // 1.2.2 OpenMP Language Terminology 12732 // Structured block - An executable statement with a single entry at the 12733 // top and a single exit at the bottom. 12734 // The point of exit cannot be a branch out of the structured block. 12735 // longjmp() and throw() must not violate the entry/exit criteria. 12736 CS->getCapturedDecl()->setNothrow(); 12737 } 12738 12739 OMPLoopBasedDirective::HelperExprs B; 12740 // In presence of clause 'collapse' with number of loops, it will 12741 // define the nested loops number. 12742 unsigned NestedLoopCount = 12743 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd, 12744 getCollapseNumberExpr(Clauses), 12745 nullptr /*ordered not a clause on distribute*/, CS, *this, 12746 *DSAStack, VarsWithImplicitDSA, B); 12747 if (NestedLoopCount == 0) 12748 return StmtError(); 12749 12750 assert((CurContext->isDependentContext() || B.builtAll()) && 12751 "omp target teams distribute parallel for simd loop exprs were not " 12752 "built"); 12753 12754 if (!CurContext->isDependentContext()) { 12755 // Finalize the clauses that need pre-built expressions for CodeGen. 12756 for (OMPClause *C : Clauses) { 12757 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12758 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12759 B.NumIterations, *this, CurScope, 12760 DSAStack)) 12761 return StmtError(); 12762 } 12763 } 12764 12765 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12766 return StmtError(); 12767 12768 setFunctionHasBranchProtectedScope(); 12769 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 12770 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12771 } 12772 12773 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 12774 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 12775 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 12776 if (!AStmt) 12777 return StmtError(); 12778 12779 auto *CS = cast<CapturedStmt>(AStmt); 12780 // 1.2.2 OpenMP Language Terminology 12781 // Structured block - An executable statement with a single entry at the 12782 // top and a single exit at the bottom. 12783 // The point of exit cannot be a branch out of the structured block. 12784 // longjmp() and throw() must not violate the entry/exit criteria. 12785 CS->getCapturedDecl()->setNothrow(); 12786 for (int ThisCaptureLevel = 12787 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd); 12788 ThisCaptureLevel > 1; --ThisCaptureLevel) { 12789 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 12790 // 1.2.2 OpenMP Language Terminology 12791 // Structured block - An executable statement with a single entry at the 12792 // top and a single exit at the bottom. 12793 // The point of exit cannot be a branch out of the structured block. 12794 // longjmp() and throw() must not violate the entry/exit criteria. 12795 CS->getCapturedDecl()->setNothrow(); 12796 } 12797 12798 OMPLoopBasedDirective::HelperExprs B; 12799 // In presence of clause 'collapse' with number of loops, it will 12800 // define the nested loops number. 12801 unsigned NestedLoopCount = checkOpenMPLoop( 12802 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 12803 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 12804 VarsWithImplicitDSA, B); 12805 if (NestedLoopCount == 0) 12806 return StmtError(); 12807 12808 assert((CurContext->isDependentContext() || B.builtAll()) && 12809 "omp target teams distribute simd loop exprs were not built"); 12810 12811 if (!CurContext->isDependentContext()) { 12812 // Finalize the clauses that need pre-built expressions for CodeGen. 12813 for (OMPClause *C : Clauses) { 12814 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 12815 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 12816 B.NumIterations, *this, CurScope, 12817 DSAStack)) 12818 return StmtError(); 12819 } 12820 } 12821 12822 if (checkSimdlenSafelenSpecified(*this, Clauses)) 12823 return StmtError(); 12824 12825 setFunctionHasBranchProtectedScope(); 12826 return OMPTargetTeamsDistributeSimdDirective::Create( 12827 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 12828 } 12829 12830 bool Sema::checkTransformableLoopNest( 12831 OpenMPDirectiveKind Kind, Stmt *AStmt, int NumLoops, 12832 SmallVectorImpl<OMPLoopBasedDirective::HelperExprs> &LoopHelpers, 12833 Stmt *&Body, 12834 SmallVectorImpl<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>> 12835 &OriginalInits) { 12836 OriginalInits.emplace_back(); 12837 bool Result = OMPLoopBasedDirective::doForAllLoops( 12838 AStmt->IgnoreContainers(), /*TryImperfectlyNestedLoops=*/false, NumLoops, 12839 [this, &LoopHelpers, &Body, &OriginalInits, Kind](unsigned Cnt, 12840 Stmt *CurStmt) { 12841 VarsWithInheritedDSAType TmpDSA; 12842 unsigned SingleNumLoops = 12843 checkOpenMPLoop(Kind, nullptr, nullptr, CurStmt, *this, *DSAStack, 12844 TmpDSA, LoopHelpers[Cnt]); 12845 if (SingleNumLoops == 0) 12846 return true; 12847 assert(SingleNumLoops == 1 && "Expect single loop iteration space"); 12848 if (auto *For = dyn_cast<ForStmt>(CurStmt)) { 12849 OriginalInits.back().push_back(For->getInit()); 12850 Body = For->getBody(); 12851 } else { 12852 assert(isa<CXXForRangeStmt>(CurStmt) && 12853 "Expected canonical for or range-based for loops."); 12854 auto *CXXFor = cast<CXXForRangeStmt>(CurStmt); 12855 OriginalInits.back().push_back(CXXFor->getBeginStmt()); 12856 Body = CXXFor->getBody(); 12857 } 12858 OriginalInits.emplace_back(); 12859 return false; 12860 }, 12861 [&OriginalInits](OMPLoopBasedDirective *Transform) { 12862 Stmt *DependentPreInits; 12863 if (auto *Dir = dyn_cast<OMPTileDirective>(Transform)) 12864 DependentPreInits = Dir->getPreInits(); 12865 else if (auto *Dir = dyn_cast<OMPUnrollDirective>(Transform)) 12866 DependentPreInits = Dir->getPreInits(); 12867 else 12868 llvm_unreachable("Unhandled loop transformation"); 12869 if (!DependentPreInits) 12870 return; 12871 for (Decl *C : cast<DeclStmt>(DependentPreInits)->getDeclGroup()) 12872 OriginalInits.back().push_back(C); 12873 }); 12874 assert(OriginalInits.back().empty() && "No preinit after innermost loop"); 12875 OriginalInits.pop_back(); 12876 return Result; 12877 } 12878 12879 StmtResult Sema::ActOnOpenMPTileDirective(ArrayRef<OMPClause *> Clauses, 12880 Stmt *AStmt, SourceLocation StartLoc, 12881 SourceLocation EndLoc) { 12882 auto SizesClauses = 12883 OMPExecutableDirective::getClausesOfKind<OMPSizesClause>(Clauses); 12884 if (SizesClauses.empty()) { 12885 // A missing 'sizes' clause is already reported by the parser. 12886 return StmtError(); 12887 } 12888 const OMPSizesClause *SizesClause = *SizesClauses.begin(); 12889 unsigned NumLoops = SizesClause->getNumSizes(); 12890 12891 // Empty statement should only be possible if there already was an error. 12892 if (!AStmt) 12893 return StmtError(); 12894 12895 // Verify and diagnose loop nest. 12896 SmallVector<OMPLoopBasedDirective::HelperExprs, 4> LoopHelpers(NumLoops); 12897 Stmt *Body = nullptr; 12898 SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, 4> 12899 OriginalInits; 12900 if (!checkTransformableLoopNest(OMPD_tile, AStmt, NumLoops, LoopHelpers, Body, 12901 OriginalInits)) 12902 return StmtError(); 12903 12904 // Delay tiling to when template is completely instantiated. 12905 if (CurContext->isDependentContext()) 12906 return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, 12907 NumLoops, AStmt, nullptr, nullptr); 12908 12909 SmallVector<Decl *, 4> PreInits; 12910 12911 // Create iteration variables for the generated loops. 12912 SmallVector<VarDecl *, 4> FloorIndVars; 12913 SmallVector<VarDecl *, 4> TileIndVars; 12914 FloorIndVars.resize(NumLoops); 12915 TileIndVars.resize(NumLoops); 12916 for (unsigned I = 0; I < NumLoops; ++I) { 12917 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I]; 12918 12919 assert(LoopHelper.Counters.size() == 1 && 12920 "Expect single-dimensional loop iteration space"); 12921 auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters.front()); 12922 std::string OrigVarName = OrigCntVar->getNameInfo().getAsString(); 12923 DeclRefExpr *IterVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef); 12924 QualType CntTy = IterVarRef->getType(); 12925 12926 // Iteration variable for the floor (i.e. outer) loop. 12927 { 12928 std::string FloorCntName = 12929 (Twine(".floor_") + llvm::utostr(I) + ".iv." + OrigVarName).str(); 12930 VarDecl *FloorCntDecl = 12931 buildVarDecl(*this, {}, CntTy, FloorCntName, nullptr, OrigCntVar); 12932 FloorIndVars[I] = FloorCntDecl; 12933 } 12934 12935 // Iteration variable for the tile (i.e. inner) loop. 12936 { 12937 std::string TileCntName = 12938 (Twine(".tile_") + llvm::utostr(I) + ".iv." + OrigVarName).str(); 12939 12940 // Reuse the iteration variable created by checkOpenMPLoop. It is also 12941 // used by the expressions to derive the original iteration variable's 12942 // value from the logical iteration number. 12943 auto *TileCntDecl = cast<VarDecl>(IterVarRef->getDecl()); 12944 TileCntDecl->setDeclName(&PP.getIdentifierTable().get(TileCntName)); 12945 TileIndVars[I] = TileCntDecl; 12946 } 12947 for (auto &P : OriginalInits[I]) { 12948 if (auto *D = P.dyn_cast<Decl *>()) 12949 PreInits.push_back(D); 12950 else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>())) 12951 PreInits.append(PI->decl_begin(), PI->decl_end()); 12952 } 12953 if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits)) 12954 PreInits.append(PI->decl_begin(), PI->decl_end()); 12955 // Gather declarations for the data members used as counters. 12956 for (Expr *CounterRef : LoopHelper.Counters) { 12957 auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl(); 12958 if (isa<OMPCapturedExprDecl>(CounterDecl)) 12959 PreInits.push_back(CounterDecl); 12960 } 12961 } 12962 12963 // Once the original iteration values are set, append the innermost body. 12964 Stmt *Inner = Body; 12965 12966 // Create tile loops from the inside to the outside. 12967 for (int I = NumLoops - 1; I >= 0; --I) { 12968 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers[I]; 12969 Expr *NumIterations = LoopHelper.NumIterations; 12970 auto *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]); 12971 QualType CntTy = OrigCntVar->getType(); 12972 Expr *DimTileSize = SizesClause->getSizesRefs()[I]; 12973 Scope *CurScope = getCurScope(); 12974 12975 // Commonly used variables. 12976 DeclRefExpr *TileIV = buildDeclRefExpr(*this, TileIndVars[I], CntTy, 12977 OrigCntVar->getExprLoc()); 12978 DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy, 12979 OrigCntVar->getExprLoc()); 12980 12981 // For init-statement: auto .tile.iv = .floor.iv 12982 AddInitializerToDecl(TileIndVars[I], DefaultLvalueConversion(FloorIV).get(), 12983 /*DirectInit=*/false); 12984 Decl *CounterDecl = TileIndVars[I]; 12985 StmtResult InitStmt = new (Context) 12986 DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1), 12987 OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc()); 12988 if (!InitStmt.isUsable()) 12989 return StmtError(); 12990 12991 // For cond-expression: .tile.iv < min(.floor.iv + DimTileSize, 12992 // NumIterations) 12993 ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 12994 BO_Add, FloorIV, DimTileSize); 12995 if (!EndOfTile.isUsable()) 12996 return StmtError(); 12997 ExprResult IsPartialTile = 12998 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, 12999 NumIterations, EndOfTile.get()); 13000 if (!IsPartialTile.isUsable()) 13001 return StmtError(); 13002 ExprResult MinTileAndIterSpace = ActOnConditionalOp( 13003 LoopHelper.Cond->getBeginLoc(), LoopHelper.Cond->getEndLoc(), 13004 IsPartialTile.get(), NumIterations, EndOfTile.get()); 13005 if (!MinTileAndIterSpace.isUsable()) 13006 return StmtError(); 13007 ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13008 BO_LT, TileIV, MinTileAndIterSpace.get()); 13009 if (!CondExpr.isUsable()) 13010 return StmtError(); 13011 13012 // For incr-statement: ++.tile.iv 13013 ExprResult IncrStmt = 13014 BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), UO_PreInc, TileIV); 13015 if (!IncrStmt.isUsable()) 13016 return StmtError(); 13017 13018 // Statements to set the original iteration variable's value from the 13019 // logical iteration number. 13020 // Generated for loop is: 13021 // Original_for_init; 13022 // for (auto .tile.iv = .floor.iv; .tile.iv < min(.floor.iv + DimTileSize, 13023 // NumIterations); ++.tile.iv) { 13024 // Original_Body; 13025 // Original_counter_update; 13026 // } 13027 // FIXME: If the innermost body is an loop itself, inserting these 13028 // statements stops it being recognized as a perfectly nested loop (e.g. 13029 // for applying tiling again). If this is the case, sink the expressions 13030 // further into the inner loop. 13031 SmallVector<Stmt *, 4> BodyParts; 13032 BodyParts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end()); 13033 BodyParts.push_back(Inner); 13034 Inner = CompoundStmt::Create(Context, BodyParts, Inner->getBeginLoc(), 13035 Inner->getEndLoc()); 13036 Inner = new (Context) 13037 ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr, 13038 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(), 13039 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 13040 } 13041 13042 // Create floor loops from the inside to the outside. 13043 for (int I = NumLoops - 1; I >= 0; --I) { 13044 auto &LoopHelper = LoopHelpers[I]; 13045 Expr *NumIterations = LoopHelper.NumIterations; 13046 DeclRefExpr *OrigCntVar = cast<DeclRefExpr>(LoopHelper.Counters[0]); 13047 QualType CntTy = OrigCntVar->getType(); 13048 Expr *DimTileSize = SizesClause->getSizesRefs()[I]; 13049 Scope *CurScope = getCurScope(); 13050 13051 // Commonly used variables. 13052 DeclRefExpr *FloorIV = buildDeclRefExpr(*this, FloorIndVars[I], CntTy, 13053 OrigCntVar->getExprLoc()); 13054 13055 // For init-statement: auto .floor.iv = 0 13056 AddInitializerToDecl( 13057 FloorIndVars[I], 13058 ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(), 13059 /*DirectInit=*/false); 13060 Decl *CounterDecl = FloorIndVars[I]; 13061 StmtResult InitStmt = new (Context) 13062 DeclStmt(DeclGroupRef::Create(Context, &CounterDecl, 1), 13063 OrigCntVar->getBeginLoc(), OrigCntVar->getEndLoc()); 13064 if (!InitStmt.isUsable()) 13065 return StmtError(); 13066 13067 // For cond-expression: .floor.iv < NumIterations 13068 ExprResult CondExpr = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13069 BO_LT, FloorIV, NumIterations); 13070 if (!CondExpr.isUsable()) 13071 return StmtError(); 13072 13073 // For incr-statement: .floor.iv += DimTileSize 13074 ExprResult IncrStmt = BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), 13075 BO_AddAssign, FloorIV, DimTileSize); 13076 if (!IncrStmt.isUsable()) 13077 return StmtError(); 13078 13079 Inner = new (Context) 13080 ForStmt(Context, InitStmt.get(), CondExpr.get(), nullptr, 13081 IncrStmt.get(), Inner, LoopHelper.Init->getBeginLoc(), 13082 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 13083 } 13084 13085 return OMPTileDirective::Create(Context, StartLoc, EndLoc, Clauses, NumLoops, 13086 AStmt, Inner, 13087 buildPreInits(Context, PreInits)); 13088 } 13089 13090 StmtResult Sema::ActOnOpenMPUnrollDirective(ArrayRef<OMPClause *> Clauses, 13091 Stmt *AStmt, 13092 SourceLocation StartLoc, 13093 SourceLocation EndLoc) { 13094 // Empty statement should only be possible if there already was an error. 13095 if (!AStmt) 13096 return StmtError(); 13097 13098 if (checkMutuallyExclusiveClauses(*this, Clauses, {OMPC_partial, OMPC_full})) 13099 return StmtError(); 13100 13101 const OMPFullClause *FullClause = 13102 OMPExecutableDirective::getSingleClause<OMPFullClause>(Clauses); 13103 const OMPPartialClause *PartialClause = 13104 OMPExecutableDirective::getSingleClause<OMPPartialClause>(Clauses); 13105 assert(!(FullClause && PartialClause) && 13106 "mutual exclusivity must have been checked before"); 13107 13108 constexpr unsigned NumLoops = 1; 13109 Stmt *Body = nullptr; 13110 SmallVector<OMPLoopBasedDirective::HelperExprs, NumLoops> LoopHelpers( 13111 NumLoops); 13112 SmallVector<SmallVector<llvm::PointerUnion<Stmt *, Decl *>, 0>, NumLoops + 1> 13113 OriginalInits; 13114 if (!checkTransformableLoopNest(OMPD_unroll, AStmt, NumLoops, LoopHelpers, 13115 Body, OriginalInits)) 13116 return StmtError(); 13117 13118 unsigned NumGeneratedLoops = PartialClause ? 1 : 0; 13119 13120 // Delay unrolling to when template is completely instantiated. 13121 if (CurContext->isDependentContext()) 13122 return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 13123 NumGeneratedLoops, nullptr, nullptr); 13124 13125 OMPLoopBasedDirective::HelperExprs &LoopHelper = LoopHelpers.front(); 13126 13127 if (FullClause) { 13128 if (!VerifyPositiveIntegerConstantInClause( 13129 LoopHelper.NumIterations, OMPC_full, /*StrictlyPositive=*/false, 13130 /*SuppressExprDigs=*/true) 13131 .isUsable()) { 13132 Diag(AStmt->getBeginLoc(), diag::err_omp_unroll_full_variable_trip_count); 13133 Diag(FullClause->getBeginLoc(), diag::note_omp_directive_here) 13134 << "#pragma omp unroll full"; 13135 return StmtError(); 13136 } 13137 } 13138 13139 // The generated loop may only be passed to other loop-associated directive 13140 // when a partial clause is specified. Without the requirement it is 13141 // sufficient to generate loop unroll metadata at code-generation. 13142 if (NumGeneratedLoops == 0) 13143 return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 13144 NumGeneratedLoops, nullptr, nullptr); 13145 13146 // Otherwise, we need to provide a de-sugared/transformed AST that can be 13147 // associated with another loop directive. 13148 // 13149 // The canonical loop analysis return by checkTransformableLoopNest assumes 13150 // the following structure to be the same loop without transformations or 13151 // directives applied: \code OriginalInits; LoopHelper.PreInits; 13152 // LoopHelper.Counters; 13153 // for (; IV < LoopHelper.NumIterations; ++IV) { 13154 // LoopHelper.Updates; 13155 // Body; 13156 // } 13157 // \endcode 13158 // where IV is a variable declared and initialized to 0 in LoopHelper.PreInits 13159 // and referenced by LoopHelper.IterationVarRef. 13160 // 13161 // The unrolling directive transforms this into the following loop: 13162 // \code 13163 // OriginalInits; \ 13164 // LoopHelper.PreInits; > NewPreInits 13165 // LoopHelper.Counters; / 13166 // for (auto UIV = 0; UIV < LoopHelper.NumIterations; UIV+=Factor) { 13167 // #pragma clang loop unroll_count(Factor) 13168 // for (IV = UIV; IV < UIV + Factor && UIV < LoopHelper.NumIterations; ++IV) 13169 // { 13170 // LoopHelper.Updates; 13171 // Body; 13172 // } 13173 // } 13174 // \endcode 13175 // where UIV is a new logical iteration counter. IV must be the same VarDecl 13176 // as the original LoopHelper.IterationVarRef because LoopHelper.Updates 13177 // references it. If the partially unrolled loop is associated with another 13178 // loop directive (like an OMPForDirective), it will use checkOpenMPLoop to 13179 // analyze this loop, i.e. the outer loop must fulfill the constraints of an 13180 // OpenMP canonical loop. The inner loop is not an associable canonical loop 13181 // and only exists to defer its unrolling to LLVM's LoopUnroll instead of 13182 // doing it in the frontend (by adding loop metadata). NewPreInits becomes a 13183 // property of the OMPLoopBasedDirective instead of statements in 13184 // CompoundStatement. This is to allow the loop to become a non-outermost loop 13185 // of a canonical loop nest where these PreInits are emitted before the 13186 // outermost directive. 13187 13188 // Determine the PreInit declarations. 13189 SmallVector<Decl *, 4> PreInits; 13190 assert(OriginalInits.size() == 1 && 13191 "Expecting a single-dimensional loop iteration space"); 13192 for (auto &P : OriginalInits[0]) { 13193 if (auto *D = P.dyn_cast<Decl *>()) 13194 PreInits.push_back(D); 13195 else if (auto *PI = dyn_cast_or_null<DeclStmt>(P.dyn_cast<Stmt *>())) 13196 PreInits.append(PI->decl_begin(), PI->decl_end()); 13197 } 13198 if (auto *PI = cast_or_null<DeclStmt>(LoopHelper.PreInits)) 13199 PreInits.append(PI->decl_begin(), PI->decl_end()); 13200 // Gather declarations for the data members used as counters. 13201 for (Expr *CounterRef : LoopHelper.Counters) { 13202 auto *CounterDecl = cast<DeclRefExpr>(CounterRef)->getDecl(); 13203 if (isa<OMPCapturedExprDecl>(CounterDecl)) 13204 PreInits.push_back(CounterDecl); 13205 } 13206 13207 auto *IterationVarRef = cast<DeclRefExpr>(LoopHelper.IterationVarRef); 13208 QualType IVTy = IterationVarRef->getType(); 13209 assert(LoopHelper.Counters.size() == 1 && 13210 "Expecting a single-dimensional loop iteration space"); 13211 auto *OrigVar = cast<DeclRefExpr>(LoopHelper.Counters.front()); 13212 13213 // Determine the unroll factor. 13214 uint64_t Factor; 13215 SourceLocation FactorLoc; 13216 if (Expr *FactorVal = PartialClause->getFactor()) { 13217 Factor = 13218 FactorVal->getIntegerConstantExpr(Context).getValue().getZExtValue(); 13219 FactorLoc = FactorVal->getExprLoc(); 13220 } else { 13221 // TODO: Use a better profitability model. 13222 Factor = 2; 13223 } 13224 assert(Factor > 0 && "Expected positive unroll factor"); 13225 auto MakeFactorExpr = [this, Factor, IVTy, FactorLoc]() { 13226 return IntegerLiteral::Create( 13227 Context, llvm::APInt(Context.getIntWidth(IVTy), Factor), IVTy, 13228 FactorLoc); 13229 }; 13230 13231 // Iteration variable SourceLocations. 13232 SourceLocation OrigVarLoc = OrigVar->getExprLoc(); 13233 SourceLocation OrigVarLocBegin = OrigVar->getBeginLoc(); 13234 SourceLocation OrigVarLocEnd = OrigVar->getEndLoc(); 13235 13236 // Internal variable names. 13237 std::string OrigVarName = OrigVar->getNameInfo().getAsString(); 13238 std::string OuterIVName = (Twine(".unrolled.iv.") + OrigVarName).str(); 13239 std::string InnerIVName = (Twine(".unroll_inner.iv.") + OrigVarName).str(); 13240 std::string InnerTripCountName = 13241 (Twine(".unroll_inner.tripcount.") + OrigVarName).str(); 13242 13243 // Create the iteration variable for the unrolled loop. 13244 VarDecl *OuterIVDecl = 13245 buildVarDecl(*this, {}, IVTy, OuterIVName, nullptr, OrigVar); 13246 auto MakeOuterRef = [this, OuterIVDecl, IVTy, OrigVarLoc]() { 13247 return buildDeclRefExpr(*this, OuterIVDecl, IVTy, OrigVarLoc); 13248 }; 13249 13250 // Iteration variable for the inner loop: Reuse the iteration variable created 13251 // by checkOpenMPLoop. 13252 auto *InnerIVDecl = cast<VarDecl>(IterationVarRef->getDecl()); 13253 InnerIVDecl->setDeclName(&PP.getIdentifierTable().get(InnerIVName)); 13254 auto MakeInnerRef = [this, InnerIVDecl, IVTy, OrigVarLoc]() { 13255 return buildDeclRefExpr(*this, InnerIVDecl, IVTy, OrigVarLoc); 13256 }; 13257 13258 // Make a copy of the NumIterations expression for each use: By the AST 13259 // constraints, every expression object in a DeclContext must be unique. 13260 CaptureVars CopyTransformer(*this); 13261 auto MakeNumIterations = [&CopyTransformer, &LoopHelper]() -> Expr * { 13262 return AssertSuccess( 13263 CopyTransformer.TransformExpr(LoopHelper.NumIterations)); 13264 }; 13265 13266 // Inner For init-statement: auto .unroll_inner.iv = .unrolled.iv 13267 ExprResult LValueConv = DefaultLvalueConversion(MakeOuterRef()); 13268 AddInitializerToDecl(InnerIVDecl, LValueConv.get(), /*DirectInit=*/false); 13269 StmtResult InnerInit = new (Context) 13270 DeclStmt(DeclGroupRef(InnerIVDecl), OrigVarLocBegin, OrigVarLocEnd); 13271 if (!InnerInit.isUsable()) 13272 return StmtError(); 13273 13274 // Inner For cond-expression: 13275 // \code 13276 // .unroll_inner.iv < .unrolled.iv + Factor && 13277 // .unroll_inner.iv < NumIterations 13278 // \endcode 13279 // This conjunction of two conditions allows ScalarEvolution to derive the 13280 // maximum trip count of the inner loop. 13281 ExprResult EndOfTile = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13282 BO_Add, MakeOuterRef(), MakeFactorExpr()); 13283 if (!EndOfTile.isUsable()) 13284 return StmtError(); 13285 ExprResult InnerCond1 = BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), 13286 BO_LE, MakeInnerRef(), EndOfTile.get()); 13287 if (!InnerCond1.isUsable()) 13288 return StmtError(); 13289 ExprResult InnerCond2 = 13290 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LE, MakeInnerRef(), 13291 MakeNumIterations()); 13292 if (!InnerCond2.isUsable()) 13293 return StmtError(); 13294 ExprResult InnerCond = 13295 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LAnd, 13296 InnerCond1.get(), InnerCond2.get()); 13297 if (!InnerCond.isUsable()) 13298 return StmtError(); 13299 13300 // Inner For incr-statement: ++.unroll_inner.iv 13301 ExprResult InnerIncr = BuildUnaryOp(CurScope, LoopHelper.Inc->getExprLoc(), 13302 UO_PreInc, MakeInnerRef()); 13303 if (!InnerIncr.isUsable()) 13304 return StmtError(); 13305 13306 // Inner For statement. 13307 SmallVector<Stmt *> InnerBodyStmts; 13308 InnerBodyStmts.append(LoopHelper.Updates.begin(), LoopHelper.Updates.end()); 13309 InnerBodyStmts.push_back(Body); 13310 CompoundStmt *InnerBody = CompoundStmt::Create( 13311 Context, InnerBodyStmts, Body->getBeginLoc(), Body->getEndLoc()); 13312 ForStmt *InnerFor = new (Context) 13313 ForStmt(Context, InnerInit.get(), InnerCond.get(), nullptr, 13314 InnerIncr.get(), InnerBody, LoopHelper.Init->getBeginLoc(), 13315 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 13316 13317 // Unroll metadata for the inner loop. 13318 // This needs to take into account the remainder portion of the unrolled loop, 13319 // hence `unroll(full)` does not apply here, even though the LoopUnroll pass 13320 // supports multiple loop exits. Instead, unroll using a factor equivalent to 13321 // the maximum trip count, which will also generate a remainder loop. Just 13322 // `unroll(enable)` (which could have been useful if the user has not 13323 // specified a concrete factor; even though the outer loop cannot be 13324 // influenced anymore, would avoid more code bloat than necessary) will refuse 13325 // the loop because "Won't unroll; remainder loop could not be generated when 13326 // assuming runtime trip count". Even if it did work, it must not choose a 13327 // larger unroll factor than the maximum loop length, or it would always just 13328 // execute the remainder loop. 13329 LoopHintAttr *UnrollHintAttr = 13330 LoopHintAttr::CreateImplicit(Context, LoopHintAttr::UnrollCount, 13331 LoopHintAttr::Numeric, MakeFactorExpr()); 13332 AttributedStmt *InnerUnrolled = 13333 AttributedStmt::Create(Context, StartLoc, {UnrollHintAttr}, InnerFor); 13334 13335 // Outer For init-statement: auto .unrolled.iv = 0 13336 AddInitializerToDecl( 13337 OuterIVDecl, ActOnIntegerConstant(LoopHelper.Init->getExprLoc(), 0).get(), 13338 /*DirectInit=*/false); 13339 StmtResult OuterInit = new (Context) 13340 DeclStmt(DeclGroupRef(OuterIVDecl), OrigVarLocBegin, OrigVarLocEnd); 13341 if (!OuterInit.isUsable()) 13342 return StmtError(); 13343 13344 // Outer For cond-expression: .unrolled.iv < NumIterations 13345 ExprResult OuterConde = 13346 BuildBinOp(CurScope, LoopHelper.Cond->getExprLoc(), BO_LT, MakeOuterRef(), 13347 MakeNumIterations()); 13348 if (!OuterConde.isUsable()) 13349 return StmtError(); 13350 13351 // Outer For incr-statement: .unrolled.iv += Factor 13352 ExprResult OuterIncr = 13353 BuildBinOp(CurScope, LoopHelper.Inc->getExprLoc(), BO_AddAssign, 13354 MakeOuterRef(), MakeFactorExpr()); 13355 if (!OuterIncr.isUsable()) 13356 return StmtError(); 13357 13358 // Outer For statement. 13359 ForStmt *OuterFor = new (Context) 13360 ForStmt(Context, OuterInit.get(), OuterConde.get(), nullptr, 13361 OuterIncr.get(), InnerUnrolled, LoopHelper.Init->getBeginLoc(), 13362 LoopHelper.Init->getBeginLoc(), LoopHelper.Inc->getEndLoc()); 13363 13364 return OMPUnrollDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 13365 NumGeneratedLoops, OuterFor, 13366 buildPreInits(Context, PreInits)); 13367 } 13368 13369 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 13370 SourceLocation StartLoc, 13371 SourceLocation LParenLoc, 13372 SourceLocation EndLoc) { 13373 OMPClause *Res = nullptr; 13374 switch (Kind) { 13375 case OMPC_final: 13376 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 13377 break; 13378 case OMPC_num_threads: 13379 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 13380 break; 13381 case OMPC_safelen: 13382 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 13383 break; 13384 case OMPC_simdlen: 13385 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 13386 break; 13387 case OMPC_allocator: 13388 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc); 13389 break; 13390 case OMPC_collapse: 13391 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 13392 break; 13393 case OMPC_ordered: 13394 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 13395 break; 13396 case OMPC_num_teams: 13397 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 13398 break; 13399 case OMPC_thread_limit: 13400 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 13401 break; 13402 case OMPC_priority: 13403 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 13404 break; 13405 case OMPC_grainsize: 13406 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 13407 break; 13408 case OMPC_num_tasks: 13409 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 13410 break; 13411 case OMPC_hint: 13412 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 13413 break; 13414 case OMPC_depobj: 13415 Res = ActOnOpenMPDepobjClause(Expr, StartLoc, LParenLoc, EndLoc); 13416 break; 13417 case OMPC_detach: 13418 Res = ActOnOpenMPDetachClause(Expr, StartLoc, LParenLoc, EndLoc); 13419 break; 13420 case OMPC_novariants: 13421 Res = ActOnOpenMPNovariantsClause(Expr, StartLoc, LParenLoc, EndLoc); 13422 break; 13423 case OMPC_nocontext: 13424 Res = ActOnOpenMPNocontextClause(Expr, StartLoc, LParenLoc, EndLoc); 13425 break; 13426 case OMPC_filter: 13427 Res = ActOnOpenMPFilterClause(Expr, StartLoc, LParenLoc, EndLoc); 13428 break; 13429 case OMPC_partial: 13430 Res = ActOnOpenMPPartialClause(Expr, StartLoc, LParenLoc, EndLoc); 13431 break; 13432 case OMPC_align: 13433 Res = ActOnOpenMPAlignClause(Expr, StartLoc, LParenLoc, EndLoc); 13434 break; 13435 case OMPC_device: 13436 case OMPC_if: 13437 case OMPC_default: 13438 case OMPC_proc_bind: 13439 case OMPC_schedule: 13440 case OMPC_private: 13441 case OMPC_firstprivate: 13442 case OMPC_lastprivate: 13443 case OMPC_shared: 13444 case OMPC_reduction: 13445 case OMPC_task_reduction: 13446 case OMPC_in_reduction: 13447 case OMPC_linear: 13448 case OMPC_aligned: 13449 case OMPC_copyin: 13450 case OMPC_copyprivate: 13451 case OMPC_nowait: 13452 case OMPC_untied: 13453 case OMPC_mergeable: 13454 case OMPC_threadprivate: 13455 case OMPC_sizes: 13456 case OMPC_allocate: 13457 case OMPC_flush: 13458 case OMPC_read: 13459 case OMPC_write: 13460 case OMPC_update: 13461 case OMPC_capture: 13462 case OMPC_seq_cst: 13463 case OMPC_acq_rel: 13464 case OMPC_acquire: 13465 case OMPC_release: 13466 case OMPC_relaxed: 13467 case OMPC_depend: 13468 case OMPC_threads: 13469 case OMPC_simd: 13470 case OMPC_map: 13471 case OMPC_nogroup: 13472 case OMPC_dist_schedule: 13473 case OMPC_defaultmap: 13474 case OMPC_unknown: 13475 case OMPC_uniform: 13476 case OMPC_to: 13477 case OMPC_from: 13478 case OMPC_use_device_ptr: 13479 case OMPC_use_device_addr: 13480 case OMPC_is_device_ptr: 13481 case OMPC_unified_address: 13482 case OMPC_unified_shared_memory: 13483 case OMPC_reverse_offload: 13484 case OMPC_dynamic_allocators: 13485 case OMPC_atomic_default_mem_order: 13486 case OMPC_device_type: 13487 case OMPC_match: 13488 case OMPC_nontemporal: 13489 case OMPC_order: 13490 case OMPC_destroy: 13491 case OMPC_inclusive: 13492 case OMPC_exclusive: 13493 case OMPC_uses_allocators: 13494 case OMPC_affinity: 13495 case OMPC_when: 13496 case OMPC_bind: 13497 default: 13498 llvm_unreachable("Clause is not allowed."); 13499 } 13500 return Res; 13501 } 13502 13503 // An OpenMP directive such as 'target parallel' has two captured regions: 13504 // for the 'target' and 'parallel' respectively. This function returns 13505 // the region in which to capture expressions associated with a clause. 13506 // A return value of OMPD_unknown signifies that the expression should not 13507 // be captured. 13508 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 13509 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion, 13510 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 13511 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 13512 switch (CKind) { 13513 case OMPC_if: 13514 switch (DKind) { 13515 case OMPD_target_parallel_for_simd: 13516 if (OpenMPVersion >= 50 && 13517 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 13518 CaptureRegion = OMPD_parallel; 13519 break; 13520 } 13521 LLVM_FALLTHROUGH; 13522 case OMPD_target_parallel: 13523 case OMPD_target_parallel_for: 13524 // If this clause applies to the nested 'parallel' region, capture within 13525 // the 'target' region, otherwise do not capture. 13526 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 13527 CaptureRegion = OMPD_target; 13528 break; 13529 case OMPD_target_teams_distribute_parallel_for_simd: 13530 if (OpenMPVersion >= 50 && 13531 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 13532 CaptureRegion = OMPD_parallel; 13533 break; 13534 } 13535 LLVM_FALLTHROUGH; 13536 case OMPD_target_teams_distribute_parallel_for: 13537 // If this clause applies to the nested 'parallel' region, capture within 13538 // the 'teams' region, otherwise do not capture. 13539 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 13540 CaptureRegion = OMPD_teams; 13541 break; 13542 case OMPD_teams_distribute_parallel_for_simd: 13543 if (OpenMPVersion >= 50 && 13544 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) { 13545 CaptureRegion = OMPD_parallel; 13546 break; 13547 } 13548 LLVM_FALLTHROUGH; 13549 case OMPD_teams_distribute_parallel_for: 13550 CaptureRegion = OMPD_teams; 13551 break; 13552 case OMPD_target_update: 13553 case OMPD_target_enter_data: 13554 case OMPD_target_exit_data: 13555 CaptureRegion = OMPD_task; 13556 break; 13557 case OMPD_parallel_master_taskloop: 13558 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop) 13559 CaptureRegion = OMPD_parallel; 13560 break; 13561 case OMPD_parallel_master_taskloop_simd: 13562 if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) || 13563 NameModifier == OMPD_taskloop) { 13564 CaptureRegion = OMPD_parallel; 13565 break; 13566 } 13567 if (OpenMPVersion <= 45) 13568 break; 13569 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 13570 CaptureRegion = OMPD_taskloop; 13571 break; 13572 case OMPD_parallel_for_simd: 13573 if (OpenMPVersion <= 45) 13574 break; 13575 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 13576 CaptureRegion = OMPD_parallel; 13577 break; 13578 case OMPD_taskloop_simd: 13579 case OMPD_master_taskloop_simd: 13580 if (OpenMPVersion <= 45) 13581 break; 13582 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 13583 CaptureRegion = OMPD_taskloop; 13584 break; 13585 case OMPD_distribute_parallel_for_simd: 13586 if (OpenMPVersion <= 45) 13587 break; 13588 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd) 13589 CaptureRegion = OMPD_parallel; 13590 break; 13591 case OMPD_target_simd: 13592 if (OpenMPVersion >= 50 && 13593 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) 13594 CaptureRegion = OMPD_target; 13595 break; 13596 case OMPD_teams_distribute_simd: 13597 case OMPD_target_teams_distribute_simd: 13598 if (OpenMPVersion >= 50 && 13599 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) 13600 CaptureRegion = OMPD_teams; 13601 break; 13602 case OMPD_cancel: 13603 case OMPD_parallel: 13604 case OMPD_parallel_master: 13605 case OMPD_parallel_sections: 13606 case OMPD_parallel_for: 13607 case OMPD_target: 13608 case OMPD_target_teams: 13609 case OMPD_target_teams_distribute: 13610 case OMPD_distribute_parallel_for: 13611 case OMPD_task: 13612 case OMPD_taskloop: 13613 case OMPD_master_taskloop: 13614 case OMPD_target_data: 13615 case OMPD_simd: 13616 case OMPD_for_simd: 13617 case OMPD_distribute_simd: 13618 // Do not capture if-clause expressions. 13619 break; 13620 case OMPD_threadprivate: 13621 case OMPD_allocate: 13622 case OMPD_taskyield: 13623 case OMPD_barrier: 13624 case OMPD_taskwait: 13625 case OMPD_cancellation_point: 13626 case OMPD_flush: 13627 case OMPD_depobj: 13628 case OMPD_scan: 13629 case OMPD_declare_reduction: 13630 case OMPD_declare_mapper: 13631 case OMPD_declare_simd: 13632 case OMPD_declare_variant: 13633 case OMPD_begin_declare_variant: 13634 case OMPD_end_declare_variant: 13635 case OMPD_declare_target: 13636 case OMPD_end_declare_target: 13637 case OMPD_loop: 13638 case OMPD_teams: 13639 case OMPD_tile: 13640 case OMPD_unroll: 13641 case OMPD_for: 13642 case OMPD_sections: 13643 case OMPD_section: 13644 case OMPD_single: 13645 case OMPD_master: 13646 case OMPD_masked: 13647 case OMPD_critical: 13648 case OMPD_taskgroup: 13649 case OMPD_distribute: 13650 case OMPD_ordered: 13651 case OMPD_atomic: 13652 case OMPD_teams_distribute: 13653 case OMPD_requires: 13654 case OMPD_metadirective: 13655 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 13656 case OMPD_unknown: 13657 default: 13658 llvm_unreachable("Unknown OpenMP directive"); 13659 } 13660 break; 13661 case OMPC_num_threads: 13662 switch (DKind) { 13663 case OMPD_target_parallel: 13664 case OMPD_target_parallel_for: 13665 case OMPD_target_parallel_for_simd: 13666 CaptureRegion = OMPD_target; 13667 break; 13668 case OMPD_teams_distribute_parallel_for: 13669 case OMPD_teams_distribute_parallel_for_simd: 13670 case OMPD_target_teams_distribute_parallel_for: 13671 case OMPD_target_teams_distribute_parallel_for_simd: 13672 CaptureRegion = OMPD_teams; 13673 break; 13674 case OMPD_parallel: 13675 case OMPD_parallel_master: 13676 case OMPD_parallel_sections: 13677 case OMPD_parallel_for: 13678 case OMPD_parallel_for_simd: 13679 case OMPD_distribute_parallel_for: 13680 case OMPD_distribute_parallel_for_simd: 13681 case OMPD_parallel_master_taskloop: 13682 case OMPD_parallel_master_taskloop_simd: 13683 // Do not capture num_threads-clause expressions. 13684 break; 13685 case OMPD_target_data: 13686 case OMPD_target_enter_data: 13687 case OMPD_target_exit_data: 13688 case OMPD_target_update: 13689 case OMPD_target: 13690 case OMPD_target_simd: 13691 case OMPD_target_teams: 13692 case OMPD_target_teams_distribute: 13693 case OMPD_target_teams_distribute_simd: 13694 case OMPD_cancel: 13695 case OMPD_task: 13696 case OMPD_taskloop: 13697 case OMPD_taskloop_simd: 13698 case OMPD_master_taskloop: 13699 case OMPD_master_taskloop_simd: 13700 case OMPD_threadprivate: 13701 case OMPD_allocate: 13702 case OMPD_taskyield: 13703 case OMPD_barrier: 13704 case OMPD_taskwait: 13705 case OMPD_cancellation_point: 13706 case OMPD_flush: 13707 case OMPD_depobj: 13708 case OMPD_scan: 13709 case OMPD_declare_reduction: 13710 case OMPD_declare_mapper: 13711 case OMPD_declare_simd: 13712 case OMPD_declare_variant: 13713 case OMPD_begin_declare_variant: 13714 case OMPD_end_declare_variant: 13715 case OMPD_declare_target: 13716 case OMPD_end_declare_target: 13717 case OMPD_loop: 13718 case OMPD_teams: 13719 case OMPD_simd: 13720 case OMPD_tile: 13721 case OMPD_unroll: 13722 case OMPD_for: 13723 case OMPD_for_simd: 13724 case OMPD_sections: 13725 case OMPD_section: 13726 case OMPD_single: 13727 case OMPD_master: 13728 case OMPD_masked: 13729 case OMPD_critical: 13730 case OMPD_taskgroup: 13731 case OMPD_distribute: 13732 case OMPD_ordered: 13733 case OMPD_atomic: 13734 case OMPD_distribute_simd: 13735 case OMPD_teams_distribute: 13736 case OMPD_teams_distribute_simd: 13737 case OMPD_requires: 13738 case OMPD_metadirective: 13739 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 13740 case OMPD_unknown: 13741 default: 13742 llvm_unreachable("Unknown OpenMP directive"); 13743 } 13744 break; 13745 case OMPC_num_teams: 13746 switch (DKind) { 13747 case OMPD_target_teams: 13748 case OMPD_target_teams_distribute: 13749 case OMPD_target_teams_distribute_simd: 13750 case OMPD_target_teams_distribute_parallel_for: 13751 case OMPD_target_teams_distribute_parallel_for_simd: 13752 CaptureRegion = OMPD_target; 13753 break; 13754 case OMPD_teams_distribute_parallel_for: 13755 case OMPD_teams_distribute_parallel_for_simd: 13756 case OMPD_teams: 13757 case OMPD_teams_distribute: 13758 case OMPD_teams_distribute_simd: 13759 // Do not capture num_teams-clause expressions. 13760 break; 13761 case OMPD_distribute_parallel_for: 13762 case OMPD_distribute_parallel_for_simd: 13763 case OMPD_task: 13764 case OMPD_taskloop: 13765 case OMPD_taskloop_simd: 13766 case OMPD_master_taskloop: 13767 case OMPD_master_taskloop_simd: 13768 case OMPD_parallel_master_taskloop: 13769 case OMPD_parallel_master_taskloop_simd: 13770 case OMPD_target_data: 13771 case OMPD_target_enter_data: 13772 case OMPD_target_exit_data: 13773 case OMPD_target_update: 13774 case OMPD_cancel: 13775 case OMPD_parallel: 13776 case OMPD_parallel_master: 13777 case OMPD_parallel_sections: 13778 case OMPD_parallel_for: 13779 case OMPD_parallel_for_simd: 13780 case OMPD_target: 13781 case OMPD_target_simd: 13782 case OMPD_target_parallel: 13783 case OMPD_target_parallel_for: 13784 case OMPD_target_parallel_for_simd: 13785 case OMPD_threadprivate: 13786 case OMPD_allocate: 13787 case OMPD_taskyield: 13788 case OMPD_barrier: 13789 case OMPD_taskwait: 13790 case OMPD_cancellation_point: 13791 case OMPD_flush: 13792 case OMPD_depobj: 13793 case OMPD_scan: 13794 case OMPD_declare_reduction: 13795 case OMPD_declare_mapper: 13796 case OMPD_declare_simd: 13797 case OMPD_declare_variant: 13798 case OMPD_begin_declare_variant: 13799 case OMPD_end_declare_variant: 13800 case OMPD_declare_target: 13801 case OMPD_end_declare_target: 13802 case OMPD_loop: 13803 case OMPD_simd: 13804 case OMPD_tile: 13805 case OMPD_unroll: 13806 case OMPD_for: 13807 case OMPD_for_simd: 13808 case OMPD_sections: 13809 case OMPD_section: 13810 case OMPD_single: 13811 case OMPD_master: 13812 case OMPD_masked: 13813 case OMPD_critical: 13814 case OMPD_taskgroup: 13815 case OMPD_distribute: 13816 case OMPD_ordered: 13817 case OMPD_atomic: 13818 case OMPD_distribute_simd: 13819 case OMPD_requires: 13820 case OMPD_metadirective: 13821 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 13822 case OMPD_unknown: 13823 default: 13824 llvm_unreachable("Unknown OpenMP directive"); 13825 } 13826 break; 13827 case OMPC_thread_limit: 13828 switch (DKind) { 13829 case OMPD_target_teams: 13830 case OMPD_target_teams_distribute: 13831 case OMPD_target_teams_distribute_simd: 13832 case OMPD_target_teams_distribute_parallel_for: 13833 case OMPD_target_teams_distribute_parallel_for_simd: 13834 CaptureRegion = OMPD_target; 13835 break; 13836 case OMPD_teams_distribute_parallel_for: 13837 case OMPD_teams_distribute_parallel_for_simd: 13838 case OMPD_teams: 13839 case OMPD_teams_distribute: 13840 case OMPD_teams_distribute_simd: 13841 // Do not capture thread_limit-clause expressions. 13842 break; 13843 case OMPD_distribute_parallel_for: 13844 case OMPD_distribute_parallel_for_simd: 13845 case OMPD_task: 13846 case OMPD_taskloop: 13847 case OMPD_taskloop_simd: 13848 case OMPD_master_taskloop: 13849 case OMPD_master_taskloop_simd: 13850 case OMPD_parallel_master_taskloop: 13851 case OMPD_parallel_master_taskloop_simd: 13852 case OMPD_target_data: 13853 case OMPD_target_enter_data: 13854 case OMPD_target_exit_data: 13855 case OMPD_target_update: 13856 case OMPD_cancel: 13857 case OMPD_parallel: 13858 case OMPD_parallel_master: 13859 case OMPD_parallel_sections: 13860 case OMPD_parallel_for: 13861 case OMPD_parallel_for_simd: 13862 case OMPD_target: 13863 case OMPD_target_simd: 13864 case OMPD_target_parallel: 13865 case OMPD_target_parallel_for: 13866 case OMPD_target_parallel_for_simd: 13867 case OMPD_threadprivate: 13868 case OMPD_allocate: 13869 case OMPD_taskyield: 13870 case OMPD_barrier: 13871 case OMPD_taskwait: 13872 case OMPD_cancellation_point: 13873 case OMPD_flush: 13874 case OMPD_depobj: 13875 case OMPD_scan: 13876 case OMPD_declare_reduction: 13877 case OMPD_declare_mapper: 13878 case OMPD_declare_simd: 13879 case OMPD_declare_variant: 13880 case OMPD_begin_declare_variant: 13881 case OMPD_end_declare_variant: 13882 case OMPD_declare_target: 13883 case OMPD_end_declare_target: 13884 case OMPD_loop: 13885 case OMPD_simd: 13886 case OMPD_tile: 13887 case OMPD_unroll: 13888 case OMPD_for: 13889 case OMPD_for_simd: 13890 case OMPD_sections: 13891 case OMPD_section: 13892 case OMPD_single: 13893 case OMPD_master: 13894 case OMPD_masked: 13895 case OMPD_critical: 13896 case OMPD_taskgroup: 13897 case OMPD_distribute: 13898 case OMPD_ordered: 13899 case OMPD_atomic: 13900 case OMPD_distribute_simd: 13901 case OMPD_requires: 13902 case OMPD_metadirective: 13903 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 13904 case OMPD_unknown: 13905 default: 13906 llvm_unreachable("Unknown OpenMP directive"); 13907 } 13908 break; 13909 case OMPC_schedule: 13910 switch (DKind) { 13911 case OMPD_parallel_for: 13912 case OMPD_parallel_for_simd: 13913 case OMPD_distribute_parallel_for: 13914 case OMPD_distribute_parallel_for_simd: 13915 case OMPD_teams_distribute_parallel_for: 13916 case OMPD_teams_distribute_parallel_for_simd: 13917 case OMPD_target_parallel_for: 13918 case OMPD_target_parallel_for_simd: 13919 case OMPD_target_teams_distribute_parallel_for: 13920 case OMPD_target_teams_distribute_parallel_for_simd: 13921 CaptureRegion = OMPD_parallel; 13922 break; 13923 case OMPD_for: 13924 case OMPD_for_simd: 13925 // Do not capture schedule-clause expressions. 13926 break; 13927 case OMPD_task: 13928 case OMPD_taskloop: 13929 case OMPD_taskloop_simd: 13930 case OMPD_master_taskloop: 13931 case OMPD_master_taskloop_simd: 13932 case OMPD_parallel_master_taskloop: 13933 case OMPD_parallel_master_taskloop_simd: 13934 case OMPD_target_data: 13935 case OMPD_target_enter_data: 13936 case OMPD_target_exit_data: 13937 case OMPD_target_update: 13938 case OMPD_teams: 13939 case OMPD_teams_distribute: 13940 case OMPD_teams_distribute_simd: 13941 case OMPD_target_teams_distribute: 13942 case OMPD_target_teams_distribute_simd: 13943 case OMPD_target: 13944 case OMPD_target_simd: 13945 case OMPD_target_parallel: 13946 case OMPD_cancel: 13947 case OMPD_parallel: 13948 case OMPD_parallel_master: 13949 case OMPD_parallel_sections: 13950 case OMPD_threadprivate: 13951 case OMPD_allocate: 13952 case OMPD_taskyield: 13953 case OMPD_barrier: 13954 case OMPD_taskwait: 13955 case OMPD_cancellation_point: 13956 case OMPD_flush: 13957 case OMPD_depobj: 13958 case OMPD_scan: 13959 case OMPD_declare_reduction: 13960 case OMPD_declare_mapper: 13961 case OMPD_declare_simd: 13962 case OMPD_declare_variant: 13963 case OMPD_begin_declare_variant: 13964 case OMPD_end_declare_variant: 13965 case OMPD_declare_target: 13966 case OMPD_end_declare_target: 13967 case OMPD_loop: 13968 case OMPD_simd: 13969 case OMPD_tile: 13970 case OMPD_unroll: 13971 case OMPD_sections: 13972 case OMPD_section: 13973 case OMPD_single: 13974 case OMPD_master: 13975 case OMPD_masked: 13976 case OMPD_critical: 13977 case OMPD_taskgroup: 13978 case OMPD_distribute: 13979 case OMPD_ordered: 13980 case OMPD_atomic: 13981 case OMPD_distribute_simd: 13982 case OMPD_target_teams: 13983 case OMPD_requires: 13984 case OMPD_metadirective: 13985 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 13986 case OMPD_unknown: 13987 default: 13988 llvm_unreachable("Unknown OpenMP directive"); 13989 } 13990 break; 13991 case OMPC_dist_schedule: 13992 switch (DKind) { 13993 case OMPD_teams_distribute_parallel_for: 13994 case OMPD_teams_distribute_parallel_for_simd: 13995 case OMPD_teams_distribute: 13996 case OMPD_teams_distribute_simd: 13997 case OMPD_target_teams_distribute_parallel_for: 13998 case OMPD_target_teams_distribute_parallel_for_simd: 13999 case OMPD_target_teams_distribute: 14000 case OMPD_target_teams_distribute_simd: 14001 CaptureRegion = OMPD_teams; 14002 break; 14003 case OMPD_distribute_parallel_for: 14004 case OMPD_distribute_parallel_for_simd: 14005 case OMPD_distribute: 14006 case OMPD_distribute_simd: 14007 // Do not capture dist_schedule-clause expressions. 14008 break; 14009 case OMPD_parallel_for: 14010 case OMPD_parallel_for_simd: 14011 case OMPD_target_parallel_for_simd: 14012 case OMPD_target_parallel_for: 14013 case OMPD_task: 14014 case OMPD_taskloop: 14015 case OMPD_taskloop_simd: 14016 case OMPD_master_taskloop: 14017 case OMPD_master_taskloop_simd: 14018 case OMPD_parallel_master_taskloop: 14019 case OMPD_parallel_master_taskloop_simd: 14020 case OMPD_target_data: 14021 case OMPD_target_enter_data: 14022 case OMPD_target_exit_data: 14023 case OMPD_target_update: 14024 case OMPD_teams: 14025 case OMPD_target: 14026 case OMPD_target_simd: 14027 case OMPD_target_parallel: 14028 case OMPD_cancel: 14029 case OMPD_parallel: 14030 case OMPD_parallel_master: 14031 case OMPD_parallel_sections: 14032 case OMPD_threadprivate: 14033 case OMPD_allocate: 14034 case OMPD_taskyield: 14035 case OMPD_barrier: 14036 case OMPD_taskwait: 14037 case OMPD_cancellation_point: 14038 case OMPD_flush: 14039 case OMPD_depobj: 14040 case OMPD_scan: 14041 case OMPD_declare_reduction: 14042 case OMPD_declare_mapper: 14043 case OMPD_declare_simd: 14044 case OMPD_declare_variant: 14045 case OMPD_begin_declare_variant: 14046 case OMPD_end_declare_variant: 14047 case OMPD_declare_target: 14048 case OMPD_end_declare_target: 14049 case OMPD_loop: 14050 case OMPD_simd: 14051 case OMPD_tile: 14052 case OMPD_unroll: 14053 case OMPD_for: 14054 case OMPD_for_simd: 14055 case OMPD_sections: 14056 case OMPD_section: 14057 case OMPD_single: 14058 case OMPD_master: 14059 case OMPD_masked: 14060 case OMPD_critical: 14061 case OMPD_taskgroup: 14062 case OMPD_ordered: 14063 case OMPD_atomic: 14064 case OMPD_target_teams: 14065 case OMPD_requires: 14066 case OMPD_metadirective: 14067 llvm_unreachable("Unexpected OpenMP directive with dist_schedule clause"); 14068 case OMPD_unknown: 14069 default: 14070 llvm_unreachable("Unknown OpenMP directive"); 14071 } 14072 break; 14073 case OMPC_device: 14074 switch (DKind) { 14075 case OMPD_target_update: 14076 case OMPD_target_enter_data: 14077 case OMPD_target_exit_data: 14078 case OMPD_target: 14079 case OMPD_target_simd: 14080 case OMPD_target_teams: 14081 case OMPD_target_parallel: 14082 case OMPD_target_teams_distribute: 14083 case OMPD_target_teams_distribute_simd: 14084 case OMPD_target_parallel_for: 14085 case OMPD_target_parallel_for_simd: 14086 case OMPD_target_teams_distribute_parallel_for: 14087 case OMPD_target_teams_distribute_parallel_for_simd: 14088 case OMPD_dispatch: 14089 CaptureRegion = OMPD_task; 14090 break; 14091 case OMPD_target_data: 14092 case OMPD_interop: 14093 // Do not capture device-clause expressions. 14094 break; 14095 case OMPD_teams_distribute_parallel_for: 14096 case OMPD_teams_distribute_parallel_for_simd: 14097 case OMPD_teams: 14098 case OMPD_teams_distribute: 14099 case OMPD_teams_distribute_simd: 14100 case OMPD_distribute_parallel_for: 14101 case OMPD_distribute_parallel_for_simd: 14102 case OMPD_task: 14103 case OMPD_taskloop: 14104 case OMPD_taskloop_simd: 14105 case OMPD_master_taskloop: 14106 case OMPD_master_taskloop_simd: 14107 case OMPD_parallel_master_taskloop: 14108 case OMPD_parallel_master_taskloop_simd: 14109 case OMPD_cancel: 14110 case OMPD_parallel: 14111 case OMPD_parallel_master: 14112 case OMPD_parallel_sections: 14113 case OMPD_parallel_for: 14114 case OMPD_parallel_for_simd: 14115 case OMPD_threadprivate: 14116 case OMPD_allocate: 14117 case OMPD_taskyield: 14118 case OMPD_barrier: 14119 case OMPD_taskwait: 14120 case OMPD_cancellation_point: 14121 case OMPD_flush: 14122 case OMPD_depobj: 14123 case OMPD_scan: 14124 case OMPD_declare_reduction: 14125 case OMPD_declare_mapper: 14126 case OMPD_declare_simd: 14127 case OMPD_declare_variant: 14128 case OMPD_begin_declare_variant: 14129 case OMPD_end_declare_variant: 14130 case OMPD_declare_target: 14131 case OMPD_end_declare_target: 14132 case OMPD_loop: 14133 case OMPD_simd: 14134 case OMPD_tile: 14135 case OMPD_unroll: 14136 case OMPD_for: 14137 case OMPD_for_simd: 14138 case OMPD_sections: 14139 case OMPD_section: 14140 case OMPD_single: 14141 case OMPD_master: 14142 case OMPD_masked: 14143 case OMPD_critical: 14144 case OMPD_taskgroup: 14145 case OMPD_distribute: 14146 case OMPD_ordered: 14147 case OMPD_atomic: 14148 case OMPD_distribute_simd: 14149 case OMPD_requires: 14150 case OMPD_metadirective: 14151 llvm_unreachable("Unexpected OpenMP directive with device-clause"); 14152 case OMPD_unknown: 14153 default: 14154 llvm_unreachable("Unknown OpenMP directive"); 14155 } 14156 break; 14157 case OMPC_grainsize: 14158 case OMPC_num_tasks: 14159 case OMPC_final: 14160 case OMPC_priority: 14161 switch (DKind) { 14162 case OMPD_task: 14163 case OMPD_taskloop: 14164 case OMPD_taskloop_simd: 14165 case OMPD_master_taskloop: 14166 case OMPD_master_taskloop_simd: 14167 break; 14168 case OMPD_parallel_master_taskloop: 14169 case OMPD_parallel_master_taskloop_simd: 14170 CaptureRegion = OMPD_parallel; 14171 break; 14172 case OMPD_target_update: 14173 case OMPD_target_enter_data: 14174 case OMPD_target_exit_data: 14175 case OMPD_target: 14176 case OMPD_target_simd: 14177 case OMPD_target_teams: 14178 case OMPD_target_parallel: 14179 case OMPD_target_teams_distribute: 14180 case OMPD_target_teams_distribute_simd: 14181 case OMPD_target_parallel_for: 14182 case OMPD_target_parallel_for_simd: 14183 case OMPD_target_teams_distribute_parallel_for: 14184 case OMPD_target_teams_distribute_parallel_for_simd: 14185 case OMPD_target_data: 14186 case OMPD_teams_distribute_parallel_for: 14187 case OMPD_teams_distribute_parallel_for_simd: 14188 case OMPD_teams: 14189 case OMPD_teams_distribute: 14190 case OMPD_teams_distribute_simd: 14191 case OMPD_distribute_parallel_for: 14192 case OMPD_distribute_parallel_for_simd: 14193 case OMPD_cancel: 14194 case OMPD_parallel: 14195 case OMPD_parallel_master: 14196 case OMPD_parallel_sections: 14197 case OMPD_parallel_for: 14198 case OMPD_parallel_for_simd: 14199 case OMPD_threadprivate: 14200 case OMPD_allocate: 14201 case OMPD_taskyield: 14202 case OMPD_barrier: 14203 case OMPD_taskwait: 14204 case OMPD_cancellation_point: 14205 case OMPD_flush: 14206 case OMPD_depobj: 14207 case OMPD_scan: 14208 case OMPD_declare_reduction: 14209 case OMPD_declare_mapper: 14210 case OMPD_declare_simd: 14211 case OMPD_declare_variant: 14212 case OMPD_begin_declare_variant: 14213 case OMPD_end_declare_variant: 14214 case OMPD_declare_target: 14215 case OMPD_end_declare_target: 14216 case OMPD_loop: 14217 case OMPD_simd: 14218 case OMPD_tile: 14219 case OMPD_unroll: 14220 case OMPD_for: 14221 case OMPD_for_simd: 14222 case OMPD_sections: 14223 case OMPD_section: 14224 case OMPD_single: 14225 case OMPD_master: 14226 case OMPD_masked: 14227 case OMPD_critical: 14228 case OMPD_taskgroup: 14229 case OMPD_distribute: 14230 case OMPD_ordered: 14231 case OMPD_atomic: 14232 case OMPD_distribute_simd: 14233 case OMPD_requires: 14234 case OMPD_metadirective: 14235 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause"); 14236 case OMPD_unknown: 14237 default: 14238 llvm_unreachable("Unknown OpenMP directive"); 14239 } 14240 break; 14241 case OMPC_novariants: 14242 case OMPC_nocontext: 14243 switch (DKind) { 14244 case OMPD_dispatch: 14245 CaptureRegion = OMPD_task; 14246 break; 14247 default: 14248 llvm_unreachable("Unexpected OpenMP directive"); 14249 } 14250 break; 14251 case OMPC_filter: 14252 // Do not capture filter-clause expressions. 14253 break; 14254 case OMPC_when: 14255 if (DKind == OMPD_metadirective) { 14256 CaptureRegion = OMPD_metadirective; 14257 } else if (DKind == OMPD_unknown) { 14258 llvm_unreachable("Unknown OpenMP directive"); 14259 } else { 14260 llvm_unreachable("Unexpected OpenMP directive with when clause"); 14261 } 14262 break; 14263 case OMPC_firstprivate: 14264 case OMPC_lastprivate: 14265 case OMPC_reduction: 14266 case OMPC_task_reduction: 14267 case OMPC_in_reduction: 14268 case OMPC_linear: 14269 case OMPC_default: 14270 case OMPC_proc_bind: 14271 case OMPC_safelen: 14272 case OMPC_simdlen: 14273 case OMPC_sizes: 14274 case OMPC_allocator: 14275 case OMPC_collapse: 14276 case OMPC_private: 14277 case OMPC_shared: 14278 case OMPC_aligned: 14279 case OMPC_copyin: 14280 case OMPC_copyprivate: 14281 case OMPC_ordered: 14282 case OMPC_nowait: 14283 case OMPC_untied: 14284 case OMPC_mergeable: 14285 case OMPC_threadprivate: 14286 case OMPC_allocate: 14287 case OMPC_flush: 14288 case OMPC_depobj: 14289 case OMPC_read: 14290 case OMPC_write: 14291 case OMPC_update: 14292 case OMPC_capture: 14293 case OMPC_seq_cst: 14294 case OMPC_acq_rel: 14295 case OMPC_acquire: 14296 case OMPC_release: 14297 case OMPC_relaxed: 14298 case OMPC_depend: 14299 case OMPC_threads: 14300 case OMPC_simd: 14301 case OMPC_map: 14302 case OMPC_nogroup: 14303 case OMPC_hint: 14304 case OMPC_defaultmap: 14305 case OMPC_unknown: 14306 case OMPC_uniform: 14307 case OMPC_to: 14308 case OMPC_from: 14309 case OMPC_use_device_ptr: 14310 case OMPC_use_device_addr: 14311 case OMPC_is_device_ptr: 14312 case OMPC_unified_address: 14313 case OMPC_unified_shared_memory: 14314 case OMPC_reverse_offload: 14315 case OMPC_dynamic_allocators: 14316 case OMPC_atomic_default_mem_order: 14317 case OMPC_device_type: 14318 case OMPC_match: 14319 case OMPC_nontemporal: 14320 case OMPC_order: 14321 case OMPC_destroy: 14322 case OMPC_detach: 14323 case OMPC_inclusive: 14324 case OMPC_exclusive: 14325 case OMPC_uses_allocators: 14326 case OMPC_affinity: 14327 case OMPC_bind: 14328 default: 14329 llvm_unreachable("Unexpected OpenMP clause."); 14330 } 14331 return CaptureRegion; 14332 } 14333 14334 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 14335 Expr *Condition, SourceLocation StartLoc, 14336 SourceLocation LParenLoc, 14337 SourceLocation NameModifierLoc, 14338 SourceLocation ColonLoc, 14339 SourceLocation EndLoc) { 14340 Expr *ValExpr = Condition; 14341 Stmt *HelperValStmt = nullptr; 14342 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 14343 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 14344 !Condition->isInstantiationDependent() && 14345 !Condition->containsUnexpandedParameterPack()) { 14346 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 14347 if (Val.isInvalid()) 14348 return nullptr; 14349 14350 ValExpr = Val.get(); 14351 14352 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 14353 CaptureRegion = getOpenMPCaptureRegionForClause( 14354 DKind, OMPC_if, LangOpts.OpenMP, NameModifier); 14355 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 14356 ValExpr = MakeFullExpr(ValExpr).get(); 14357 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14358 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 14359 HelperValStmt = buildPreInits(Context, Captures); 14360 } 14361 } 14362 14363 return new (Context) 14364 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 14365 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 14366 } 14367 14368 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 14369 SourceLocation StartLoc, 14370 SourceLocation LParenLoc, 14371 SourceLocation EndLoc) { 14372 Expr *ValExpr = Condition; 14373 Stmt *HelperValStmt = nullptr; 14374 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 14375 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 14376 !Condition->isInstantiationDependent() && 14377 !Condition->containsUnexpandedParameterPack()) { 14378 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 14379 if (Val.isInvalid()) 14380 return nullptr; 14381 14382 ValExpr = MakeFullExpr(Val.get()).get(); 14383 14384 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 14385 CaptureRegion = 14386 getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP); 14387 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 14388 ValExpr = MakeFullExpr(ValExpr).get(); 14389 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14390 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 14391 HelperValStmt = buildPreInits(Context, Captures); 14392 } 14393 } 14394 14395 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion, 14396 StartLoc, LParenLoc, EndLoc); 14397 } 14398 14399 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 14400 Expr *Op) { 14401 if (!Op) 14402 return ExprError(); 14403 14404 class IntConvertDiagnoser : public ICEConvertDiagnoser { 14405 public: 14406 IntConvertDiagnoser() 14407 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 14408 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 14409 QualType T) override { 14410 return S.Diag(Loc, diag::err_omp_not_integral) << T; 14411 } 14412 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 14413 QualType T) override { 14414 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 14415 } 14416 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 14417 QualType T, 14418 QualType ConvTy) override { 14419 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 14420 } 14421 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 14422 QualType ConvTy) override { 14423 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 14424 << ConvTy->isEnumeralType() << ConvTy; 14425 } 14426 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 14427 QualType T) override { 14428 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 14429 } 14430 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 14431 QualType ConvTy) override { 14432 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 14433 << ConvTy->isEnumeralType() << ConvTy; 14434 } 14435 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 14436 QualType) override { 14437 llvm_unreachable("conversion functions are permitted"); 14438 } 14439 } ConvertDiagnoser; 14440 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 14441 } 14442 14443 static bool 14444 isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind, 14445 bool StrictlyPositive, bool BuildCapture = false, 14446 OpenMPDirectiveKind DKind = OMPD_unknown, 14447 OpenMPDirectiveKind *CaptureRegion = nullptr, 14448 Stmt **HelperValStmt = nullptr) { 14449 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 14450 !ValExpr->isInstantiationDependent()) { 14451 SourceLocation Loc = ValExpr->getExprLoc(); 14452 ExprResult Value = 14453 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 14454 if (Value.isInvalid()) 14455 return false; 14456 14457 ValExpr = Value.get(); 14458 // The expression must evaluate to a non-negative integer value. 14459 if (Optional<llvm::APSInt> Result = 14460 ValExpr->getIntegerConstantExpr(SemaRef.Context)) { 14461 if (Result->isSigned() && 14462 !((!StrictlyPositive && Result->isNonNegative()) || 14463 (StrictlyPositive && Result->isStrictlyPositive()))) { 14464 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 14465 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 14466 << ValExpr->getSourceRange(); 14467 return false; 14468 } 14469 } 14470 if (!BuildCapture) 14471 return true; 14472 *CaptureRegion = 14473 getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP); 14474 if (*CaptureRegion != OMPD_unknown && 14475 !SemaRef.CurContext->isDependentContext()) { 14476 ValExpr = SemaRef.MakeFullExpr(ValExpr).get(); 14477 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14478 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get(); 14479 *HelperValStmt = buildPreInits(SemaRef.Context, Captures); 14480 } 14481 } 14482 return true; 14483 } 14484 14485 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 14486 SourceLocation StartLoc, 14487 SourceLocation LParenLoc, 14488 SourceLocation EndLoc) { 14489 Expr *ValExpr = NumThreads; 14490 Stmt *HelperValStmt = nullptr; 14491 14492 // OpenMP [2.5, Restrictions] 14493 // The num_threads expression must evaluate to a positive integer value. 14494 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 14495 /*StrictlyPositive=*/true)) 14496 return nullptr; 14497 14498 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 14499 OpenMPDirectiveKind CaptureRegion = 14500 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP); 14501 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 14502 ValExpr = MakeFullExpr(ValExpr).get(); 14503 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 14504 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 14505 HelperValStmt = buildPreInits(Context, Captures); 14506 } 14507 14508 return new (Context) OMPNumThreadsClause( 14509 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 14510 } 14511 14512 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 14513 OpenMPClauseKind CKind, 14514 bool StrictlyPositive, 14515 bool SuppressExprDiags) { 14516 if (!E) 14517 return ExprError(); 14518 if (E->isValueDependent() || E->isTypeDependent() || 14519 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 14520 return E; 14521 14522 llvm::APSInt Result; 14523 ExprResult ICE; 14524 if (SuppressExprDiags) { 14525 // Use a custom diagnoser that suppresses 'note' diagnostics about the 14526 // expression. 14527 struct SuppressedDiagnoser : public Sema::VerifyICEDiagnoser { 14528 SuppressedDiagnoser() : VerifyICEDiagnoser(/*Suppress=*/true) {} 14529 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S, 14530 SourceLocation Loc) override { 14531 llvm_unreachable("Diagnostic suppressed"); 14532 } 14533 } Diagnoser; 14534 ICE = VerifyIntegerConstantExpression(E, &Result, Diagnoser, AllowFold); 14535 } else { 14536 ICE = VerifyIntegerConstantExpression(E, &Result, /*FIXME*/ AllowFold); 14537 } 14538 if (ICE.isInvalid()) 14539 return ExprError(); 14540 14541 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 14542 (!StrictlyPositive && !Result.isNonNegative())) { 14543 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 14544 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 14545 << E->getSourceRange(); 14546 return ExprError(); 14547 } 14548 if ((CKind == OMPC_aligned || CKind == OMPC_align) && !Result.isPowerOf2()) { 14549 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 14550 << E->getSourceRange(); 14551 return ExprError(); 14552 } 14553 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 14554 DSAStack->setAssociatedLoops(Result.getExtValue()); 14555 else if (CKind == OMPC_ordered) 14556 DSAStack->setAssociatedLoops(Result.getExtValue()); 14557 return ICE; 14558 } 14559 14560 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 14561 SourceLocation LParenLoc, 14562 SourceLocation EndLoc) { 14563 // OpenMP [2.8.1, simd construct, Description] 14564 // The parameter of the safelen clause must be a constant 14565 // positive integer expression. 14566 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 14567 if (Safelen.isInvalid()) 14568 return nullptr; 14569 return new (Context) 14570 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 14571 } 14572 14573 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 14574 SourceLocation LParenLoc, 14575 SourceLocation EndLoc) { 14576 // OpenMP [2.8.1, simd construct, Description] 14577 // The parameter of the simdlen clause must be a constant 14578 // positive integer expression. 14579 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 14580 if (Simdlen.isInvalid()) 14581 return nullptr; 14582 return new (Context) 14583 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 14584 } 14585 14586 /// Tries to find omp_allocator_handle_t type. 14587 static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc, 14588 DSAStackTy *Stack) { 14589 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT(); 14590 if (!OMPAllocatorHandleT.isNull()) 14591 return true; 14592 // Build the predefined allocator expressions. 14593 bool ErrorFound = false; 14594 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 14595 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 14596 StringRef Allocator = 14597 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind); 14598 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator); 14599 auto *VD = dyn_cast_or_null<ValueDecl>( 14600 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName)); 14601 if (!VD) { 14602 ErrorFound = true; 14603 break; 14604 } 14605 QualType AllocatorType = 14606 VD->getType().getNonLValueExprType(S.getASTContext()); 14607 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc); 14608 if (!Res.isUsable()) { 14609 ErrorFound = true; 14610 break; 14611 } 14612 if (OMPAllocatorHandleT.isNull()) 14613 OMPAllocatorHandleT = AllocatorType; 14614 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) { 14615 ErrorFound = true; 14616 break; 14617 } 14618 Stack->setAllocator(AllocatorKind, Res.get()); 14619 } 14620 if (ErrorFound) { 14621 S.Diag(Loc, diag::err_omp_implied_type_not_found) 14622 << "omp_allocator_handle_t"; 14623 return false; 14624 } 14625 OMPAllocatorHandleT.addConst(); 14626 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT); 14627 return true; 14628 } 14629 14630 OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc, 14631 SourceLocation LParenLoc, 14632 SourceLocation EndLoc) { 14633 // OpenMP [2.11.3, allocate Directive, Description] 14634 // allocator is an expression of omp_allocator_handle_t type. 14635 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack)) 14636 return nullptr; 14637 14638 ExprResult Allocator = DefaultLvalueConversion(A); 14639 if (Allocator.isInvalid()) 14640 return nullptr; 14641 Allocator = PerformImplicitConversion(Allocator.get(), 14642 DSAStack->getOMPAllocatorHandleT(), 14643 Sema::AA_Initializing, 14644 /*AllowExplicit=*/true); 14645 if (Allocator.isInvalid()) 14646 return nullptr; 14647 return new (Context) 14648 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc); 14649 } 14650 14651 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 14652 SourceLocation StartLoc, 14653 SourceLocation LParenLoc, 14654 SourceLocation EndLoc) { 14655 // OpenMP [2.7.1, loop construct, Description] 14656 // OpenMP [2.8.1, simd construct, Description] 14657 // OpenMP [2.9.6, distribute construct, Description] 14658 // The parameter of the collapse clause must be a constant 14659 // positive integer expression. 14660 ExprResult NumForLoopsResult = 14661 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 14662 if (NumForLoopsResult.isInvalid()) 14663 return nullptr; 14664 return new (Context) 14665 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 14666 } 14667 14668 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 14669 SourceLocation EndLoc, 14670 SourceLocation LParenLoc, 14671 Expr *NumForLoops) { 14672 // OpenMP [2.7.1, loop construct, Description] 14673 // OpenMP [2.8.1, simd construct, Description] 14674 // OpenMP [2.9.6, distribute construct, Description] 14675 // The parameter of the ordered clause must be a constant 14676 // positive integer expression if any. 14677 if (NumForLoops && LParenLoc.isValid()) { 14678 ExprResult NumForLoopsResult = 14679 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 14680 if (NumForLoopsResult.isInvalid()) 14681 return nullptr; 14682 NumForLoops = NumForLoopsResult.get(); 14683 } else { 14684 NumForLoops = nullptr; 14685 } 14686 auto *Clause = OMPOrderedClause::Create( 14687 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0, 14688 StartLoc, LParenLoc, EndLoc); 14689 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause); 14690 return Clause; 14691 } 14692 14693 OMPClause *Sema::ActOnOpenMPSimpleClause( 14694 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 14695 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 14696 OMPClause *Res = nullptr; 14697 switch (Kind) { 14698 case OMPC_default: 14699 Res = ActOnOpenMPDefaultClause(static_cast<DefaultKind>(Argument), 14700 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 14701 break; 14702 case OMPC_proc_bind: 14703 Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument), 14704 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 14705 break; 14706 case OMPC_atomic_default_mem_order: 14707 Res = ActOnOpenMPAtomicDefaultMemOrderClause( 14708 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument), 14709 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 14710 break; 14711 case OMPC_order: 14712 Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument), 14713 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 14714 break; 14715 case OMPC_update: 14716 Res = ActOnOpenMPUpdateClause(static_cast<OpenMPDependClauseKind>(Argument), 14717 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 14718 break; 14719 case OMPC_bind: 14720 Res = ActOnOpenMPBindClause(static_cast<OpenMPBindClauseKind>(Argument), 14721 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 14722 break; 14723 case OMPC_if: 14724 case OMPC_final: 14725 case OMPC_num_threads: 14726 case OMPC_safelen: 14727 case OMPC_simdlen: 14728 case OMPC_sizes: 14729 case OMPC_allocator: 14730 case OMPC_collapse: 14731 case OMPC_schedule: 14732 case OMPC_private: 14733 case OMPC_firstprivate: 14734 case OMPC_lastprivate: 14735 case OMPC_shared: 14736 case OMPC_reduction: 14737 case OMPC_task_reduction: 14738 case OMPC_in_reduction: 14739 case OMPC_linear: 14740 case OMPC_aligned: 14741 case OMPC_copyin: 14742 case OMPC_copyprivate: 14743 case OMPC_ordered: 14744 case OMPC_nowait: 14745 case OMPC_untied: 14746 case OMPC_mergeable: 14747 case OMPC_threadprivate: 14748 case OMPC_allocate: 14749 case OMPC_flush: 14750 case OMPC_depobj: 14751 case OMPC_read: 14752 case OMPC_write: 14753 case OMPC_capture: 14754 case OMPC_seq_cst: 14755 case OMPC_acq_rel: 14756 case OMPC_acquire: 14757 case OMPC_release: 14758 case OMPC_relaxed: 14759 case OMPC_depend: 14760 case OMPC_device: 14761 case OMPC_threads: 14762 case OMPC_simd: 14763 case OMPC_map: 14764 case OMPC_num_teams: 14765 case OMPC_thread_limit: 14766 case OMPC_priority: 14767 case OMPC_grainsize: 14768 case OMPC_nogroup: 14769 case OMPC_num_tasks: 14770 case OMPC_hint: 14771 case OMPC_dist_schedule: 14772 case OMPC_defaultmap: 14773 case OMPC_unknown: 14774 case OMPC_uniform: 14775 case OMPC_to: 14776 case OMPC_from: 14777 case OMPC_use_device_ptr: 14778 case OMPC_use_device_addr: 14779 case OMPC_is_device_ptr: 14780 case OMPC_unified_address: 14781 case OMPC_unified_shared_memory: 14782 case OMPC_reverse_offload: 14783 case OMPC_dynamic_allocators: 14784 case OMPC_device_type: 14785 case OMPC_match: 14786 case OMPC_nontemporal: 14787 case OMPC_destroy: 14788 case OMPC_novariants: 14789 case OMPC_nocontext: 14790 case OMPC_detach: 14791 case OMPC_inclusive: 14792 case OMPC_exclusive: 14793 case OMPC_uses_allocators: 14794 case OMPC_affinity: 14795 case OMPC_when: 14796 default: 14797 llvm_unreachable("Clause is not allowed."); 14798 } 14799 return Res; 14800 } 14801 14802 static std::string 14803 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 14804 ArrayRef<unsigned> Exclude = llvm::None) { 14805 SmallString<256> Buffer; 14806 llvm::raw_svector_ostream Out(Buffer); 14807 unsigned Skipped = Exclude.size(); 14808 auto S = Exclude.begin(), E = Exclude.end(); 14809 for (unsigned I = First; I < Last; ++I) { 14810 if (std::find(S, E, I) != E) { 14811 --Skipped; 14812 continue; 14813 } 14814 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'"; 14815 if (I + Skipped + 2 == Last) 14816 Out << " or "; 14817 else if (I + Skipped + 1 != Last) 14818 Out << ", "; 14819 } 14820 return std::string(Out.str()); 14821 } 14822 14823 OMPClause *Sema::ActOnOpenMPDefaultClause(DefaultKind Kind, 14824 SourceLocation KindKwLoc, 14825 SourceLocation StartLoc, 14826 SourceLocation LParenLoc, 14827 SourceLocation EndLoc) { 14828 if (Kind == OMP_DEFAULT_unknown) { 14829 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 14830 << getListOfPossibleValues(OMPC_default, /*First=*/0, 14831 /*Last=*/unsigned(OMP_DEFAULT_unknown)) 14832 << getOpenMPClauseName(OMPC_default); 14833 return nullptr; 14834 } 14835 14836 switch (Kind) { 14837 case OMP_DEFAULT_none: 14838 DSAStack->setDefaultDSANone(KindKwLoc); 14839 break; 14840 case OMP_DEFAULT_shared: 14841 DSAStack->setDefaultDSAShared(KindKwLoc); 14842 break; 14843 case OMP_DEFAULT_firstprivate: 14844 DSAStack->setDefaultDSAFirstPrivate(KindKwLoc); 14845 break; 14846 default: 14847 llvm_unreachable("DSA unexpected in OpenMP default clause"); 14848 } 14849 14850 return new (Context) 14851 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 14852 } 14853 14854 OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind, 14855 SourceLocation KindKwLoc, 14856 SourceLocation StartLoc, 14857 SourceLocation LParenLoc, 14858 SourceLocation EndLoc) { 14859 if (Kind == OMP_PROC_BIND_unknown) { 14860 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 14861 << getListOfPossibleValues(OMPC_proc_bind, 14862 /*First=*/unsigned(OMP_PROC_BIND_master), 14863 /*Last=*/ 14864 unsigned(LangOpts.OpenMP > 50 14865 ? OMP_PROC_BIND_primary 14866 : OMP_PROC_BIND_spread) + 14867 1) 14868 << getOpenMPClauseName(OMPC_proc_bind); 14869 return nullptr; 14870 } 14871 if (Kind == OMP_PROC_BIND_primary && LangOpts.OpenMP < 51) 14872 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 14873 << getListOfPossibleValues(OMPC_proc_bind, 14874 /*First=*/unsigned(OMP_PROC_BIND_master), 14875 /*Last=*/ 14876 unsigned(OMP_PROC_BIND_spread) + 1) 14877 << getOpenMPClauseName(OMPC_proc_bind); 14878 return new (Context) 14879 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 14880 } 14881 14882 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause( 14883 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc, 14884 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 14885 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) { 14886 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 14887 << getListOfPossibleValues( 14888 OMPC_atomic_default_mem_order, /*First=*/0, 14889 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) 14890 << getOpenMPClauseName(OMPC_atomic_default_mem_order); 14891 return nullptr; 14892 } 14893 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc, 14894 LParenLoc, EndLoc); 14895 } 14896 14897 OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind, 14898 SourceLocation KindKwLoc, 14899 SourceLocation StartLoc, 14900 SourceLocation LParenLoc, 14901 SourceLocation EndLoc) { 14902 if (Kind == OMPC_ORDER_unknown) { 14903 static_assert(OMPC_ORDER_unknown > 0, 14904 "OMPC_ORDER_unknown not greater than 0"); 14905 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 14906 << getListOfPossibleValues(OMPC_order, /*First=*/0, 14907 /*Last=*/OMPC_ORDER_unknown) 14908 << getOpenMPClauseName(OMPC_order); 14909 return nullptr; 14910 } 14911 return new (Context) 14912 OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 14913 } 14914 14915 OMPClause *Sema::ActOnOpenMPUpdateClause(OpenMPDependClauseKind Kind, 14916 SourceLocation KindKwLoc, 14917 SourceLocation StartLoc, 14918 SourceLocation LParenLoc, 14919 SourceLocation EndLoc) { 14920 if (Kind == OMPC_DEPEND_unknown || Kind == OMPC_DEPEND_source || 14921 Kind == OMPC_DEPEND_sink || Kind == OMPC_DEPEND_depobj) { 14922 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink, 14923 OMPC_DEPEND_depobj}; 14924 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 14925 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 14926 /*Last=*/OMPC_DEPEND_unknown, Except) 14927 << getOpenMPClauseName(OMPC_update); 14928 return nullptr; 14929 } 14930 return OMPUpdateClause::Create(Context, StartLoc, LParenLoc, KindKwLoc, Kind, 14931 EndLoc); 14932 } 14933 14934 OMPClause *Sema::ActOnOpenMPSizesClause(ArrayRef<Expr *> SizeExprs, 14935 SourceLocation StartLoc, 14936 SourceLocation LParenLoc, 14937 SourceLocation EndLoc) { 14938 for (Expr *SizeExpr : SizeExprs) { 14939 ExprResult NumForLoopsResult = VerifyPositiveIntegerConstantInClause( 14940 SizeExpr, OMPC_sizes, /*StrictlyPositive=*/true); 14941 if (!NumForLoopsResult.isUsable()) 14942 return nullptr; 14943 } 14944 14945 DSAStack->setAssociatedLoops(SizeExprs.size()); 14946 return OMPSizesClause::Create(Context, StartLoc, LParenLoc, EndLoc, 14947 SizeExprs); 14948 } 14949 14950 OMPClause *Sema::ActOnOpenMPFullClause(SourceLocation StartLoc, 14951 SourceLocation EndLoc) { 14952 return OMPFullClause::Create(Context, StartLoc, EndLoc); 14953 } 14954 14955 OMPClause *Sema::ActOnOpenMPPartialClause(Expr *FactorExpr, 14956 SourceLocation StartLoc, 14957 SourceLocation LParenLoc, 14958 SourceLocation EndLoc) { 14959 if (FactorExpr) { 14960 // If an argument is specified, it must be a constant (or an unevaluated 14961 // template expression). 14962 ExprResult FactorResult = VerifyPositiveIntegerConstantInClause( 14963 FactorExpr, OMPC_partial, /*StrictlyPositive=*/true); 14964 if (FactorResult.isInvalid()) 14965 return nullptr; 14966 FactorExpr = FactorResult.get(); 14967 } 14968 14969 return OMPPartialClause::Create(Context, StartLoc, LParenLoc, EndLoc, 14970 FactorExpr); 14971 } 14972 14973 OMPClause *Sema::ActOnOpenMPAlignClause(Expr *A, SourceLocation StartLoc, 14974 SourceLocation LParenLoc, 14975 SourceLocation EndLoc) { 14976 ExprResult AlignVal; 14977 AlignVal = VerifyPositiveIntegerConstantInClause(A, OMPC_align); 14978 if (AlignVal.isInvalid()) 14979 return nullptr; 14980 return OMPAlignClause::Create(Context, AlignVal.get(), StartLoc, LParenLoc, 14981 EndLoc); 14982 } 14983 14984 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 14985 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 14986 SourceLocation StartLoc, SourceLocation LParenLoc, 14987 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 14988 SourceLocation EndLoc) { 14989 OMPClause *Res = nullptr; 14990 switch (Kind) { 14991 case OMPC_schedule: 14992 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 14993 assert(Argument.size() == NumberOfElements && 14994 ArgumentLoc.size() == NumberOfElements); 14995 Res = ActOnOpenMPScheduleClause( 14996 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 14997 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 14998 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 14999 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 15000 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 15001 break; 15002 case OMPC_if: 15003 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 15004 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 15005 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 15006 DelimLoc, EndLoc); 15007 break; 15008 case OMPC_dist_schedule: 15009 Res = ActOnOpenMPDistScheduleClause( 15010 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 15011 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 15012 break; 15013 case OMPC_defaultmap: 15014 enum { Modifier, DefaultmapKind }; 15015 Res = ActOnOpenMPDefaultmapClause( 15016 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 15017 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 15018 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 15019 EndLoc); 15020 break; 15021 case OMPC_device: 15022 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 15023 Res = ActOnOpenMPDeviceClause( 15024 static_cast<OpenMPDeviceClauseModifier>(Argument.back()), Expr, 15025 StartLoc, LParenLoc, ArgumentLoc.back(), EndLoc); 15026 break; 15027 case OMPC_final: 15028 case OMPC_num_threads: 15029 case OMPC_safelen: 15030 case OMPC_simdlen: 15031 case OMPC_sizes: 15032 case OMPC_allocator: 15033 case OMPC_collapse: 15034 case OMPC_default: 15035 case OMPC_proc_bind: 15036 case OMPC_private: 15037 case OMPC_firstprivate: 15038 case OMPC_lastprivate: 15039 case OMPC_shared: 15040 case OMPC_reduction: 15041 case OMPC_task_reduction: 15042 case OMPC_in_reduction: 15043 case OMPC_linear: 15044 case OMPC_aligned: 15045 case OMPC_copyin: 15046 case OMPC_copyprivate: 15047 case OMPC_ordered: 15048 case OMPC_nowait: 15049 case OMPC_untied: 15050 case OMPC_mergeable: 15051 case OMPC_threadprivate: 15052 case OMPC_allocate: 15053 case OMPC_flush: 15054 case OMPC_depobj: 15055 case OMPC_read: 15056 case OMPC_write: 15057 case OMPC_update: 15058 case OMPC_capture: 15059 case OMPC_seq_cst: 15060 case OMPC_acq_rel: 15061 case OMPC_acquire: 15062 case OMPC_release: 15063 case OMPC_relaxed: 15064 case OMPC_depend: 15065 case OMPC_threads: 15066 case OMPC_simd: 15067 case OMPC_map: 15068 case OMPC_num_teams: 15069 case OMPC_thread_limit: 15070 case OMPC_priority: 15071 case OMPC_grainsize: 15072 case OMPC_nogroup: 15073 case OMPC_num_tasks: 15074 case OMPC_hint: 15075 case OMPC_unknown: 15076 case OMPC_uniform: 15077 case OMPC_to: 15078 case OMPC_from: 15079 case OMPC_use_device_ptr: 15080 case OMPC_use_device_addr: 15081 case OMPC_is_device_ptr: 15082 case OMPC_unified_address: 15083 case OMPC_unified_shared_memory: 15084 case OMPC_reverse_offload: 15085 case OMPC_dynamic_allocators: 15086 case OMPC_atomic_default_mem_order: 15087 case OMPC_device_type: 15088 case OMPC_match: 15089 case OMPC_nontemporal: 15090 case OMPC_order: 15091 case OMPC_destroy: 15092 case OMPC_novariants: 15093 case OMPC_nocontext: 15094 case OMPC_detach: 15095 case OMPC_inclusive: 15096 case OMPC_exclusive: 15097 case OMPC_uses_allocators: 15098 case OMPC_affinity: 15099 case OMPC_when: 15100 case OMPC_bind: 15101 default: 15102 llvm_unreachable("Clause is not allowed."); 15103 } 15104 return Res; 15105 } 15106 15107 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 15108 OpenMPScheduleClauseModifier M2, 15109 SourceLocation M1Loc, SourceLocation M2Loc) { 15110 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 15111 SmallVector<unsigned, 2> Excluded; 15112 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 15113 Excluded.push_back(M2); 15114 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 15115 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 15116 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 15117 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 15118 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 15119 << getListOfPossibleValues(OMPC_schedule, 15120 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 15121 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 15122 Excluded) 15123 << getOpenMPClauseName(OMPC_schedule); 15124 return true; 15125 } 15126 return false; 15127 } 15128 15129 OMPClause *Sema::ActOnOpenMPScheduleClause( 15130 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 15131 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 15132 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 15133 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 15134 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 15135 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 15136 return nullptr; 15137 // OpenMP, 2.7.1, Loop Construct, Restrictions 15138 // Either the monotonic modifier or the nonmonotonic modifier can be specified 15139 // but not both. 15140 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 15141 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 15142 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 15143 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 15144 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 15145 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 15146 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 15147 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 15148 return nullptr; 15149 } 15150 if (Kind == OMPC_SCHEDULE_unknown) { 15151 std::string Values; 15152 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 15153 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 15154 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 15155 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 15156 Exclude); 15157 } else { 15158 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 15159 /*Last=*/OMPC_SCHEDULE_unknown); 15160 } 15161 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 15162 << Values << getOpenMPClauseName(OMPC_schedule); 15163 return nullptr; 15164 } 15165 // OpenMP, 2.7.1, Loop Construct, Restrictions 15166 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 15167 // schedule(guided). 15168 // OpenMP 5.0 does not have this restriction. 15169 if (LangOpts.OpenMP < 50 && 15170 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 15171 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 15172 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 15173 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 15174 diag::err_omp_schedule_nonmonotonic_static); 15175 return nullptr; 15176 } 15177 Expr *ValExpr = ChunkSize; 15178 Stmt *HelperValStmt = nullptr; 15179 if (ChunkSize) { 15180 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 15181 !ChunkSize->isInstantiationDependent() && 15182 !ChunkSize->containsUnexpandedParameterPack()) { 15183 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 15184 ExprResult Val = 15185 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 15186 if (Val.isInvalid()) 15187 return nullptr; 15188 15189 ValExpr = Val.get(); 15190 15191 // OpenMP [2.7.1, Restrictions] 15192 // chunk_size must be a loop invariant integer expression with a positive 15193 // value. 15194 if (Optional<llvm::APSInt> Result = 15195 ValExpr->getIntegerConstantExpr(Context)) { 15196 if (Result->isSigned() && !Result->isStrictlyPositive()) { 15197 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 15198 << "schedule" << 1 << ChunkSize->getSourceRange(); 15199 return nullptr; 15200 } 15201 } else if (getOpenMPCaptureRegionForClause( 15202 DSAStack->getCurrentDirective(), OMPC_schedule, 15203 LangOpts.OpenMP) != OMPD_unknown && 15204 !CurContext->isDependentContext()) { 15205 ValExpr = MakeFullExpr(ValExpr).get(); 15206 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 15207 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 15208 HelperValStmt = buildPreInits(Context, Captures); 15209 } 15210 } 15211 } 15212 15213 return new (Context) 15214 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 15215 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 15216 } 15217 15218 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 15219 SourceLocation StartLoc, 15220 SourceLocation EndLoc) { 15221 OMPClause *Res = nullptr; 15222 switch (Kind) { 15223 case OMPC_ordered: 15224 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 15225 break; 15226 case OMPC_nowait: 15227 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 15228 break; 15229 case OMPC_untied: 15230 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 15231 break; 15232 case OMPC_mergeable: 15233 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 15234 break; 15235 case OMPC_read: 15236 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 15237 break; 15238 case OMPC_write: 15239 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 15240 break; 15241 case OMPC_update: 15242 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 15243 break; 15244 case OMPC_capture: 15245 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 15246 break; 15247 case OMPC_seq_cst: 15248 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 15249 break; 15250 case OMPC_acq_rel: 15251 Res = ActOnOpenMPAcqRelClause(StartLoc, EndLoc); 15252 break; 15253 case OMPC_acquire: 15254 Res = ActOnOpenMPAcquireClause(StartLoc, EndLoc); 15255 break; 15256 case OMPC_release: 15257 Res = ActOnOpenMPReleaseClause(StartLoc, EndLoc); 15258 break; 15259 case OMPC_relaxed: 15260 Res = ActOnOpenMPRelaxedClause(StartLoc, EndLoc); 15261 break; 15262 case OMPC_threads: 15263 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 15264 break; 15265 case OMPC_simd: 15266 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 15267 break; 15268 case OMPC_nogroup: 15269 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 15270 break; 15271 case OMPC_unified_address: 15272 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc); 15273 break; 15274 case OMPC_unified_shared_memory: 15275 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 15276 break; 15277 case OMPC_reverse_offload: 15278 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc); 15279 break; 15280 case OMPC_dynamic_allocators: 15281 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc); 15282 break; 15283 case OMPC_destroy: 15284 Res = ActOnOpenMPDestroyClause(/*InteropVar=*/nullptr, StartLoc, 15285 /*LParenLoc=*/SourceLocation(), 15286 /*VarLoc=*/SourceLocation(), EndLoc); 15287 break; 15288 case OMPC_full: 15289 Res = ActOnOpenMPFullClause(StartLoc, EndLoc); 15290 break; 15291 case OMPC_partial: 15292 Res = ActOnOpenMPPartialClause(nullptr, StartLoc, /*LParenLoc=*/{}, EndLoc); 15293 break; 15294 case OMPC_if: 15295 case OMPC_final: 15296 case OMPC_num_threads: 15297 case OMPC_safelen: 15298 case OMPC_simdlen: 15299 case OMPC_sizes: 15300 case OMPC_allocator: 15301 case OMPC_collapse: 15302 case OMPC_schedule: 15303 case OMPC_private: 15304 case OMPC_firstprivate: 15305 case OMPC_lastprivate: 15306 case OMPC_shared: 15307 case OMPC_reduction: 15308 case OMPC_task_reduction: 15309 case OMPC_in_reduction: 15310 case OMPC_linear: 15311 case OMPC_aligned: 15312 case OMPC_copyin: 15313 case OMPC_copyprivate: 15314 case OMPC_default: 15315 case OMPC_proc_bind: 15316 case OMPC_threadprivate: 15317 case OMPC_allocate: 15318 case OMPC_flush: 15319 case OMPC_depobj: 15320 case OMPC_depend: 15321 case OMPC_device: 15322 case OMPC_map: 15323 case OMPC_num_teams: 15324 case OMPC_thread_limit: 15325 case OMPC_priority: 15326 case OMPC_grainsize: 15327 case OMPC_num_tasks: 15328 case OMPC_hint: 15329 case OMPC_dist_schedule: 15330 case OMPC_defaultmap: 15331 case OMPC_unknown: 15332 case OMPC_uniform: 15333 case OMPC_to: 15334 case OMPC_from: 15335 case OMPC_use_device_ptr: 15336 case OMPC_use_device_addr: 15337 case OMPC_is_device_ptr: 15338 case OMPC_atomic_default_mem_order: 15339 case OMPC_device_type: 15340 case OMPC_match: 15341 case OMPC_nontemporal: 15342 case OMPC_order: 15343 case OMPC_novariants: 15344 case OMPC_nocontext: 15345 case OMPC_detach: 15346 case OMPC_inclusive: 15347 case OMPC_exclusive: 15348 case OMPC_uses_allocators: 15349 case OMPC_affinity: 15350 case OMPC_when: 15351 default: 15352 llvm_unreachable("Clause is not allowed."); 15353 } 15354 return Res; 15355 } 15356 15357 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 15358 SourceLocation EndLoc) { 15359 DSAStack->setNowaitRegion(); 15360 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 15361 } 15362 15363 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 15364 SourceLocation EndLoc) { 15365 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 15366 } 15367 15368 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 15369 SourceLocation EndLoc) { 15370 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 15371 } 15372 15373 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 15374 SourceLocation EndLoc) { 15375 return new (Context) OMPReadClause(StartLoc, EndLoc); 15376 } 15377 15378 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 15379 SourceLocation EndLoc) { 15380 return new (Context) OMPWriteClause(StartLoc, EndLoc); 15381 } 15382 15383 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 15384 SourceLocation EndLoc) { 15385 return OMPUpdateClause::Create(Context, StartLoc, EndLoc); 15386 } 15387 15388 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 15389 SourceLocation EndLoc) { 15390 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 15391 } 15392 15393 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 15394 SourceLocation EndLoc) { 15395 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 15396 } 15397 15398 OMPClause *Sema::ActOnOpenMPAcqRelClause(SourceLocation StartLoc, 15399 SourceLocation EndLoc) { 15400 return new (Context) OMPAcqRelClause(StartLoc, EndLoc); 15401 } 15402 15403 OMPClause *Sema::ActOnOpenMPAcquireClause(SourceLocation StartLoc, 15404 SourceLocation EndLoc) { 15405 return new (Context) OMPAcquireClause(StartLoc, EndLoc); 15406 } 15407 15408 OMPClause *Sema::ActOnOpenMPReleaseClause(SourceLocation StartLoc, 15409 SourceLocation EndLoc) { 15410 return new (Context) OMPReleaseClause(StartLoc, EndLoc); 15411 } 15412 15413 OMPClause *Sema::ActOnOpenMPRelaxedClause(SourceLocation StartLoc, 15414 SourceLocation EndLoc) { 15415 return new (Context) OMPRelaxedClause(StartLoc, EndLoc); 15416 } 15417 15418 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 15419 SourceLocation EndLoc) { 15420 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 15421 } 15422 15423 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 15424 SourceLocation EndLoc) { 15425 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 15426 } 15427 15428 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 15429 SourceLocation EndLoc) { 15430 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 15431 } 15432 15433 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, 15434 SourceLocation EndLoc) { 15435 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc); 15436 } 15437 15438 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, 15439 SourceLocation EndLoc) { 15440 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 15441 } 15442 15443 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, 15444 SourceLocation EndLoc) { 15445 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc); 15446 } 15447 15448 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, 15449 SourceLocation EndLoc) { 15450 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc); 15451 } 15452 15453 StmtResult Sema::ActOnOpenMPInteropDirective(ArrayRef<OMPClause *> Clauses, 15454 SourceLocation StartLoc, 15455 SourceLocation EndLoc) { 15456 15457 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 15458 // At least one action-clause must appear on a directive. 15459 if (!hasClauses(Clauses, OMPC_init, OMPC_use, OMPC_destroy, OMPC_nowait)) { 15460 StringRef Expected = "'init', 'use', 'destroy', or 'nowait'"; 15461 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 15462 << Expected << getOpenMPDirectiveName(OMPD_interop); 15463 return StmtError(); 15464 } 15465 15466 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 15467 // A depend clause can only appear on the directive if a targetsync 15468 // interop-type is present or the interop-var was initialized with 15469 // the targetsync interop-type. 15470 15471 // If there is any 'init' clause diagnose if there is no 'init' clause with 15472 // interop-type of 'targetsync'. Cases involving other directives cannot be 15473 // diagnosed. 15474 const OMPDependClause *DependClause = nullptr; 15475 bool HasInitClause = false; 15476 bool IsTargetSync = false; 15477 for (const OMPClause *C : Clauses) { 15478 if (IsTargetSync) 15479 break; 15480 if (const auto *InitClause = dyn_cast<OMPInitClause>(C)) { 15481 HasInitClause = true; 15482 if (InitClause->getIsTargetSync()) 15483 IsTargetSync = true; 15484 } else if (const auto *DC = dyn_cast<OMPDependClause>(C)) { 15485 DependClause = DC; 15486 } 15487 } 15488 if (DependClause && HasInitClause && !IsTargetSync) { 15489 Diag(DependClause->getBeginLoc(), diag::err_omp_interop_bad_depend_clause); 15490 return StmtError(); 15491 } 15492 15493 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 15494 // Each interop-var may be specified for at most one action-clause of each 15495 // interop construct. 15496 llvm::SmallPtrSet<const VarDecl *, 4> InteropVars; 15497 for (const OMPClause *C : Clauses) { 15498 OpenMPClauseKind ClauseKind = C->getClauseKind(); 15499 const DeclRefExpr *DRE = nullptr; 15500 SourceLocation VarLoc; 15501 15502 if (ClauseKind == OMPC_init) { 15503 const auto *IC = cast<OMPInitClause>(C); 15504 VarLoc = IC->getVarLoc(); 15505 DRE = dyn_cast_or_null<DeclRefExpr>(IC->getInteropVar()); 15506 } else if (ClauseKind == OMPC_use) { 15507 const auto *UC = cast<OMPUseClause>(C); 15508 VarLoc = UC->getVarLoc(); 15509 DRE = dyn_cast_or_null<DeclRefExpr>(UC->getInteropVar()); 15510 } else if (ClauseKind == OMPC_destroy) { 15511 const auto *DC = cast<OMPDestroyClause>(C); 15512 VarLoc = DC->getVarLoc(); 15513 DRE = dyn_cast_or_null<DeclRefExpr>(DC->getInteropVar()); 15514 } 15515 15516 if (!DRE) 15517 continue; 15518 15519 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 15520 if (!InteropVars.insert(VD->getCanonicalDecl()).second) { 15521 Diag(VarLoc, diag::err_omp_interop_var_multiple_actions) << VD; 15522 return StmtError(); 15523 } 15524 } 15525 } 15526 15527 return OMPInteropDirective::Create(Context, StartLoc, EndLoc, Clauses); 15528 } 15529 15530 static bool isValidInteropVariable(Sema &SemaRef, Expr *InteropVarExpr, 15531 SourceLocation VarLoc, 15532 OpenMPClauseKind Kind) { 15533 if (InteropVarExpr->isValueDependent() || InteropVarExpr->isTypeDependent() || 15534 InteropVarExpr->isInstantiationDependent() || 15535 InteropVarExpr->containsUnexpandedParameterPack()) 15536 return true; 15537 15538 const auto *DRE = dyn_cast<DeclRefExpr>(InteropVarExpr); 15539 if (!DRE || !isa<VarDecl>(DRE->getDecl())) { 15540 SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) << 0; 15541 return false; 15542 } 15543 15544 // Interop variable should be of type omp_interop_t. 15545 bool HasError = false; 15546 QualType InteropType; 15547 LookupResult Result(SemaRef, &SemaRef.Context.Idents.get("omp_interop_t"), 15548 VarLoc, Sema::LookupOrdinaryName); 15549 if (SemaRef.LookupName(Result, SemaRef.getCurScope())) { 15550 NamedDecl *ND = Result.getFoundDecl(); 15551 if (const auto *TD = dyn_cast<TypeDecl>(ND)) { 15552 InteropType = QualType(TD->getTypeForDecl(), 0); 15553 } else { 15554 HasError = true; 15555 } 15556 } else { 15557 HasError = true; 15558 } 15559 15560 if (HasError) { 15561 SemaRef.Diag(VarLoc, diag::err_omp_implied_type_not_found) 15562 << "omp_interop_t"; 15563 return false; 15564 } 15565 15566 QualType VarType = InteropVarExpr->getType().getUnqualifiedType(); 15567 if (!SemaRef.Context.hasSameType(InteropType, VarType)) { 15568 SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_wrong_type); 15569 return false; 15570 } 15571 15572 // OpenMP 5.1 [2.15.1, interop Construct, Restrictions] 15573 // The interop-var passed to init or destroy must be non-const. 15574 if ((Kind == OMPC_init || Kind == OMPC_destroy) && 15575 isConstNotMutableType(SemaRef, InteropVarExpr->getType())) { 15576 SemaRef.Diag(VarLoc, diag::err_omp_interop_variable_expected) 15577 << /*non-const*/ 1; 15578 return false; 15579 } 15580 return true; 15581 } 15582 15583 OMPClause * 15584 Sema::ActOnOpenMPInitClause(Expr *InteropVar, ArrayRef<Expr *> PrefExprs, 15585 bool IsTarget, bool IsTargetSync, 15586 SourceLocation StartLoc, SourceLocation LParenLoc, 15587 SourceLocation VarLoc, SourceLocation EndLoc) { 15588 15589 if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_init)) 15590 return nullptr; 15591 15592 // Check prefer_type values. These foreign-runtime-id values are either 15593 // string literals or constant integral expressions. 15594 for (const Expr *E : PrefExprs) { 15595 if (E->isValueDependent() || E->isTypeDependent() || 15596 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 15597 continue; 15598 if (E->isIntegerConstantExpr(Context)) 15599 continue; 15600 if (isa<StringLiteral>(E)) 15601 continue; 15602 Diag(E->getExprLoc(), diag::err_omp_interop_prefer_type); 15603 return nullptr; 15604 } 15605 15606 return OMPInitClause::Create(Context, InteropVar, PrefExprs, IsTarget, 15607 IsTargetSync, StartLoc, LParenLoc, VarLoc, 15608 EndLoc); 15609 } 15610 15611 OMPClause *Sema::ActOnOpenMPUseClause(Expr *InteropVar, SourceLocation StartLoc, 15612 SourceLocation LParenLoc, 15613 SourceLocation VarLoc, 15614 SourceLocation EndLoc) { 15615 15616 if (!isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_use)) 15617 return nullptr; 15618 15619 return new (Context) 15620 OMPUseClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc); 15621 } 15622 15623 OMPClause *Sema::ActOnOpenMPDestroyClause(Expr *InteropVar, 15624 SourceLocation StartLoc, 15625 SourceLocation LParenLoc, 15626 SourceLocation VarLoc, 15627 SourceLocation EndLoc) { 15628 if (InteropVar && 15629 !isValidInteropVariable(*this, InteropVar, VarLoc, OMPC_destroy)) 15630 return nullptr; 15631 15632 return new (Context) 15633 OMPDestroyClause(InteropVar, StartLoc, LParenLoc, VarLoc, EndLoc); 15634 } 15635 15636 OMPClause *Sema::ActOnOpenMPNovariantsClause(Expr *Condition, 15637 SourceLocation StartLoc, 15638 SourceLocation LParenLoc, 15639 SourceLocation EndLoc) { 15640 Expr *ValExpr = Condition; 15641 Stmt *HelperValStmt = nullptr; 15642 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 15643 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 15644 !Condition->isInstantiationDependent() && 15645 !Condition->containsUnexpandedParameterPack()) { 15646 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 15647 if (Val.isInvalid()) 15648 return nullptr; 15649 15650 ValExpr = MakeFullExpr(Val.get()).get(); 15651 15652 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 15653 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_novariants, 15654 LangOpts.OpenMP); 15655 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 15656 ValExpr = MakeFullExpr(ValExpr).get(); 15657 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 15658 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 15659 HelperValStmt = buildPreInits(Context, Captures); 15660 } 15661 } 15662 15663 return new (Context) OMPNovariantsClause( 15664 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 15665 } 15666 15667 OMPClause *Sema::ActOnOpenMPNocontextClause(Expr *Condition, 15668 SourceLocation StartLoc, 15669 SourceLocation LParenLoc, 15670 SourceLocation EndLoc) { 15671 Expr *ValExpr = Condition; 15672 Stmt *HelperValStmt = nullptr; 15673 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 15674 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 15675 !Condition->isInstantiationDependent() && 15676 !Condition->containsUnexpandedParameterPack()) { 15677 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 15678 if (Val.isInvalid()) 15679 return nullptr; 15680 15681 ValExpr = MakeFullExpr(Val.get()).get(); 15682 15683 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 15684 CaptureRegion = 15685 getOpenMPCaptureRegionForClause(DKind, OMPC_nocontext, LangOpts.OpenMP); 15686 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 15687 ValExpr = MakeFullExpr(ValExpr).get(); 15688 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 15689 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 15690 HelperValStmt = buildPreInits(Context, Captures); 15691 } 15692 } 15693 15694 return new (Context) OMPNocontextClause(ValExpr, HelperValStmt, CaptureRegion, 15695 StartLoc, LParenLoc, EndLoc); 15696 } 15697 15698 OMPClause *Sema::ActOnOpenMPFilterClause(Expr *ThreadID, 15699 SourceLocation StartLoc, 15700 SourceLocation LParenLoc, 15701 SourceLocation EndLoc) { 15702 Expr *ValExpr = ThreadID; 15703 Stmt *HelperValStmt = nullptr; 15704 15705 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 15706 OpenMPDirectiveKind CaptureRegion = 15707 getOpenMPCaptureRegionForClause(DKind, OMPC_filter, LangOpts.OpenMP); 15708 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 15709 ValExpr = MakeFullExpr(ValExpr).get(); 15710 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 15711 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 15712 HelperValStmt = buildPreInits(Context, Captures); 15713 } 15714 15715 return new (Context) OMPFilterClause(ValExpr, HelperValStmt, CaptureRegion, 15716 StartLoc, LParenLoc, EndLoc); 15717 } 15718 15719 OMPClause *Sema::ActOnOpenMPVarListClause( 15720 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *DepModOrTailExpr, 15721 const OMPVarListLocTy &Locs, SourceLocation ColonLoc, 15722 CXXScopeSpec &ReductionOrMapperIdScopeSpec, 15723 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier, 15724 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 15725 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit, 15726 SourceLocation ExtraModifierLoc, 15727 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 15728 ArrayRef<SourceLocation> MotionModifiersLoc) { 15729 SourceLocation StartLoc = Locs.StartLoc; 15730 SourceLocation LParenLoc = Locs.LParenLoc; 15731 SourceLocation EndLoc = Locs.EndLoc; 15732 OMPClause *Res = nullptr; 15733 switch (Kind) { 15734 case OMPC_private: 15735 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 15736 break; 15737 case OMPC_firstprivate: 15738 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 15739 break; 15740 case OMPC_lastprivate: 15741 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown && 15742 "Unexpected lastprivate modifier."); 15743 Res = ActOnOpenMPLastprivateClause( 15744 VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier), 15745 ExtraModifierLoc, ColonLoc, StartLoc, LParenLoc, EndLoc); 15746 break; 15747 case OMPC_shared: 15748 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 15749 break; 15750 case OMPC_reduction: 15751 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_REDUCTION_unknown && 15752 "Unexpected lastprivate modifier."); 15753 Res = ActOnOpenMPReductionClause( 15754 VarList, static_cast<OpenMPReductionClauseModifier>(ExtraModifier), 15755 StartLoc, LParenLoc, ExtraModifierLoc, ColonLoc, EndLoc, 15756 ReductionOrMapperIdScopeSpec, ReductionOrMapperId); 15757 break; 15758 case OMPC_task_reduction: 15759 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 15760 EndLoc, ReductionOrMapperIdScopeSpec, 15761 ReductionOrMapperId); 15762 break; 15763 case OMPC_in_reduction: 15764 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 15765 EndLoc, ReductionOrMapperIdScopeSpec, 15766 ReductionOrMapperId); 15767 break; 15768 case OMPC_linear: 15769 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown && 15770 "Unexpected linear modifier."); 15771 Res = ActOnOpenMPLinearClause( 15772 VarList, DepModOrTailExpr, StartLoc, LParenLoc, 15773 static_cast<OpenMPLinearClauseKind>(ExtraModifier), ExtraModifierLoc, 15774 ColonLoc, EndLoc); 15775 break; 15776 case OMPC_aligned: 15777 Res = ActOnOpenMPAlignedClause(VarList, DepModOrTailExpr, StartLoc, 15778 LParenLoc, ColonLoc, EndLoc); 15779 break; 15780 case OMPC_copyin: 15781 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 15782 break; 15783 case OMPC_copyprivate: 15784 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 15785 break; 15786 case OMPC_flush: 15787 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 15788 break; 15789 case OMPC_depend: 15790 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown && 15791 "Unexpected depend modifier."); 15792 Res = ActOnOpenMPDependClause( 15793 DepModOrTailExpr, static_cast<OpenMPDependClauseKind>(ExtraModifier), 15794 ExtraModifierLoc, ColonLoc, VarList, StartLoc, LParenLoc, EndLoc); 15795 break; 15796 case OMPC_map: 15797 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown && 15798 "Unexpected map modifier."); 15799 Res = ActOnOpenMPMapClause( 15800 MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec, 15801 ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier), 15802 IsMapTypeImplicit, ExtraModifierLoc, ColonLoc, VarList, Locs); 15803 break; 15804 case OMPC_to: 15805 Res = ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc, 15806 ReductionOrMapperIdScopeSpec, ReductionOrMapperId, 15807 ColonLoc, VarList, Locs); 15808 break; 15809 case OMPC_from: 15810 Res = ActOnOpenMPFromClause(MotionModifiers, MotionModifiersLoc, 15811 ReductionOrMapperIdScopeSpec, 15812 ReductionOrMapperId, ColonLoc, VarList, Locs); 15813 break; 15814 case OMPC_use_device_ptr: 15815 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs); 15816 break; 15817 case OMPC_use_device_addr: 15818 Res = ActOnOpenMPUseDeviceAddrClause(VarList, Locs); 15819 break; 15820 case OMPC_is_device_ptr: 15821 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs); 15822 break; 15823 case OMPC_allocate: 15824 Res = ActOnOpenMPAllocateClause(DepModOrTailExpr, VarList, StartLoc, 15825 LParenLoc, ColonLoc, EndLoc); 15826 break; 15827 case OMPC_nontemporal: 15828 Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc); 15829 break; 15830 case OMPC_inclusive: 15831 Res = ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc, EndLoc); 15832 break; 15833 case OMPC_exclusive: 15834 Res = ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc, EndLoc); 15835 break; 15836 case OMPC_affinity: 15837 Res = ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc, EndLoc, 15838 DepModOrTailExpr, VarList); 15839 break; 15840 case OMPC_if: 15841 case OMPC_depobj: 15842 case OMPC_final: 15843 case OMPC_num_threads: 15844 case OMPC_safelen: 15845 case OMPC_simdlen: 15846 case OMPC_sizes: 15847 case OMPC_allocator: 15848 case OMPC_collapse: 15849 case OMPC_default: 15850 case OMPC_proc_bind: 15851 case OMPC_schedule: 15852 case OMPC_ordered: 15853 case OMPC_nowait: 15854 case OMPC_untied: 15855 case OMPC_mergeable: 15856 case OMPC_threadprivate: 15857 case OMPC_read: 15858 case OMPC_write: 15859 case OMPC_update: 15860 case OMPC_capture: 15861 case OMPC_seq_cst: 15862 case OMPC_acq_rel: 15863 case OMPC_acquire: 15864 case OMPC_release: 15865 case OMPC_relaxed: 15866 case OMPC_device: 15867 case OMPC_threads: 15868 case OMPC_simd: 15869 case OMPC_num_teams: 15870 case OMPC_thread_limit: 15871 case OMPC_priority: 15872 case OMPC_grainsize: 15873 case OMPC_nogroup: 15874 case OMPC_num_tasks: 15875 case OMPC_hint: 15876 case OMPC_dist_schedule: 15877 case OMPC_defaultmap: 15878 case OMPC_unknown: 15879 case OMPC_uniform: 15880 case OMPC_unified_address: 15881 case OMPC_unified_shared_memory: 15882 case OMPC_reverse_offload: 15883 case OMPC_dynamic_allocators: 15884 case OMPC_atomic_default_mem_order: 15885 case OMPC_device_type: 15886 case OMPC_match: 15887 case OMPC_order: 15888 case OMPC_destroy: 15889 case OMPC_novariants: 15890 case OMPC_nocontext: 15891 case OMPC_detach: 15892 case OMPC_uses_allocators: 15893 case OMPC_when: 15894 case OMPC_bind: 15895 default: 15896 llvm_unreachable("Clause is not allowed."); 15897 } 15898 return Res; 15899 } 15900 15901 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 15902 ExprObjectKind OK, SourceLocation Loc) { 15903 ExprResult Res = BuildDeclRefExpr( 15904 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 15905 if (!Res.isUsable()) 15906 return ExprError(); 15907 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 15908 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 15909 if (!Res.isUsable()) 15910 return ExprError(); 15911 } 15912 if (VK != VK_LValue && Res.get()->isGLValue()) { 15913 Res = DefaultLvalueConversion(Res.get()); 15914 if (!Res.isUsable()) 15915 return ExprError(); 15916 } 15917 return Res; 15918 } 15919 15920 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 15921 SourceLocation StartLoc, 15922 SourceLocation LParenLoc, 15923 SourceLocation EndLoc) { 15924 SmallVector<Expr *, 8> Vars; 15925 SmallVector<Expr *, 8> PrivateCopies; 15926 for (Expr *RefExpr : VarList) { 15927 assert(RefExpr && "NULL expr in OpenMP private clause."); 15928 SourceLocation ELoc; 15929 SourceRange ERange; 15930 Expr *SimpleRefExpr = RefExpr; 15931 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 15932 if (Res.second) { 15933 // It will be analyzed later. 15934 Vars.push_back(RefExpr); 15935 PrivateCopies.push_back(nullptr); 15936 } 15937 ValueDecl *D = Res.first; 15938 if (!D) 15939 continue; 15940 15941 QualType Type = D->getType(); 15942 auto *VD = dyn_cast<VarDecl>(D); 15943 15944 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 15945 // A variable that appears in a private clause must not have an incomplete 15946 // type or a reference type. 15947 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 15948 continue; 15949 Type = Type.getNonReferenceType(); 15950 15951 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 15952 // A variable that is privatized must not have a const-qualified type 15953 // unless it is of class type with a mutable member. This restriction does 15954 // not apply to the firstprivate clause. 15955 // 15956 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions] 15957 // A variable that appears in a private clause must not have a 15958 // const-qualified type unless it is of class type with a mutable member. 15959 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc)) 15960 continue; 15961 15962 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 15963 // in a Construct] 15964 // Variables with the predetermined data-sharing attributes may not be 15965 // listed in data-sharing attributes clauses, except for the cases 15966 // listed below. For these exceptions only, listing a predetermined 15967 // variable in a data-sharing attribute clause is allowed and overrides 15968 // the variable's predetermined data-sharing attributes. 15969 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 15970 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 15971 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 15972 << getOpenMPClauseName(OMPC_private); 15973 reportOriginalDsa(*this, DSAStack, D, DVar); 15974 continue; 15975 } 15976 15977 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 15978 // Variably modified types are not supported for tasks. 15979 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 15980 isOpenMPTaskingDirective(CurrDir)) { 15981 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 15982 << getOpenMPClauseName(OMPC_private) << Type 15983 << getOpenMPDirectiveName(CurrDir); 15984 bool IsDecl = 15985 !VD || 15986 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 15987 Diag(D->getLocation(), 15988 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 15989 << D; 15990 continue; 15991 } 15992 15993 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 15994 // A list item cannot appear in both a map clause and a data-sharing 15995 // attribute clause on the same construct 15996 // 15997 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 15998 // A list item cannot appear in both a map clause and a data-sharing 15999 // attribute clause on the same construct unless the construct is a 16000 // combined construct. 16001 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) || 16002 CurrDir == OMPD_target) { 16003 OpenMPClauseKind ConflictKind; 16004 if (DSAStack->checkMappableExprComponentListsForDecl( 16005 VD, /*CurrentRegionOnly=*/true, 16006 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 16007 OpenMPClauseKind WhereFoundClauseKind) -> bool { 16008 ConflictKind = WhereFoundClauseKind; 16009 return true; 16010 })) { 16011 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 16012 << getOpenMPClauseName(OMPC_private) 16013 << getOpenMPClauseName(ConflictKind) 16014 << getOpenMPDirectiveName(CurrDir); 16015 reportOriginalDsa(*this, DSAStack, D, DVar); 16016 continue; 16017 } 16018 } 16019 16020 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 16021 // A variable of class type (or array thereof) that appears in a private 16022 // clause requires an accessible, unambiguous default constructor for the 16023 // class type. 16024 // Generate helper private variable and initialize it with the default 16025 // value. The address of the original variable is replaced by the address of 16026 // the new private variable in CodeGen. This new variable is not added to 16027 // IdResolver, so the code in the OpenMP region uses original variable for 16028 // proper diagnostics. 16029 Type = Type.getUnqualifiedType(); 16030 VarDecl *VDPrivate = 16031 buildVarDecl(*this, ELoc, Type, D->getName(), 16032 D->hasAttrs() ? &D->getAttrs() : nullptr, 16033 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 16034 ActOnUninitializedDecl(VDPrivate); 16035 if (VDPrivate->isInvalidDecl()) 16036 continue; 16037 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 16038 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 16039 16040 DeclRefExpr *Ref = nullptr; 16041 if (!VD && !CurContext->isDependentContext()) 16042 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 16043 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 16044 Vars.push_back((VD || CurContext->isDependentContext()) 16045 ? RefExpr->IgnoreParens() 16046 : Ref); 16047 PrivateCopies.push_back(VDPrivateRefExpr); 16048 } 16049 16050 if (Vars.empty()) 16051 return nullptr; 16052 16053 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 16054 PrivateCopies); 16055 } 16056 16057 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 16058 SourceLocation StartLoc, 16059 SourceLocation LParenLoc, 16060 SourceLocation EndLoc) { 16061 SmallVector<Expr *, 8> Vars; 16062 SmallVector<Expr *, 8> PrivateCopies; 16063 SmallVector<Expr *, 8> Inits; 16064 SmallVector<Decl *, 4> ExprCaptures; 16065 bool IsImplicitClause = 16066 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 16067 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc(); 16068 16069 for (Expr *RefExpr : VarList) { 16070 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 16071 SourceLocation ELoc; 16072 SourceRange ERange; 16073 Expr *SimpleRefExpr = RefExpr; 16074 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 16075 if (Res.second) { 16076 // It will be analyzed later. 16077 Vars.push_back(RefExpr); 16078 PrivateCopies.push_back(nullptr); 16079 Inits.push_back(nullptr); 16080 } 16081 ValueDecl *D = Res.first; 16082 if (!D) 16083 continue; 16084 16085 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 16086 QualType Type = D->getType(); 16087 auto *VD = dyn_cast<VarDecl>(D); 16088 16089 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 16090 // A variable that appears in a private clause must not have an incomplete 16091 // type or a reference type. 16092 if (RequireCompleteType(ELoc, Type, 16093 diag::err_omp_firstprivate_incomplete_type)) 16094 continue; 16095 Type = Type.getNonReferenceType(); 16096 16097 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 16098 // A variable of class type (or array thereof) that appears in a private 16099 // clause requires an accessible, unambiguous copy constructor for the 16100 // class type. 16101 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 16102 16103 // If an implicit firstprivate variable found it was checked already. 16104 DSAStackTy::DSAVarData TopDVar; 16105 if (!IsImplicitClause) { 16106 DSAStackTy::DSAVarData DVar = 16107 DSAStack->getTopDSA(D, /*FromParent=*/false); 16108 TopDVar = DVar; 16109 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 16110 bool IsConstant = ElemType.isConstant(Context); 16111 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 16112 // A list item that specifies a given variable may not appear in more 16113 // than one clause on the same directive, except that a variable may be 16114 // specified in both firstprivate and lastprivate clauses. 16115 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 16116 // A list item may appear in a firstprivate or lastprivate clause but not 16117 // both. 16118 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 16119 (isOpenMPDistributeDirective(CurrDir) || 16120 DVar.CKind != OMPC_lastprivate) && 16121 DVar.RefExpr) { 16122 Diag(ELoc, diag::err_omp_wrong_dsa) 16123 << getOpenMPClauseName(DVar.CKind) 16124 << getOpenMPClauseName(OMPC_firstprivate); 16125 reportOriginalDsa(*this, DSAStack, D, DVar); 16126 continue; 16127 } 16128 16129 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 16130 // in a Construct] 16131 // Variables with the predetermined data-sharing attributes may not be 16132 // listed in data-sharing attributes clauses, except for the cases 16133 // listed below. For these exceptions only, listing a predetermined 16134 // variable in a data-sharing attribute clause is allowed and overrides 16135 // the variable's predetermined data-sharing attributes. 16136 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 16137 // in a Construct, C/C++, p.2] 16138 // Variables with const-qualified type having no mutable member may be 16139 // listed in a firstprivate clause, even if they are static data members. 16140 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 16141 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 16142 Diag(ELoc, diag::err_omp_wrong_dsa) 16143 << getOpenMPClauseName(DVar.CKind) 16144 << getOpenMPClauseName(OMPC_firstprivate); 16145 reportOriginalDsa(*this, DSAStack, D, DVar); 16146 continue; 16147 } 16148 16149 // OpenMP [2.9.3.4, Restrictions, p.2] 16150 // A list item that is private within a parallel region must not appear 16151 // in a firstprivate clause on a worksharing construct if any of the 16152 // worksharing regions arising from the worksharing construct ever bind 16153 // to any of the parallel regions arising from the parallel construct. 16154 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 16155 // A list item that is private within a teams region must not appear in a 16156 // firstprivate clause on a distribute construct if any of the distribute 16157 // regions arising from the distribute construct ever bind to any of the 16158 // teams regions arising from the teams construct. 16159 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 16160 // A list item that appears in a reduction clause of a teams construct 16161 // must not appear in a firstprivate clause on a distribute construct if 16162 // any of the distribute regions arising from the distribute construct 16163 // ever bind to any of the teams regions arising from the teams construct. 16164 if ((isOpenMPWorksharingDirective(CurrDir) || 16165 isOpenMPDistributeDirective(CurrDir)) && 16166 !isOpenMPParallelDirective(CurrDir) && 16167 !isOpenMPTeamsDirective(CurrDir)) { 16168 DVar = DSAStack->getImplicitDSA(D, true); 16169 if (DVar.CKind != OMPC_shared && 16170 (isOpenMPParallelDirective(DVar.DKind) || 16171 isOpenMPTeamsDirective(DVar.DKind) || 16172 DVar.DKind == OMPD_unknown)) { 16173 Diag(ELoc, diag::err_omp_required_access) 16174 << getOpenMPClauseName(OMPC_firstprivate) 16175 << getOpenMPClauseName(OMPC_shared); 16176 reportOriginalDsa(*this, DSAStack, D, DVar); 16177 continue; 16178 } 16179 } 16180 // OpenMP [2.9.3.4, Restrictions, p.3] 16181 // A list item that appears in a reduction clause of a parallel construct 16182 // must not appear in a firstprivate clause on a worksharing or task 16183 // construct if any of the worksharing or task regions arising from the 16184 // worksharing or task construct ever bind to any of the parallel regions 16185 // arising from the parallel construct. 16186 // OpenMP [2.9.3.4, Restrictions, p.4] 16187 // A list item that appears in a reduction clause in worksharing 16188 // construct must not appear in a firstprivate clause in a task construct 16189 // encountered during execution of any of the worksharing regions arising 16190 // from the worksharing construct. 16191 if (isOpenMPTaskingDirective(CurrDir)) { 16192 DVar = DSAStack->hasInnermostDSA( 16193 D, 16194 [](OpenMPClauseKind C, bool AppliedToPointee) { 16195 return C == OMPC_reduction && !AppliedToPointee; 16196 }, 16197 [](OpenMPDirectiveKind K) { 16198 return isOpenMPParallelDirective(K) || 16199 isOpenMPWorksharingDirective(K) || 16200 isOpenMPTeamsDirective(K); 16201 }, 16202 /*FromParent=*/true); 16203 if (DVar.CKind == OMPC_reduction && 16204 (isOpenMPParallelDirective(DVar.DKind) || 16205 isOpenMPWorksharingDirective(DVar.DKind) || 16206 isOpenMPTeamsDirective(DVar.DKind))) { 16207 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 16208 << getOpenMPDirectiveName(DVar.DKind); 16209 reportOriginalDsa(*this, DSAStack, D, DVar); 16210 continue; 16211 } 16212 } 16213 16214 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 16215 // A list item cannot appear in both a map clause and a data-sharing 16216 // attribute clause on the same construct 16217 // 16218 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 16219 // A list item cannot appear in both a map clause and a data-sharing 16220 // attribute clause on the same construct unless the construct is a 16221 // combined construct. 16222 if ((LangOpts.OpenMP <= 45 && 16223 isOpenMPTargetExecutionDirective(CurrDir)) || 16224 CurrDir == OMPD_target) { 16225 OpenMPClauseKind ConflictKind; 16226 if (DSAStack->checkMappableExprComponentListsForDecl( 16227 VD, /*CurrentRegionOnly=*/true, 16228 [&ConflictKind]( 16229 OMPClauseMappableExprCommon::MappableExprComponentListRef, 16230 OpenMPClauseKind WhereFoundClauseKind) { 16231 ConflictKind = WhereFoundClauseKind; 16232 return true; 16233 })) { 16234 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 16235 << getOpenMPClauseName(OMPC_firstprivate) 16236 << getOpenMPClauseName(ConflictKind) 16237 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 16238 reportOriginalDsa(*this, DSAStack, D, DVar); 16239 continue; 16240 } 16241 } 16242 } 16243 16244 // Variably modified types are not supported for tasks. 16245 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 16246 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 16247 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 16248 << getOpenMPClauseName(OMPC_firstprivate) << Type 16249 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 16250 bool IsDecl = 16251 !VD || 16252 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 16253 Diag(D->getLocation(), 16254 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 16255 << D; 16256 continue; 16257 } 16258 16259 Type = Type.getUnqualifiedType(); 16260 VarDecl *VDPrivate = 16261 buildVarDecl(*this, ELoc, Type, D->getName(), 16262 D->hasAttrs() ? &D->getAttrs() : nullptr, 16263 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 16264 // Generate helper private variable and initialize it with the value of the 16265 // original variable. The address of the original variable is replaced by 16266 // the address of the new private variable in the CodeGen. This new variable 16267 // is not added to IdResolver, so the code in the OpenMP region uses 16268 // original variable for proper diagnostics and variable capturing. 16269 Expr *VDInitRefExpr = nullptr; 16270 // For arrays generate initializer for single element and replace it by the 16271 // original array element in CodeGen. 16272 if (Type->isArrayType()) { 16273 VarDecl *VDInit = 16274 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 16275 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 16276 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get(); 16277 ElemType = ElemType.getUnqualifiedType(); 16278 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 16279 ".firstprivate.temp"); 16280 InitializedEntity Entity = 16281 InitializedEntity::InitializeVariable(VDInitTemp); 16282 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 16283 16284 InitializationSequence InitSeq(*this, Entity, Kind, Init); 16285 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 16286 if (Result.isInvalid()) 16287 VDPrivate->setInvalidDecl(); 16288 else 16289 VDPrivate->setInit(Result.getAs<Expr>()); 16290 // Remove temp variable declaration. 16291 Context.Deallocate(VDInitTemp); 16292 } else { 16293 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 16294 ".firstprivate.temp"); 16295 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 16296 RefExpr->getExprLoc()); 16297 AddInitializerToDecl(VDPrivate, 16298 DefaultLvalueConversion(VDInitRefExpr).get(), 16299 /*DirectInit=*/false); 16300 } 16301 if (VDPrivate->isInvalidDecl()) { 16302 if (IsImplicitClause) { 16303 Diag(RefExpr->getExprLoc(), 16304 diag::note_omp_task_predetermined_firstprivate_here); 16305 } 16306 continue; 16307 } 16308 CurContext->addDecl(VDPrivate); 16309 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 16310 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 16311 RefExpr->getExprLoc()); 16312 DeclRefExpr *Ref = nullptr; 16313 if (!VD && !CurContext->isDependentContext()) { 16314 if (TopDVar.CKind == OMPC_lastprivate) { 16315 Ref = TopDVar.PrivateCopy; 16316 } else { 16317 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 16318 if (!isOpenMPCapturedDecl(D)) 16319 ExprCaptures.push_back(Ref->getDecl()); 16320 } 16321 } 16322 if (!IsImplicitClause) 16323 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 16324 Vars.push_back((VD || CurContext->isDependentContext()) 16325 ? RefExpr->IgnoreParens() 16326 : Ref); 16327 PrivateCopies.push_back(VDPrivateRefExpr); 16328 Inits.push_back(VDInitRefExpr); 16329 } 16330 16331 if (Vars.empty()) 16332 return nullptr; 16333 16334 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 16335 Vars, PrivateCopies, Inits, 16336 buildPreInits(Context, ExprCaptures)); 16337 } 16338 16339 OMPClause *Sema::ActOnOpenMPLastprivateClause( 16340 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind, 16341 SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc, 16342 SourceLocation LParenLoc, SourceLocation EndLoc) { 16343 if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) { 16344 assert(ColonLoc.isValid() && "Colon location must be valid."); 16345 Diag(LPKindLoc, diag::err_omp_unexpected_clause_value) 16346 << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0, 16347 /*Last=*/OMPC_LASTPRIVATE_unknown) 16348 << getOpenMPClauseName(OMPC_lastprivate); 16349 return nullptr; 16350 } 16351 16352 SmallVector<Expr *, 8> Vars; 16353 SmallVector<Expr *, 8> SrcExprs; 16354 SmallVector<Expr *, 8> DstExprs; 16355 SmallVector<Expr *, 8> AssignmentOps; 16356 SmallVector<Decl *, 4> ExprCaptures; 16357 SmallVector<Expr *, 4> ExprPostUpdates; 16358 for (Expr *RefExpr : VarList) { 16359 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 16360 SourceLocation ELoc; 16361 SourceRange ERange; 16362 Expr *SimpleRefExpr = RefExpr; 16363 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 16364 if (Res.second) { 16365 // It will be analyzed later. 16366 Vars.push_back(RefExpr); 16367 SrcExprs.push_back(nullptr); 16368 DstExprs.push_back(nullptr); 16369 AssignmentOps.push_back(nullptr); 16370 } 16371 ValueDecl *D = Res.first; 16372 if (!D) 16373 continue; 16374 16375 QualType Type = D->getType(); 16376 auto *VD = dyn_cast<VarDecl>(D); 16377 16378 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 16379 // A variable that appears in a lastprivate clause must not have an 16380 // incomplete type or a reference type. 16381 if (RequireCompleteType(ELoc, Type, 16382 diag::err_omp_lastprivate_incomplete_type)) 16383 continue; 16384 Type = Type.getNonReferenceType(); 16385 16386 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 16387 // A variable that is privatized must not have a const-qualified type 16388 // unless it is of class type with a mutable member. This restriction does 16389 // not apply to the firstprivate clause. 16390 // 16391 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions] 16392 // A variable that appears in a lastprivate clause must not have a 16393 // const-qualified type unless it is of class type with a mutable member. 16394 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc)) 16395 continue; 16396 16397 // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions] 16398 // A list item that appears in a lastprivate clause with the conditional 16399 // modifier must be a scalar variable. 16400 if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) { 16401 Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar); 16402 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 16403 VarDecl::DeclarationOnly; 16404 Diag(D->getLocation(), 16405 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 16406 << D; 16407 continue; 16408 } 16409 16410 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 16411 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 16412 // in a Construct] 16413 // Variables with the predetermined data-sharing attributes may not be 16414 // listed in data-sharing attributes clauses, except for the cases 16415 // listed below. 16416 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 16417 // A list item may appear in a firstprivate or lastprivate clause but not 16418 // both. 16419 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 16420 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 16421 (isOpenMPDistributeDirective(CurrDir) || 16422 DVar.CKind != OMPC_firstprivate) && 16423 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 16424 Diag(ELoc, diag::err_omp_wrong_dsa) 16425 << getOpenMPClauseName(DVar.CKind) 16426 << getOpenMPClauseName(OMPC_lastprivate); 16427 reportOriginalDsa(*this, DSAStack, D, DVar); 16428 continue; 16429 } 16430 16431 // OpenMP [2.14.3.5, Restrictions, p.2] 16432 // A list item that is private within a parallel region, or that appears in 16433 // the reduction clause of a parallel construct, must not appear in a 16434 // lastprivate clause on a worksharing construct if any of the corresponding 16435 // worksharing regions ever binds to any of the corresponding parallel 16436 // regions. 16437 DSAStackTy::DSAVarData TopDVar = DVar; 16438 if (isOpenMPWorksharingDirective(CurrDir) && 16439 !isOpenMPParallelDirective(CurrDir) && 16440 !isOpenMPTeamsDirective(CurrDir)) { 16441 DVar = DSAStack->getImplicitDSA(D, true); 16442 if (DVar.CKind != OMPC_shared) { 16443 Diag(ELoc, diag::err_omp_required_access) 16444 << getOpenMPClauseName(OMPC_lastprivate) 16445 << getOpenMPClauseName(OMPC_shared); 16446 reportOriginalDsa(*this, DSAStack, D, DVar); 16447 continue; 16448 } 16449 } 16450 16451 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 16452 // A variable of class type (or array thereof) that appears in a 16453 // lastprivate clause requires an accessible, unambiguous default 16454 // constructor for the class type, unless the list item is also specified 16455 // in a firstprivate clause. 16456 // A variable of class type (or array thereof) that appears in a 16457 // lastprivate clause requires an accessible, unambiguous copy assignment 16458 // operator for the class type. 16459 Type = Context.getBaseElementType(Type).getNonReferenceType(); 16460 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(), 16461 Type.getUnqualifiedType(), ".lastprivate.src", 16462 D->hasAttrs() ? &D->getAttrs() : nullptr); 16463 DeclRefExpr *PseudoSrcExpr = 16464 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 16465 VarDecl *DstVD = 16466 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 16467 D->hasAttrs() ? &D->getAttrs() : nullptr); 16468 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 16469 // For arrays generate assignment operation for single element and replace 16470 // it by the original array element in CodeGen. 16471 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 16472 PseudoDstExpr, PseudoSrcExpr); 16473 if (AssignmentOp.isInvalid()) 16474 continue; 16475 AssignmentOp = 16476 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 16477 if (AssignmentOp.isInvalid()) 16478 continue; 16479 16480 DeclRefExpr *Ref = nullptr; 16481 if (!VD && !CurContext->isDependentContext()) { 16482 if (TopDVar.CKind == OMPC_firstprivate) { 16483 Ref = TopDVar.PrivateCopy; 16484 } else { 16485 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 16486 if (!isOpenMPCapturedDecl(D)) 16487 ExprCaptures.push_back(Ref->getDecl()); 16488 } 16489 if ((TopDVar.CKind == OMPC_firstprivate && !TopDVar.PrivateCopy) || 16490 (!isOpenMPCapturedDecl(D) && 16491 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 16492 ExprResult RefRes = DefaultLvalueConversion(Ref); 16493 if (!RefRes.isUsable()) 16494 continue; 16495 ExprResult PostUpdateRes = 16496 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 16497 RefRes.get()); 16498 if (!PostUpdateRes.isUsable()) 16499 continue; 16500 ExprPostUpdates.push_back( 16501 IgnoredValueConversions(PostUpdateRes.get()).get()); 16502 } 16503 } 16504 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 16505 Vars.push_back((VD || CurContext->isDependentContext()) 16506 ? RefExpr->IgnoreParens() 16507 : Ref); 16508 SrcExprs.push_back(PseudoSrcExpr); 16509 DstExprs.push_back(PseudoDstExpr); 16510 AssignmentOps.push_back(AssignmentOp.get()); 16511 } 16512 16513 if (Vars.empty()) 16514 return nullptr; 16515 16516 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 16517 Vars, SrcExprs, DstExprs, AssignmentOps, 16518 LPKind, LPKindLoc, ColonLoc, 16519 buildPreInits(Context, ExprCaptures), 16520 buildPostUpdate(*this, ExprPostUpdates)); 16521 } 16522 16523 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 16524 SourceLocation StartLoc, 16525 SourceLocation LParenLoc, 16526 SourceLocation EndLoc) { 16527 SmallVector<Expr *, 8> Vars; 16528 for (Expr *RefExpr : VarList) { 16529 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 16530 SourceLocation ELoc; 16531 SourceRange ERange; 16532 Expr *SimpleRefExpr = RefExpr; 16533 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 16534 if (Res.second) { 16535 // It will be analyzed later. 16536 Vars.push_back(RefExpr); 16537 } 16538 ValueDecl *D = Res.first; 16539 if (!D) 16540 continue; 16541 16542 auto *VD = dyn_cast<VarDecl>(D); 16543 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 16544 // in a Construct] 16545 // Variables with the predetermined data-sharing attributes may not be 16546 // listed in data-sharing attributes clauses, except for the cases 16547 // listed below. For these exceptions only, listing a predetermined 16548 // variable in a data-sharing attribute clause is allowed and overrides 16549 // the variable's predetermined data-sharing attributes. 16550 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 16551 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 16552 DVar.RefExpr) { 16553 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 16554 << getOpenMPClauseName(OMPC_shared); 16555 reportOriginalDsa(*this, DSAStack, D, DVar); 16556 continue; 16557 } 16558 16559 DeclRefExpr *Ref = nullptr; 16560 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 16561 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 16562 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 16563 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 16564 ? RefExpr->IgnoreParens() 16565 : Ref); 16566 } 16567 16568 if (Vars.empty()) 16569 return nullptr; 16570 16571 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 16572 } 16573 16574 namespace { 16575 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 16576 DSAStackTy *Stack; 16577 16578 public: 16579 bool VisitDeclRefExpr(DeclRefExpr *E) { 16580 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 16581 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 16582 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 16583 return false; 16584 if (DVar.CKind != OMPC_unknown) 16585 return true; 16586 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 16587 VD, 16588 [](OpenMPClauseKind C, bool AppliedToPointee) { 16589 return isOpenMPPrivate(C) && !AppliedToPointee; 16590 }, 16591 [](OpenMPDirectiveKind) { return true; }, 16592 /*FromParent=*/true); 16593 return DVarPrivate.CKind != OMPC_unknown; 16594 } 16595 return false; 16596 } 16597 bool VisitStmt(Stmt *S) { 16598 for (Stmt *Child : S->children()) { 16599 if (Child && Visit(Child)) 16600 return true; 16601 } 16602 return false; 16603 } 16604 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 16605 }; 16606 } // namespace 16607 16608 namespace { 16609 // Transform MemberExpression for specified FieldDecl of current class to 16610 // DeclRefExpr to specified OMPCapturedExprDecl. 16611 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 16612 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 16613 ValueDecl *Field = nullptr; 16614 DeclRefExpr *CapturedExpr = nullptr; 16615 16616 public: 16617 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 16618 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 16619 16620 ExprResult TransformMemberExpr(MemberExpr *E) { 16621 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 16622 E->getMemberDecl() == Field) { 16623 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 16624 return CapturedExpr; 16625 } 16626 return BaseTransform::TransformMemberExpr(E); 16627 } 16628 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 16629 }; 16630 } // namespace 16631 16632 template <typename T, typename U> 16633 static T filterLookupForUDReductionAndMapper( 16634 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) { 16635 for (U &Set : Lookups) { 16636 for (auto *D : Set) { 16637 if (T Res = Gen(cast<ValueDecl>(D))) 16638 return Res; 16639 } 16640 } 16641 return T(); 16642 } 16643 16644 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) { 16645 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case"); 16646 16647 for (auto RD : D->redecls()) { 16648 // Don't bother with extra checks if we already know this one isn't visible. 16649 if (RD == D) 16650 continue; 16651 16652 auto ND = cast<NamedDecl>(RD); 16653 if (LookupResult::isVisible(SemaRef, ND)) 16654 return ND; 16655 } 16656 16657 return nullptr; 16658 } 16659 16660 static void 16661 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id, 16662 SourceLocation Loc, QualType Ty, 16663 SmallVectorImpl<UnresolvedSet<8>> &Lookups) { 16664 // Find all of the associated namespaces and classes based on the 16665 // arguments we have. 16666 Sema::AssociatedNamespaceSet AssociatedNamespaces; 16667 Sema::AssociatedClassSet AssociatedClasses; 16668 OpaqueValueExpr OVE(Loc, Ty, VK_LValue); 16669 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces, 16670 AssociatedClasses); 16671 16672 // C++ [basic.lookup.argdep]p3: 16673 // Let X be the lookup set produced by unqualified lookup (3.4.1) 16674 // and let Y be the lookup set produced by argument dependent 16675 // lookup (defined as follows). If X contains [...] then Y is 16676 // empty. Otherwise Y is the set of declarations found in the 16677 // namespaces associated with the argument types as described 16678 // below. The set of declarations found by the lookup of the name 16679 // is the union of X and Y. 16680 // 16681 // Here, we compute Y and add its members to the overloaded 16682 // candidate set. 16683 for (auto *NS : AssociatedNamespaces) { 16684 // When considering an associated namespace, the lookup is the 16685 // same as the lookup performed when the associated namespace is 16686 // used as a qualifier (3.4.3.2) except that: 16687 // 16688 // -- Any using-directives in the associated namespace are 16689 // ignored. 16690 // 16691 // -- Any namespace-scope friend functions declared in 16692 // associated classes are visible within their respective 16693 // namespaces even if they are not visible during an ordinary 16694 // lookup (11.4). 16695 DeclContext::lookup_result R = NS->lookup(Id.getName()); 16696 for (auto *D : R) { 16697 auto *Underlying = D; 16698 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 16699 Underlying = USD->getTargetDecl(); 16700 16701 if (!isa<OMPDeclareReductionDecl>(Underlying) && 16702 !isa<OMPDeclareMapperDecl>(Underlying)) 16703 continue; 16704 16705 if (!SemaRef.isVisible(D)) { 16706 D = findAcceptableDecl(SemaRef, D); 16707 if (!D) 16708 continue; 16709 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 16710 Underlying = USD->getTargetDecl(); 16711 } 16712 Lookups.emplace_back(); 16713 Lookups.back().addDecl(Underlying); 16714 } 16715 } 16716 } 16717 16718 static ExprResult 16719 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 16720 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 16721 const DeclarationNameInfo &ReductionId, QualType Ty, 16722 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 16723 if (ReductionIdScopeSpec.isInvalid()) 16724 return ExprError(); 16725 SmallVector<UnresolvedSet<8>, 4> Lookups; 16726 if (S) { 16727 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 16728 Lookup.suppressDiagnostics(); 16729 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 16730 NamedDecl *D = Lookup.getRepresentativeDecl(); 16731 do { 16732 S = S->getParent(); 16733 } while (S && !S->isDeclScope(D)); 16734 if (S) 16735 S = S->getParent(); 16736 Lookups.emplace_back(); 16737 Lookups.back().append(Lookup.begin(), Lookup.end()); 16738 Lookup.clear(); 16739 } 16740 } else if (auto *ULE = 16741 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 16742 Lookups.push_back(UnresolvedSet<8>()); 16743 Decl *PrevD = nullptr; 16744 for (NamedDecl *D : ULE->decls()) { 16745 if (D == PrevD) 16746 Lookups.push_back(UnresolvedSet<8>()); 16747 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D)) 16748 Lookups.back().addDecl(DRD); 16749 PrevD = D; 16750 } 16751 } 16752 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || 16753 Ty->isInstantiationDependentType() || 16754 Ty->containsUnexpandedParameterPack() || 16755 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 16756 return !D->isInvalidDecl() && 16757 (D->getType()->isDependentType() || 16758 D->getType()->isInstantiationDependentType() || 16759 D->getType()->containsUnexpandedParameterPack()); 16760 })) { 16761 UnresolvedSet<8> ResSet; 16762 for (const UnresolvedSet<8> &Set : Lookups) { 16763 if (Set.empty()) 16764 continue; 16765 ResSet.append(Set.begin(), Set.end()); 16766 // The last item marks the end of all declarations at the specified scope. 16767 ResSet.addDecl(Set[Set.size() - 1]); 16768 } 16769 return UnresolvedLookupExpr::Create( 16770 SemaRef.Context, /*NamingClass=*/nullptr, 16771 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 16772 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 16773 } 16774 // Lookup inside the classes. 16775 // C++ [over.match.oper]p3: 16776 // For a unary operator @ with an operand of a type whose 16777 // cv-unqualified version is T1, and for a binary operator @ with 16778 // a left operand of a type whose cv-unqualified version is T1 and 16779 // a right operand of a type whose cv-unqualified version is T2, 16780 // three sets of candidate functions, designated member 16781 // candidates, non-member candidates and built-in candidates, are 16782 // constructed as follows: 16783 // -- If T1 is a complete class type or a class currently being 16784 // defined, the set of member candidates is the result of the 16785 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 16786 // the set of member candidates is empty. 16787 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 16788 Lookup.suppressDiagnostics(); 16789 if (const auto *TyRec = Ty->getAs<RecordType>()) { 16790 // Complete the type if it can be completed. 16791 // If the type is neither complete nor being defined, bail out now. 16792 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() || 16793 TyRec->getDecl()->getDefinition()) { 16794 Lookup.clear(); 16795 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl()); 16796 if (Lookup.empty()) { 16797 Lookups.emplace_back(); 16798 Lookups.back().append(Lookup.begin(), Lookup.end()); 16799 } 16800 } 16801 } 16802 // Perform ADL. 16803 if (SemaRef.getLangOpts().CPlusPlus) 16804 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups); 16805 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 16806 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 16807 if (!D->isInvalidDecl() && 16808 SemaRef.Context.hasSameType(D->getType(), Ty)) 16809 return D; 16810 return nullptr; 16811 })) 16812 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), 16813 VK_LValue, Loc); 16814 if (SemaRef.getLangOpts().CPlusPlus) { 16815 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 16816 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 16817 if (!D->isInvalidDecl() && 16818 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 16819 !Ty.isMoreQualifiedThan(D->getType())) 16820 return D; 16821 return nullptr; 16822 })) { 16823 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 16824 /*DetectVirtual=*/false); 16825 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 16826 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 16827 VD->getType().getUnqualifiedType()))) { 16828 if (SemaRef.CheckBaseClassAccess( 16829 Loc, VD->getType(), Ty, Paths.front(), 16830 /*DiagID=*/0) != Sema::AR_inaccessible) { 16831 SemaRef.BuildBasePathArray(Paths, BasePath); 16832 return SemaRef.BuildDeclRefExpr( 16833 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc); 16834 } 16835 } 16836 } 16837 } 16838 } 16839 if (ReductionIdScopeSpec.isSet()) { 16840 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) 16841 << Ty << Range; 16842 return ExprError(); 16843 } 16844 return ExprEmpty(); 16845 } 16846 16847 namespace { 16848 /// Data for the reduction-based clauses. 16849 struct ReductionData { 16850 /// List of original reduction items. 16851 SmallVector<Expr *, 8> Vars; 16852 /// List of private copies of the reduction items. 16853 SmallVector<Expr *, 8> Privates; 16854 /// LHS expressions for the reduction_op expressions. 16855 SmallVector<Expr *, 8> LHSs; 16856 /// RHS expressions for the reduction_op expressions. 16857 SmallVector<Expr *, 8> RHSs; 16858 /// Reduction operation expression. 16859 SmallVector<Expr *, 8> ReductionOps; 16860 /// inscan copy operation expressions. 16861 SmallVector<Expr *, 8> InscanCopyOps; 16862 /// inscan copy temp array expressions for prefix sums. 16863 SmallVector<Expr *, 8> InscanCopyArrayTemps; 16864 /// inscan copy temp array element expressions for prefix sums. 16865 SmallVector<Expr *, 8> InscanCopyArrayElems; 16866 /// Taskgroup descriptors for the corresponding reduction items in 16867 /// in_reduction clauses. 16868 SmallVector<Expr *, 8> TaskgroupDescriptors; 16869 /// List of captures for clause. 16870 SmallVector<Decl *, 4> ExprCaptures; 16871 /// List of postupdate expressions. 16872 SmallVector<Expr *, 4> ExprPostUpdates; 16873 /// Reduction modifier. 16874 unsigned RedModifier = 0; 16875 ReductionData() = delete; 16876 /// Reserves required memory for the reduction data. 16877 ReductionData(unsigned Size, unsigned Modifier = 0) : RedModifier(Modifier) { 16878 Vars.reserve(Size); 16879 Privates.reserve(Size); 16880 LHSs.reserve(Size); 16881 RHSs.reserve(Size); 16882 ReductionOps.reserve(Size); 16883 if (RedModifier == OMPC_REDUCTION_inscan) { 16884 InscanCopyOps.reserve(Size); 16885 InscanCopyArrayTemps.reserve(Size); 16886 InscanCopyArrayElems.reserve(Size); 16887 } 16888 TaskgroupDescriptors.reserve(Size); 16889 ExprCaptures.reserve(Size); 16890 ExprPostUpdates.reserve(Size); 16891 } 16892 /// Stores reduction item and reduction operation only (required for dependent 16893 /// reduction item). 16894 void push(Expr *Item, Expr *ReductionOp) { 16895 Vars.emplace_back(Item); 16896 Privates.emplace_back(nullptr); 16897 LHSs.emplace_back(nullptr); 16898 RHSs.emplace_back(nullptr); 16899 ReductionOps.emplace_back(ReductionOp); 16900 TaskgroupDescriptors.emplace_back(nullptr); 16901 if (RedModifier == OMPC_REDUCTION_inscan) { 16902 InscanCopyOps.push_back(nullptr); 16903 InscanCopyArrayTemps.push_back(nullptr); 16904 InscanCopyArrayElems.push_back(nullptr); 16905 } 16906 } 16907 /// Stores reduction data. 16908 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp, 16909 Expr *TaskgroupDescriptor, Expr *CopyOp, Expr *CopyArrayTemp, 16910 Expr *CopyArrayElem) { 16911 Vars.emplace_back(Item); 16912 Privates.emplace_back(Private); 16913 LHSs.emplace_back(LHS); 16914 RHSs.emplace_back(RHS); 16915 ReductionOps.emplace_back(ReductionOp); 16916 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor); 16917 if (RedModifier == OMPC_REDUCTION_inscan) { 16918 InscanCopyOps.push_back(CopyOp); 16919 InscanCopyArrayTemps.push_back(CopyArrayTemp); 16920 InscanCopyArrayElems.push_back(CopyArrayElem); 16921 } else { 16922 assert(CopyOp == nullptr && CopyArrayTemp == nullptr && 16923 CopyArrayElem == nullptr && 16924 "Copy operation must be used for inscan reductions only."); 16925 } 16926 } 16927 }; 16928 } // namespace 16929 16930 static bool checkOMPArraySectionConstantForReduction( 16931 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement, 16932 SmallVectorImpl<llvm::APSInt> &ArraySizes) { 16933 const Expr *Length = OASE->getLength(); 16934 if (Length == nullptr) { 16935 // For array sections of the form [1:] or [:], we would need to analyze 16936 // the lower bound... 16937 if (OASE->getColonLocFirst().isValid()) 16938 return false; 16939 16940 // This is an array subscript which has implicit length 1! 16941 SingleElement = true; 16942 ArraySizes.push_back(llvm::APSInt::get(1)); 16943 } else { 16944 Expr::EvalResult Result; 16945 if (!Length->EvaluateAsInt(Result, Context)) 16946 return false; 16947 16948 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 16949 SingleElement = (ConstantLengthValue.getSExtValue() == 1); 16950 ArraySizes.push_back(ConstantLengthValue); 16951 } 16952 16953 // Get the base of this array section and walk up from there. 16954 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 16955 16956 // We require length = 1 for all array sections except the right-most to 16957 // guarantee that the memory region is contiguous and has no holes in it. 16958 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) { 16959 Length = TempOASE->getLength(); 16960 if (Length == nullptr) { 16961 // For array sections of the form [1:] or [:], we would need to analyze 16962 // the lower bound... 16963 if (OASE->getColonLocFirst().isValid()) 16964 return false; 16965 16966 // This is an array subscript which has implicit length 1! 16967 ArraySizes.push_back(llvm::APSInt::get(1)); 16968 } else { 16969 Expr::EvalResult Result; 16970 if (!Length->EvaluateAsInt(Result, Context)) 16971 return false; 16972 16973 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 16974 if (ConstantLengthValue.getSExtValue() != 1) 16975 return false; 16976 16977 ArraySizes.push_back(ConstantLengthValue); 16978 } 16979 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 16980 } 16981 16982 // If we have a single element, we don't need to add the implicit lengths. 16983 if (!SingleElement) { 16984 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) { 16985 // Has implicit length 1! 16986 ArraySizes.push_back(llvm::APSInt::get(1)); 16987 Base = TempASE->getBase()->IgnoreParenImpCasts(); 16988 } 16989 } 16990 16991 // This array section can be privatized as a single value or as a constant 16992 // sized array. 16993 return true; 16994 } 16995 16996 static BinaryOperatorKind 16997 getRelatedCompoundReductionOp(BinaryOperatorKind BOK) { 16998 if (BOK == BO_Add) 16999 return BO_AddAssign; 17000 if (BOK == BO_Mul) 17001 return BO_MulAssign; 17002 if (BOK == BO_And) 17003 return BO_AndAssign; 17004 if (BOK == BO_Or) 17005 return BO_OrAssign; 17006 if (BOK == BO_Xor) 17007 return BO_XorAssign; 17008 return BOK; 17009 } 17010 17011 static bool actOnOMPReductionKindClause( 17012 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, 17013 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 17014 SourceLocation ColonLoc, SourceLocation EndLoc, 17015 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 17016 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { 17017 DeclarationName DN = ReductionId.getName(); 17018 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator(); 17019 BinaryOperatorKind BOK = BO_Comma; 17020 17021 ASTContext &Context = S.Context; 17022 // OpenMP [2.14.3.6, reduction clause] 17023 // C 17024 // reduction-identifier is either an identifier or one of the following 17025 // operators: +, -, *, &, |, ^, && and || 17026 // C++ 17027 // reduction-identifier is either an id-expression or one of the following 17028 // operators: +, -, *, &, |, ^, && and || 17029 switch (OOK) { 17030 case OO_Plus: 17031 case OO_Minus: 17032 BOK = BO_Add; 17033 break; 17034 case OO_Star: 17035 BOK = BO_Mul; 17036 break; 17037 case OO_Amp: 17038 BOK = BO_And; 17039 break; 17040 case OO_Pipe: 17041 BOK = BO_Or; 17042 break; 17043 case OO_Caret: 17044 BOK = BO_Xor; 17045 break; 17046 case OO_AmpAmp: 17047 BOK = BO_LAnd; 17048 break; 17049 case OO_PipePipe: 17050 BOK = BO_LOr; 17051 break; 17052 case OO_New: 17053 case OO_Delete: 17054 case OO_Array_New: 17055 case OO_Array_Delete: 17056 case OO_Slash: 17057 case OO_Percent: 17058 case OO_Tilde: 17059 case OO_Exclaim: 17060 case OO_Equal: 17061 case OO_Less: 17062 case OO_Greater: 17063 case OO_LessEqual: 17064 case OO_GreaterEqual: 17065 case OO_PlusEqual: 17066 case OO_MinusEqual: 17067 case OO_StarEqual: 17068 case OO_SlashEqual: 17069 case OO_PercentEqual: 17070 case OO_CaretEqual: 17071 case OO_AmpEqual: 17072 case OO_PipeEqual: 17073 case OO_LessLess: 17074 case OO_GreaterGreater: 17075 case OO_LessLessEqual: 17076 case OO_GreaterGreaterEqual: 17077 case OO_EqualEqual: 17078 case OO_ExclaimEqual: 17079 case OO_Spaceship: 17080 case OO_PlusPlus: 17081 case OO_MinusMinus: 17082 case OO_Comma: 17083 case OO_ArrowStar: 17084 case OO_Arrow: 17085 case OO_Call: 17086 case OO_Subscript: 17087 case OO_Conditional: 17088 case OO_Coawait: 17089 case NUM_OVERLOADED_OPERATORS: 17090 llvm_unreachable("Unexpected reduction identifier"); 17091 case OO_None: 17092 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) { 17093 if (II->isStr("max")) 17094 BOK = BO_GT; 17095 else if (II->isStr("min")) 17096 BOK = BO_LT; 17097 } 17098 break; 17099 } 17100 SourceRange ReductionIdRange; 17101 if (ReductionIdScopeSpec.isValid()) 17102 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 17103 else 17104 ReductionIdRange.setBegin(ReductionId.getBeginLoc()); 17105 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 17106 17107 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 17108 bool FirstIter = true; 17109 for (Expr *RefExpr : VarList) { 17110 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 17111 // OpenMP [2.1, C/C++] 17112 // A list item is a variable or array section, subject to the restrictions 17113 // specified in Section 2.4 on page 42 and in each of the sections 17114 // describing clauses and directives for which a list appears. 17115 // OpenMP [2.14.3.3, Restrictions, p.1] 17116 // A variable that is part of another variable (as an array or 17117 // structure element) cannot appear in a private clause. 17118 if (!FirstIter && IR != ER) 17119 ++IR; 17120 FirstIter = false; 17121 SourceLocation ELoc; 17122 SourceRange ERange; 17123 Expr *SimpleRefExpr = RefExpr; 17124 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 17125 /*AllowArraySection=*/true); 17126 if (Res.second) { 17127 // Try to find 'declare reduction' corresponding construct before using 17128 // builtin/overloaded operators. 17129 QualType Type = Context.DependentTy; 17130 CXXCastPath BasePath; 17131 ExprResult DeclareReductionRef = buildDeclareReductionRef( 17132 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 17133 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 17134 Expr *ReductionOp = nullptr; 17135 if (S.CurContext->isDependentContext() && 17136 (DeclareReductionRef.isUnset() || 17137 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 17138 ReductionOp = DeclareReductionRef.get(); 17139 // It will be analyzed later. 17140 RD.push(RefExpr, ReductionOp); 17141 } 17142 ValueDecl *D = Res.first; 17143 if (!D) 17144 continue; 17145 17146 Expr *TaskgroupDescriptor = nullptr; 17147 QualType Type; 17148 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 17149 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 17150 if (ASE) { 17151 Type = ASE->getType().getNonReferenceType(); 17152 } else if (OASE) { 17153 QualType BaseType = 17154 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 17155 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 17156 Type = ATy->getElementType(); 17157 else 17158 Type = BaseType->getPointeeType(); 17159 Type = Type.getNonReferenceType(); 17160 } else { 17161 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 17162 } 17163 auto *VD = dyn_cast<VarDecl>(D); 17164 17165 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 17166 // A variable that appears in a private clause must not have an incomplete 17167 // type or a reference type. 17168 if (S.RequireCompleteType(ELoc, D->getType(), 17169 diag::err_omp_reduction_incomplete_type)) 17170 continue; 17171 // OpenMP [2.14.3.6, reduction clause, Restrictions] 17172 // A list item that appears in a reduction clause must not be 17173 // const-qualified. 17174 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc, 17175 /*AcceptIfMutable*/ false, ASE || OASE)) 17176 continue; 17177 17178 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); 17179 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 17180 // If a list-item is a reference type then it must bind to the same object 17181 // for all threads of the team. 17182 if (!ASE && !OASE) { 17183 if (VD) { 17184 VarDecl *VDDef = VD->getDefinition(); 17185 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 17186 DSARefChecker Check(Stack); 17187 if (Check.Visit(VDDef->getInit())) { 17188 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) 17189 << getOpenMPClauseName(ClauseKind) << ERange; 17190 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 17191 continue; 17192 } 17193 } 17194 } 17195 17196 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 17197 // in a Construct] 17198 // Variables with the predetermined data-sharing attributes may not be 17199 // listed in data-sharing attributes clauses, except for the cases 17200 // listed below. For these exceptions only, listing a predetermined 17201 // variable in a data-sharing attribute clause is allowed and overrides 17202 // the variable's predetermined data-sharing attributes. 17203 // OpenMP [2.14.3.6, Restrictions, p.3] 17204 // Any number of reduction clauses can be specified on the directive, 17205 // but a list item can appear only once in the reduction clauses for that 17206 // directive. 17207 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 17208 if (DVar.CKind == OMPC_reduction) { 17209 S.Diag(ELoc, diag::err_omp_once_referenced) 17210 << getOpenMPClauseName(ClauseKind); 17211 if (DVar.RefExpr) 17212 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 17213 continue; 17214 } 17215 if (DVar.CKind != OMPC_unknown) { 17216 S.Diag(ELoc, diag::err_omp_wrong_dsa) 17217 << getOpenMPClauseName(DVar.CKind) 17218 << getOpenMPClauseName(OMPC_reduction); 17219 reportOriginalDsa(S, Stack, D, DVar); 17220 continue; 17221 } 17222 17223 // OpenMP [2.14.3.6, Restrictions, p.1] 17224 // A list item that appears in a reduction clause of a worksharing 17225 // construct must be shared in the parallel regions to which any of the 17226 // worksharing regions arising from the worksharing construct bind. 17227 if (isOpenMPWorksharingDirective(CurrDir) && 17228 !isOpenMPParallelDirective(CurrDir) && 17229 !isOpenMPTeamsDirective(CurrDir)) { 17230 DVar = Stack->getImplicitDSA(D, true); 17231 if (DVar.CKind != OMPC_shared) { 17232 S.Diag(ELoc, diag::err_omp_required_access) 17233 << getOpenMPClauseName(OMPC_reduction) 17234 << getOpenMPClauseName(OMPC_shared); 17235 reportOriginalDsa(S, Stack, D, DVar); 17236 continue; 17237 } 17238 } 17239 } else { 17240 // Threadprivates cannot be shared between threads, so dignose if the base 17241 // is a threadprivate variable. 17242 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 17243 if (DVar.CKind == OMPC_threadprivate) { 17244 S.Diag(ELoc, diag::err_omp_wrong_dsa) 17245 << getOpenMPClauseName(DVar.CKind) 17246 << getOpenMPClauseName(OMPC_reduction); 17247 reportOriginalDsa(S, Stack, D, DVar); 17248 continue; 17249 } 17250 } 17251 17252 // Try to find 'declare reduction' corresponding construct before using 17253 // builtin/overloaded operators. 17254 CXXCastPath BasePath; 17255 ExprResult DeclareReductionRef = buildDeclareReductionRef( 17256 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 17257 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 17258 if (DeclareReductionRef.isInvalid()) 17259 continue; 17260 if (S.CurContext->isDependentContext() && 17261 (DeclareReductionRef.isUnset() || 17262 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 17263 RD.push(RefExpr, DeclareReductionRef.get()); 17264 continue; 17265 } 17266 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 17267 // Not allowed reduction identifier is found. 17268 S.Diag(ReductionId.getBeginLoc(), 17269 diag::err_omp_unknown_reduction_identifier) 17270 << Type << ReductionIdRange; 17271 continue; 17272 } 17273 17274 // OpenMP [2.14.3.6, reduction clause, Restrictions] 17275 // The type of a list item that appears in a reduction clause must be valid 17276 // for the reduction-identifier. For a max or min reduction in C, the type 17277 // of the list item must be an allowed arithmetic data type: char, int, 17278 // float, double, or _Bool, possibly modified with long, short, signed, or 17279 // unsigned. For a max or min reduction in C++, the type of the list item 17280 // must be an allowed arithmetic data type: char, wchar_t, int, float, 17281 // double, or bool, possibly modified with long, short, signed, or unsigned. 17282 if (DeclareReductionRef.isUnset()) { 17283 if ((BOK == BO_GT || BOK == BO_LT) && 17284 !(Type->isScalarType() || 17285 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 17286 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 17287 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; 17288 if (!ASE && !OASE) { 17289 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 17290 VarDecl::DeclarationOnly; 17291 S.Diag(D->getLocation(), 17292 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17293 << D; 17294 } 17295 continue; 17296 } 17297 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 17298 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { 17299 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) 17300 << getOpenMPClauseName(ClauseKind); 17301 if (!ASE && !OASE) { 17302 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 17303 VarDecl::DeclarationOnly; 17304 S.Diag(D->getLocation(), 17305 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17306 << D; 17307 } 17308 continue; 17309 } 17310 } 17311 17312 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 17313 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", 17314 D->hasAttrs() ? &D->getAttrs() : nullptr); 17315 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), 17316 D->hasAttrs() ? &D->getAttrs() : nullptr); 17317 QualType PrivateTy = Type; 17318 17319 // Try if we can determine constant lengths for all array sections and avoid 17320 // the VLA. 17321 bool ConstantLengthOASE = false; 17322 if (OASE) { 17323 bool SingleElement; 17324 llvm::SmallVector<llvm::APSInt, 4> ArraySizes; 17325 ConstantLengthOASE = checkOMPArraySectionConstantForReduction( 17326 Context, OASE, SingleElement, ArraySizes); 17327 17328 // If we don't have a single element, we must emit a constant array type. 17329 if (ConstantLengthOASE && !SingleElement) { 17330 for (llvm::APSInt &Size : ArraySizes) 17331 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr, 17332 ArrayType::Normal, 17333 /*IndexTypeQuals=*/0); 17334 } 17335 } 17336 17337 if ((OASE && !ConstantLengthOASE) || 17338 (!OASE && !ASE && 17339 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 17340 if (!Context.getTargetInfo().isVLASupported()) { 17341 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) { 17342 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 17343 S.Diag(ELoc, diag::note_vla_unsupported); 17344 continue; 17345 } else { 17346 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 17347 S.targetDiag(ELoc, diag::note_vla_unsupported); 17348 } 17349 } 17350 // For arrays/array sections only: 17351 // Create pseudo array type for private copy. The size for this array will 17352 // be generated during codegen. 17353 // For array subscripts or single variables Private Ty is the same as Type 17354 // (type of the variable or single array element). 17355 PrivateTy = Context.getVariableArrayType( 17356 Type, 17357 new (Context) 17358 OpaqueValueExpr(ELoc, Context.getSizeType(), VK_PRValue), 17359 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 17360 } else if (!ASE && !OASE && 17361 Context.getAsArrayType(D->getType().getNonReferenceType())) { 17362 PrivateTy = D->getType().getNonReferenceType(); 17363 } 17364 // Private copy. 17365 VarDecl *PrivateVD = 17366 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 17367 D->hasAttrs() ? &D->getAttrs() : nullptr, 17368 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 17369 // Add initializer for private variable. 17370 Expr *Init = nullptr; 17371 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); 17372 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); 17373 if (DeclareReductionRef.isUsable()) { 17374 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 17375 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 17376 if (DRD->getInitializer()) { 17377 Init = DRDRef; 17378 RHSVD->setInit(DRDRef); 17379 RHSVD->setInitStyle(VarDecl::CallInit); 17380 } 17381 } else { 17382 switch (BOK) { 17383 case BO_Add: 17384 case BO_Xor: 17385 case BO_Or: 17386 case BO_LOr: 17387 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 17388 if (Type->isScalarType() || Type->isAnyComplexType()) 17389 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 17390 break; 17391 case BO_Mul: 17392 case BO_LAnd: 17393 if (Type->isScalarType() || Type->isAnyComplexType()) { 17394 // '*' and '&&' reduction ops - initializer is '1'. 17395 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 17396 } 17397 break; 17398 case BO_And: { 17399 // '&' reduction op - initializer is '~0'. 17400 QualType OrigType = Type; 17401 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 17402 Type = ComplexTy->getElementType(); 17403 if (Type->isRealFloatingType()) { 17404 llvm::APFloat InitValue = llvm::APFloat::getAllOnesValue( 17405 Context.getFloatTypeSemantics(Type)); 17406 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 17407 Type, ELoc); 17408 } else if (Type->isScalarType()) { 17409 uint64_t Size = Context.getTypeSize(Type); 17410 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 17411 llvm::APInt InitValue = llvm::APInt::getAllOnes(Size); 17412 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 17413 } 17414 if (Init && OrigType->isAnyComplexType()) { 17415 // Init = 0xFFFF + 0xFFFFi; 17416 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 17417 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 17418 } 17419 Type = OrigType; 17420 break; 17421 } 17422 case BO_LT: 17423 case BO_GT: { 17424 // 'min' reduction op - initializer is 'Largest representable number in 17425 // the reduction list item type'. 17426 // 'max' reduction op - initializer is 'Least representable number in 17427 // the reduction list item type'. 17428 if (Type->isIntegerType() || Type->isPointerType()) { 17429 bool IsSigned = Type->hasSignedIntegerRepresentation(); 17430 uint64_t Size = Context.getTypeSize(Type); 17431 QualType IntTy = 17432 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 17433 llvm::APInt InitValue = 17434 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 17435 : llvm::APInt::getMinValue(Size) 17436 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 17437 : llvm::APInt::getMaxValue(Size); 17438 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 17439 if (Type->isPointerType()) { 17440 // Cast to pointer type. 17441 ExprResult CastExpr = S.BuildCStyleCastExpr( 17442 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init); 17443 if (CastExpr.isInvalid()) 17444 continue; 17445 Init = CastExpr.get(); 17446 } 17447 } else if (Type->isRealFloatingType()) { 17448 llvm::APFloat InitValue = llvm::APFloat::getLargest( 17449 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 17450 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 17451 Type, ELoc); 17452 } 17453 break; 17454 } 17455 case BO_PtrMemD: 17456 case BO_PtrMemI: 17457 case BO_MulAssign: 17458 case BO_Div: 17459 case BO_Rem: 17460 case BO_Sub: 17461 case BO_Shl: 17462 case BO_Shr: 17463 case BO_LE: 17464 case BO_GE: 17465 case BO_EQ: 17466 case BO_NE: 17467 case BO_Cmp: 17468 case BO_AndAssign: 17469 case BO_XorAssign: 17470 case BO_OrAssign: 17471 case BO_Assign: 17472 case BO_AddAssign: 17473 case BO_SubAssign: 17474 case BO_DivAssign: 17475 case BO_RemAssign: 17476 case BO_ShlAssign: 17477 case BO_ShrAssign: 17478 case BO_Comma: 17479 llvm_unreachable("Unexpected reduction operation"); 17480 } 17481 } 17482 if (Init && DeclareReductionRef.isUnset()) { 17483 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 17484 // Store initializer for single element in private copy. Will be used 17485 // during codegen. 17486 PrivateVD->setInit(RHSVD->getInit()); 17487 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 17488 } else if (!Init) { 17489 S.ActOnUninitializedDecl(RHSVD); 17490 // Store initializer for single element in private copy. Will be used 17491 // during codegen. 17492 PrivateVD->setInit(RHSVD->getInit()); 17493 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 17494 } 17495 if (RHSVD->isInvalidDecl()) 17496 continue; 17497 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 17498 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) 17499 << Type << ReductionIdRange; 17500 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 17501 VarDecl::DeclarationOnly; 17502 S.Diag(D->getLocation(), 17503 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17504 << D; 17505 continue; 17506 } 17507 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); 17508 ExprResult ReductionOp; 17509 if (DeclareReductionRef.isUsable()) { 17510 QualType RedTy = DeclareReductionRef.get()->getType(); 17511 QualType PtrRedTy = Context.getPointerType(RedTy); 17512 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 17513 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 17514 if (!BasePath.empty()) { 17515 LHS = S.DefaultLvalueConversion(LHS.get()); 17516 RHS = S.DefaultLvalueConversion(RHS.get()); 17517 LHS = ImplicitCastExpr::Create( 17518 Context, PtrRedTy, CK_UncheckedDerivedToBase, LHS.get(), &BasePath, 17519 LHS.get()->getValueKind(), FPOptionsOverride()); 17520 RHS = ImplicitCastExpr::Create( 17521 Context, PtrRedTy, CK_UncheckedDerivedToBase, RHS.get(), &BasePath, 17522 RHS.get()->getValueKind(), FPOptionsOverride()); 17523 } 17524 FunctionProtoType::ExtProtoInfo EPI; 17525 QualType Params[] = {PtrRedTy, PtrRedTy}; 17526 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 17527 auto *OVE = new (Context) OpaqueValueExpr( 17528 ELoc, Context.getPointerType(FnTy), VK_PRValue, OK_Ordinary, 17529 S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); 17530 Expr *Args[] = {LHS.get(), RHS.get()}; 17531 ReductionOp = 17532 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_PRValue, ELoc, 17533 S.CurFPFeatureOverrides()); 17534 } else { 17535 BinaryOperatorKind CombBOK = getRelatedCompoundReductionOp(BOK); 17536 if (Type->isRecordType() && CombBOK != BOK) { 17537 Sema::TentativeAnalysisScope Trap(S); 17538 ReductionOp = 17539 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 17540 CombBOK, LHSDRE, RHSDRE); 17541 } 17542 if (!ReductionOp.isUsable()) { 17543 ReductionOp = 17544 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, 17545 LHSDRE, RHSDRE); 17546 if (ReductionOp.isUsable()) { 17547 if (BOK != BO_LT && BOK != BO_GT) { 17548 ReductionOp = 17549 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 17550 BO_Assign, LHSDRE, ReductionOp.get()); 17551 } else { 17552 auto *ConditionalOp = new (Context) 17553 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, 17554 RHSDRE, Type, VK_LValue, OK_Ordinary); 17555 ReductionOp = 17556 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 17557 BO_Assign, LHSDRE, ConditionalOp); 17558 } 17559 } 17560 } 17561 if (ReductionOp.isUsable()) 17562 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(), 17563 /*DiscardedValue*/ false); 17564 if (!ReductionOp.isUsable()) 17565 continue; 17566 } 17567 17568 // Add copy operations for inscan reductions. 17569 // LHS = RHS; 17570 ExprResult CopyOpRes, TempArrayRes, TempArrayElem; 17571 if (ClauseKind == OMPC_reduction && 17572 RD.RedModifier == OMPC_REDUCTION_inscan) { 17573 ExprResult RHS = S.DefaultLvalueConversion(RHSDRE); 17574 CopyOpRes = S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, LHSDRE, 17575 RHS.get()); 17576 if (!CopyOpRes.isUsable()) 17577 continue; 17578 CopyOpRes = 17579 S.ActOnFinishFullExpr(CopyOpRes.get(), /*DiscardedValue=*/true); 17580 if (!CopyOpRes.isUsable()) 17581 continue; 17582 // For simd directive and simd-based directives in simd mode no need to 17583 // construct temp array, need just a single temp element. 17584 if (Stack->getCurrentDirective() == OMPD_simd || 17585 (S.getLangOpts().OpenMPSimd && 17586 isOpenMPSimdDirective(Stack->getCurrentDirective()))) { 17587 VarDecl *TempArrayVD = 17588 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 17589 D->hasAttrs() ? &D->getAttrs() : nullptr); 17590 // Add a constructor to the temp decl. 17591 S.ActOnUninitializedDecl(TempArrayVD); 17592 TempArrayRes = buildDeclRefExpr(S, TempArrayVD, PrivateTy, ELoc); 17593 } else { 17594 // Build temp array for prefix sum. 17595 auto *Dim = new (S.Context) 17596 OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue); 17597 QualType ArrayTy = 17598 S.Context.getVariableArrayType(PrivateTy, Dim, ArrayType::Normal, 17599 /*IndexTypeQuals=*/0, {ELoc, ELoc}); 17600 VarDecl *TempArrayVD = 17601 buildVarDecl(S, ELoc, ArrayTy, D->getName(), 17602 D->hasAttrs() ? &D->getAttrs() : nullptr); 17603 // Add a constructor to the temp decl. 17604 S.ActOnUninitializedDecl(TempArrayVD); 17605 TempArrayRes = buildDeclRefExpr(S, TempArrayVD, ArrayTy, ELoc); 17606 TempArrayElem = 17607 S.DefaultFunctionArrayLvalueConversion(TempArrayRes.get()); 17608 auto *Idx = new (S.Context) 17609 OpaqueValueExpr(ELoc, S.Context.getSizeType(), VK_PRValue); 17610 TempArrayElem = S.CreateBuiltinArraySubscriptExpr(TempArrayElem.get(), 17611 ELoc, Idx, ELoc); 17612 } 17613 } 17614 17615 // OpenMP [2.15.4.6, Restrictions, p.2] 17616 // A list item that appears in an in_reduction clause of a task construct 17617 // must appear in a task_reduction clause of a construct associated with a 17618 // taskgroup region that includes the participating task in its taskgroup 17619 // set. The construct associated with the innermost region that meets this 17620 // condition must specify the same reduction-identifier as the in_reduction 17621 // clause. 17622 if (ClauseKind == OMPC_in_reduction) { 17623 SourceRange ParentSR; 17624 BinaryOperatorKind ParentBOK; 17625 const Expr *ParentReductionOp = nullptr; 17626 Expr *ParentBOKTD = nullptr, *ParentReductionOpTD = nullptr; 17627 DSAStackTy::DSAVarData ParentBOKDSA = 17628 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK, 17629 ParentBOKTD); 17630 DSAStackTy::DSAVarData ParentReductionOpDSA = 17631 Stack->getTopMostTaskgroupReductionData( 17632 D, ParentSR, ParentReductionOp, ParentReductionOpTD); 17633 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown; 17634 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown; 17635 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) || 17636 (DeclareReductionRef.isUsable() && IsParentBOK) || 17637 (IsParentBOK && BOK != ParentBOK) || IsParentReductionOp) { 17638 bool EmitError = true; 17639 if (IsParentReductionOp && DeclareReductionRef.isUsable()) { 17640 llvm::FoldingSetNodeID RedId, ParentRedId; 17641 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true); 17642 DeclareReductionRef.get()->Profile(RedId, Context, 17643 /*Canonical=*/true); 17644 EmitError = RedId != ParentRedId; 17645 } 17646 if (EmitError) { 17647 S.Diag(ReductionId.getBeginLoc(), 17648 diag::err_omp_reduction_identifier_mismatch) 17649 << ReductionIdRange << RefExpr->getSourceRange(); 17650 S.Diag(ParentSR.getBegin(), 17651 diag::note_omp_previous_reduction_identifier) 17652 << ParentSR 17653 << (IsParentBOK ? ParentBOKDSA.RefExpr 17654 : ParentReductionOpDSA.RefExpr) 17655 ->getSourceRange(); 17656 continue; 17657 } 17658 } 17659 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD; 17660 } 17661 17662 DeclRefExpr *Ref = nullptr; 17663 Expr *VarsExpr = RefExpr->IgnoreParens(); 17664 if (!VD && !S.CurContext->isDependentContext()) { 17665 if (ASE || OASE) { 17666 TransformExprToCaptures RebuildToCapture(S, D); 17667 VarsExpr = 17668 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 17669 Ref = RebuildToCapture.getCapturedExpr(); 17670 } else { 17671 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); 17672 } 17673 if (!S.isOpenMPCapturedDecl(D)) { 17674 RD.ExprCaptures.emplace_back(Ref->getDecl()); 17675 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 17676 ExprResult RefRes = S.DefaultLvalueConversion(Ref); 17677 if (!RefRes.isUsable()) 17678 continue; 17679 ExprResult PostUpdateRes = 17680 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 17681 RefRes.get()); 17682 if (!PostUpdateRes.isUsable()) 17683 continue; 17684 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 17685 Stack->getCurrentDirective() == OMPD_taskgroup) { 17686 S.Diag(RefExpr->getExprLoc(), 17687 diag::err_omp_reduction_non_addressable_expression) 17688 << RefExpr->getSourceRange(); 17689 continue; 17690 } 17691 RD.ExprPostUpdates.emplace_back( 17692 S.IgnoredValueConversions(PostUpdateRes.get()).get()); 17693 } 17694 } 17695 } 17696 // All reduction items are still marked as reduction (to do not increase 17697 // code base size). 17698 unsigned Modifier = RD.RedModifier; 17699 // Consider task_reductions as reductions with task modifier. Required for 17700 // correct analysis of in_reduction clauses. 17701 if (CurrDir == OMPD_taskgroup && ClauseKind == OMPC_task_reduction) 17702 Modifier = OMPC_REDUCTION_task; 17703 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref, Modifier, 17704 ASE || OASE); 17705 if (Modifier == OMPC_REDUCTION_task && 17706 (CurrDir == OMPD_taskgroup || 17707 ((isOpenMPParallelDirective(CurrDir) || 17708 isOpenMPWorksharingDirective(CurrDir)) && 17709 !isOpenMPSimdDirective(CurrDir)))) { 17710 if (DeclareReductionRef.isUsable()) 17711 Stack->addTaskgroupReductionData(D, ReductionIdRange, 17712 DeclareReductionRef.get()); 17713 else 17714 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK); 17715 } 17716 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(), 17717 TaskgroupDescriptor, CopyOpRes.get(), TempArrayRes.get(), 17718 TempArrayElem.get()); 17719 } 17720 return RD.Vars.empty(); 17721 } 17722 17723 OMPClause *Sema::ActOnOpenMPReductionClause( 17724 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier, 17725 SourceLocation StartLoc, SourceLocation LParenLoc, 17726 SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, 17727 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 17728 ArrayRef<Expr *> UnresolvedReductions) { 17729 if (ModifierLoc.isValid() && Modifier == OMPC_REDUCTION_unknown) { 17730 Diag(LParenLoc, diag::err_omp_unexpected_clause_value) 17731 << getListOfPossibleValues(OMPC_reduction, /*First=*/0, 17732 /*Last=*/OMPC_REDUCTION_unknown) 17733 << getOpenMPClauseName(OMPC_reduction); 17734 return nullptr; 17735 } 17736 // OpenMP 5.0, 2.19.5.4 reduction Clause, Restrictions 17737 // A reduction clause with the inscan reduction-modifier may only appear on a 17738 // worksharing-loop construct, a worksharing-loop SIMD construct, a simd 17739 // construct, a parallel worksharing-loop construct or a parallel 17740 // worksharing-loop SIMD construct. 17741 if (Modifier == OMPC_REDUCTION_inscan && 17742 (DSAStack->getCurrentDirective() != OMPD_for && 17743 DSAStack->getCurrentDirective() != OMPD_for_simd && 17744 DSAStack->getCurrentDirective() != OMPD_simd && 17745 DSAStack->getCurrentDirective() != OMPD_parallel_for && 17746 DSAStack->getCurrentDirective() != OMPD_parallel_for_simd)) { 17747 Diag(ModifierLoc, diag::err_omp_wrong_inscan_reduction); 17748 return nullptr; 17749 } 17750 17751 ReductionData RD(VarList.size(), Modifier); 17752 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, 17753 StartLoc, LParenLoc, ColonLoc, EndLoc, 17754 ReductionIdScopeSpec, ReductionId, 17755 UnresolvedReductions, RD)) 17756 return nullptr; 17757 17758 return OMPReductionClause::Create( 17759 Context, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc, Modifier, 17760 RD.Vars, ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 17761 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.InscanCopyOps, 17762 RD.InscanCopyArrayTemps, RD.InscanCopyArrayElems, 17763 buildPreInits(Context, RD.ExprCaptures), 17764 buildPostUpdate(*this, RD.ExprPostUpdates)); 17765 } 17766 17767 OMPClause *Sema::ActOnOpenMPTaskReductionClause( 17768 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 17769 SourceLocation ColonLoc, SourceLocation EndLoc, 17770 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 17771 ArrayRef<Expr *> UnresolvedReductions) { 17772 ReductionData RD(VarList.size()); 17773 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList, 17774 StartLoc, LParenLoc, ColonLoc, EndLoc, 17775 ReductionIdScopeSpec, ReductionId, 17776 UnresolvedReductions, RD)) 17777 return nullptr; 17778 17779 return OMPTaskReductionClause::Create( 17780 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 17781 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 17782 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 17783 buildPreInits(Context, RD.ExprCaptures), 17784 buildPostUpdate(*this, RD.ExprPostUpdates)); 17785 } 17786 17787 OMPClause *Sema::ActOnOpenMPInReductionClause( 17788 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 17789 SourceLocation ColonLoc, SourceLocation EndLoc, 17790 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 17791 ArrayRef<Expr *> UnresolvedReductions) { 17792 ReductionData RD(VarList.size()); 17793 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList, 17794 StartLoc, LParenLoc, ColonLoc, EndLoc, 17795 ReductionIdScopeSpec, ReductionId, 17796 UnresolvedReductions, RD)) 17797 return nullptr; 17798 17799 return OMPInReductionClause::Create( 17800 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 17801 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 17802 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors, 17803 buildPreInits(Context, RD.ExprCaptures), 17804 buildPostUpdate(*this, RD.ExprPostUpdates)); 17805 } 17806 17807 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 17808 SourceLocation LinLoc) { 17809 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 17810 LinKind == OMPC_LINEAR_unknown) { 17811 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 17812 return true; 17813 } 17814 return false; 17815 } 17816 17817 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, 17818 OpenMPLinearClauseKind LinKind, QualType Type, 17819 bool IsDeclareSimd) { 17820 const auto *VD = dyn_cast_or_null<VarDecl>(D); 17821 // A variable must not have an incomplete type or a reference type. 17822 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 17823 return true; 17824 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 17825 !Type->isReferenceType()) { 17826 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 17827 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 17828 return true; 17829 } 17830 Type = Type.getNonReferenceType(); 17831 17832 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 17833 // A variable that is privatized must not have a const-qualified type 17834 // unless it is of class type with a mutable member. This restriction does 17835 // not apply to the firstprivate clause, nor to the linear clause on 17836 // declarative directives (like declare simd). 17837 if (!IsDeclareSimd && 17838 rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc)) 17839 return true; 17840 17841 // A list item must be of integral or pointer type. 17842 Type = Type.getUnqualifiedType().getCanonicalType(); 17843 const auto *Ty = Type.getTypePtrOrNull(); 17844 if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() && 17845 !Ty->isIntegralType(Context) && !Ty->isPointerType())) { 17846 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 17847 if (D) { 17848 bool IsDecl = 17849 !VD || 17850 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 17851 Diag(D->getLocation(), 17852 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 17853 << D; 17854 } 17855 return true; 17856 } 17857 return false; 17858 } 17859 17860 OMPClause *Sema::ActOnOpenMPLinearClause( 17861 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 17862 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 17863 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 17864 SmallVector<Expr *, 8> Vars; 17865 SmallVector<Expr *, 8> Privates; 17866 SmallVector<Expr *, 8> Inits; 17867 SmallVector<Decl *, 4> ExprCaptures; 17868 SmallVector<Expr *, 4> ExprPostUpdates; 17869 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 17870 LinKind = OMPC_LINEAR_val; 17871 for (Expr *RefExpr : VarList) { 17872 assert(RefExpr && "NULL expr in OpenMP linear clause."); 17873 SourceLocation ELoc; 17874 SourceRange ERange; 17875 Expr *SimpleRefExpr = RefExpr; 17876 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 17877 if (Res.second) { 17878 // It will be analyzed later. 17879 Vars.push_back(RefExpr); 17880 Privates.push_back(nullptr); 17881 Inits.push_back(nullptr); 17882 } 17883 ValueDecl *D = Res.first; 17884 if (!D) 17885 continue; 17886 17887 QualType Type = D->getType(); 17888 auto *VD = dyn_cast<VarDecl>(D); 17889 17890 // OpenMP [2.14.3.7, linear clause] 17891 // A list-item cannot appear in more than one linear clause. 17892 // A list-item that appears in a linear clause cannot appear in any 17893 // other data-sharing attribute clause. 17894 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 17895 if (DVar.RefExpr) { 17896 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 17897 << getOpenMPClauseName(OMPC_linear); 17898 reportOriginalDsa(*this, DSAStack, D, DVar); 17899 continue; 17900 } 17901 17902 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 17903 continue; 17904 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 17905 17906 // Build private copy of original var. 17907 VarDecl *Private = 17908 buildVarDecl(*this, ELoc, Type, D->getName(), 17909 D->hasAttrs() ? &D->getAttrs() : nullptr, 17910 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 17911 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 17912 // Build var to save initial value. 17913 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 17914 Expr *InitExpr; 17915 DeclRefExpr *Ref = nullptr; 17916 if (!VD && !CurContext->isDependentContext()) { 17917 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 17918 if (!isOpenMPCapturedDecl(D)) { 17919 ExprCaptures.push_back(Ref->getDecl()); 17920 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 17921 ExprResult RefRes = DefaultLvalueConversion(Ref); 17922 if (!RefRes.isUsable()) 17923 continue; 17924 ExprResult PostUpdateRes = 17925 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 17926 SimpleRefExpr, RefRes.get()); 17927 if (!PostUpdateRes.isUsable()) 17928 continue; 17929 ExprPostUpdates.push_back( 17930 IgnoredValueConversions(PostUpdateRes.get()).get()); 17931 } 17932 } 17933 } 17934 if (LinKind == OMPC_LINEAR_uval) 17935 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 17936 else 17937 InitExpr = VD ? SimpleRefExpr : Ref; 17938 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 17939 /*DirectInit=*/false); 17940 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 17941 17942 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 17943 Vars.push_back((VD || CurContext->isDependentContext()) 17944 ? RefExpr->IgnoreParens() 17945 : Ref); 17946 Privates.push_back(PrivateRef); 17947 Inits.push_back(InitRef); 17948 } 17949 17950 if (Vars.empty()) 17951 return nullptr; 17952 17953 Expr *StepExpr = Step; 17954 Expr *CalcStepExpr = nullptr; 17955 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 17956 !Step->isInstantiationDependent() && 17957 !Step->containsUnexpandedParameterPack()) { 17958 SourceLocation StepLoc = Step->getBeginLoc(); 17959 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 17960 if (Val.isInvalid()) 17961 return nullptr; 17962 StepExpr = Val.get(); 17963 17964 // Build var to save the step value. 17965 VarDecl *SaveVar = 17966 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 17967 ExprResult SaveRef = 17968 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 17969 ExprResult CalcStep = 17970 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 17971 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false); 17972 17973 // Warn about zero linear step (it would be probably better specified as 17974 // making corresponding variables 'const'). 17975 if (Optional<llvm::APSInt> Result = 17976 StepExpr->getIntegerConstantExpr(Context)) { 17977 if (!Result->isNegative() && !Result->isStrictlyPositive()) 17978 Diag(StepLoc, diag::warn_omp_linear_step_zero) 17979 << Vars[0] << (Vars.size() > 1); 17980 } else if (CalcStep.isUsable()) { 17981 // Calculate the step beforehand instead of doing this on each iteration. 17982 // (This is not used if the number of iterations may be kfold-ed). 17983 CalcStepExpr = CalcStep.get(); 17984 } 17985 } 17986 17987 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 17988 ColonLoc, EndLoc, Vars, Privates, Inits, 17989 StepExpr, CalcStepExpr, 17990 buildPreInits(Context, ExprCaptures), 17991 buildPostUpdate(*this, ExprPostUpdates)); 17992 } 17993 17994 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 17995 Expr *NumIterations, Sema &SemaRef, 17996 Scope *S, DSAStackTy *Stack) { 17997 // Walk the vars and build update/final expressions for the CodeGen. 17998 SmallVector<Expr *, 8> Updates; 17999 SmallVector<Expr *, 8> Finals; 18000 SmallVector<Expr *, 8> UsedExprs; 18001 Expr *Step = Clause.getStep(); 18002 Expr *CalcStep = Clause.getCalcStep(); 18003 // OpenMP [2.14.3.7, linear clause] 18004 // If linear-step is not specified it is assumed to be 1. 18005 if (!Step) 18006 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 18007 else if (CalcStep) 18008 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 18009 bool HasErrors = false; 18010 auto CurInit = Clause.inits().begin(); 18011 auto CurPrivate = Clause.privates().begin(); 18012 OpenMPLinearClauseKind LinKind = Clause.getModifier(); 18013 for (Expr *RefExpr : Clause.varlists()) { 18014 SourceLocation ELoc; 18015 SourceRange ERange; 18016 Expr *SimpleRefExpr = RefExpr; 18017 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange); 18018 ValueDecl *D = Res.first; 18019 if (Res.second || !D) { 18020 Updates.push_back(nullptr); 18021 Finals.push_back(nullptr); 18022 HasErrors = true; 18023 continue; 18024 } 18025 auto &&Info = Stack->isLoopControlVariable(D); 18026 // OpenMP [2.15.11, distribute simd Construct] 18027 // A list item may not appear in a linear clause, unless it is the loop 18028 // iteration variable. 18029 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) && 18030 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) { 18031 SemaRef.Diag(ELoc, 18032 diag::err_omp_linear_distribute_var_non_loop_iteration); 18033 Updates.push_back(nullptr); 18034 Finals.push_back(nullptr); 18035 HasErrors = true; 18036 continue; 18037 } 18038 Expr *InitExpr = *CurInit; 18039 18040 // Build privatized reference to the current linear var. 18041 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 18042 Expr *CapturedRef; 18043 if (LinKind == OMPC_LINEAR_uval) 18044 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 18045 else 18046 CapturedRef = 18047 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 18048 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 18049 /*RefersToCapture=*/true); 18050 18051 // Build update: Var = InitExpr + IV * Step 18052 ExprResult Update; 18053 if (!Info.first) 18054 Update = buildCounterUpdate( 18055 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step, 18056 /*Subtract=*/false, /*IsNonRectangularLB=*/false); 18057 else 18058 Update = *CurPrivate; 18059 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(), 18060 /*DiscardedValue*/ false); 18061 18062 // Build final: Var = InitExpr + NumIterations * Step 18063 ExprResult Final; 18064 if (!Info.first) 18065 Final = 18066 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 18067 InitExpr, NumIterations, Step, /*Subtract=*/false, 18068 /*IsNonRectangularLB=*/false); 18069 else 18070 Final = *CurPrivate; 18071 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(), 18072 /*DiscardedValue*/ false); 18073 18074 if (!Update.isUsable() || !Final.isUsable()) { 18075 Updates.push_back(nullptr); 18076 Finals.push_back(nullptr); 18077 UsedExprs.push_back(nullptr); 18078 HasErrors = true; 18079 } else { 18080 Updates.push_back(Update.get()); 18081 Finals.push_back(Final.get()); 18082 if (!Info.first) 18083 UsedExprs.push_back(SimpleRefExpr); 18084 } 18085 ++CurInit; 18086 ++CurPrivate; 18087 } 18088 if (Expr *S = Clause.getStep()) 18089 UsedExprs.push_back(S); 18090 // Fill the remaining part with the nullptr. 18091 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr); 18092 Clause.setUpdates(Updates); 18093 Clause.setFinals(Finals); 18094 Clause.setUsedExprs(UsedExprs); 18095 return HasErrors; 18096 } 18097 18098 OMPClause *Sema::ActOnOpenMPAlignedClause( 18099 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 18100 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 18101 SmallVector<Expr *, 8> Vars; 18102 for (Expr *RefExpr : VarList) { 18103 assert(RefExpr && "NULL expr in OpenMP linear clause."); 18104 SourceLocation ELoc; 18105 SourceRange ERange; 18106 Expr *SimpleRefExpr = RefExpr; 18107 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 18108 if (Res.second) { 18109 // It will be analyzed later. 18110 Vars.push_back(RefExpr); 18111 } 18112 ValueDecl *D = Res.first; 18113 if (!D) 18114 continue; 18115 18116 QualType QType = D->getType(); 18117 auto *VD = dyn_cast<VarDecl>(D); 18118 18119 // OpenMP [2.8.1, simd construct, Restrictions] 18120 // The type of list items appearing in the aligned clause must be 18121 // array, pointer, reference to array, or reference to pointer. 18122 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 18123 const Type *Ty = QType.getTypePtrOrNull(); 18124 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 18125 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 18126 << QType << getLangOpts().CPlusPlus << ERange; 18127 bool IsDecl = 18128 !VD || 18129 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 18130 Diag(D->getLocation(), 18131 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 18132 << D; 18133 continue; 18134 } 18135 18136 // OpenMP [2.8.1, simd construct, Restrictions] 18137 // A list-item cannot appear in more than one aligned clause. 18138 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 18139 Diag(ELoc, diag::err_omp_used_in_clause_twice) 18140 << 0 << getOpenMPClauseName(OMPC_aligned) << ERange; 18141 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 18142 << getOpenMPClauseName(OMPC_aligned); 18143 continue; 18144 } 18145 18146 DeclRefExpr *Ref = nullptr; 18147 if (!VD && isOpenMPCapturedDecl(D)) 18148 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 18149 Vars.push_back(DefaultFunctionArrayConversion( 18150 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 18151 .get()); 18152 } 18153 18154 // OpenMP [2.8.1, simd construct, Description] 18155 // The parameter of the aligned clause, alignment, must be a constant 18156 // positive integer expression. 18157 // If no optional parameter is specified, implementation-defined default 18158 // alignments for SIMD instructions on the target platforms are assumed. 18159 if (Alignment != nullptr) { 18160 ExprResult AlignResult = 18161 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 18162 if (AlignResult.isInvalid()) 18163 return nullptr; 18164 Alignment = AlignResult.get(); 18165 } 18166 if (Vars.empty()) 18167 return nullptr; 18168 18169 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 18170 EndLoc, Vars, Alignment); 18171 } 18172 18173 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 18174 SourceLocation StartLoc, 18175 SourceLocation LParenLoc, 18176 SourceLocation EndLoc) { 18177 SmallVector<Expr *, 8> Vars; 18178 SmallVector<Expr *, 8> SrcExprs; 18179 SmallVector<Expr *, 8> DstExprs; 18180 SmallVector<Expr *, 8> AssignmentOps; 18181 for (Expr *RefExpr : VarList) { 18182 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 18183 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 18184 // It will be analyzed later. 18185 Vars.push_back(RefExpr); 18186 SrcExprs.push_back(nullptr); 18187 DstExprs.push_back(nullptr); 18188 AssignmentOps.push_back(nullptr); 18189 continue; 18190 } 18191 18192 SourceLocation ELoc = RefExpr->getExprLoc(); 18193 // OpenMP [2.1, C/C++] 18194 // A list item is a variable name. 18195 // OpenMP [2.14.4.1, Restrictions, p.1] 18196 // A list item that appears in a copyin clause must be threadprivate. 18197 auto *DE = dyn_cast<DeclRefExpr>(RefExpr); 18198 if (!DE || !isa<VarDecl>(DE->getDecl())) { 18199 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 18200 << 0 << RefExpr->getSourceRange(); 18201 continue; 18202 } 18203 18204 Decl *D = DE->getDecl(); 18205 auto *VD = cast<VarDecl>(D); 18206 18207 QualType Type = VD->getType(); 18208 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 18209 // It will be analyzed later. 18210 Vars.push_back(DE); 18211 SrcExprs.push_back(nullptr); 18212 DstExprs.push_back(nullptr); 18213 AssignmentOps.push_back(nullptr); 18214 continue; 18215 } 18216 18217 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 18218 // A list item that appears in a copyin clause must be threadprivate. 18219 if (!DSAStack->isThreadPrivate(VD)) { 18220 Diag(ELoc, diag::err_omp_required_access) 18221 << getOpenMPClauseName(OMPC_copyin) 18222 << getOpenMPDirectiveName(OMPD_threadprivate); 18223 continue; 18224 } 18225 18226 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 18227 // A variable of class type (or array thereof) that appears in a 18228 // copyin clause requires an accessible, unambiguous copy assignment 18229 // operator for the class type. 18230 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 18231 VarDecl *SrcVD = 18232 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(), 18233 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 18234 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr( 18235 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 18236 VarDecl *DstVD = 18237 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst", 18238 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 18239 DeclRefExpr *PseudoDstExpr = 18240 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 18241 // For arrays generate assignment operation for single element and replace 18242 // it by the original array element in CodeGen. 18243 ExprResult AssignmentOp = 18244 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr, 18245 PseudoSrcExpr); 18246 if (AssignmentOp.isInvalid()) 18247 continue; 18248 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 18249 /*DiscardedValue*/ false); 18250 if (AssignmentOp.isInvalid()) 18251 continue; 18252 18253 DSAStack->addDSA(VD, DE, OMPC_copyin); 18254 Vars.push_back(DE); 18255 SrcExprs.push_back(PseudoSrcExpr); 18256 DstExprs.push_back(PseudoDstExpr); 18257 AssignmentOps.push_back(AssignmentOp.get()); 18258 } 18259 18260 if (Vars.empty()) 18261 return nullptr; 18262 18263 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 18264 SrcExprs, DstExprs, AssignmentOps); 18265 } 18266 18267 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 18268 SourceLocation StartLoc, 18269 SourceLocation LParenLoc, 18270 SourceLocation EndLoc) { 18271 SmallVector<Expr *, 8> Vars; 18272 SmallVector<Expr *, 8> SrcExprs; 18273 SmallVector<Expr *, 8> DstExprs; 18274 SmallVector<Expr *, 8> AssignmentOps; 18275 for (Expr *RefExpr : VarList) { 18276 assert(RefExpr && "NULL expr in OpenMP linear clause."); 18277 SourceLocation ELoc; 18278 SourceRange ERange; 18279 Expr *SimpleRefExpr = RefExpr; 18280 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 18281 if (Res.second) { 18282 // It will be analyzed later. 18283 Vars.push_back(RefExpr); 18284 SrcExprs.push_back(nullptr); 18285 DstExprs.push_back(nullptr); 18286 AssignmentOps.push_back(nullptr); 18287 } 18288 ValueDecl *D = Res.first; 18289 if (!D) 18290 continue; 18291 18292 QualType Type = D->getType(); 18293 auto *VD = dyn_cast<VarDecl>(D); 18294 18295 // OpenMP [2.14.4.2, Restrictions, p.2] 18296 // A list item that appears in a copyprivate clause may not appear in a 18297 // private or firstprivate clause on the single construct. 18298 if (!VD || !DSAStack->isThreadPrivate(VD)) { 18299 DSAStackTy::DSAVarData DVar = 18300 DSAStack->getTopDSA(D, /*FromParent=*/false); 18301 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 18302 DVar.RefExpr) { 18303 Diag(ELoc, diag::err_omp_wrong_dsa) 18304 << getOpenMPClauseName(DVar.CKind) 18305 << getOpenMPClauseName(OMPC_copyprivate); 18306 reportOriginalDsa(*this, DSAStack, D, DVar); 18307 continue; 18308 } 18309 18310 // OpenMP [2.11.4.2, Restrictions, p.1] 18311 // All list items that appear in a copyprivate clause must be either 18312 // threadprivate or private in the enclosing context. 18313 if (DVar.CKind == OMPC_unknown) { 18314 DVar = DSAStack->getImplicitDSA(D, false); 18315 if (DVar.CKind == OMPC_shared) { 18316 Diag(ELoc, diag::err_omp_required_access) 18317 << getOpenMPClauseName(OMPC_copyprivate) 18318 << "threadprivate or private in the enclosing context"; 18319 reportOriginalDsa(*this, DSAStack, D, DVar); 18320 continue; 18321 } 18322 } 18323 } 18324 18325 // Variably modified types are not supported. 18326 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 18327 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 18328 << getOpenMPClauseName(OMPC_copyprivate) << Type 18329 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 18330 bool IsDecl = 18331 !VD || 18332 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 18333 Diag(D->getLocation(), 18334 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 18335 << D; 18336 continue; 18337 } 18338 18339 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 18340 // A variable of class type (or array thereof) that appears in a 18341 // copyin clause requires an accessible, unambiguous copy assignment 18342 // operator for the class type. 18343 Type = Context.getBaseElementType(Type.getNonReferenceType()) 18344 .getUnqualifiedType(); 18345 VarDecl *SrcVD = 18346 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src", 18347 D->hasAttrs() ? &D->getAttrs() : nullptr); 18348 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 18349 VarDecl *DstVD = 18350 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst", 18351 D->hasAttrs() ? &D->getAttrs() : nullptr); 18352 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 18353 ExprResult AssignmentOp = BuildBinOp( 18354 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr); 18355 if (AssignmentOp.isInvalid()) 18356 continue; 18357 AssignmentOp = 18358 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 18359 if (AssignmentOp.isInvalid()) 18360 continue; 18361 18362 // No need to mark vars as copyprivate, they are already threadprivate or 18363 // implicitly private. 18364 assert(VD || isOpenMPCapturedDecl(D)); 18365 Vars.push_back( 18366 VD ? RefExpr->IgnoreParens() 18367 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 18368 SrcExprs.push_back(PseudoSrcExpr); 18369 DstExprs.push_back(PseudoDstExpr); 18370 AssignmentOps.push_back(AssignmentOp.get()); 18371 } 18372 18373 if (Vars.empty()) 18374 return nullptr; 18375 18376 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 18377 Vars, SrcExprs, DstExprs, AssignmentOps); 18378 } 18379 18380 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 18381 SourceLocation StartLoc, 18382 SourceLocation LParenLoc, 18383 SourceLocation EndLoc) { 18384 if (VarList.empty()) 18385 return nullptr; 18386 18387 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 18388 } 18389 18390 /// Tries to find omp_depend_t. type. 18391 static bool findOMPDependT(Sema &S, SourceLocation Loc, DSAStackTy *Stack, 18392 bool Diagnose = true) { 18393 QualType OMPDependT = Stack->getOMPDependT(); 18394 if (!OMPDependT.isNull()) 18395 return true; 18396 IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_depend_t"); 18397 ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope()); 18398 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 18399 if (Diagnose) 18400 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_depend_t"; 18401 return false; 18402 } 18403 Stack->setOMPDependT(PT.get()); 18404 return true; 18405 } 18406 18407 OMPClause *Sema::ActOnOpenMPDepobjClause(Expr *Depobj, SourceLocation StartLoc, 18408 SourceLocation LParenLoc, 18409 SourceLocation EndLoc) { 18410 if (!Depobj) 18411 return nullptr; 18412 18413 bool OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack); 18414 18415 // OpenMP 5.0, 2.17.10.1 depobj Construct 18416 // depobj is an lvalue expression of type omp_depend_t. 18417 if (!Depobj->isTypeDependent() && !Depobj->isValueDependent() && 18418 !Depobj->isInstantiationDependent() && 18419 !Depobj->containsUnexpandedParameterPack() && 18420 (OMPDependTFound && 18421 !Context.typesAreCompatible(DSAStack->getOMPDependT(), Depobj->getType(), 18422 /*CompareUnqualified=*/true))) { 18423 Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue) 18424 << 0 << Depobj->getType() << Depobj->getSourceRange(); 18425 } 18426 18427 if (!Depobj->isLValue()) { 18428 Diag(Depobj->getExprLoc(), diag::err_omp_expected_omp_depend_t_lvalue) 18429 << 1 << Depobj->getSourceRange(); 18430 } 18431 18432 return OMPDepobjClause::Create(Context, StartLoc, LParenLoc, EndLoc, Depobj); 18433 } 18434 18435 OMPClause * 18436 Sema::ActOnOpenMPDependClause(Expr *DepModifier, OpenMPDependClauseKind DepKind, 18437 SourceLocation DepLoc, SourceLocation ColonLoc, 18438 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 18439 SourceLocation LParenLoc, SourceLocation EndLoc) { 18440 if (DSAStack->getCurrentDirective() == OMPD_ordered && 18441 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 18442 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 18443 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 18444 return nullptr; 18445 } 18446 if (DSAStack->getCurrentDirective() == OMPD_taskwait && 18447 DepKind == OMPC_DEPEND_mutexinoutset) { 18448 Diag(DepLoc, diag::err_omp_taskwait_depend_mutexinoutset_not_allowed); 18449 return nullptr; 18450 } 18451 if ((DSAStack->getCurrentDirective() != OMPD_ordered || 18452 DSAStack->getCurrentDirective() == OMPD_depobj) && 18453 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 18454 DepKind == OMPC_DEPEND_sink || 18455 ((LangOpts.OpenMP < 50 || 18456 DSAStack->getCurrentDirective() == OMPD_depobj) && 18457 DepKind == OMPC_DEPEND_depobj))) { 18458 SmallVector<unsigned, 3> Except; 18459 Except.push_back(OMPC_DEPEND_source); 18460 Except.push_back(OMPC_DEPEND_sink); 18461 if (LangOpts.OpenMP < 50 || DSAStack->getCurrentDirective() == OMPD_depobj) 18462 Except.push_back(OMPC_DEPEND_depobj); 18463 std::string Expected = (LangOpts.OpenMP >= 50 && !DepModifier) 18464 ? "depend modifier(iterator) or " 18465 : ""; 18466 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 18467 << Expected + getListOfPossibleValues(OMPC_depend, /*First=*/0, 18468 /*Last=*/OMPC_DEPEND_unknown, 18469 Except) 18470 << getOpenMPClauseName(OMPC_depend); 18471 return nullptr; 18472 } 18473 if (DepModifier && 18474 (DepKind == OMPC_DEPEND_source || DepKind == OMPC_DEPEND_sink)) { 18475 Diag(DepModifier->getExprLoc(), 18476 diag::err_omp_depend_sink_source_with_modifier); 18477 return nullptr; 18478 } 18479 if (DepModifier && 18480 !DepModifier->getType()->isSpecificBuiltinType(BuiltinType::OMPIterator)) 18481 Diag(DepModifier->getExprLoc(), diag::err_omp_depend_modifier_not_iterator); 18482 18483 SmallVector<Expr *, 8> Vars; 18484 DSAStackTy::OperatorOffsetTy OpsOffs; 18485 llvm::APSInt DepCounter(/*BitWidth=*/32); 18486 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 18487 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) { 18488 if (const Expr *OrderedCountExpr = 18489 DSAStack->getParentOrderedRegionParam().first) { 18490 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 18491 TotalDepCount.setIsUnsigned(/*Val=*/true); 18492 } 18493 } 18494 for (Expr *RefExpr : VarList) { 18495 assert(RefExpr && "NULL expr in OpenMP shared clause."); 18496 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 18497 // It will be analyzed later. 18498 Vars.push_back(RefExpr); 18499 continue; 18500 } 18501 18502 SourceLocation ELoc = RefExpr->getExprLoc(); 18503 Expr *SimpleExpr = RefExpr->IgnoreParenCasts(); 18504 if (DepKind == OMPC_DEPEND_sink) { 18505 if (DSAStack->getParentOrderedRegionParam().first && 18506 DepCounter >= TotalDepCount) { 18507 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 18508 continue; 18509 } 18510 ++DepCounter; 18511 // OpenMP [2.13.9, Summary] 18512 // depend(dependence-type : vec), where dependence-type is: 18513 // 'sink' and where vec is the iteration vector, which has the form: 18514 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 18515 // where n is the value specified by the ordered clause in the loop 18516 // directive, xi denotes the loop iteration variable of the i-th nested 18517 // loop associated with the loop directive, and di is a constant 18518 // non-negative integer. 18519 if (CurContext->isDependentContext()) { 18520 // It will be analyzed later. 18521 Vars.push_back(RefExpr); 18522 continue; 18523 } 18524 SimpleExpr = SimpleExpr->IgnoreImplicit(); 18525 OverloadedOperatorKind OOK = OO_None; 18526 SourceLocation OOLoc; 18527 Expr *LHS = SimpleExpr; 18528 Expr *RHS = nullptr; 18529 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 18530 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 18531 OOLoc = BO->getOperatorLoc(); 18532 LHS = BO->getLHS()->IgnoreParenImpCasts(); 18533 RHS = BO->getRHS()->IgnoreParenImpCasts(); 18534 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 18535 OOK = OCE->getOperator(); 18536 OOLoc = OCE->getOperatorLoc(); 18537 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 18538 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 18539 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 18540 OOK = MCE->getMethodDecl() 18541 ->getNameInfo() 18542 .getName() 18543 .getCXXOverloadedOperator(); 18544 OOLoc = MCE->getCallee()->getExprLoc(); 18545 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 18546 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 18547 } 18548 SourceLocation ELoc; 18549 SourceRange ERange; 18550 auto Res = getPrivateItem(*this, LHS, ELoc, ERange); 18551 if (Res.second) { 18552 // It will be analyzed later. 18553 Vars.push_back(RefExpr); 18554 } 18555 ValueDecl *D = Res.first; 18556 if (!D) 18557 continue; 18558 18559 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 18560 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 18561 continue; 18562 } 18563 if (RHS) { 18564 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 18565 RHS, OMPC_depend, /*StrictlyPositive=*/false); 18566 if (RHSRes.isInvalid()) 18567 continue; 18568 } 18569 if (!CurContext->isDependentContext() && 18570 DSAStack->getParentOrderedRegionParam().first && 18571 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 18572 const ValueDecl *VD = 18573 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue()); 18574 if (VD) 18575 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 18576 << 1 << VD; 18577 else 18578 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; 18579 continue; 18580 } 18581 OpsOffs.emplace_back(RHS, OOK); 18582 } else { 18583 bool OMPDependTFound = LangOpts.OpenMP >= 50; 18584 if (OMPDependTFound) 18585 OMPDependTFound = findOMPDependT(*this, StartLoc, DSAStack, 18586 DepKind == OMPC_DEPEND_depobj); 18587 if (DepKind == OMPC_DEPEND_depobj) { 18588 // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++ 18589 // List items used in depend clauses with the depobj dependence type 18590 // must be expressions of the omp_depend_t type. 18591 if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() && 18592 !RefExpr->isInstantiationDependent() && 18593 !RefExpr->containsUnexpandedParameterPack() && 18594 (OMPDependTFound && 18595 !Context.hasSameUnqualifiedType(DSAStack->getOMPDependT(), 18596 RefExpr->getType()))) { 18597 Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue) 18598 << 0 << RefExpr->getType() << RefExpr->getSourceRange(); 18599 continue; 18600 } 18601 if (!RefExpr->isLValue()) { 18602 Diag(ELoc, diag::err_omp_expected_omp_depend_t_lvalue) 18603 << 1 << RefExpr->getType() << RefExpr->getSourceRange(); 18604 continue; 18605 } 18606 } else { 18607 // OpenMP 5.0 [2.17.11, Restrictions] 18608 // List items used in depend clauses cannot be zero-length array 18609 // sections. 18610 QualType ExprTy = RefExpr->getType().getNonReferenceType(); 18611 const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr); 18612 if (OASE) { 18613 QualType BaseType = 18614 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 18615 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 18616 ExprTy = ATy->getElementType(); 18617 else 18618 ExprTy = BaseType->getPointeeType(); 18619 ExprTy = ExprTy.getNonReferenceType(); 18620 const Expr *Length = OASE->getLength(); 18621 Expr::EvalResult Result; 18622 if (Length && !Length->isValueDependent() && 18623 Length->EvaluateAsInt(Result, Context) && 18624 Result.Val.getInt().isZero()) { 18625 Diag(ELoc, 18626 diag::err_omp_depend_zero_length_array_section_not_allowed) 18627 << SimpleExpr->getSourceRange(); 18628 continue; 18629 } 18630 } 18631 18632 // OpenMP 5.0, 2.17.11 depend Clause, Restrictions, C/C++ 18633 // List items used in depend clauses with the in, out, inout or 18634 // mutexinoutset dependence types cannot be expressions of the 18635 // omp_depend_t type. 18636 if (!RefExpr->isValueDependent() && !RefExpr->isTypeDependent() && 18637 !RefExpr->isInstantiationDependent() && 18638 !RefExpr->containsUnexpandedParameterPack() && 18639 (OMPDependTFound && 18640 DSAStack->getOMPDependT().getTypePtr() == ExprTy.getTypePtr())) { 18641 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 18642 << (LangOpts.OpenMP >= 50 ? 1 : 0) << 1 18643 << RefExpr->getSourceRange(); 18644 continue; 18645 } 18646 18647 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 18648 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 18649 (ASE && !ASE->getBase()->isTypeDependent() && 18650 !ASE->getBase() 18651 ->getType() 18652 .getNonReferenceType() 18653 ->isPointerType() && 18654 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 18655 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 18656 << (LangOpts.OpenMP >= 50 ? 1 : 0) 18657 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 18658 continue; 18659 } 18660 18661 ExprResult Res; 18662 { 18663 Sema::TentativeAnalysisScope Trap(*this); 18664 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, 18665 RefExpr->IgnoreParenImpCasts()); 18666 } 18667 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) && 18668 !isa<OMPArrayShapingExpr>(SimpleExpr)) { 18669 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 18670 << (LangOpts.OpenMP >= 50 ? 1 : 0) 18671 << (LangOpts.OpenMP >= 50 ? 1 : 0) << RefExpr->getSourceRange(); 18672 continue; 18673 } 18674 } 18675 } 18676 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 18677 } 18678 18679 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 18680 TotalDepCount > VarList.size() && 18681 DSAStack->getParentOrderedRegionParam().first && 18682 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { 18683 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 18684 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 18685 } 18686 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 18687 Vars.empty()) 18688 return nullptr; 18689 18690 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 18691 DepModifier, DepKind, DepLoc, ColonLoc, 18692 Vars, TotalDepCount.getZExtValue()); 18693 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) && 18694 DSAStack->isParentOrderedRegion()) 18695 DSAStack->addDoacrossDependClause(C, OpsOffs); 18696 return C; 18697 } 18698 18699 OMPClause *Sema::ActOnOpenMPDeviceClause(OpenMPDeviceClauseModifier Modifier, 18700 Expr *Device, SourceLocation StartLoc, 18701 SourceLocation LParenLoc, 18702 SourceLocation ModifierLoc, 18703 SourceLocation EndLoc) { 18704 assert((ModifierLoc.isInvalid() || LangOpts.OpenMP >= 50) && 18705 "Unexpected device modifier in OpenMP < 50."); 18706 18707 bool ErrorFound = false; 18708 if (ModifierLoc.isValid() && Modifier == OMPC_DEVICE_unknown) { 18709 std::string Values = 18710 getListOfPossibleValues(OMPC_device, /*First=*/0, OMPC_DEVICE_unknown); 18711 Diag(ModifierLoc, diag::err_omp_unexpected_clause_value) 18712 << Values << getOpenMPClauseName(OMPC_device); 18713 ErrorFound = true; 18714 } 18715 18716 Expr *ValExpr = Device; 18717 Stmt *HelperValStmt = nullptr; 18718 18719 // OpenMP [2.9.1, Restrictions] 18720 // The device expression must evaluate to a non-negative integer value. 18721 ErrorFound = !isNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 18722 /*StrictlyPositive=*/false) || 18723 ErrorFound; 18724 if (ErrorFound) 18725 return nullptr; 18726 18727 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 18728 OpenMPDirectiveKind CaptureRegion = 18729 getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP); 18730 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 18731 ValExpr = MakeFullExpr(ValExpr).get(); 18732 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 18733 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 18734 HelperValStmt = buildPreInits(Context, Captures); 18735 } 18736 18737 return new (Context) 18738 OMPDeviceClause(Modifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 18739 LParenLoc, ModifierLoc, EndLoc); 18740 } 18741 18742 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 18743 DSAStackTy *Stack, QualType QTy, 18744 bool FullCheck = true) { 18745 if (SemaRef.RequireCompleteType(SL, QTy, diag::err_incomplete_type)) 18746 return false; 18747 if (FullCheck && !SemaRef.CurContext->isDependentContext() && 18748 !QTy.isTriviallyCopyableType(SemaRef.Context)) 18749 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR; 18750 return true; 18751 } 18752 18753 /// Return true if it can be proven that the provided array expression 18754 /// (array section or array subscript) does NOT specify the whole size of the 18755 /// array whose base type is \a BaseQTy. 18756 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 18757 const Expr *E, 18758 QualType BaseQTy) { 18759 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 18760 18761 // If this is an array subscript, it refers to the whole size if the size of 18762 // the dimension is constant and equals 1. Also, an array section assumes the 18763 // format of an array subscript if no colon is used. 18764 if (isa<ArraySubscriptExpr>(E) || 18765 (OASE && OASE->getColonLocFirst().isInvalid())) { 18766 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 18767 return ATy->getSize().getSExtValue() != 1; 18768 // Size can't be evaluated statically. 18769 return false; 18770 } 18771 18772 assert(OASE && "Expecting array section if not an array subscript."); 18773 const Expr *LowerBound = OASE->getLowerBound(); 18774 const Expr *Length = OASE->getLength(); 18775 18776 // If there is a lower bound that does not evaluates to zero, we are not 18777 // covering the whole dimension. 18778 if (LowerBound) { 18779 Expr::EvalResult Result; 18780 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext())) 18781 return false; // Can't get the integer value as a constant. 18782 18783 llvm::APSInt ConstLowerBound = Result.Val.getInt(); 18784 if (ConstLowerBound.getSExtValue()) 18785 return true; 18786 } 18787 18788 // If we don't have a length we covering the whole dimension. 18789 if (!Length) 18790 return false; 18791 18792 // If the base is a pointer, we don't have a way to get the size of the 18793 // pointee. 18794 if (BaseQTy->isPointerType()) 18795 return false; 18796 18797 // We can only check if the length is the same as the size of the dimension 18798 // if we have a constant array. 18799 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 18800 if (!CATy) 18801 return false; 18802 18803 Expr::EvalResult Result; 18804 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 18805 return false; // Can't get the integer value as a constant. 18806 18807 llvm::APSInt ConstLength = Result.Val.getInt(); 18808 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 18809 } 18810 18811 // Return true if it can be proven that the provided array expression (array 18812 // section or array subscript) does NOT specify a single element of the array 18813 // whose base type is \a BaseQTy. 18814 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 18815 const Expr *E, 18816 QualType BaseQTy) { 18817 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 18818 18819 // An array subscript always refer to a single element. Also, an array section 18820 // assumes the format of an array subscript if no colon is used. 18821 if (isa<ArraySubscriptExpr>(E) || 18822 (OASE && OASE->getColonLocFirst().isInvalid())) 18823 return false; 18824 18825 assert(OASE && "Expecting array section if not an array subscript."); 18826 const Expr *Length = OASE->getLength(); 18827 18828 // If we don't have a length we have to check if the array has unitary size 18829 // for this dimension. Also, we should always expect a length if the base type 18830 // is pointer. 18831 if (!Length) { 18832 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 18833 return ATy->getSize().getSExtValue() != 1; 18834 // We cannot assume anything. 18835 return false; 18836 } 18837 18838 // Check if the length evaluates to 1. 18839 Expr::EvalResult Result; 18840 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 18841 return false; // Can't get the integer value as a constant. 18842 18843 llvm::APSInt ConstLength = Result.Val.getInt(); 18844 return ConstLength.getSExtValue() != 1; 18845 } 18846 18847 // The base of elements of list in a map clause have to be either: 18848 // - a reference to variable or field. 18849 // - a member expression. 18850 // - an array expression. 18851 // 18852 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 18853 // reference to 'r'. 18854 // 18855 // If we have: 18856 // 18857 // struct SS { 18858 // Bla S; 18859 // foo() { 18860 // #pragma omp target map (S.Arr[:12]); 18861 // } 18862 // } 18863 // 18864 // We want to retrieve the member expression 'this->S'; 18865 18866 // OpenMP 5.0 [2.19.7.1, map Clause, Restrictions, p.2] 18867 // If a list item is an array section, it must specify contiguous storage. 18868 // 18869 // For this restriction it is sufficient that we make sure only references 18870 // to variables or fields and array expressions, and that no array sections 18871 // exist except in the rightmost expression (unless they cover the whole 18872 // dimension of the array). E.g. these would be invalid: 18873 // 18874 // r.ArrS[3:5].Arr[6:7] 18875 // 18876 // r.ArrS[3:5].x 18877 // 18878 // but these would be valid: 18879 // r.ArrS[3].Arr[6:7] 18880 // 18881 // r.ArrS[3].x 18882 namespace { 18883 class MapBaseChecker final : public StmtVisitor<MapBaseChecker, bool> { 18884 Sema &SemaRef; 18885 OpenMPClauseKind CKind = OMPC_unknown; 18886 OpenMPDirectiveKind DKind = OMPD_unknown; 18887 OMPClauseMappableExprCommon::MappableExprComponentList &Components; 18888 bool IsNonContiguous = false; 18889 bool NoDiagnose = false; 18890 const Expr *RelevantExpr = nullptr; 18891 bool AllowUnitySizeArraySection = true; 18892 bool AllowWholeSizeArraySection = true; 18893 bool AllowAnotherPtr = true; 18894 SourceLocation ELoc; 18895 SourceRange ERange; 18896 18897 void emitErrorMsg() { 18898 // If nothing else worked, this is not a valid map clause expression. 18899 if (SemaRef.getLangOpts().OpenMP < 50) { 18900 SemaRef.Diag(ELoc, 18901 diag::err_omp_expected_named_var_member_or_array_expression) 18902 << ERange; 18903 } else { 18904 SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses) 18905 << getOpenMPClauseName(CKind) << ERange; 18906 } 18907 } 18908 18909 public: 18910 bool VisitDeclRefExpr(DeclRefExpr *DRE) { 18911 if (!isa<VarDecl>(DRE->getDecl())) { 18912 emitErrorMsg(); 18913 return false; 18914 } 18915 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 18916 RelevantExpr = DRE; 18917 // Record the component. 18918 Components.emplace_back(DRE, DRE->getDecl(), IsNonContiguous); 18919 return true; 18920 } 18921 18922 bool VisitMemberExpr(MemberExpr *ME) { 18923 Expr *E = ME; 18924 Expr *BaseE = ME->getBase()->IgnoreParenCasts(); 18925 18926 if (isa<CXXThisExpr>(BaseE)) { 18927 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 18928 // We found a base expression: this->Val. 18929 RelevantExpr = ME; 18930 } else { 18931 E = BaseE; 18932 } 18933 18934 if (!isa<FieldDecl>(ME->getMemberDecl())) { 18935 if (!NoDiagnose) { 18936 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 18937 << ME->getSourceRange(); 18938 return false; 18939 } 18940 if (RelevantExpr) 18941 return false; 18942 return Visit(E); 18943 } 18944 18945 auto *FD = cast<FieldDecl>(ME->getMemberDecl()); 18946 18947 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 18948 // A bit-field cannot appear in a map clause. 18949 // 18950 if (FD->isBitField()) { 18951 if (!NoDiagnose) { 18952 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 18953 << ME->getSourceRange() << getOpenMPClauseName(CKind); 18954 return false; 18955 } 18956 if (RelevantExpr) 18957 return false; 18958 return Visit(E); 18959 } 18960 18961 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 18962 // If the type of a list item is a reference to a type T then the type 18963 // will be considered to be T for all purposes of this clause. 18964 QualType CurType = BaseE->getType().getNonReferenceType(); 18965 18966 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 18967 // A list item cannot be a variable that is a member of a structure with 18968 // a union type. 18969 // 18970 if (CurType->isUnionType()) { 18971 if (!NoDiagnose) { 18972 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 18973 << ME->getSourceRange(); 18974 return false; 18975 } 18976 return RelevantExpr || Visit(E); 18977 } 18978 18979 // If we got a member expression, we should not expect any array section 18980 // before that: 18981 // 18982 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 18983 // If a list item is an element of a structure, only the rightmost symbol 18984 // of the variable reference can be an array section. 18985 // 18986 AllowUnitySizeArraySection = false; 18987 AllowWholeSizeArraySection = false; 18988 18989 // Record the component. 18990 Components.emplace_back(ME, FD, IsNonContiguous); 18991 return RelevantExpr || Visit(E); 18992 } 18993 18994 bool VisitArraySubscriptExpr(ArraySubscriptExpr *AE) { 18995 Expr *E = AE->getBase()->IgnoreParenImpCasts(); 18996 18997 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 18998 if (!NoDiagnose) { 18999 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 19000 << 0 << AE->getSourceRange(); 19001 return false; 19002 } 19003 return RelevantExpr || Visit(E); 19004 } 19005 19006 // If we got an array subscript that express the whole dimension we 19007 // can have any array expressions before. If it only expressing part of 19008 // the dimension, we can only have unitary-size array expressions. 19009 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, AE, 19010 E->getType())) 19011 AllowWholeSizeArraySection = false; 19012 19013 if (const auto *TE = dyn_cast<CXXThisExpr>(E->IgnoreParenCasts())) { 19014 Expr::EvalResult Result; 19015 if (!AE->getIdx()->isValueDependent() && 19016 AE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext()) && 19017 !Result.Val.getInt().isZero()) { 19018 SemaRef.Diag(AE->getIdx()->getExprLoc(), 19019 diag::err_omp_invalid_map_this_expr); 19020 SemaRef.Diag(AE->getIdx()->getExprLoc(), 19021 diag::note_omp_invalid_subscript_on_this_ptr_map); 19022 } 19023 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19024 RelevantExpr = TE; 19025 } 19026 19027 // Record the component - we don't have any declaration associated. 19028 Components.emplace_back(AE, nullptr, IsNonContiguous); 19029 19030 return RelevantExpr || Visit(E); 19031 } 19032 19033 bool VisitOMPArraySectionExpr(OMPArraySectionExpr *OASE) { 19034 // After OMP 5.0 Array section in reduction clause will be implicitly 19035 // mapped 19036 assert(!(SemaRef.getLangOpts().OpenMP < 50 && NoDiagnose) && 19037 "Array sections cannot be implicitly mapped."); 19038 Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 19039 QualType CurType = 19040 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 19041 19042 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 19043 // If the type of a list item is a reference to a type T then the type 19044 // will be considered to be T for all purposes of this clause. 19045 if (CurType->isReferenceType()) 19046 CurType = CurType->getPointeeType(); 19047 19048 bool IsPointer = CurType->isAnyPointerType(); 19049 19050 if (!IsPointer && !CurType->isArrayType()) { 19051 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 19052 << 0 << OASE->getSourceRange(); 19053 return false; 19054 } 19055 19056 bool NotWhole = 19057 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, OASE, CurType); 19058 bool NotUnity = 19059 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, OASE, CurType); 19060 19061 if (AllowWholeSizeArraySection) { 19062 // Any array section is currently allowed. Allowing a whole size array 19063 // section implies allowing a unity array section as well. 19064 // 19065 // If this array section refers to the whole dimension we can still 19066 // accept other array sections before this one, except if the base is a 19067 // pointer. Otherwise, only unitary sections are accepted. 19068 if (NotWhole || IsPointer) 19069 AllowWholeSizeArraySection = false; 19070 } else if (DKind == OMPD_target_update && 19071 SemaRef.getLangOpts().OpenMP >= 50) { 19072 if (IsPointer && !AllowAnotherPtr) 19073 SemaRef.Diag(ELoc, diag::err_omp_section_length_undefined) 19074 << /*array of unknown bound */ 1; 19075 else 19076 IsNonContiguous = true; 19077 } else if (AllowUnitySizeArraySection && NotUnity) { 19078 // A unity or whole array section is not allowed and that is not 19079 // compatible with the properties of the current array section. 19080 if (NoDiagnose) 19081 return false; 19082 SemaRef.Diag( 19083 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 19084 << OASE->getSourceRange(); 19085 return false; 19086 } 19087 19088 if (IsPointer) 19089 AllowAnotherPtr = false; 19090 19091 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) { 19092 Expr::EvalResult ResultR; 19093 Expr::EvalResult ResultL; 19094 if (!OASE->getLength()->isValueDependent() && 19095 OASE->getLength()->EvaluateAsInt(ResultR, SemaRef.getASTContext()) && 19096 !ResultR.Val.getInt().isOne()) { 19097 SemaRef.Diag(OASE->getLength()->getExprLoc(), 19098 diag::err_omp_invalid_map_this_expr); 19099 SemaRef.Diag(OASE->getLength()->getExprLoc(), 19100 diag::note_omp_invalid_length_on_this_ptr_mapping); 19101 } 19102 if (OASE->getLowerBound() && !OASE->getLowerBound()->isValueDependent() && 19103 OASE->getLowerBound()->EvaluateAsInt(ResultL, 19104 SemaRef.getASTContext()) && 19105 !ResultL.Val.getInt().isZero()) { 19106 SemaRef.Diag(OASE->getLowerBound()->getExprLoc(), 19107 diag::err_omp_invalid_map_this_expr); 19108 SemaRef.Diag(OASE->getLowerBound()->getExprLoc(), 19109 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping); 19110 } 19111 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19112 RelevantExpr = TE; 19113 } 19114 19115 // Record the component - we don't have any declaration associated. 19116 Components.emplace_back(OASE, nullptr, /*IsNonContiguous=*/false); 19117 return RelevantExpr || Visit(E); 19118 } 19119 bool VisitOMPArrayShapingExpr(OMPArrayShapingExpr *E) { 19120 Expr *Base = E->getBase(); 19121 19122 // Record the component - we don't have any declaration associated. 19123 Components.emplace_back(E, nullptr, IsNonContiguous); 19124 19125 return Visit(Base->IgnoreParenImpCasts()); 19126 } 19127 19128 bool VisitUnaryOperator(UnaryOperator *UO) { 19129 if (SemaRef.getLangOpts().OpenMP < 50 || !UO->isLValue() || 19130 UO->getOpcode() != UO_Deref) { 19131 emitErrorMsg(); 19132 return false; 19133 } 19134 if (!RelevantExpr) { 19135 // Record the component if haven't found base decl. 19136 Components.emplace_back(UO, nullptr, /*IsNonContiguous=*/false); 19137 } 19138 return RelevantExpr || Visit(UO->getSubExpr()->IgnoreParenImpCasts()); 19139 } 19140 bool VisitBinaryOperator(BinaryOperator *BO) { 19141 if (SemaRef.getLangOpts().OpenMP < 50 || !BO->getType()->isPointerType()) { 19142 emitErrorMsg(); 19143 return false; 19144 } 19145 19146 // Pointer arithmetic is the only thing we expect to happen here so after we 19147 // make sure the binary operator is a pointer type, the we only thing need 19148 // to to is to visit the subtree that has the same type as root (so that we 19149 // know the other subtree is just an offset) 19150 Expr *LE = BO->getLHS()->IgnoreParenImpCasts(); 19151 Expr *RE = BO->getRHS()->IgnoreParenImpCasts(); 19152 Components.emplace_back(BO, nullptr, false); 19153 assert((LE->getType().getTypePtr() == BO->getType().getTypePtr() || 19154 RE->getType().getTypePtr() == BO->getType().getTypePtr()) && 19155 "Either LHS or RHS have base decl inside"); 19156 if (BO->getType().getTypePtr() == LE->getType().getTypePtr()) 19157 return RelevantExpr || Visit(LE); 19158 return RelevantExpr || Visit(RE); 19159 } 19160 bool VisitCXXThisExpr(CXXThisExpr *CTE) { 19161 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19162 RelevantExpr = CTE; 19163 Components.emplace_back(CTE, nullptr, IsNonContiguous); 19164 return true; 19165 } 19166 bool VisitCXXOperatorCallExpr(CXXOperatorCallExpr *COCE) { 19167 assert(!RelevantExpr && "RelevantExpr is expected to be nullptr"); 19168 Components.emplace_back(COCE, nullptr, IsNonContiguous); 19169 return true; 19170 } 19171 bool VisitOpaqueValueExpr(OpaqueValueExpr *E) { 19172 Expr *Source = E->getSourceExpr(); 19173 if (!Source) { 19174 emitErrorMsg(); 19175 return false; 19176 } 19177 return Visit(Source); 19178 } 19179 bool VisitStmt(Stmt *) { 19180 emitErrorMsg(); 19181 return false; 19182 } 19183 const Expr *getFoundBase() const { 19184 return RelevantExpr; 19185 } 19186 explicit MapBaseChecker( 19187 Sema &SemaRef, OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, 19188 OMPClauseMappableExprCommon::MappableExprComponentList &Components, 19189 bool NoDiagnose, SourceLocation &ELoc, SourceRange &ERange) 19190 : SemaRef(SemaRef), CKind(CKind), DKind(DKind), Components(Components), 19191 NoDiagnose(NoDiagnose), ELoc(ELoc), ERange(ERange) {} 19192 }; 19193 } // namespace 19194 19195 /// Return the expression of the base of the mappable expression or null if it 19196 /// cannot be determined and do all the necessary checks to see if the expression 19197 /// is valid as a standalone mappable expression. In the process, record all the 19198 /// components of the expression. 19199 static const Expr *checkMapClauseExpressionBase( 19200 Sema &SemaRef, Expr *E, 19201 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 19202 OpenMPClauseKind CKind, OpenMPDirectiveKind DKind, bool NoDiagnose) { 19203 SourceLocation ELoc = E->getExprLoc(); 19204 SourceRange ERange = E->getSourceRange(); 19205 MapBaseChecker Checker(SemaRef, CKind, DKind, CurComponents, NoDiagnose, ELoc, 19206 ERange); 19207 if (Checker.Visit(E->IgnoreParens())) { 19208 // Check if the highest dimension array section has length specified 19209 if (SemaRef.getLangOpts().OpenMP >= 50 && !CurComponents.empty() && 19210 (CKind == OMPC_to || CKind == OMPC_from)) { 19211 auto CI = CurComponents.rbegin(); 19212 auto CE = CurComponents.rend(); 19213 for (; CI != CE; ++CI) { 19214 const auto *OASE = 19215 dyn_cast<OMPArraySectionExpr>(CI->getAssociatedExpression()); 19216 if (!OASE) 19217 continue; 19218 if (OASE && OASE->getLength()) 19219 break; 19220 SemaRef.Diag(ELoc, diag::err_array_section_does_not_specify_length) 19221 << ERange; 19222 } 19223 } 19224 return Checker.getFoundBase(); 19225 } 19226 return nullptr; 19227 } 19228 19229 // Return true if expression E associated with value VD has conflicts with other 19230 // map information. 19231 static bool checkMapConflicts( 19232 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E, 19233 bool CurrentRegionOnly, 19234 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 19235 OpenMPClauseKind CKind) { 19236 assert(VD && E); 19237 SourceLocation ELoc = E->getExprLoc(); 19238 SourceRange ERange = E->getSourceRange(); 19239 19240 // In order to easily check the conflicts we need to match each component of 19241 // the expression under test with the components of the expressions that are 19242 // already in the stack. 19243 19244 assert(!CurComponents.empty() && "Map clause expression with no components!"); 19245 assert(CurComponents.back().getAssociatedDeclaration() == VD && 19246 "Map clause expression with unexpected base!"); 19247 19248 // Variables to help detecting enclosing problems in data environment nests. 19249 bool IsEnclosedByDataEnvironmentExpr = false; 19250 const Expr *EnclosingExpr = nullptr; 19251 19252 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 19253 VD, CurrentRegionOnly, 19254 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc, 19255 ERange, CKind, &EnclosingExpr, 19256 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef 19257 StackComponents, 19258 OpenMPClauseKind Kind) { 19259 if (CKind == Kind && SemaRef.LangOpts.OpenMP >= 50) 19260 return false; 19261 assert(!StackComponents.empty() && 19262 "Map clause expression with no components!"); 19263 assert(StackComponents.back().getAssociatedDeclaration() == VD && 19264 "Map clause expression with unexpected base!"); 19265 (void)VD; 19266 19267 // The whole expression in the stack. 19268 const Expr *RE = StackComponents.front().getAssociatedExpression(); 19269 19270 // Expressions must start from the same base. Here we detect at which 19271 // point both expressions diverge from each other and see if we can 19272 // detect if the memory referred to both expressions is contiguous and 19273 // do not overlap. 19274 auto CI = CurComponents.rbegin(); 19275 auto CE = CurComponents.rend(); 19276 auto SI = StackComponents.rbegin(); 19277 auto SE = StackComponents.rend(); 19278 for (; CI != CE && SI != SE; ++CI, ++SI) { 19279 19280 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 19281 // At most one list item can be an array item derived from a given 19282 // variable in map clauses of the same construct. 19283 if (CurrentRegionOnly && 19284 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 19285 isa<OMPArraySectionExpr>(CI->getAssociatedExpression()) || 19286 isa<OMPArrayShapingExpr>(CI->getAssociatedExpression())) && 19287 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 19288 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()) || 19289 isa<OMPArrayShapingExpr>(SI->getAssociatedExpression()))) { 19290 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 19291 diag::err_omp_multiple_array_items_in_map_clause) 19292 << CI->getAssociatedExpression()->getSourceRange(); 19293 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 19294 diag::note_used_here) 19295 << SI->getAssociatedExpression()->getSourceRange(); 19296 return true; 19297 } 19298 19299 // Do both expressions have the same kind? 19300 if (CI->getAssociatedExpression()->getStmtClass() != 19301 SI->getAssociatedExpression()->getStmtClass()) 19302 break; 19303 19304 // Are we dealing with different variables/fields? 19305 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 19306 break; 19307 } 19308 // Check if the extra components of the expressions in the enclosing 19309 // data environment are redundant for the current base declaration. 19310 // If they are, the maps completely overlap, which is legal. 19311 for (; SI != SE; ++SI) { 19312 QualType Type; 19313 if (const auto *ASE = 19314 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 19315 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 19316 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>( 19317 SI->getAssociatedExpression())) { 19318 const Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 19319 Type = 19320 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 19321 } else if (const auto *OASE = dyn_cast<OMPArrayShapingExpr>( 19322 SI->getAssociatedExpression())) { 19323 Type = OASE->getBase()->getType()->getPointeeType(); 19324 } 19325 if (Type.isNull() || Type->isAnyPointerType() || 19326 checkArrayExpressionDoesNotReferToWholeSize( 19327 SemaRef, SI->getAssociatedExpression(), Type)) 19328 break; 19329 } 19330 19331 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 19332 // List items of map clauses in the same construct must not share 19333 // original storage. 19334 // 19335 // If the expressions are exactly the same or one is a subset of the 19336 // other, it means they are sharing storage. 19337 if (CI == CE && SI == SE) { 19338 if (CurrentRegionOnly) { 19339 if (CKind == OMPC_map) { 19340 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 19341 } else { 19342 assert(CKind == OMPC_to || CKind == OMPC_from); 19343 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 19344 << ERange; 19345 } 19346 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 19347 << RE->getSourceRange(); 19348 return true; 19349 } 19350 // If we find the same expression in the enclosing data environment, 19351 // that is legal. 19352 IsEnclosedByDataEnvironmentExpr = true; 19353 return false; 19354 } 19355 19356 QualType DerivedType = 19357 std::prev(CI)->getAssociatedDeclaration()->getType(); 19358 SourceLocation DerivedLoc = 19359 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 19360 19361 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 19362 // If the type of a list item is a reference to a type T then the type 19363 // will be considered to be T for all purposes of this clause. 19364 DerivedType = DerivedType.getNonReferenceType(); 19365 19366 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 19367 // A variable for which the type is pointer and an array section 19368 // derived from that variable must not appear as list items of map 19369 // clauses of the same construct. 19370 // 19371 // Also, cover one of the cases in: 19372 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 19373 // If any part of the original storage of a list item has corresponding 19374 // storage in the device data environment, all of the original storage 19375 // must have corresponding storage in the device data environment. 19376 // 19377 if (DerivedType->isAnyPointerType()) { 19378 if (CI == CE || SI == SE) { 19379 SemaRef.Diag( 19380 DerivedLoc, 19381 diag::err_omp_pointer_mapped_along_with_derived_section) 19382 << DerivedLoc; 19383 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 19384 << RE->getSourceRange(); 19385 return true; 19386 } 19387 if (CI->getAssociatedExpression()->getStmtClass() != 19388 SI->getAssociatedExpression()->getStmtClass() || 19389 CI->getAssociatedDeclaration()->getCanonicalDecl() == 19390 SI->getAssociatedDeclaration()->getCanonicalDecl()) { 19391 assert(CI != CE && SI != SE); 19392 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced) 19393 << DerivedLoc; 19394 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 19395 << RE->getSourceRange(); 19396 return true; 19397 } 19398 } 19399 19400 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 19401 // List items of map clauses in the same construct must not share 19402 // original storage. 19403 // 19404 // An expression is a subset of the other. 19405 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 19406 if (CKind == OMPC_map) { 19407 if (CI != CE || SI != SE) { 19408 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is 19409 // a pointer. 19410 auto Begin = 19411 CI != CE ? CurComponents.begin() : StackComponents.begin(); 19412 auto End = CI != CE ? CurComponents.end() : StackComponents.end(); 19413 auto It = Begin; 19414 while (It != End && !It->getAssociatedDeclaration()) 19415 std::advance(It, 1); 19416 assert(It != End && 19417 "Expected at least one component with the declaration."); 19418 if (It != Begin && It->getAssociatedDeclaration() 19419 ->getType() 19420 .getCanonicalType() 19421 ->isAnyPointerType()) { 19422 IsEnclosedByDataEnvironmentExpr = false; 19423 EnclosingExpr = nullptr; 19424 return false; 19425 } 19426 } 19427 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 19428 } else { 19429 assert(CKind == OMPC_to || CKind == OMPC_from); 19430 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 19431 << ERange; 19432 } 19433 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 19434 << RE->getSourceRange(); 19435 return true; 19436 } 19437 19438 // The current expression uses the same base as other expression in the 19439 // data environment but does not contain it completely. 19440 if (!CurrentRegionOnly && SI != SE) 19441 EnclosingExpr = RE; 19442 19443 // The current expression is a subset of the expression in the data 19444 // environment. 19445 IsEnclosedByDataEnvironmentExpr |= 19446 (!CurrentRegionOnly && CI != CE && SI == SE); 19447 19448 return false; 19449 }); 19450 19451 if (CurrentRegionOnly) 19452 return FoundError; 19453 19454 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 19455 // If any part of the original storage of a list item has corresponding 19456 // storage in the device data environment, all of the original storage must 19457 // have corresponding storage in the device data environment. 19458 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 19459 // If a list item is an element of a structure, and a different element of 19460 // the structure has a corresponding list item in the device data environment 19461 // prior to a task encountering the construct associated with the map clause, 19462 // then the list item must also have a corresponding list item in the device 19463 // data environment prior to the task encountering the construct. 19464 // 19465 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 19466 SemaRef.Diag(ELoc, 19467 diag::err_omp_original_storage_is_shared_and_does_not_contain) 19468 << ERange; 19469 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 19470 << EnclosingExpr->getSourceRange(); 19471 return true; 19472 } 19473 19474 return FoundError; 19475 } 19476 19477 // Look up the user-defined mapper given the mapper name and mapped type, and 19478 // build a reference to it. 19479 static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S, 19480 CXXScopeSpec &MapperIdScopeSpec, 19481 const DeclarationNameInfo &MapperId, 19482 QualType Type, 19483 Expr *UnresolvedMapper) { 19484 if (MapperIdScopeSpec.isInvalid()) 19485 return ExprError(); 19486 // Get the actual type for the array type. 19487 if (Type->isArrayType()) { 19488 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type"); 19489 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType(); 19490 } 19491 // Find all user-defined mappers with the given MapperId. 19492 SmallVector<UnresolvedSet<8>, 4> Lookups; 19493 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName); 19494 Lookup.suppressDiagnostics(); 19495 if (S) { 19496 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) { 19497 NamedDecl *D = Lookup.getRepresentativeDecl(); 19498 while (S && !S->isDeclScope(D)) 19499 S = S->getParent(); 19500 if (S) 19501 S = S->getParent(); 19502 Lookups.emplace_back(); 19503 Lookups.back().append(Lookup.begin(), Lookup.end()); 19504 Lookup.clear(); 19505 } 19506 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) { 19507 // Extract the user-defined mappers with the given MapperId. 19508 Lookups.push_back(UnresolvedSet<8>()); 19509 for (NamedDecl *D : ULE->decls()) { 19510 auto *DMD = cast<OMPDeclareMapperDecl>(D); 19511 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation."); 19512 Lookups.back().addDecl(DMD); 19513 } 19514 } 19515 // Defer the lookup for dependent types. The results will be passed through 19516 // UnresolvedMapper on instantiation. 19517 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() || 19518 Type->isInstantiationDependentType() || 19519 Type->containsUnexpandedParameterPack() || 19520 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) { 19521 return !D->isInvalidDecl() && 19522 (D->getType()->isDependentType() || 19523 D->getType()->isInstantiationDependentType() || 19524 D->getType()->containsUnexpandedParameterPack()); 19525 })) { 19526 UnresolvedSet<8> URS; 19527 for (const UnresolvedSet<8> &Set : Lookups) { 19528 if (Set.empty()) 19529 continue; 19530 URS.append(Set.begin(), Set.end()); 19531 } 19532 return UnresolvedLookupExpr::Create( 19533 SemaRef.Context, /*NamingClass=*/nullptr, 19534 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId, 19535 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end()); 19536 } 19537 SourceLocation Loc = MapperId.getLoc(); 19538 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 19539 // The type must be of struct, union or class type in C and C++ 19540 if (!Type->isStructureOrClassType() && !Type->isUnionType() && 19541 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) { 19542 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type); 19543 return ExprError(); 19544 } 19545 // Perform argument dependent lookup. 19546 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet()) 19547 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups); 19548 // Return the first user-defined mapper with the desired type. 19549 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 19550 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * { 19551 if (!D->isInvalidDecl() && 19552 SemaRef.Context.hasSameType(D->getType(), Type)) 19553 return D; 19554 return nullptr; 19555 })) 19556 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 19557 // Find the first user-defined mapper with a type derived from the desired 19558 // type. 19559 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>( 19560 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * { 19561 if (!D->isInvalidDecl() && 19562 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) && 19563 !Type.isMoreQualifiedThan(D->getType())) 19564 return D; 19565 return nullptr; 19566 })) { 19567 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 19568 /*DetectVirtual=*/false); 19569 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) { 19570 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 19571 VD->getType().getUnqualifiedType()))) { 19572 if (SemaRef.CheckBaseClassAccess( 19573 Loc, VD->getType(), Type, Paths.front(), 19574 /*DiagID=*/0) != Sema::AR_inaccessible) { 19575 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc); 19576 } 19577 } 19578 } 19579 } 19580 // Report error if a mapper is specified, but cannot be found. 19581 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") { 19582 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper) 19583 << Type << MapperId.getName(); 19584 return ExprError(); 19585 } 19586 return ExprEmpty(); 19587 } 19588 19589 namespace { 19590 // Utility struct that gathers all the related lists associated with a mappable 19591 // expression. 19592 struct MappableVarListInfo { 19593 // The list of expressions. 19594 ArrayRef<Expr *> VarList; 19595 // The list of processed expressions. 19596 SmallVector<Expr *, 16> ProcessedVarList; 19597 // The mappble components for each expression. 19598 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 19599 // The base declaration of the variable. 19600 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 19601 // The reference to the user-defined mapper associated with every expression. 19602 SmallVector<Expr *, 16> UDMapperList; 19603 19604 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 19605 // We have a list of components and base declarations for each entry in the 19606 // variable list. 19607 VarComponents.reserve(VarList.size()); 19608 VarBaseDeclarations.reserve(VarList.size()); 19609 } 19610 }; 19611 } 19612 19613 // Check the validity of the provided variable list for the provided clause kind 19614 // \a CKind. In the check process the valid expressions, mappable expression 19615 // components, variables, and user-defined mappers are extracted and used to 19616 // fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a 19617 // UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec, 19618 // and \a MapperId are expected to be valid if the clause kind is 'map'. 19619 static void checkMappableExpressionList( 19620 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind, 19621 MappableVarListInfo &MVLI, SourceLocation StartLoc, 19622 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId, 19623 ArrayRef<Expr *> UnresolvedMappers, 19624 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 19625 ArrayRef<OpenMPMapModifierKind> Modifiers = None, 19626 bool IsMapTypeImplicit = false, bool NoDiagnose = false) { 19627 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 19628 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 19629 "Unexpected clause kind with mappable expressions!"); 19630 19631 // If the identifier of user-defined mapper is not specified, it is "default". 19632 // We do not change the actual name in this clause to distinguish whether a 19633 // mapper is specified explicitly, i.e., it is not explicitly specified when 19634 // MapperId.getName() is empty. 19635 if (!MapperId.getName() || MapperId.getName().isEmpty()) { 19636 auto &DeclNames = SemaRef.getASTContext().DeclarationNames; 19637 MapperId.setName(DeclNames.getIdentifier( 19638 &SemaRef.getASTContext().Idents.get("default"))); 19639 MapperId.setLoc(StartLoc); 19640 } 19641 19642 // Iterators to find the current unresolved mapper expression. 19643 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end(); 19644 bool UpdateUMIt = false; 19645 Expr *UnresolvedMapper = nullptr; 19646 19647 bool HasHoldModifier = 19648 llvm::is_contained(Modifiers, OMPC_MAP_MODIFIER_ompx_hold); 19649 19650 // Keep track of the mappable components and base declarations in this clause. 19651 // Each entry in the list is going to have a list of components associated. We 19652 // record each set of the components so that we can build the clause later on. 19653 // In the end we should have the same amount of declarations and component 19654 // lists. 19655 19656 for (Expr *RE : MVLI.VarList) { 19657 assert(RE && "Null expr in omp to/from/map clause"); 19658 SourceLocation ELoc = RE->getExprLoc(); 19659 19660 // Find the current unresolved mapper expression. 19661 if (UpdateUMIt && UMIt != UMEnd) { 19662 UMIt++; 19663 assert( 19664 UMIt != UMEnd && 19665 "Expect the size of UnresolvedMappers to match with that of VarList"); 19666 } 19667 UpdateUMIt = true; 19668 if (UMIt != UMEnd) 19669 UnresolvedMapper = *UMIt; 19670 19671 const Expr *VE = RE->IgnoreParenLValueCasts(); 19672 19673 if (VE->isValueDependent() || VE->isTypeDependent() || 19674 VE->isInstantiationDependent() || 19675 VE->containsUnexpandedParameterPack()) { 19676 // Try to find the associated user-defined mapper. 19677 ExprResult ER = buildUserDefinedMapperRef( 19678 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 19679 VE->getType().getCanonicalType(), UnresolvedMapper); 19680 if (ER.isInvalid()) 19681 continue; 19682 MVLI.UDMapperList.push_back(ER.get()); 19683 // We can only analyze this information once the missing information is 19684 // resolved. 19685 MVLI.ProcessedVarList.push_back(RE); 19686 continue; 19687 } 19688 19689 Expr *SimpleExpr = RE->IgnoreParenCasts(); 19690 19691 if (!RE->isLValue()) { 19692 if (SemaRef.getLangOpts().OpenMP < 50) { 19693 SemaRef.Diag( 19694 ELoc, diag::err_omp_expected_named_var_member_or_array_expression) 19695 << RE->getSourceRange(); 19696 } else { 19697 SemaRef.Diag(ELoc, diag::err_omp_non_lvalue_in_map_or_motion_clauses) 19698 << getOpenMPClauseName(CKind) << RE->getSourceRange(); 19699 } 19700 continue; 19701 } 19702 19703 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 19704 ValueDecl *CurDeclaration = nullptr; 19705 19706 // Obtain the array or member expression bases if required. Also, fill the 19707 // components array with all the components identified in the process. 19708 const Expr *BE = 19709 checkMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind, 19710 DSAS->getCurrentDirective(), NoDiagnose); 19711 if (!BE) 19712 continue; 19713 19714 assert(!CurComponents.empty() && 19715 "Invalid mappable expression information."); 19716 19717 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) { 19718 // Add store "this" pointer to class in DSAStackTy for future checking 19719 DSAS->addMappedClassesQualTypes(TE->getType()); 19720 // Try to find the associated user-defined mapper. 19721 ExprResult ER = buildUserDefinedMapperRef( 19722 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 19723 VE->getType().getCanonicalType(), UnresolvedMapper); 19724 if (ER.isInvalid()) 19725 continue; 19726 MVLI.UDMapperList.push_back(ER.get()); 19727 // Skip restriction checking for variable or field declarations 19728 MVLI.ProcessedVarList.push_back(RE); 19729 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 19730 MVLI.VarComponents.back().append(CurComponents.begin(), 19731 CurComponents.end()); 19732 MVLI.VarBaseDeclarations.push_back(nullptr); 19733 continue; 19734 } 19735 19736 // For the following checks, we rely on the base declaration which is 19737 // expected to be associated with the last component. The declaration is 19738 // expected to be a variable or a field (if 'this' is being mapped). 19739 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 19740 assert(CurDeclaration && "Null decl on map clause."); 19741 assert( 19742 CurDeclaration->isCanonicalDecl() && 19743 "Expecting components to have associated only canonical declarations."); 19744 19745 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 19746 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 19747 19748 assert((VD || FD) && "Only variables or fields are expected here!"); 19749 (void)FD; 19750 19751 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 19752 // threadprivate variables cannot appear in a map clause. 19753 // OpenMP 4.5 [2.10.5, target update Construct] 19754 // threadprivate variables cannot appear in a from clause. 19755 if (VD && DSAS->isThreadPrivate(VD)) { 19756 if (NoDiagnose) 19757 continue; 19758 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 19759 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 19760 << getOpenMPClauseName(CKind); 19761 reportOriginalDsa(SemaRef, DSAS, VD, DVar); 19762 continue; 19763 } 19764 19765 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 19766 // A list item cannot appear in both a map clause and a data-sharing 19767 // attribute clause on the same construct. 19768 19769 // Check conflicts with other map clause expressions. We check the conflicts 19770 // with the current construct separately from the enclosing data 19771 // environment, because the restrictions are different. We only have to 19772 // check conflicts across regions for the map clauses. 19773 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 19774 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 19775 break; 19776 if (CKind == OMPC_map && 19777 (SemaRef.getLangOpts().OpenMP <= 45 || StartLoc.isValid()) && 19778 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 19779 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 19780 break; 19781 19782 // OpenMP 4.5 [2.10.5, target update Construct] 19783 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 19784 // If the type of a list item is a reference to a type T then the type will 19785 // be considered to be T for all purposes of this clause. 19786 auto I = llvm::find_if( 19787 CurComponents, 19788 [](const OMPClauseMappableExprCommon::MappableComponent &MC) { 19789 return MC.getAssociatedDeclaration(); 19790 }); 19791 assert(I != CurComponents.end() && "Null decl on map clause."); 19792 (void)I; 19793 QualType Type; 19794 auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens()); 19795 auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens()); 19796 auto *OAShE = dyn_cast<OMPArrayShapingExpr>(VE->IgnoreParens()); 19797 if (ASE) { 19798 Type = ASE->getType().getNonReferenceType(); 19799 } else if (OASE) { 19800 QualType BaseType = 19801 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 19802 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 19803 Type = ATy->getElementType(); 19804 else 19805 Type = BaseType->getPointeeType(); 19806 Type = Type.getNonReferenceType(); 19807 } else if (OAShE) { 19808 Type = OAShE->getBase()->getType()->getPointeeType(); 19809 } else { 19810 Type = VE->getType(); 19811 } 19812 19813 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 19814 // A list item in a to or from clause must have a mappable type. 19815 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 19816 // A list item must have a mappable type. 19817 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 19818 DSAS, Type, /*FullCheck=*/true)) 19819 continue; 19820 19821 if (CKind == OMPC_map) { 19822 // target enter data 19823 // OpenMP [2.10.2, Restrictions, p. 99] 19824 // A map-type must be specified in all map clauses and must be either 19825 // to or alloc. 19826 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 19827 if (DKind == OMPD_target_enter_data && 19828 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 19829 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 19830 << (IsMapTypeImplicit ? 1 : 0) 19831 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 19832 << getOpenMPDirectiveName(DKind); 19833 continue; 19834 } 19835 19836 // target exit_data 19837 // OpenMP [2.10.3, Restrictions, p. 102] 19838 // A map-type must be specified in all map clauses and must be either 19839 // from, release, or delete. 19840 if (DKind == OMPD_target_exit_data && 19841 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 19842 MapType == OMPC_MAP_delete)) { 19843 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 19844 << (IsMapTypeImplicit ? 1 : 0) 19845 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 19846 << getOpenMPDirectiveName(DKind); 19847 continue; 19848 } 19849 19850 // The 'ompx_hold' modifier is specifically intended to be used on a 19851 // 'target' or 'target data' directive to prevent data from being unmapped 19852 // during the associated statement. It is not permitted on a 'target 19853 // enter data' or 'target exit data' directive, which have no associated 19854 // statement. 19855 if ((DKind == OMPD_target_enter_data || DKind == OMPD_target_exit_data) && 19856 HasHoldModifier) { 19857 SemaRef.Diag(StartLoc, 19858 diag::err_omp_invalid_map_type_modifier_for_directive) 19859 << getOpenMPSimpleClauseTypeName(OMPC_map, 19860 OMPC_MAP_MODIFIER_ompx_hold) 19861 << getOpenMPDirectiveName(DKind); 19862 continue; 19863 } 19864 19865 // target, target data 19866 // OpenMP 5.0 [2.12.2, Restrictions, p. 163] 19867 // OpenMP 5.0 [2.12.5, Restrictions, p. 174] 19868 // A map-type in a map clause must be to, from, tofrom or alloc 19869 if ((DKind == OMPD_target_data || 19870 isOpenMPTargetExecutionDirective(DKind)) && 19871 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_from || 19872 MapType == OMPC_MAP_tofrom || MapType == OMPC_MAP_alloc)) { 19873 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 19874 << (IsMapTypeImplicit ? 1 : 0) 19875 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 19876 << getOpenMPDirectiveName(DKind); 19877 continue; 19878 } 19879 19880 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 19881 // A list item cannot appear in both a map clause and a data-sharing 19882 // attribute clause on the same construct 19883 // 19884 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7] 19885 // A list item cannot appear in both a map clause and a data-sharing 19886 // attribute clause on the same construct unless the construct is a 19887 // combined construct. 19888 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 && 19889 isOpenMPTargetExecutionDirective(DKind)) || 19890 DKind == OMPD_target)) { 19891 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 19892 if (isOpenMPPrivate(DVar.CKind)) { 19893 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 19894 << getOpenMPClauseName(DVar.CKind) 19895 << getOpenMPClauseName(OMPC_map) 19896 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 19897 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar); 19898 continue; 19899 } 19900 } 19901 } 19902 19903 // Try to find the associated user-defined mapper. 19904 ExprResult ER = buildUserDefinedMapperRef( 19905 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId, 19906 Type.getCanonicalType(), UnresolvedMapper); 19907 if (ER.isInvalid()) 19908 continue; 19909 MVLI.UDMapperList.push_back(ER.get()); 19910 19911 // Save the current expression. 19912 MVLI.ProcessedVarList.push_back(RE); 19913 19914 // Store the components in the stack so that they can be used to check 19915 // against other clauses later on. 19916 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 19917 /*WhereFoundClauseKind=*/OMPC_map); 19918 19919 // Save the components and declaration to create the clause. For purposes of 19920 // the clause creation, any component list that has has base 'this' uses 19921 // null as base declaration. 19922 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 19923 MVLI.VarComponents.back().append(CurComponents.begin(), 19924 CurComponents.end()); 19925 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 19926 : CurDeclaration); 19927 } 19928 } 19929 19930 OMPClause *Sema::ActOnOpenMPMapClause( 19931 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 19932 ArrayRef<SourceLocation> MapTypeModifiersLoc, 19933 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 19934 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc, 19935 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 19936 const OMPVarListLocTy &Locs, bool NoDiagnose, 19937 ArrayRef<Expr *> UnresolvedMappers) { 19938 OpenMPMapModifierKind Modifiers[] = { 19939 OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown, 19940 OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown, 19941 OMPC_MAP_MODIFIER_unknown}; 19942 SourceLocation ModifiersLoc[NumberOfOMPMapClauseModifiers]; 19943 19944 // Process map-type-modifiers, flag errors for duplicate modifiers. 19945 unsigned Count = 0; 19946 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) { 19947 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown && 19948 llvm::is_contained(Modifiers, MapTypeModifiers[I])) { 19949 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier); 19950 continue; 19951 } 19952 assert(Count < NumberOfOMPMapClauseModifiers && 19953 "Modifiers exceed the allowed number of map type modifiers"); 19954 Modifiers[Count] = MapTypeModifiers[I]; 19955 ModifiersLoc[Count] = MapTypeModifiersLoc[I]; 19956 ++Count; 19957 } 19958 19959 MappableVarListInfo MVLI(VarList); 19960 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc, 19961 MapperIdScopeSpec, MapperId, UnresolvedMappers, 19962 MapType, Modifiers, IsMapTypeImplicit, 19963 NoDiagnose); 19964 19965 // We need to produce a map clause even if we don't have variables so that 19966 // other diagnostics related with non-existing map clauses are accurate. 19967 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList, 19968 MVLI.VarBaseDeclarations, MVLI.VarComponents, 19969 MVLI.UDMapperList, Modifiers, ModifiersLoc, 19970 MapperIdScopeSpec.getWithLocInContext(Context), 19971 MapperId, MapType, IsMapTypeImplicit, MapLoc); 19972 } 19973 19974 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 19975 TypeResult ParsedType) { 19976 assert(ParsedType.isUsable()); 19977 19978 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 19979 if (ReductionType.isNull()) 19980 return QualType(); 19981 19982 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 19983 // A type name in a declare reduction directive cannot be a function type, an 19984 // array type, a reference type, or a type qualified with const, volatile or 19985 // restrict. 19986 if (ReductionType.hasQualifiers()) { 19987 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 19988 return QualType(); 19989 } 19990 19991 if (ReductionType->isFunctionType()) { 19992 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 19993 return QualType(); 19994 } 19995 if (ReductionType->isReferenceType()) { 19996 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 19997 return QualType(); 19998 } 19999 if (ReductionType->isArrayType()) { 20000 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 20001 return QualType(); 20002 } 20003 return ReductionType; 20004 } 20005 20006 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 20007 Scope *S, DeclContext *DC, DeclarationName Name, 20008 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 20009 AccessSpecifier AS, Decl *PrevDeclInScope) { 20010 SmallVector<Decl *, 8> Decls; 20011 Decls.reserve(ReductionTypes.size()); 20012 20013 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 20014 forRedeclarationInCurContext()); 20015 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 20016 // A reduction-identifier may not be re-declared in the current scope for the 20017 // same type or for a type that is compatible according to the base language 20018 // rules. 20019 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 20020 OMPDeclareReductionDecl *PrevDRD = nullptr; 20021 bool InCompoundScope = true; 20022 if (S != nullptr) { 20023 // Find previous declaration with the same name not referenced in other 20024 // declarations. 20025 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 20026 InCompoundScope = 20027 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 20028 LookupName(Lookup, S); 20029 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 20030 /*AllowInlineNamespace=*/false); 20031 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 20032 LookupResult::Filter Filter = Lookup.makeFilter(); 20033 while (Filter.hasNext()) { 20034 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 20035 if (InCompoundScope) { 20036 auto I = UsedAsPrevious.find(PrevDecl); 20037 if (I == UsedAsPrevious.end()) 20038 UsedAsPrevious[PrevDecl] = false; 20039 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope()) 20040 UsedAsPrevious[D] = true; 20041 } 20042 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 20043 PrevDecl->getLocation(); 20044 } 20045 Filter.done(); 20046 if (InCompoundScope) { 20047 for (const auto &PrevData : UsedAsPrevious) { 20048 if (!PrevData.second) { 20049 PrevDRD = PrevData.first; 20050 break; 20051 } 20052 } 20053 } 20054 } else if (PrevDeclInScope != nullptr) { 20055 auto *PrevDRDInScope = PrevDRD = 20056 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 20057 do { 20058 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 20059 PrevDRDInScope->getLocation(); 20060 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 20061 } while (PrevDRDInScope != nullptr); 20062 } 20063 for (const auto &TyData : ReductionTypes) { 20064 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 20065 bool Invalid = false; 20066 if (I != PreviousRedeclTypes.end()) { 20067 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 20068 << TyData.first; 20069 Diag(I->second, diag::note_previous_definition); 20070 Invalid = true; 20071 } 20072 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 20073 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 20074 Name, TyData.first, PrevDRD); 20075 DC->addDecl(DRD); 20076 DRD->setAccess(AS); 20077 Decls.push_back(DRD); 20078 if (Invalid) 20079 DRD->setInvalidDecl(); 20080 else 20081 PrevDRD = DRD; 20082 } 20083 20084 return DeclGroupPtrTy::make( 20085 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 20086 } 20087 20088 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 20089 auto *DRD = cast<OMPDeclareReductionDecl>(D); 20090 20091 // Enter new function scope. 20092 PushFunctionScope(); 20093 setFunctionHasBranchProtectedScope(); 20094 getCurFunction()->setHasOMPDeclareReductionCombiner(); 20095 20096 if (S != nullptr) 20097 PushDeclContext(S, DRD); 20098 else 20099 CurContext = DRD; 20100 20101 PushExpressionEvaluationContext( 20102 ExpressionEvaluationContext::PotentiallyEvaluated); 20103 20104 QualType ReductionType = DRD->getType(); 20105 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 20106 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 20107 // uses semantics of argument handles by value, but it should be passed by 20108 // reference. C lang does not support references, so pass all parameters as 20109 // pointers. 20110 // Create 'T omp_in;' variable. 20111 VarDecl *OmpInParm = 20112 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 20113 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 20114 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 20115 // uses semantics of argument handles by value, but it should be passed by 20116 // reference. C lang does not support references, so pass all parameters as 20117 // pointers. 20118 // Create 'T omp_out;' variable. 20119 VarDecl *OmpOutParm = 20120 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 20121 if (S != nullptr) { 20122 PushOnScopeChains(OmpInParm, S); 20123 PushOnScopeChains(OmpOutParm, S); 20124 } else { 20125 DRD->addDecl(OmpInParm); 20126 DRD->addDecl(OmpOutParm); 20127 } 20128 Expr *InE = 20129 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation()); 20130 Expr *OutE = 20131 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation()); 20132 DRD->setCombinerData(InE, OutE); 20133 } 20134 20135 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 20136 auto *DRD = cast<OMPDeclareReductionDecl>(D); 20137 DiscardCleanupsInEvaluationContext(); 20138 PopExpressionEvaluationContext(); 20139 20140 PopDeclContext(); 20141 PopFunctionScopeInfo(); 20142 20143 if (Combiner != nullptr) 20144 DRD->setCombiner(Combiner); 20145 else 20146 DRD->setInvalidDecl(); 20147 } 20148 20149 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 20150 auto *DRD = cast<OMPDeclareReductionDecl>(D); 20151 20152 // Enter new function scope. 20153 PushFunctionScope(); 20154 setFunctionHasBranchProtectedScope(); 20155 20156 if (S != nullptr) 20157 PushDeclContext(S, DRD); 20158 else 20159 CurContext = DRD; 20160 20161 PushExpressionEvaluationContext( 20162 ExpressionEvaluationContext::PotentiallyEvaluated); 20163 20164 QualType ReductionType = DRD->getType(); 20165 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 20166 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 20167 // uses semantics of argument handles by value, but it should be passed by 20168 // reference. C lang does not support references, so pass all parameters as 20169 // pointers. 20170 // Create 'T omp_priv;' variable. 20171 VarDecl *OmpPrivParm = 20172 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 20173 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 20174 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 20175 // uses semantics of argument handles by value, but it should be passed by 20176 // reference. C lang does not support references, so pass all parameters as 20177 // pointers. 20178 // Create 'T omp_orig;' variable. 20179 VarDecl *OmpOrigParm = 20180 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 20181 if (S != nullptr) { 20182 PushOnScopeChains(OmpPrivParm, S); 20183 PushOnScopeChains(OmpOrigParm, S); 20184 } else { 20185 DRD->addDecl(OmpPrivParm); 20186 DRD->addDecl(OmpOrigParm); 20187 } 20188 Expr *OrigE = 20189 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation()); 20190 Expr *PrivE = 20191 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation()); 20192 DRD->setInitializerData(OrigE, PrivE); 20193 return OmpPrivParm; 20194 } 20195 20196 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 20197 VarDecl *OmpPrivParm) { 20198 auto *DRD = cast<OMPDeclareReductionDecl>(D); 20199 DiscardCleanupsInEvaluationContext(); 20200 PopExpressionEvaluationContext(); 20201 20202 PopDeclContext(); 20203 PopFunctionScopeInfo(); 20204 20205 if (Initializer != nullptr) { 20206 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit); 20207 } else if (OmpPrivParm->hasInit()) { 20208 DRD->setInitializer(OmpPrivParm->getInit(), 20209 OmpPrivParm->isDirectInit() 20210 ? OMPDeclareReductionDecl::DirectInit 20211 : OMPDeclareReductionDecl::CopyInit); 20212 } else { 20213 DRD->setInvalidDecl(); 20214 } 20215 } 20216 20217 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 20218 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 20219 for (Decl *D : DeclReductions.get()) { 20220 if (IsValid) { 20221 if (S) 20222 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S, 20223 /*AddToContext=*/false); 20224 } else { 20225 D->setInvalidDecl(); 20226 } 20227 } 20228 return DeclReductions; 20229 } 20230 20231 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) { 20232 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 20233 QualType T = TInfo->getType(); 20234 if (D.isInvalidType()) 20235 return true; 20236 20237 if (getLangOpts().CPlusPlus) { 20238 // Check that there are no default arguments (C++ only). 20239 CheckExtraCXXDefaultArguments(D); 20240 } 20241 20242 return CreateParsedType(T, TInfo); 20243 } 20244 20245 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, 20246 TypeResult ParsedType) { 20247 assert(ParsedType.isUsable() && "Expect usable parsed mapper type"); 20248 20249 QualType MapperType = GetTypeFromParser(ParsedType.get()); 20250 assert(!MapperType.isNull() && "Expect valid mapper type"); 20251 20252 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 20253 // The type must be of struct, union or class type in C and C++ 20254 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) { 20255 Diag(TyLoc, diag::err_omp_mapper_wrong_type); 20256 return QualType(); 20257 } 20258 return MapperType; 20259 } 20260 20261 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareMapperDirective( 20262 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, 20263 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, 20264 Expr *MapperVarRef, ArrayRef<OMPClause *> Clauses, Decl *PrevDeclInScope) { 20265 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName, 20266 forRedeclarationInCurContext()); 20267 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 20268 // A mapper-identifier may not be redeclared in the current scope for the 20269 // same type or for a type that is compatible according to the base language 20270 // rules. 20271 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 20272 OMPDeclareMapperDecl *PrevDMD = nullptr; 20273 bool InCompoundScope = true; 20274 if (S != nullptr) { 20275 // Find previous declaration with the same name not referenced in other 20276 // declarations. 20277 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 20278 InCompoundScope = 20279 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 20280 LookupName(Lookup, S); 20281 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 20282 /*AllowInlineNamespace=*/false); 20283 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious; 20284 LookupResult::Filter Filter = Lookup.makeFilter(); 20285 while (Filter.hasNext()) { 20286 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next()); 20287 if (InCompoundScope) { 20288 auto I = UsedAsPrevious.find(PrevDecl); 20289 if (I == UsedAsPrevious.end()) 20290 UsedAsPrevious[PrevDecl] = false; 20291 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope()) 20292 UsedAsPrevious[D] = true; 20293 } 20294 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 20295 PrevDecl->getLocation(); 20296 } 20297 Filter.done(); 20298 if (InCompoundScope) { 20299 for (const auto &PrevData : UsedAsPrevious) { 20300 if (!PrevData.second) { 20301 PrevDMD = PrevData.first; 20302 break; 20303 } 20304 } 20305 } 20306 } else if (PrevDeclInScope) { 20307 auto *PrevDMDInScope = PrevDMD = 20308 cast<OMPDeclareMapperDecl>(PrevDeclInScope); 20309 do { 20310 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] = 20311 PrevDMDInScope->getLocation(); 20312 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope(); 20313 } while (PrevDMDInScope != nullptr); 20314 } 20315 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType()); 20316 bool Invalid = false; 20317 if (I != PreviousRedeclTypes.end()) { 20318 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition) 20319 << MapperType << Name; 20320 Diag(I->second, diag::note_previous_definition); 20321 Invalid = true; 20322 } 20323 // Build expressions for implicit maps of data members with 'default' 20324 // mappers. 20325 SmallVector<OMPClause *, 4> ClausesWithImplicit(Clauses.begin(), 20326 Clauses.end()); 20327 if (LangOpts.OpenMP >= 50) 20328 processImplicitMapsWithDefaultMappers(*this, DSAStack, ClausesWithImplicit); 20329 auto *DMD = 20330 OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, MapperType, VN, 20331 ClausesWithImplicit, PrevDMD); 20332 if (S) 20333 PushOnScopeChains(DMD, S); 20334 else 20335 DC->addDecl(DMD); 20336 DMD->setAccess(AS); 20337 if (Invalid) 20338 DMD->setInvalidDecl(); 20339 20340 auto *VD = cast<DeclRefExpr>(MapperVarRef)->getDecl(); 20341 VD->setDeclContext(DMD); 20342 VD->setLexicalDeclContext(DMD); 20343 DMD->addDecl(VD); 20344 DMD->setMapperVarRef(MapperVarRef); 20345 20346 return DeclGroupPtrTy::make(DeclGroupRef(DMD)); 20347 } 20348 20349 ExprResult 20350 Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(Scope *S, QualType MapperType, 20351 SourceLocation StartLoc, 20352 DeclarationName VN) { 20353 TypeSourceInfo *TInfo = 20354 Context.getTrivialTypeSourceInfo(MapperType, StartLoc); 20355 auto *VD = VarDecl::Create(Context, Context.getTranslationUnitDecl(), 20356 StartLoc, StartLoc, VN.getAsIdentifierInfo(), 20357 MapperType, TInfo, SC_None); 20358 if (S) 20359 PushOnScopeChains(VD, S, /*AddToContext=*/false); 20360 Expr *E = buildDeclRefExpr(*this, VD, MapperType, StartLoc); 20361 DSAStack->addDeclareMapperVarRef(E); 20362 return E; 20363 } 20364 20365 bool Sema::isOpenMPDeclareMapperVarDeclAllowed(const VarDecl *VD) const { 20366 assert(LangOpts.OpenMP && "Expected OpenMP mode."); 20367 const Expr *Ref = DSAStack->getDeclareMapperVarRef(); 20368 if (const auto *DRE = cast_or_null<DeclRefExpr>(Ref)) { 20369 if (VD->getCanonicalDecl() == DRE->getDecl()->getCanonicalDecl()) 20370 return true; 20371 if (VD->isUsableInConstantExpressions(Context)) 20372 return true; 20373 return false; 20374 } 20375 return true; 20376 } 20377 20378 const ValueDecl *Sema::getOpenMPDeclareMapperVarName() const { 20379 assert(LangOpts.OpenMP && "Expected OpenMP mode."); 20380 return cast<DeclRefExpr>(DSAStack->getDeclareMapperVarRef())->getDecl(); 20381 } 20382 20383 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 20384 SourceLocation StartLoc, 20385 SourceLocation LParenLoc, 20386 SourceLocation EndLoc) { 20387 Expr *ValExpr = NumTeams; 20388 Stmt *HelperValStmt = nullptr; 20389 20390 // OpenMP [teams Constrcut, Restrictions] 20391 // The num_teams expression must evaluate to a positive integer value. 20392 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 20393 /*StrictlyPositive=*/true)) 20394 return nullptr; 20395 20396 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 20397 OpenMPDirectiveKind CaptureRegion = 20398 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP); 20399 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 20400 ValExpr = MakeFullExpr(ValExpr).get(); 20401 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 20402 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 20403 HelperValStmt = buildPreInits(Context, Captures); 20404 } 20405 20406 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 20407 StartLoc, LParenLoc, EndLoc); 20408 } 20409 20410 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 20411 SourceLocation StartLoc, 20412 SourceLocation LParenLoc, 20413 SourceLocation EndLoc) { 20414 Expr *ValExpr = ThreadLimit; 20415 Stmt *HelperValStmt = nullptr; 20416 20417 // OpenMP [teams Constrcut, Restrictions] 20418 // The thread_limit expression must evaluate to a positive integer value. 20419 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 20420 /*StrictlyPositive=*/true)) 20421 return nullptr; 20422 20423 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 20424 OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause( 20425 DKind, OMPC_thread_limit, LangOpts.OpenMP); 20426 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 20427 ValExpr = MakeFullExpr(ValExpr).get(); 20428 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 20429 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 20430 HelperValStmt = buildPreInits(Context, Captures); 20431 } 20432 20433 return new (Context) OMPThreadLimitClause( 20434 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 20435 } 20436 20437 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 20438 SourceLocation StartLoc, 20439 SourceLocation LParenLoc, 20440 SourceLocation EndLoc) { 20441 Expr *ValExpr = Priority; 20442 Stmt *HelperValStmt = nullptr; 20443 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 20444 20445 // OpenMP [2.9.1, task Constrcut] 20446 // The priority-value is a non-negative numerical scalar expression. 20447 if (!isNonNegativeIntegerValue( 20448 ValExpr, *this, OMPC_priority, 20449 /*StrictlyPositive=*/false, /*BuildCapture=*/true, 20450 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 20451 return nullptr; 20452 20453 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion, 20454 StartLoc, LParenLoc, EndLoc); 20455 } 20456 20457 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 20458 SourceLocation StartLoc, 20459 SourceLocation LParenLoc, 20460 SourceLocation EndLoc) { 20461 Expr *ValExpr = Grainsize; 20462 Stmt *HelperValStmt = nullptr; 20463 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 20464 20465 // OpenMP [2.9.2, taskloop Constrcut] 20466 // The parameter of the grainsize clause must be a positive integer 20467 // expression. 20468 if (!isNonNegativeIntegerValue( 20469 ValExpr, *this, OMPC_grainsize, 20470 /*StrictlyPositive=*/true, /*BuildCapture=*/true, 20471 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 20472 return nullptr; 20473 20474 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion, 20475 StartLoc, LParenLoc, EndLoc); 20476 } 20477 20478 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 20479 SourceLocation StartLoc, 20480 SourceLocation LParenLoc, 20481 SourceLocation EndLoc) { 20482 Expr *ValExpr = NumTasks; 20483 Stmt *HelperValStmt = nullptr; 20484 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 20485 20486 // OpenMP [2.9.2, taskloop Constrcut] 20487 // The parameter of the num_tasks clause must be a positive integer 20488 // expression. 20489 if (!isNonNegativeIntegerValue( 20490 ValExpr, *this, OMPC_num_tasks, 20491 /*StrictlyPositive=*/true, /*BuildCapture=*/true, 20492 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt)) 20493 return nullptr; 20494 20495 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion, 20496 StartLoc, LParenLoc, EndLoc); 20497 } 20498 20499 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 20500 SourceLocation LParenLoc, 20501 SourceLocation EndLoc) { 20502 // OpenMP [2.13.2, critical construct, Description] 20503 // ... where hint-expression is an integer constant expression that evaluates 20504 // to a valid lock hint. 20505 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 20506 if (HintExpr.isInvalid()) 20507 return nullptr; 20508 return new (Context) 20509 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 20510 } 20511 20512 /// Tries to find omp_event_handle_t type. 20513 static bool findOMPEventHandleT(Sema &S, SourceLocation Loc, 20514 DSAStackTy *Stack) { 20515 QualType OMPEventHandleT = Stack->getOMPEventHandleT(); 20516 if (!OMPEventHandleT.isNull()) 20517 return true; 20518 IdentifierInfo *II = &S.PP.getIdentifierTable().get("omp_event_handle_t"); 20519 ParsedType PT = S.getTypeName(*II, Loc, S.getCurScope()); 20520 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 20521 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_event_handle_t"; 20522 return false; 20523 } 20524 Stack->setOMPEventHandleT(PT.get()); 20525 return true; 20526 } 20527 20528 OMPClause *Sema::ActOnOpenMPDetachClause(Expr *Evt, SourceLocation StartLoc, 20529 SourceLocation LParenLoc, 20530 SourceLocation EndLoc) { 20531 if (!Evt->isValueDependent() && !Evt->isTypeDependent() && 20532 !Evt->isInstantiationDependent() && 20533 !Evt->containsUnexpandedParameterPack()) { 20534 if (!findOMPEventHandleT(*this, Evt->getExprLoc(), DSAStack)) 20535 return nullptr; 20536 // OpenMP 5.0, 2.10.1 task Construct. 20537 // event-handle is a variable of the omp_event_handle_t type. 20538 auto *Ref = dyn_cast<DeclRefExpr>(Evt->IgnoreParenImpCasts()); 20539 if (!Ref) { 20540 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 20541 << "omp_event_handle_t" << 0 << Evt->getSourceRange(); 20542 return nullptr; 20543 } 20544 auto *VD = dyn_cast_or_null<VarDecl>(Ref->getDecl()); 20545 if (!VD) { 20546 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 20547 << "omp_event_handle_t" << 0 << Evt->getSourceRange(); 20548 return nullptr; 20549 } 20550 if (!Context.hasSameUnqualifiedType(DSAStack->getOMPEventHandleT(), 20551 VD->getType()) || 20552 VD->getType().isConstant(Context)) { 20553 Diag(Evt->getExprLoc(), diag::err_omp_var_expected) 20554 << "omp_event_handle_t" << 1 << VD->getType() 20555 << Evt->getSourceRange(); 20556 return nullptr; 20557 } 20558 // OpenMP 5.0, 2.10.1 task Construct 20559 // [detach clause]... The event-handle will be considered as if it was 20560 // specified on a firstprivate clause. 20561 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(VD, /*FromParent=*/false); 20562 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 20563 DVar.RefExpr) { 20564 Diag(Evt->getExprLoc(), diag::err_omp_wrong_dsa) 20565 << getOpenMPClauseName(DVar.CKind) 20566 << getOpenMPClauseName(OMPC_firstprivate); 20567 reportOriginalDsa(*this, DSAStack, VD, DVar); 20568 return nullptr; 20569 } 20570 } 20571 20572 return new (Context) OMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc); 20573 } 20574 20575 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 20576 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 20577 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 20578 SourceLocation EndLoc) { 20579 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 20580 std::string Values; 20581 Values += "'"; 20582 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 20583 Values += "'"; 20584 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 20585 << Values << getOpenMPClauseName(OMPC_dist_schedule); 20586 return nullptr; 20587 } 20588 Expr *ValExpr = ChunkSize; 20589 Stmt *HelperValStmt = nullptr; 20590 if (ChunkSize) { 20591 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 20592 !ChunkSize->isInstantiationDependent() && 20593 !ChunkSize->containsUnexpandedParameterPack()) { 20594 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 20595 ExprResult Val = 20596 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 20597 if (Val.isInvalid()) 20598 return nullptr; 20599 20600 ValExpr = Val.get(); 20601 20602 // OpenMP [2.7.1, Restrictions] 20603 // chunk_size must be a loop invariant integer expression with a positive 20604 // value. 20605 if (Optional<llvm::APSInt> Result = 20606 ValExpr->getIntegerConstantExpr(Context)) { 20607 if (Result->isSigned() && !Result->isStrictlyPositive()) { 20608 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 20609 << "dist_schedule" << ChunkSize->getSourceRange(); 20610 return nullptr; 20611 } 20612 } else if (getOpenMPCaptureRegionForClause( 20613 DSAStack->getCurrentDirective(), OMPC_dist_schedule, 20614 LangOpts.OpenMP) != OMPD_unknown && 20615 !CurContext->isDependentContext()) { 20616 ValExpr = MakeFullExpr(ValExpr).get(); 20617 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 20618 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 20619 HelperValStmt = buildPreInits(Context, Captures); 20620 } 20621 } 20622 } 20623 20624 return new (Context) 20625 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 20626 Kind, ValExpr, HelperValStmt); 20627 } 20628 20629 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 20630 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 20631 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 20632 SourceLocation KindLoc, SourceLocation EndLoc) { 20633 if (getLangOpts().OpenMP < 50) { 20634 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || 20635 Kind != OMPC_DEFAULTMAP_scalar) { 20636 std::string Value; 20637 SourceLocation Loc; 20638 Value += "'"; 20639 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 20640 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 20641 OMPC_DEFAULTMAP_MODIFIER_tofrom); 20642 Loc = MLoc; 20643 } else { 20644 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 20645 OMPC_DEFAULTMAP_scalar); 20646 Loc = KindLoc; 20647 } 20648 Value += "'"; 20649 Diag(Loc, diag::err_omp_unexpected_clause_value) 20650 << Value << getOpenMPClauseName(OMPC_defaultmap); 20651 return nullptr; 20652 } 20653 } else { 20654 bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown); 20655 bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown) || 20656 (LangOpts.OpenMP >= 50 && KindLoc.isInvalid()); 20657 if (!isDefaultmapKind || !isDefaultmapModifier) { 20658 StringRef KindValue = "'scalar', 'aggregate', 'pointer'"; 20659 if (LangOpts.OpenMP == 50) { 20660 StringRef ModifierValue = "'alloc', 'from', 'to', 'tofrom', " 20661 "'firstprivate', 'none', 'default'"; 20662 if (!isDefaultmapKind && isDefaultmapModifier) { 20663 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 20664 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 20665 } else if (isDefaultmapKind && !isDefaultmapModifier) { 20666 Diag(MLoc, diag::err_omp_unexpected_clause_value) 20667 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 20668 } else { 20669 Diag(MLoc, diag::err_omp_unexpected_clause_value) 20670 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 20671 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 20672 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 20673 } 20674 } else { 20675 StringRef ModifierValue = 20676 "'alloc', 'from', 'to', 'tofrom', " 20677 "'firstprivate', 'none', 'default', 'present'"; 20678 if (!isDefaultmapKind && isDefaultmapModifier) { 20679 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 20680 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 20681 } else if (isDefaultmapKind && !isDefaultmapModifier) { 20682 Diag(MLoc, diag::err_omp_unexpected_clause_value) 20683 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 20684 } else { 20685 Diag(MLoc, diag::err_omp_unexpected_clause_value) 20686 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap); 20687 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 20688 << KindValue << getOpenMPClauseName(OMPC_defaultmap); 20689 } 20690 } 20691 return nullptr; 20692 } 20693 20694 // OpenMP [5.0, 2.12.5, Restrictions, p. 174] 20695 // At most one defaultmap clause for each category can appear on the 20696 // directive. 20697 if (DSAStack->checkDefaultmapCategory(Kind)) { 20698 Diag(StartLoc, diag::err_omp_one_defaultmap_each_category); 20699 return nullptr; 20700 } 20701 } 20702 if (Kind == OMPC_DEFAULTMAP_unknown) { 20703 // Variable category is not specified - mark all categories. 20704 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_aggregate, StartLoc); 20705 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_scalar, StartLoc); 20706 DSAStack->setDefaultDMAAttr(M, OMPC_DEFAULTMAP_pointer, StartLoc); 20707 } else { 20708 DSAStack->setDefaultDMAAttr(M, Kind, StartLoc); 20709 } 20710 20711 return new (Context) 20712 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 20713 } 20714 20715 bool Sema::ActOnStartOpenMPDeclareTargetContext( 20716 DeclareTargetContextInfo &DTCI) { 20717 DeclContext *CurLexicalContext = getCurLexicalContext(); 20718 if (!CurLexicalContext->isFileContext() && 20719 !CurLexicalContext->isExternCContext() && 20720 !CurLexicalContext->isExternCXXContext() && 20721 !isa<CXXRecordDecl>(CurLexicalContext) && 20722 !isa<ClassTemplateDecl>(CurLexicalContext) && 20723 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) && 20724 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) { 20725 Diag(DTCI.Loc, diag::err_omp_region_not_file_context); 20726 return false; 20727 } 20728 DeclareTargetNesting.push_back(DTCI); 20729 return true; 20730 } 20731 20732 const Sema::DeclareTargetContextInfo 20733 Sema::ActOnOpenMPEndDeclareTargetDirective() { 20734 assert(!DeclareTargetNesting.empty() && 20735 "check isInOpenMPDeclareTargetContext() first!"); 20736 return DeclareTargetNesting.pop_back_val(); 20737 } 20738 20739 void Sema::ActOnFinishedOpenMPDeclareTargetContext( 20740 DeclareTargetContextInfo &DTCI) { 20741 for (auto &It : DTCI.ExplicitlyMapped) 20742 ActOnOpenMPDeclareTargetName(It.first, It.second.Loc, It.second.MT, 20743 DTCI.DT); 20744 } 20745 20746 NamedDecl *Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, 20747 CXXScopeSpec &ScopeSpec, 20748 const DeclarationNameInfo &Id) { 20749 LookupResult Lookup(*this, Id, LookupOrdinaryName); 20750 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 20751 20752 if (Lookup.isAmbiguous()) 20753 return nullptr; 20754 Lookup.suppressDiagnostics(); 20755 20756 if (!Lookup.isSingleResult()) { 20757 VarOrFuncDeclFilterCCC CCC(*this); 20758 if (TypoCorrection Corrected = 20759 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC, 20760 CTK_ErrorRecovery)) { 20761 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 20762 << Id.getName()); 20763 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 20764 return nullptr; 20765 } 20766 20767 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 20768 return nullptr; 20769 } 20770 20771 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 20772 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) && 20773 !isa<FunctionTemplateDecl>(ND)) { 20774 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 20775 return nullptr; 20776 } 20777 return ND; 20778 } 20779 20780 void Sema::ActOnOpenMPDeclareTargetName( 20781 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT, 20782 OMPDeclareTargetDeclAttr::DevTypeTy DT) { 20783 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) || 20784 isa<FunctionTemplateDecl>(ND)) && 20785 "Expected variable, function or function template."); 20786 20787 // Diagnose marking after use as it may lead to incorrect diagnosis and 20788 // codegen. 20789 if (LangOpts.OpenMP >= 50 && 20790 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced())) 20791 Diag(Loc, diag::warn_omp_declare_target_after_first_use); 20792 20793 // Explicit declare target lists have precedence. 20794 const unsigned Level = -1; 20795 20796 auto *VD = cast<ValueDecl>(ND); 20797 llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 20798 OMPDeclareTargetDeclAttr::getActiveAttr(VD); 20799 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getDevType() != DT && 20800 ActiveAttr.getValue()->getLevel() == Level) { 20801 Diag(Loc, diag::err_omp_device_type_mismatch) 20802 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT) 20803 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr( 20804 ActiveAttr.getValue()->getDevType()); 20805 return; 20806 } 20807 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getMapType() != MT && 20808 ActiveAttr.getValue()->getLevel() == Level) { 20809 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND; 20810 return; 20811 } 20812 20813 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() == Level) 20814 return; 20815 20816 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT, Level, 20817 SourceRange(Loc, Loc)); 20818 ND->addAttr(A); 20819 if (ASTMutationListener *ML = Context.getASTMutationListener()) 20820 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 20821 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc); 20822 } 20823 20824 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 20825 Sema &SemaRef, Decl *D) { 20826 if (!D || !isa<VarDecl>(D)) 20827 return; 20828 auto *VD = cast<VarDecl>(D); 20829 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy = 20830 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 20831 if (SemaRef.LangOpts.OpenMP >= 50 && 20832 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) || 20833 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) && 20834 VD->hasGlobalStorage()) { 20835 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) { 20836 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions 20837 // If a lambda declaration and definition appears between a 20838 // declare target directive and the matching end declare target 20839 // directive, all variables that are captured by the lambda 20840 // expression must also appear in a to clause. 20841 SemaRef.Diag(VD->getLocation(), 20842 diag::err_omp_lambda_capture_in_declare_target_not_to); 20843 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here) 20844 << VD << 0 << SR; 20845 return; 20846 } 20847 } 20848 if (MapTy.hasValue()) 20849 return; 20850 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context); 20851 SemaRef.Diag(SL, diag::note_used_here) << SR; 20852 } 20853 20854 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 20855 Sema &SemaRef, DSAStackTy *Stack, 20856 ValueDecl *VD) { 20857 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) || 20858 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(), 20859 /*FullCheck=*/false); 20860 } 20861 20862 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 20863 SourceLocation IdLoc) { 20864 if (!D || D->isInvalidDecl()) 20865 return; 20866 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 20867 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation(); 20868 if (auto *VD = dyn_cast<VarDecl>(D)) { 20869 // Only global variables can be marked as declare target. 20870 if (!VD->isFileVarDecl() && !VD->isStaticLocal() && 20871 !VD->isStaticDataMember()) 20872 return; 20873 // 2.10.6: threadprivate variable cannot appear in a declare target 20874 // directive. 20875 if (DSAStack->isThreadPrivate(VD)) { 20876 Diag(SL, diag::err_omp_threadprivate_in_target); 20877 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 20878 return; 20879 } 20880 } 20881 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) 20882 D = FTD->getTemplatedDecl(); 20883 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 20884 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 20885 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD); 20886 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) { 20887 Diag(IdLoc, diag::err_omp_function_in_link_clause); 20888 Diag(FD->getLocation(), diag::note_defined_here) << FD; 20889 return; 20890 } 20891 } 20892 if (auto *VD = dyn_cast<ValueDecl>(D)) { 20893 // Problem if any with var declared with incomplete type will be reported 20894 // as normal, so no need to check it here. 20895 if ((E || !VD->getType()->isIncompleteType()) && 20896 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) 20897 return; 20898 if (!E && isInOpenMPDeclareTargetContext()) { 20899 // Checking declaration inside declare target region. 20900 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) || 20901 isa<FunctionTemplateDecl>(D)) { 20902 llvm::Optional<OMPDeclareTargetDeclAttr *> ActiveAttr = 20903 OMPDeclareTargetDeclAttr::getActiveAttr(VD); 20904 unsigned Level = DeclareTargetNesting.size(); 20905 if (ActiveAttr.hasValue() && ActiveAttr.getValue()->getLevel() >= Level) 20906 return; 20907 DeclareTargetContextInfo &DTCI = DeclareTargetNesting.back(); 20908 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit( 20909 Context, OMPDeclareTargetDeclAttr::MT_To, DTCI.DT, Level, 20910 SourceRange(DTCI.Loc, DTCI.Loc)); 20911 D->addAttr(A); 20912 if (ASTMutationListener *ML = Context.getASTMutationListener()) 20913 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 20914 } 20915 return; 20916 } 20917 } 20918 if (!E) 20919 return; 20920 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 20921 } 20922 20923 OMPClause *Sema::ActOnOpenMPToClause( 20924 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 20925 ArrayRef<SourceLocation> MotionModifiersLoc, 20926 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 20927 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 20928 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) { 20929 OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown, 20930 OMPC_MOTION_MODIFIER_unknown}; 20931 SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers]; 20932 20933 // Process motion-modifiers, flag errors for duplicate modifiers. 20934 unsigned Count = 0; 20935 for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) { 20936 if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown && 20937 llvm::is_contained(Modifiers, MotionModifiers[I])) { 20938 Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier); 20939 continue; 20940 } 20941 assert(Count < NumberOfOMPMotionModifiers && 20942 "Modifiers exceed the allowed number of motion modifiers"); 20943 Modifiers[Count] = MotionModifiers[I]; 20944 ModifiersLoc[Count] = MotionModifiersLoc[I]; 20945 ++Count; 20946 } 20947 20948 MappableVarListInfo MVLI(VarList); 20949 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc, 20950 MapperIdScopeSpec, MapperId, UnresolvedMappers); 20951 if (MVLI.ProcessedVarList.empty()) 20952 return nullptr; 20953 20954 return OMPToClause::Create( 20955 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 20956 MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc, 20957 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 20958 } 20959 20960 OMPClause *Sema::ActOnOpenMPFromClause( 20961 ArrayRef<OpenMPMotionModifierKind> MotionModifiers, 20962 ArrayRef<SourceLocation> MotionModifiersLoc, 20963 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId, 20964 SourceLocation ColonLoc, ArrayRef<Expr *> VarList, 20965 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) { 20966 OpenMPMotionModifierKind Modifiers[] = {OMPC_MOTION_MODIFIER_unknown, 20967 OMPC_MOTION_MODIFIER_unknown}; 20968 SourceLocation ModifiersLoc[NumberOfOMPMotionModifiers]; 20969 20970 // Process motion-modifiers, flag errors for duplicate modifiers. 20971 unsigned Count = 0; 20972 for (unsigned I = 0, E = MotionModifiers.size(); I < E; ++I) { 20973 if (MotionModifiers[I] != OMPC_MOTION_MODIFIER_unknown && 20974 llvm::is_contained(Modifiers, MotionModifiers[I])) { 20975 Diag(MotionModifiersLoc[I], diag::err_omp_duplicate_motion_modifier); 20976 continue; 20977 } 20978 assert(Count < NumberOfOMPMotionModifiers && 20979 "Modifiers exceed the allowed number of motion modifiers"); 20980 Modifiers[Count] = MotionModifiers[I]; 20981 ModifiersLoc[Count] = MotionModifiersLoc[I]; 20982 ++Count; 20983 } 20984 20985 MappableVarListInfo MVLI(VarList); 20986 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc, 20987 MapperIdScopeSpec, MapperId, UnresolvedMappers); 20988 if (MVLI.ProcessedVarList.empty()) 20989 return nullptr; 20990 20991 return OMPFromClause::Create( 20992 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 20993 MVLI.VarComponents, MVLI.UDMapperList, Modifiers, ModifiersLoc, 20994 MapperIdScopeSpec.getWithLocInContext(Context), MapperId); 20995 } 20996 20997 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 20998 const OMPVarListLocTy &Locs) { 20999 MappableVarListInfo MVLI(VarList); 21000 SmallVector<Expr *, 8> PrivateCopies; 21001 SmallVector<Expr *, 8> Inits; 21002 21003 for (Expr *RefExpr : VarList) { 21004 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 21005 SourceLocation ELoc; 21006 SourceRange ERange; 21007 Expr *SimpleRefExpr = RefExpr; 21008 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 21009 if (Res.second) { 21010 // It will be analyzed later. 21011 MVLI.ProcessedVarList.push_back(RefExpr); 21012 PrivateCopies.push_back(nullptr); 21013 Inits.push_back(nullptr); 21014 } 21015 ValueDecl *D = Res.first; 21016 if (!D) 21017 continue; 21018 21019 QualType Type = D->getType(); 21020 Type = Type.getNonReferenceType().getUnqualifiedType(); 21021 21022 auto *VD = dyn_cast<VarDecl>(D); 21023 21024 // Item should be a pointer or reference to pointer. 21025 if (!Type->isPointerType()) { 21026 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 21027 << 0 << RefExpr->getSourceRange(); 21028 continue; 21029 } 21030 21031 // Build the private variable and the expression that refers to it. 21032 auto VDPrivate = 21033 buildVarDecl(*this, ELoc, Type, D->getName(), 21034 D->hasAttrs() ? &D->getAttrs() : nullptr, 21035 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 21036 if (VDPrivate->isInvalidDecl()) 21037 continue; 21038 21039 CurContext->addDecl(VDPrivate); 21040 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 21041 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 21042 21043 // Add temporary variable to initialize the private copy of the pointer. 21044 VarDecl *VDInit = 21045 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 21046 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr( 21047 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc()); 21048 AddInitializerToDecl(VDPrivate, 21049 DefaultLvalueConversion(VDInitRefExpr).get(), 21050 /*DirectInit=*/false); 21051 21052 // If required, build a capture to implement the privatization initialized 21053 // with the current list item value. 21054 DeclRefExpr *Ref = nullptr; 21055 if (!VD) 21056 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 21057 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 21058 PrivateCopies.push_back(VDPrivateRefExpr); 21059 Inits.push_back(VDInitRefExpr); 21060 21061 // We need to add a data sharing attribute for this variable to make sure it 21062 // is correctly captured. A variable that shows up in a use_device_ptr has 21063 // similar properties of a first private variable. 21064 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 21065 21066 // Create a mappable component for the list item. List items in this clause 21067 // only need a component. 21068 MVLI.VarBaseDeclarations.push_back(D); 21069 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 21070 MVLI.VarComponents.back().emplace_back(SimpleRefExpr, D, 21071 /*IsNonContiguous=*/false); 21072 } 21073 21074 if (MVLI.ProcessedVarList.empty()) 21075 return nullptr; 21076 21077 return OMPUseDevicePtrClause::Create( 21078 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits, 21079 MVLI.VarBaseDeclarations, MVLI.VarComponents); 21080 } 21081 21082 OMPClause *Sema::ActOnOpenMPUseDeviceAddrClause(ArrayRef<Expr *> VarList, 21083 const OMPVarListLocTy &Locs) { 21084 MappableVarListInfo MVLI(VarList); 21085 21086 for (Expr *RefExpr : VarList) { 21087 assert(RefExpr && "NULL expr in OpenMP use_device_addr clause."); 21088 SourceLocation ELoc; 21089 SourceRange ERange; 21090 Expr *SimpleRefExpr = RefExpr; 21091 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 21092 /*AllowArraySection=*/true); 21093 if (Res.second) { 21094 // It will be analyzed later. 21095 MVLI.ProcessedVarList.push_back(RefExpr); 21096 } 21097 ValueDecl *D = Res.first; 21098 if (!D) 21099 continue; 21100 auto *VD = dyn_cast<VarDecl>(D); 21101 21102 // If required, build a capture to implement the privatization initialized 21103 // with the current list item value. 21104 DeclRefExpr *Ref = nullptr; 21105 if (!VD) 21106 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 21107 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 21108 21109 // We need to add a data sharing attribute for this variable to make sure it 21110 // is correctly captured. A variable that shows up in a use_device_addr has 21111 // similar properties of a first private variable. 21112 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 21113 21114 // Create a mappable component for the list item. List items in this clause 21115 // only need a component. 21116 MVLI.VarBaseDeclarations.push_back(D); 21117 MVLI.VarComponents.emplace_back(); 21118 Expr *Component = SimpleRefExpr; 21119 if (VD && (isa<OMPArraySectionExpr>(RefExpr->IgnoreParenImpCasts()) || 21120 isa<ArraySubscriptExpr>(RefExpr->IgnoreParenImpCasts()))) 21121 Component = DefaultFunctionArrayLvalueConversion(SimpleRefExpr).get(); 21122 MVLI.VarComponents.back().emplace_back(Component, D, 21123 /*IsNonContiguous=*/false); 21124 } 21125 21126 if (MVLI.ProcessedVarList.empty()) 21127 return nullptr; 21128 21129 return OMPUseDeviceAddrClause::Create(Context, Locs, MVLI.ProcessedVarList, 21130 MVLI.VarBaseDeclarations, 21131 MVLI.VarComponents); 21132 } 21133 21134 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 21135 const OMPVarListLocTy &Locs) { 21136 MappableVarListInfo MVLI(VarList); 21137 for (Expr *RefExpr : VarList) { 21138 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 21139 SourceLocation ELoc; 21140 SourceRange ERange; 21141 Expr *SimpleRefExpr = RefExpr; 21142 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 21143 if (Res.second) { 21144 // It will be analyzed later. 21145 MVLI.ProcessedVarList.push_back(RefExpr); 21146 } 21147 ValueDecl *D = Res.first; 21148 if (!D) 21149 continue; 21150 21151 QualType Type = D->getType(); 21152 // item should be a pointer or array or reference to pointer or array 21153 if (!Type.getNonReferenceType()->isPointerType() && 21154 !Type.getNonReferenceType()->isArrayType()) { 21155 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 21156 << 0 << RefExpr->getSourceRange(); 21157 continue; 21158 } 21159 21160 // Check if the declaration in the clause does not show up in any data 21161 // sharing attribute. 21162 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 21163 if (isOpenMPPrivate(DVar.CKind)) { 21164 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 21165 << getOpenMPClauseName(DVar.CKind) 21166 << getOpenMPClauseName(OMPC_is_device_ptr) 21167 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 21168 reportOriginalDsa(*this, DSAStack, D, DVar); 21169 continue; 21170 } 21171 21172 const Expr *ConflictExpr; 21173 if (DSAStack->checkMappableExprComponentListsForDecl( 21174 D, /*CurrentRegionOnly=*/true, 21175 [&ConflictExpr]( 21176 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 21177 OpenMPClauseKind) -> bool { 21178 ConflictExpr = R.front().getAssociatedExpression(); 21179 return true; 21180 })) { 21181 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 21182 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 21183 << ConflictExpr->getSourceRange(); 21184 continue; 21185 } 21186 21187 // Store the components in the stack so that they can be used to check 21188 // against other clauses later on. 21189 OMPClauseMappableExprCommon::MappableComponent MC( 21190 SimpleRefExpr, D, /*IsNonContiguous=*/false); 21191 DSAStack->addMappableExpressionComponents( 21192 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 21193 21194 // Record the expression we've just processed. 21195 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 21196 21197 // Create a mappable component for the list item. List items in this clause 21198 // only need a component. We use a null declaration to signal fields in 21199 // 'this'. 21200 assert((isa<DeclRefExpr>(SimpleRefExpr) || 21201 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 21202 "Unexpected device pointer expression!"); 21203 MVLI.VarBaseDeclarations.push_back( 21204 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 21205 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 21206 MVLI.VarComponents.back().push_back(MC); 21207 } 21208 21209 if (MVLI.ProcessedVarList.empty()) 21210 return nullptr; 21211 21212 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList, 21213 MVLI.VarBaseDeclarations, 21214 MVLI.VarComponents); 21215 } 21216 21217 OMPClause *Sema::ActOnOpenMPAllocateClause( 21218 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc, 21219 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 21220 if (Allocator) { 21221 // OpenMP [2.11.4 allocate Clause, Description] 21222 // allocator is an expression of omp_allocator_handle_t type. 21223 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack)) 21224 return nullptr; 21225 21226 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator); 21227 if (AllocatorRes.isInvalid()) 21228 return nullptr; 21229 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(), 21230 DSAStack->getOMPAllocatorHandleT(), 21231 Sema::AA_Initializing, 21232 /*AllowExplicit=*/true); 21233 if (AllocatorRes.isInvalid()) 21234 return nullptr; 21235 Allocator = AllocatorRes.get(); 21236 } else { 21237 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions. 21238 // allocate clauses that appear on a target construct or on constructs in a 21239 // target region must specify an allocator expression unless a requires 21240 // directive with the dynamic_allocators clause is present in the same 21241 // compilation unit. 21242 if (LangOpts.OpenMPIsDevice && 21243 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>()) 21244 targetDiag(StartLoc, diag::err_expected_allocator_expression); 21245 } 21246 // Analyze and build list of variables. 21247 SmallVector<Expr *, 8> Vars; 21248 for (Expr *RefExpr : VarList) { 21249 assert(RefExpr && "NULL expr in OpenMP private clause."); 21250 SourceLocation ELoc; 21251 SourceRange ERange; 21252 Expr *SimpleRefExpr = RefExpr; 21253 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 21254 if (Res.second) { 21255 // It will be analyzed later. 21256 Vars.push_back(RefExpr); 21257 } 21258 ValueDecl *D = Res.first; 21259 if (!D) 21260 continue; 21261 21262 auto *VD = dyn_cast<VarDecl>(D); 21263 DeclRefExpr *Ref = nullptr; 21264 if (!VD && !CurContext->isDependentContext()) 21265 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 21266 Vars.push_back((VD || CurContext->isDependentContext()) 21267 ? RefExpr->IgnoreParens() 21268 : Ref); 21269 } 21270 21271 if (Vars.empty()) 21272 return nullptr; 21273 21274 if (Allocator) 21275 DSAStack->addInnerAllocatorExpr(Allocator); 21276 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator, 21277 ColonLoc, EndLoc, Vars); 21278 } 21279 21280 OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList, 21281 SourceLocation StartLoc, 21282 SourceLocation LParenLoc, 21283 SourceLocation EndLoc) { 21284 SmallVector<Expr *, 8> Vars; 21285 for (Expr *RefExpr : VarList) { 21286 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 21287 SourceLocation ELoc; 21288 SourceRange ERange; 21289 Expr *SimpleRefExpr = RefExpr; 21290 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 21291 if (Res.second) 21292 // It will be analyzed later. 21293 Vars.push_back(RefExpr); 21294 ValueDecl *D = Res.first; 21295 if (!D) 21296 continue; 21297 21298 // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions. 21299 // A list-item cannot appear in more than one nontemporal clause. 21300 if (const Expr *PrevRef = 21301 DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) { 21302 Diag(ELoc, diag::err_omp_used_in_clause_twice) 21303 << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange; 21304 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 21305 << getOpenMPClauseName(OMPC_nontemporal); 21306 continue; 21307 } 21308 21309 Vars.push_back(RefExpr); 21310 } 21311 21312 if (Vars.empty()) 21313 return nullptr; 21314 21315 return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc, 21316 Vars); 21317 } 21318 21319 OMPClause *Sema::ActOnOpenMPInclusiveClause(ArrayRef<Expr *> VarList, 21320 SourceLocation StartLoc, 21321 SourceLocation LParenLoc, 21322 SourceLocation EndLoc) { 21323 SmallVector<Expr *, 8> Vars; 21324 for (Expr *RefExpr : VarList) { 21325 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 21326 SourceLocation ELoc; 21327 SourceRange ERange; 21328 Expr *SimpleRefExpr = RefExpr; 21329 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 21330 /*AllowArraySection=*/true); 21331 if (Res.second) 21332 // It will be analyzed later. 21333 Vars.push_back(RefExpr); 21334 ValueDecl *D = Res.first; 21335 if (!D) 21336 continue; 21337 21338 const DSAStackTy::DSAVarData DVar = 21339 DSAStack->getTopDSA(D, /*FromParent=*/true); 21340 // OpenMP 5.0, 2.9.6, scan Directive, Restrictions. 21341 // A list item that appears in the inclusive or exclusive clause must appear 21342 // in a reduction clause with the inscan modifier on the enclosing 21343 // worksharing-loop, worksharing-loop SIMD, or simd construct. 21344 if (DVar.CKind != OMPC_reduction || 21345 DVar.Modifier != OMPC_REDUCTION_inscan) 21346 Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction) 21347 << RefExpr->getSourceRange(); 21348 21349 if (DSAStack->getParentDirective() != OMPD_unknown) 21350 DSAStack->markDeclAsUsedInScanDirective(D); 21351 Vars.push_back(RefExpr); 21352 } 21353 21354 if (Vars.empty()) 21355 return nullptr; 21356 21357 return OMPInclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 21358 } 21359 21360 OMPClause *Sema::ActOnOpenMPExclusiveClause(ArrayRef<Expr *> VarList, 21361 SourceLocation StartLoc, 21362 SourceLocation LParenLoc, 21363 SourceLocation EndLoc) { 21364 SmallVector<Expr *, 8> Vars; 21365 for (Expr *RefExpr : VarList) { 21366 assert(RefExpr && "NULL expr in OpenMP nontemporal clause."); 21367 SourceLocation ELoc; 21368 SourceRange ERange; 21369 Expr *SimpleRefExpr = RefExpr; 21370 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 21371 /*AllowArraySection=*/true); 21372 if (Res.second) 21373 // It will be analyzed later. 21374 Vars.push_back(RefExpr); 21375 ValueDecl *D = Res.first; 21376 if (!D) 21377 continue; 21378 21379 OpenMPDirectiveKind ParentDirective = DSAStack->getParentDirective(); 21380 DSAStackTy::DSAVarData DVar; 21381 if (ParentDirective != OMPD_unknown) 21382 DVar = DSAStack->getTopDSA(D, /*FromParent=*/true); 21383 // OpenMP 5.0, 2.9.6, scan Directive, Restrictions. 21384 // A list item that appears in the inclusive or exclusive clause must appear 21385 // in a reduction clause with the inscan modifier on the enclosing 21386 // worksharing-loop, worksharing-loop SIMD, or simd construct. 21387 if (ParentDirective == OMPD_unknown || DVar.CKind != OMPC_reduction || 21388 DVar.Modifier != OMPC_REDUCTION_inscan) { 21389 Diag(ELoc, diag::err_omp_inclusive_exclusive_not_reduction) 21390 << RefExpr->getSourceRange(); 21391 } else { 21392 DSAStack->markDeclAsUsedInScanDirective(D); 21393 } 21394 Vars.push_back(RefExpr); 21395 } 21396 21397 if (Vars.empty()) 21398 return nullptr; 21399 21400 return OMPExclusiveClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 21401 } 21402 21403 /// Tries to find omp_alloctrait_t type. 21404 static bool findOMPAlloctraitT(Sema &S, SourceLocation Loc, DSAStackTy *Stack) { 21405 QualType OMPAlloctraitT = Stack->getOMPAlloctraitT(); 21406 if (!OMPAlloctraitT.isNull()) 21407 return true; 21408 IdentifierInfo &II = S.PP.getIdentifierTable().get("omp_alloctrait_t"); 21409 ParsedType PT = S.getTypeName(II, Loc, S.getCurScope()); 21410 if (!PT.getAsOpaquePtr() || PT.get().isNull()) { 21411 S.Diag(Loc, diag::err_omp_implied_type_not_found) << "omp_alloctrait_t"; 21412 return false; 21413 } 21414 Stack->setOMPAlloctraitT(PT.get()); 21415 return true; 21416 } 21417 21418 OMPClause *Sema::ActOnOpenMPUsesAllocatorClause( 21419 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, 21420 ArrayRef<UsesAllocatorsData> Data) { 21421 // OpenMP [2.12.5, target Construct] 21422 // allocator is an identifier of omp_allocator_handle_t type. 21423 if (!findOMPAllocatorHandleT(*this, StartLoc, DSAStack)) 21424 return nullptr; 21425 // OpenMP [2.12.5, target Construct] 21426 // allocator-traits-array is an identifier of const omp_alloctrait_t * type. 21427 if (llvm::any_of( 21428 Data, 21429 [](const UsesAllocatorsData &D) { return D.AllocatorTraits; }) && 21430 !findOMPAlloctraitT(*this, StartLoc, DSAStack)) 21431 return nullptr; 21432 llvm::SmallPtrSet<CanonicalDeclPtr<Decl>, 4> PredefinedAllocators; 21433 for (int I = 0; I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) { 21434 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I); 21435 StringRef Allocator = 21436 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind); 21437 DeclarationName AllocatorName = &Context.Idents.get(Allocator); 21438 PredefinedAllocators.insert(LookupSingleName( 21439 TUScope, AllocatorName, StartLoc, Sema::LookupAnyName)); 21440 } 21441 21442 SmallVector<OMPUsesAllocatorsClause::Data, 4> NewData; 21443 for (const UsesAllocatorsData &D : Data) { 21444 Expr *AllocatorExpr = nullptr; 21445 // Check allocator expression. 21446 if (D.Allocator->isTypeDependent()) { 21447 AllocatorExpr = D.Allocator; 21448 } else { 21449 // Traits were specified - need to assign new allocator to the specified 21450 // allocator, so it must be an lvalue. 21451 AllocatorExpr = D.Allocator->IgnoreParenImpCasts(); 21452 auto *DRE = dyn_cast<DeclRefExpr>(AllocatorExpr); 21453 bool IsPredefinedAllocator = false; 21454 if (DRE) 21455 IsPredefinedAllocator = PredefinedAllocators.count(DRE->getDecl()); 21456 if (!DRE || 21457 !(Context.hasSameUnqualifiedType( 21458 AllocatorExpr->getType(), DSAStack->getOMPAllocatorHandleT()) || 21459 Context.typesAreCompatible(AllocatorExpr->getType(), 21460 DSAStack->getOMPAllocatorHandleT(), 21461 /*CompareUnqualified=*/true)) || 21462 (!IsPredefinedAllocator && 21463 (AllocatorExpr->getType().isConstant(Context) || 21464 !AllocatorExpr->isLValue()))) { 21465 Diag(D.Allocator->getExprLoc(), diag::err_omp_var_expected) 21466 << "omp_allocator_handle_t" << (DRE ? 1 : 0) 21467 << AllocatorExpr->getType() << D.Allocator->getSourceRange(); 21468 continue; 21469 } 21470 // OpenMP [2.12.5, target Construct] 21471 // Predefined allocators appearing in a uses_allocators clause cannot have 21472 // traits specified. 21473 if (IsPredefinedAllocator && D.AllocatorTraits) { 21474 Diag(D.AllocatorTraits->getExprLoc(), 21475 diag::err_omp_predefined_allocator_with_traits) 21476 << D.AllocatorTraits->getSourceRange(); 21477 Diag(D.Allocator->getExprLoc(), diag::note_omp_predefined_allocator) 21478 << cast<NamedDecl>(DRE->getDecl())->getName() 21479 << D.Allocator->getSourceRange(); 21480 continue; 21481 } 21482 // OpenMP [2.12.5, target Construct] 21483 // Non-predefined allocators appearing in a uses_allocators clause must 21484 // have traits specified. 21485 if (!IsPredefinedAllocator && !D.AllocatorTraits) { 21486 Diag(D.Allocator->getExprLoc(), 21487 diag::err_omp_nonpredefined_allocator_without_traits); 21488 continue; 21489 } 21490 // No allocator traits - just convert it to rvalue. 21491 if (!D.AllocatorTraits) 21492 AllocatorExpr = DefaultLvalueConversion(AllocatorExpr).get(); 21493 DSAStack->addUsesAllocatorsDecl( 21494 DRE->getDecl(), 21495 IsPredefinedAllocator 21496 ? DSAStackTy::UsesAllocatorsDeclKind::PredefinedAllocator 21497 : DSAStackTy::UsesAllocatorsDeclKind::UserDefinedAllocator); 21498 } 21499 Expr *AllocatorTraitsExpr = nullptr; 21500 if (D.AllocatorTraits) { 21501 if (D.AllocatorTraits->isTypeDependent()) { 21502 AllocatorTraitsExpr = D.AllocatorTraits; 21503 } else { 21504 // OpenMP [2.12.5, target Construct] 21505 // Arrays that contain allocator traits that appear in a uses_allocators 21506 // clause must be constant arrays, have constant values and be defined 21507 // in the same scope as the construct in which the clause appears. 21508 AllocatorTraitsExpr = D.AllocatorTraits->IgnoreParenImpCasts(); 21509 // Check that traits expr is a constant array. 21510 QualType TraitTy; 21511 if (const ArrayType *Ty = 21512 AllocatorTraitsExpr->getType()->getAsArrayTypeUnsafe()) 21513 if (const auto *ConstArrayTy = dyn_cast<ConstantArrayType>(Ty)) 21514 TraitTy = ConstArrayTy->getElementType(); 21515 if (TraitTy.isNull() || 21516 !(Context.hasSameUnqualifiedType(TraitTy, 21517 DSAStack->getOMPAlloctraitT()) || 21518 Context.typesAreCompatible(TraitTy, DSAStack->getOMPAlloctraitT(), 21519 /*CompareUnqualified=*/true))) { 21520 Diag(D.AllocatorTraits->getExprLoc(), 21521 diag::err_omp_expected_array_alloctraits) 21522 << AllocatorTraitsExpr->getType(); 21523 continue; 21524 } 21525 // Do not map by default allocator traits if it is a standalone 21526 // variable. 21527 if (auto *DRE = dyn_cast<DeclRefExpr>(AllocatorTraitsExpr)) 21528 DSAStack->addUsesAllocatorsDecl( 21529 DRE->getDecl(), 21530 DSAStackTy::UsesAllocatorsDeclKind::AllocatorTrait); 21531 } 21532 } 21533 OMPUsesAllocatorsClause::Data &NewD = NewData.emplace_back(); 21534 NewD.Allocator = AllocatorExpr; 21535 NewD.AllocatorTraits = AllocatorTraitsExpr; 21536 NewD.LParenLoc = D.LParenLoc; 21537 NewD.RParenLoc = D.RParenLoc; 21538 } 21539 return OMPUsesAllocatorsClause::Create(Context, StartLoc, LParenLoc, EndLoc, 21540 NewData); 21541 } 21542 21543 OMPClause *Sema::ActOnOpenMPAffinityClause( 21544 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 21545 SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators) { 21546 SmallVector<Expr *, 8> Vars; 21547 for (Expr *RefExpr : Locators) { 21548 assert(RefExpr && "NULL expr in OpenMP shared clause."); 21549 if (isa<DependentScopeDeclRefExpr>(RefExpr) || RefExpr->isTypeDependent()) { 21550 // It will be analyzed later. 21551 Vars.push_back(RefExpr); 21552 continue; 21553 } 21554 21555 SourceLocation ELoc = RefExpr->getExprLoc(); 21556 Expr *SimpleExpr = RefExpr->IgnoreParenImpCasts(); 21557 21558 if (!SimpleExpr->isLValue()) { 21559 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 21560 << 1 << 0 << RefExpr->getSourceRange(); 21561 continue; 21562 } 21563 21564 ExprResult Res; 21565 { 21566 Sema::TentativeAnalysisScope Trap(*this); 21567 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, SimpleExpr); 21568 } 21569 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr) && 21570 !isa<OMPArrayShapingExpr>(SimpleExpr)) { 21571 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 21572 << 1 << 0 << RefExpr->getSourceRange(); 21573 continue; 21574 } 21575 Vars.push_back(SimpleExpr); 21576 } 21577 21578 return OMPAffinityClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 21579 EndLoc, Modifier, Vars); 21580 } 21581 21582 OMPClause *Sema::ActOnOpenMPBindClause(OpenMPBindClauseKind Kind, 21583 SourceLocation KindLoc, 21584 SourceLocation StartLoc, 21585 SourceLocation LParenLoc, 21586 SourceLocation EndLoc) { 21587 if (Kind == OMPC_BIND_unknown) { 21588 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 21589 << getListOfPossibleValues(OMPC_bind, /*First=*/0, 21590 /*Last=*/unsigned(OMPC_BIND_unknown)) 21591 << getOpenMPClauseName(OMPC_bind); 21592 return nullptr; 21593 } 21594 21595 return OMPBindClause::Create(Context, Kind, KindLoc, StartLoc, LParenLoc, 21596 EndLoc); 21597 } 21598