1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// \file 9 /// This file implements semantic analysis for OpenMP directives and 10 /// clauses. 11 /// 12 //===----------------------------------------------------------------------===// 13 14 #include "TreeTransform.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/Decl.h" 19 #include "clang/AST/DeclCXX.h" 20 #include "clang/AST/DeclOpenMP.h" 21 #include "clang/AST/StmtCXX.h" 22 #include "clang/AST/StmtOpenMP.h" 23 #include "clang/AST/StmtVisitor.h" 24 #include "clang/AST/TypeOrdering.h" 25 #include "clang/Basic/OpenMPKinds.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/Scope.h" 29 #include "clang/Sema/ScopeInfo.h" 30 #include "clang/Sema/SemaInternal.h" 31 #include "llvm/ADT/PointerEmbeddedInt.h" 32 using namespace clang; 33 34 //===----------------------------------------------------------------------===// 35 // Stack of data-sharing attributes for variables 36 //===----------------------------------------------------------------------===// 37 38 static const Expr *checkMapClauseExpressionBase( 39 Sema &SemaRef, Expr *E, 40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 41 OpenMPClauseKind CKind, bool NoDiagnose); 42 43 namespace { 44 /// Default data sharing attributes, which can be applied to directive. 45 enum DefaultDataSharingAttributes { 46 DSA_unspecified = 0, /// Data sharing attribute not specified. 47 DSA_none = 1 << 0, /// Default data sharing attribute 'none'. 48 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'. 49 }; 50 51 /// Attributes of the defaultmap clause. 52 enum DefaultMapAttributes { 53 DMA_unspecified, /// Default mapping is not specified. 54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'. 55 }; 56 57 /// Stack for tracking declarations used in OpenMP directives and 58 /// clauses and their data-sharing attributes. 59 class DSAStackTy { 60 public: 61 struct DSAVarData { 62 OpenMPDirectiveKind DKind = OMPD_unknown; 63 OpenMPClauseKind CKind = OMPC_unknown; 64 const Expr *RefExpr = nullptr; 65 DeclRefExpr *PrivateCopy = nullptr; 66 SourceLocation ImplicitDSALoc; 67 DSAVarData() = default; 68 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 69 const Expr *RefExpr, DeclRefExpr *PrivateCopy, 70 SourceLocation ImplicitDSALoc) 71 : DKind(DKind), CKind(CKind), RefExpr(RefExpr), 72 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {} 73 }; 74 using OperatorOffsetTy = 75 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>; 76 using DoacrossDependMapTy = 77 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>; 78 79 private: 80 struct DSAInfo { 81 OpenMPClauseKind Attributes = OMPC_unknown; 82 /// Pointer to a reference expression and a flag which shows that the 83 /// variable is marked as lastprivate(true) or not (false). 84 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr; 85 DeclRefExpr *PrivateCopy = nullptr; 86 }; 87 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>; 88 using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>; 89 using LCDeclInfo = std::pair<unsigned, VarDecl *>; 90 using LoopControlVariablesMapTy = 91 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>; 92 /// Struct that associates a component with the clause kind where they are 93 /// found. 94 struct MappedExprComponentTy { 95 OMPClauseMappableExprCommon::MappableExprComponentLists Components; 96 OpenMPClauseKind Kind = OMPC_unknown; 97 }; 98 using MappedExprComponentsTy = 99 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>; 100 using CriticalsWithHintsTy = 101 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>; 102 struct ReductionData { 103 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>; 104 SourceRange ReductionRange; 105 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp; 106 ReductionData() = default; 107 void set(BinaryOperatorKind BO, SourceRange RR) { 108 ReductionRange = RR; 109 ReductionOp = BO; 110 } 111 void set(const Expr *RefExpr, SourceRange RR) { 112 ReductionRange = RR; 113 ReductionOp = RefExpr; 114 } 115 }; 116 using DeclReductionMapTy = 117 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>; 118 119 struct SharingMapTy { 120 DeclSAMapTy SharingMap; 121 DeclReductionMapTy ReductionMap; 122 AlignedMapTy AlignedMap; 123 MappedExprComponentsTy MappedExprComponents; 124 LoopControlVariablesMapTy LCVMap; 125 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 126 SourceLocation DefaultAttrLoc; 127 DefaultMapAttributes DefaultMapAttr = DMA_unspecified; 128 SourceLocation DefaultMapAttrLoc; 129 OpenMPDirectiveKind Directive = OMPD_unknown; 130 DeclarationNameInfo DirectiveName; 131 Scope *CurScope = nullptr; 132 SourceLocation ConstructLoc; 133 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 134 /// get the data (loop counters etc.) about enclosing loop-based construct. 135 /// This data is required during codegen. 136 DoacrossDependMapTy DoacrossDepends; 137 /// First argument (Expr *) contains optional argument of the 138 /// 'ordered' clause, the second one is true if the regions has 'ordered' 139 /// clause, false otherwise. 140 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion; 141 unsigned AssociatedLoops = 1; 142 const Decl *PossiblyLoopCounter = nullptr; 143 bool NowaitRegion = false; 144 bool CancelRegion = false; 145 bool LoopStart = false; 146 SourceLocation InnerTeamsRegionLoc; 147 /// Reference to the taskgroup task_reduction reference expression. 148 Expr *TaskgroupReductionRef = nullptr; 149 llvm::DenseSet<QualType> MappedClassesQualTypes; 150 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 151 Scope *CurScope, SourceLocation Loc) 152 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 153 ConstructLoc(Loc) {} 154 SharingMapTy() = default; 155 }; 156 157 using StackTy = SmallVector<SharingMapTy, 4>; 158 159 /// Stack of used declaration and their data-sharing attributes. 160 DeclSAMapTy Threadprivates; 161 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr; 162 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack; 163 /// true, if check for DSA must be from parent directive, false, if 164 /// from current directive. 165 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 166 Sema &SemaRef; 167 bool ForceCapturing = false; 168 /// true if all the vaiables in the target executable directives must be 169 /// captured by reference. 170 bool ForceCaptureByReferenceInTargetExecutable = false; 171 CriticalsWithHintsTy Criticals; 172 173 using iterator = StackTy::const_reverse_iterator; 174 175 DSAVarData getDSA(iterator &Iter, ValueDecl *D) const; 176 177 /// Checks if the variable is a local for OpenMP region. 178 bool isOpenMPLocal(VarDecl *D, iterator Iter) const; 179 180 bool isStackEmpty() const { 181 return Stack.empty() || 182 Stack.back().second != CurrentNonCapturingFunctionScope || 183 Stack.back().first.empty(); 184 } 185 186 /// Vector of previously declared requires directives 187 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls; 188 189 public: 190 explicit DSAStackTy(Sema &S) : SemaRef(S) {} 191 192 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 193 OpenMPClauseKind getClauseParsingMode() const { 194 assert(isClauseParsingMode() && "Must be in clause parsing mode."); 195 return ClauseKindMode; 196 } 197 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 198 199 bool isForceVarCapturing() const { return ForceCapturing; } 200 void setForceVarCapturing(bool V) { ForceCapturing = V; } 201 202 void setForceCaptureByReferenceInTargetExecutable(bool V) { 203 ForceCaptureByReferenceInTargetExecutable = V; 204 } 205 bool isForceCaptureByReferenceInTargetExecutable() const { 206 return ForceCaptureByReferenceInTargetExecutable; 207 } 208 209 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 210 Scope *CurScope, SourceLocation Loc) { 211 if (Stack.empty() || 212 Stack.back().second != CurrentNonCapturingFunctionScope) 213 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope); 214 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc); 215 Stack.back().first.back().DefaultAttrLoc = Loc; 216 } 217 218 void pop() { 219 assert(!Stack.back().first.empty() && 220 "Data-sharing attributes stack is empty!"); 221 Stack.back().first.pop_back(); 222 } 223 224 /// Marks that we're started loop parsing. 225 void loopInit() { 226 assert(isOpenMPLoopDirective(getCurrentDirective()) && 227 "Expected loop-based directive."); 228 Stack.back().first.back().LoopStart = true; 229 } 230 /// Start capturing of the variables in the loop context. 231 void loopStart() { 232 assert(isOpenMPLoopDirective(getCurrentDirective()) && 233 "Expected loop-based directive."); 234 Stack.back().first.back().LoopStart = false; 235 } 236 /// true, if variables are captured, false otherwise. 237 bool isLoopStarted() const { 238 assert(isOpenMPLoopDirective(getCurrentDirective()) && 239 "Expected loop-based directive."); 240 return !Stack.back().first.back().LoopStart; 241 } 242 /// Marks (or clears) declaration as possibly loop counter. 243 void resetPossibleLoopCounter(const Decl *D = nullptr) { 244 Stack.back().first.back().PossiblyLoopCounter = 245 D ? D->getCanonicalDecl() : D; 246 } 247 /// Gets the possible loop counter decl. 248 const Decl *getPossiblyLoopCunter() const { 249 return Stack.back().first.back().PossiblyLoopCounter; 250 } 251 /// Start new OpenMP region stack in new non-capturing function. 252 void pushFunction() { 253 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction(); 254 assert(!isa<CapturingScopeInfo>(CurFnScope)); 255 CurrentNonCapturingFunctionScope = CurFnScope; 256 } 257 /// Pop region stack for non-capturing function. 258 void popFunction(const FunctionScopeInfo *OldFSI) { 259 if (!Stack.empty() && Stack.back().second == OldFSI) { 260 assert(Stack.back().first.empty()); 261 Stack.pop_back(); 262 } 263 CurrentNonCapturingFunctionScope = nullptr; 264 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) { 265 if (!isa<CapturingScopeInfo>(FSI)) { 266 CurrentNonCapturingFunctionScope = FSI; 267 break; 268 } 269 } 270 } 271 272 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) { 273 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint); 274 } 275 const std::pair<const OMPCriticalDirective *, llvm::APSInt> 276 getCriticalWithHint(const DeclarationNameInfo &Name) const { 277 auto I = Criticals.find(Name.getAsString()); 278 if (I != Criticals.end()) 279 return I->second; 280 return std::make_pair(nullptr, llvm::APSInt()); 281 } 282 /// If 'aligned' declaration for given variable \a D was not seen yet, 283 /// add it and return NULL; otherwise return previous occurrence's expression 284 /// for diagnostics. 285 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE); 286 287 /// Register specified variable as loop control variable. 288 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture); 289 /// Check if the specified variable is a loop control variable for 290 /// current region. 291 /// \return The index of the loop control variable in the list of associated 292 /// for-loops (from outer to inner). 293 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const; 294 /// Check if the specified variable is a loop control variable for 295 /// parent region. 296 /// \return The index of the loop control variable in the list of associated 297 /// for-loops (from outer to inner). 298 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const; 299 /// Get the loop control variable for the I-th loop (or nullptr) in 300 /// parent directive. 301 const ValueDecl *getParentLoopControlVariable(unsigned I) const; 302 303 /// Adds explicit data sharing attribute to the specified declaration. 304 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 305 DeclRefExpr *PrivateCopy = nullptr); 306 307 /// Adds additional information for the reduction items with the reduction id 308 /// represented as an operator. 309 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 310 BinaryOperatorKind BOK); 311 /// Adds additional information for the reduction items with the reduction id 312 /// represented as reduction identifier. 313 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 314 const Expr *ReductionRef); 315 /// Returns the location and reduction operation from the innermost parent 316 /// region for the given \p D. 317 const DSAVarData 318 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 319 BinaryOperatorKind &BOK, 320 Expr *&TaskgroupDescriptor) const; 321 /// Returns the location and reduction operation from the innermost parent 322 /// region for the given \p D. 323 const DSAVarData 324 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR, 325 const Expr *&ReductionRef, 326 Expr *&TaskgroupDescriptor) const; 327 /// Return reduction reference expression for the current taskgroup. 328 Expr *getTaskgroupReductionRef() const { 329 assert(Stack.back().first.back().Directive == OMPD_taskgroup && 330 "taskgroup reference expression requested for non taskgroup " 331 "directive."); 332 return Stack.back().first.back().TaskgroupReductionRef; 333 } 334 /// Checks if the given \p VD declaration is actually a taskgroup reduction 335 /// descriptor variable at the \p Level of OpenMP regions. 336 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const { 337 return Stack.back().first[Level].TaskgroupReductionRef && 338 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef) 339 ->getDecl() == VD; 340 } 341 342 /// Returns data sharing attributes from top of the stack for the 343 /// specified declaration. 344 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 345 /// Returns data-sharing attributes for the specified declaration. 346 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const; 347 /// Checks if the specified variables has data-sharing attributes which 348 /// match specified \a CPred predicate in any directive which matches \a DPred 349 /// predicate. 350 const DSAVarData 351 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 352 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 353 bool FromParent) const; 354 /// Checks if the specified variables has data-sharing attributes which 355 /// match specified \a CPred predicate in any innermost directive which 356 /// matches \a DPred predicate. 357 const DSAVarData 358 hasInnermostDSA(ValueDecl *D, 359 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 360 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 361 bool FromParent) const; 362 /// Checks if the specified variables has explicit data-sharing 363 /// attributes which match specified \a CPred predicate at the specified 364 /// OpenMP region. 365 bool hasExplicitDSA(const ValueDecl *D, 366 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 367 unsigned Level, bool NotLastprivate = false) const; 368 369 /// Returns true if the directive at level \Level matches in the 370 /// specified \a DPred predicate. 371 bool hasExplicitDirective( 372 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 373 unsigned Level) const; 374 375 /// Finds a directive which matches specified \a DPred predicate. 376 bool hasDirective( 377 const llvm::function_ref<bool( 378 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)> 379 DPred, 380 bool FromParent) const; 381 382 /// Returns currently analyzed directive. 383 OpenMPDirectiveKind getCurrentDirective() const { 384 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive; 385 } 386 /// Returns directive kind at specified level. 387 OpenMPDirectiveKind getDirective(unsigned Level) const { 388 assert(!isStackEmpty() && "No directive at specified level."); 389 return Stack.back().first[Level].Directive; 390 } 391 /// Returns parent directive. 392 OpenMPDirectiveKind getParentDirective() const { 393 if (isStackEmpty() || Stack.back().first.size() == 1) 394 return OMPD_unknown; 395 return std::next(Stack.back().first.rbegin())->Directive; 396 } 397 398 /// Add requires decl to internal vector 399 void addRequiresDecl(OMPRequiresDecl *RD) { 400 RequiresDecls.push_back(RD); 401 } 402 403 /// Checks for a duplicate clause amongst previously declared requires 404 /// directives 405 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const { 406 bool IsDuplicate = false; 407 for (OMPClause *CNew : ClauseList) { 408 for (const OMPRequiresDecl *D : RequiresDecls) { 409 for (const OMPClause *CPrev : D->clauselists()) { 410 if (CNew->getClauseKind() == CPrev->getClauseKind()) { 411 SemaRef.Diag(CNew->getBeginLoc(), 412 diag::err_omp_requires_clause_redeclaration) 413 << getOpenMPClauseName(CNew->getClauseKind()); 414 SemaRef.Diag(CPrev->getBeginLoc(), 415 diag::note_omp_requires_previous_clause) 416 << getOpenMPClauseName(CPrev->getClauseKind()); 417 IsDuplicate = true; 418 } 419 } 420 } 421 } 422 return IsDuplicate; 423 } 424 425 /// Set default data sharing attribute to none. 426 void setDefaultDSANone(SourceLocation Loc) { 427 assert(!isStackEmpty()); 428 Stack.back().first.back().DefaultAttr = DSA_none; 429 Stack.back().first.back().DefaultAttrLoc = Loc; 430 } 431 /// Set default data sharing attribute to shared. 432 void setDefaultDSAShared(SourceLocation Loc) { 433 assert(!isStackEmpty()); 434 Stack.back().first.back().DefaultAttr = DSA_shared; 435 Stack.back().first.back().DefaultAttrLoc = Loc; 436 } 437 /// Set default data mapping attribute to 'tofrom:scalar'. 438 void setDefaultDMAToFromScalar(SourceLocation Loc) { 439 assert(!isStackEmpty()); 440 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar; 441 Stack.back().first.back().DefaultMapAttrLoc = Loc; 442 } 443 444 DefaultDataSharingAttributes getDefaultDSA() const { 445 return isStackEmpty() ? DSA_unspecified 446 : Stack.back().first.back().DefaultAttr; 447 } 448 SourceLocation getDefaultDSALocation() const { 449 return isStackEmpty() ? SourceLocation() 450 : Stack.back().first.back().DefaultAttrLoc; 451 } 452 DefaultMapAttributes getDefaultDMA() const { 453 return isStackEmpty() ? DMA_unspecified 454 : Stack.back().first.back().DefaultMapAttr; 455 } 456 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const { 457 return Stack.back().first[Level].DefaultMapAttr; 458 } 459 SourceLocation getDefaultDMALocation() const { 460 return isStackEmpty() ? SourceLocation() 461 : Stack.back().first.back().DefaultMapAttrLoc; 462 } 463 464 /// Checks if the specified variable is a threadprivate. 465 bool isThreadPrivate(VarDecl *D) { 466 const DSAVarData DVar = getTopDSA(D, false); 467 return isOpenMPThreadPrivate(DVar.CKind); 468 } 469 470 /// Marks current region as ordered (it has an 'ordered' clause). 471 void setOrderedRegion(bool IsOrdered, const Expr *Param, 472 OMPOrderedClause *Clause) { 473 assert(!isStackEmpty()); 474 if (IsOrdered) 475 Stack.back().first.back().OrderedRegion.emplace(Param, Clause); 476 else 477 Stack.back().first.back().OrderedRegion.reset(); 478 } 479 /// Returns true, if region is ordered (has associated 'ordered' clause), 480 /// false - otherwise. 481 bool isOrderedRegion() const { 482 if (isStackEmpty()) 483 return false; 484 return Stack.back().first.rbegin()->OrderedRegion.hasValue(); 485 } 486 /// Returns optional parameter for the ordered region. 487 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const { 488 if (isStackEmpty() || 489 !Stack.back().first.rbegin()->OrderedRegion.hasValue()) 490 return std::make_pair(nullptr, nullptr); 491 return Stack.back().first.rbegin()->OrderedRegion.getValue(); 492 } 493 /// Returns true, if parent region is ordered (has associated 494 /// 'ordered' clause), false - otherwise. 495 bool isParentOrderedRegion() const { 496 if (isStackEmpty() || Stack.back().first.size() == 1) 497 return false; 498 return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue(); 499 } 500 /// Returns optional parameter for the ordered region. 501 std::pair<const Expr *, OMPOrderedClause *> 502 getParentOrderedRegionParam() const { 503 if (isStackEmpty() || Stack.back().first.size() == 1 || 504 !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue()) 505 return std::make_pair(nullptr, nullptr); 506 return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue(); 507 } 508 /// Marks current region as nowait (it has a 'nowait' clause). 509 void setNowaitRegion(bool IsNowait = true) { 510 assert(!isStackEmpty()); 511 Stack.back().first.back().NowaitRegion = IsNowait; 512 } 513 /// Returns true, if parent region is nowait (has associated 514 /// 'nowait' clause), false - otherwise. 515 bool isParentNowaitRegion() const { 516 if (isStackEmpty() || Stack.back().first.size() == 1) 517 return false; 518 return std::next(Stack.back().first.rbegin())->NowaitRegion; 519 } 520 /// Marks parent region as cancel region. 521 void setParentCancelRegion(bool Cancel = true) { 522 if (!isStackEmpty() && Stack.back().first.size() > 1) { 523 auto &StackElemRef = *std::next(Stack.back().first.rbegin()); 524 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel; 525 } 526 } 527 /// Return true if current region has inner cancel construct. 528 bool isCancelRegion() const { 529 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion; 530 } 531 532 /// Set collapse value for the region. 533 void setAssociatedLoops(unsigned Val) { 534 assert(!isStackEmpty()); 535 Stack.back().first.back().AssociatedLoops = Val; 536 } 537 /// Return collapse value for region. 538 unsigned getAssociatedLoops() const { 539 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops; 540 } 541 542 /// Marks current target region as one with closely nested teams 543 /// region. 544 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 545 if (!isStackEmpty() && Stack.back().first.size() > 1) { 546 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc = 547 TeamsRegionLoc; 548 } 549 } 550 /// Returns true, if current region has closely nested teams region. 551 bool hasInnerTeamsRegion() const { 552 return getInnerTeamsRegionLoc().isValid(); 553 } 554 /// Returns location of the nested teams region (if any). 555 SourceLocation getInnerTeamsRegionLoc() const { 556 return isStackEmpty() ? SourceLocation() 557 : Stack.back().first.back().InnerTeamsRegionLoc; 558 } 559 560 Scope *getCurScope() const { 561 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope; 562 } 563 SourceLocation getConstructLoc() const { 564 return isStackEmpty() ? SourceLocation() 565 : Stack.back().first.back().ConstructLoc; 566 } 567 568 /// Do the check specified in \a Check to all component lists and return true 569 /// if any issue is found. 570 bool checkMappableExprComponentListsForDecl( 571 const ValueDecl *VD, bool CurrentRegionOnly, 572 const llvm::function_ref< 573 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 574 OpenMPClauseKind)> 575 Check) const { 576 if (isStackEmpty()) 577 return false; 578 auto SI = Stack.back().first.rbegin(); 579 auto SE = Stack.back().first.rend(); 580 581 if (SI == SE) 582 return false; 583 584 if (CurrentRegionOnly) 585 SE = std::next(SI); 586 else 587 std::advance(SI, 1); 588 589 for (; SI != SE; ++SI) { 590 auto MI = SI->MappedExprComponents.find(VD); 591 if (MI != SI->MappedExprComponents.end()) 592 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 593 MI->second.Components) 594 if (Check(L, MI->second.Kind)) 595 return true; 596 } 597 return false; 598 } 599 600 /// Do the check specified in \a Check to all component lists at a given level 601 /// and return true if any issue is found. 602 bool checkMappableExprComponentListsForDeclAtLevel( 603 const ValueDecl *VD, unsigned Level, 604 const llvm::function_ref< 605 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 606 OpenMPClauseKind)> 607 Check) const { 608 if (isStackEmpty()) 609 return false; 610 611 auto StartI = Stack.back().first.begin(); 612 auto EndI = Stack.back().first.end(); 613 if (std::distance(StartI, EndI) <= (int)Level) 614 return false; 615 std::advance(StartI, Level); 616 617 auto MI = StartI->MappedExprComponents.find(VD); 618 if (MI != StartI->MappedExprComponents.end()) 619 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L : 620 MI->second.Components) 621 if (Check(L, MI->second.Kind)) 622 return true; 623 return false; 624 } 625 626 /// Create a new mappable expression component list associated with a given 627 /// declaration and initialize it with the provided list of components. 628 void addMappableExpressionComponents( 629 const ValueDecl *VD, 630 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 631 OpenMPClauseKind WhereFoundClauseKind) { 632 assert(!isStackEmpty() && 633 "Not expecting to retrieve components from a empty stack!"); 634 MappedExprComponentTy &MEC = 635 Stack.back().first.back().MappedExprComponents[VD]; 636 // Create new entry and append the new components there. 637 MEC.Components.resize(MEC.Components.size() + 1); 638 MEC.Components.back().append(Components.begin(), Components.end()); 639 MEC.Kind = WhereFoundClauseKind; 640 } 641 642 unsigned getNestingLevel() const { 643 assert(!isStackEmpty()); 644 return Stack.back().first.size() - 1; 645 } 646 void addDoacrossDependClause(OMPDependClause *C, 647 const OperatorOffsetTy &OpsOffs) { 648 assert(!isStackEmpty() && Stack.back().first.size() > 1); 649 SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin()); 650 assert(isOpenMPWorksharingDirective(StackElem.Directive)); 651 StackElem.DoacrossDepends.try_emplace(C, OpsOffs); 652 } 653 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 654 getDoacrossDependClauses() const { 655 assert(!isStackEmpty()); 656 const SharingMapTy &StackElem = Stack.back().first.back(); 657 if (isOpenMPWorksharingDirective(StackElem.Directive)) { 658 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends; 659 return llvm::make_range(Ref.begin(), Ref.end()); 660 } 661 return llvm::make_range(StackElem.DoacrossDepends.end(), 662 StackElem.DoacrossDepends.end()); 663 } 664 665 // Store types of classes which have been explicitly mapped 666 void addMappedClassesQualTypes(QualType QT) { 667 SharingMapTy &StackElem = Stack.back().first.back(); 668 StackElem.MappedClassesQualTypes.insert(QT); 669 } 670 671 // Return set of mapped classes types 672 bool isClassPreviouslyMapped(QualType QT) const { 673 const SharingMapTy &StackElem = Stack.back().first.back(); 674 return StackElem.MappedClassesQualTypes.count(QT) != 0; 675 } 676 677 }; 678 679 bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) { 680 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind); 681 } 682 683 bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) { 684 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || DKind == OMPD_unknown; 685 } 686 687 } // namespace 688 689 static const Expr *getExprAsWritten(const Expr *E) { 690 if (const auto *FE = dyn_cast<FullExpr>(E)) 691 E = FE->getSubExpr(); 692 693 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 694 E = MTE->GetTemporaryExpr(); 695 696 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 697 E = Binder->getSubExpr(); 698 699 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 700 E = ICE->getSubExprAsWritten(); 701 return E->IgnoreParens(); 702 } 703 704 static Expr *getExprAsWritten(Expr *E) { 705 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E))); 706 } 707 708 static const ValueDecl *getCanonicalDecl(const ValueDecl *D) { 709 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) 710 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 711 D = ME->getMemberDecl(); 712 const auto *VD = dyn_cast<VarDecl>(D); 713 const auto *FD = dyn_cast<FieldDecl>(D); 714 if (VD != nullptr) { 715 VD = VD->getCanonicalDecl(); 716 D = VD; 717 } else { 718 assert(FD); 719 FD = FD->getCanonicalDecl(); 720 D = FD; 721 } 722 return D; 723 } 724 725 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 726 return const_cast<ValueDecl *>( 727 getCanonicalDecl(const_cast<const ValueDecl *>(D))); 728 } 729 730 DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter, 731 ValueDecl *D) const { 732 D = getCanonicalDecl(D); 733 auto *VD = dyn_cast<VarDecl>(D); 734 const auto *FD = dyn_cast<FieldDecl>(D); 735 DSAVarData DVar; 736 if (isStackEmpty() || Iter == Stack.back().first.rend()) { 737 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 738 // in a region but not in construct] 739 // File-scope or namespace-scope variables referenced in called routines 740 // in the region are shared unless they appear in a threadprivate 741 // directive. 742 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD)) 743 DVar.CKind = OMPC_shared; 744 745 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 746 // in a region but not in construct] 747 // Variables with static storage duration that are declared in called 748 // routines in the region are shared. 749 if (VD && VD->hasGlobalStorage()) 750 DVar.CKind = OMPC_shared; 751 752 // Non-static data members are shared by default. 753 if (FD) 754 DVar.CKind = OMPC_shared; 755 756 return DVar; 757 } 758 759 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 760 // in a Construct, C/C++, predetermined, p.1] 761 // Variables with automatic storage duration that are declared in a scope 762 // inside the construct are private. 763 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 764 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 765 DVar.CKind = OMPC_private; 766 return DVar; 767 } 768 769 DVar.DKind = Iter->Directive; 770 // Explicitly specified attributes and local variables with predetermined 771 // attributes. 772 if (Iter->SharingMap.count(D)) { 773 const DSAInfo &Data = Iter->SharingMap.lookup(D); 774 DVar.RefExpr = Data.RefExpr.getPointer(); 775 DVar.PrivateCopy = Data.PrivateCopy; 776 DVar.CKind = Data.Attributes; 777 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 778 return DVar; 779 } 780 781 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 782 // in a Construct, C/C++, implicitly determined, p.1] 783 // In a parallel or task construct, the data-sharing attributes of these 784 // variables are determined by the default clause, if present. 785 switch (Iter->DefaultAttr) { 786 case DSA_shared: 787 DVar.CKind = OMPC_shared; 788 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 789 return DVar; 790 case DSA_none: 791 return DVar; 792 case DSA_unspecified: 793 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 794 // in a Construct, implicitly determined, p.2] 795 // In a parallel construct, if no default clause is present, these 796 // variables are shared. 797 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 798 if (isOpenMPParallelDirective(DVar.DKind) || 799 isOpenMPTeamsDirective(DVar.DKind)) { 800 DVar.CKind = OMPC_shared; 801 return DVar; 802 } 803 804 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 805 // in a Construct, implicitly determined, p.4] 806 // In a task construct, if no default clause is present, a variable that in 807 // the enclosing context is determined to be shared by all implicit tasks 808 // bound to the current team is shared. 809 if (isOpenMPTaskingDirective(DVar.DKind)) { 810 DSAVarData DVarTemp; 811 iterator I = Iter, E = Stack.back().first.rend(); 812 do { 813 ++I; 814 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 815 // Referenced in a Construct, implicitly determined, p.6] 816 // In a task construct, if no default clause is present, a variable 817 // whose data-sharing attribute is not determined by the rules above is 818 // firstprivate. 819 DVarTemp = getDSA(I, D); 820 if (DVarTemp.CKind != OMPC_shared) { 821 DVar.RefExpr = nullptr; 822 DVar.CKind = OMPC_firstprivate; 823 return DVar; 824 } 825 } while (I != E && !isImplicitTaskingRegion(I->Directive)); 826 DVar.CKind = 827 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 828 return DVar; 829 } 830 } 831 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 832 // in a Construct, implicitly determined, p.3] 833 // For constructs other than task, if no default clause is present, these 834 // variables inherit their data-sharing attributes from the enclosing 835 // context. 836 return getDSA(++Iter, D); 837 } 838 839 const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D, 840 const Expr *NewDE) { 841 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 842 D = getCanonicalDecl(D); 843 SharingMapTy &StackElem = Stack.back().first.back(); 844 auto It = StackElem.AlignedMap.find(D); 845 if (It == StackElem.AlignedMap.end()) { 846 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 847 StackElem.AlignedMap[D] = NewDE; 848 return nullptr; 849 } 850 assert(It->second && "Unexpected nullptr expr in the aligned map"); 851 return It->second; 852 } 853 854 void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) { 855 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 856 D = getCanonicalDecl(D); 857 SharingMapTy &StackElem = Stack.back().first.back(); 858 StackElem.LCVMap.try_emplace( 859 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)); 860 } 861 862 const DSAStackTy::LCDeclInfo 863 DSAStackTy::isLoopControlVariable(const ValueDecl *D) const { 864 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 865 D = getCanonicalDecl(D); 866 const SharingMapTy &StackElem = Stack.back().first.back(); 867 auto It = StackElem.LCVMap.find(D); 868 if (It != StackElem.LCVMap.end()) 869 return It->second; 870 return {0, nullptr}; 871 } 872 873 const DSAStackTy::LCDeclInfo 874 DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const { 875 assert(!isStackEmpty() && Stack.back().first.size() > 1 && 876 "Data-sharing attributes stack is empty"); 877 D = getCanonicalDecl(D); 878 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin()); 879 auto It = StackElem.LCVMap.find(D); 880 if (It != StackElem.LCVMap.end()) 881 return It->second; 882 return {0, nullptr}; 883 } 884 885 const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const { 886 assert(!isStackEmpty() && Stack.back().first.size() > 1 && 887 "Data-sharing attributes stack is empty"); 888 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin()); 889 if (StackElem.LCVMap.size() < I) 890 return nullptr; 891 for (const auto &Pair : StackElem.LCVMap) 892 if (Pair.second.first == I) 893 return Pair.first; 894 return nullptr; 895 } 896 897 void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A, 898 DeclRefExpr *PrivateCopy) { 899 D = getCanonicalDecl(D); 900 if (A == OMPC_threadprivate) { 901 DSAInfo &Data = Threadprivates[D]; 902 Data.Attributes = A; 903 Data.RefExpr.setPointer(E); 904 Data.PrivateCopy = nullptr; 905 } else { 906 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 907 DSAInfo &Data = Stack.back().first.back().SharingMap[D]; 908 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 909 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 910 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 911 (isLoopControlVariable(D).first && A == OMPC_private)); 912 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 913 Data.RefExpr.setInt(/*IntVal=*/true); 914 return; 915 } 916 const bool IsLastprivate = 917 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 918 Data.Attributes = A; 919 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 920 Data.PrivateCopy = PrivateCopy; 921 if (PrivateCopy) { 922 DSAInfo &Data = 923 Stack.back().first.back().SharingMap[PrivateCopy->getDecl()]; 924 Data.Attributes = A; 925 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 926 Data.PrivateCopy = nullptr; 927 } 928 } 929 } 930 931 /// Build a variable declaration for OpenMP loop iteration variable. 932 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 933 StringRef Name, const AttrVec *Attrs = nullptr, 934 DeclRefExpr *OrigRef = nullptr) { 935 DeclContext *DC = SemaRef.CurContext; 936 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 937 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 938 auto *Decl = 939 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 940 if (Attrs) { 941 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 942 I != E; ++I) 943 Decl->addAttr(*I); 944 } 945 Decl->setImplicit(); 946 if (OrigRef) { 947 Decl->addAttr( 948 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef)); 949 } 950 return Decl; 951 } 952 953 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 954 SourceLocation Loc, 955 bool RefersToCapture = false) { 956 D->setReferenced(); 957 D->markUsed(S.Context); 958 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 959 SourceLocation(), D, RefersToCapture, Loc, Ty, 960 VK_LValue); 961 } 962 963 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 964 BinaryOperatorKind BOK) { 965 D = getCanonicalDecl(D); 966 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 967 assert( 968 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && 969 "Additional reduction info may be specified only for reduction items."); 970 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D]; 971 assert(ReductionData.ReductionRange.isInvalid() && 972 Stack.back().first.back().Directive == OMPD_taskgroup && 973 "Additional reduction info may be specified only once for reduction " 974 "items."); 975 ReductionData.set(BOK, SR); 976 Expr *&TaskgroupReductionRef = 977 Stack.back().first.back().TaskgroupReductionRef; 978 if (!TaskgroupReductionRef) { 979 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 980 SemaRef.Context.VoidPtrTy, ".task_red."); 981 TaskgroupReductionRef = 982 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 983 } 984 } 985 986 void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR, 987 const Expr *ReductionRef) { 988 D = getCanonicalDecl(D); 989 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 990 assert( 991 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && 992 "Additional reduction info may be specified only for reduction items."); 993 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D]; 994 assert(ReductionData.ReductionRange.isInvalid() && 995 Stack.back().first.back().Directive == OMPD_taskgroup && 996 "Additional reduction info may be specified only once for reduction " 997 "items."); 998 ReductionData.set(ReductionRef, SR); 999 Expr *&TaskgroupReductionRef = 1000 Stack.back().first.back().TaskgroupReductionRef; 1001 if (!TaskgroupReductionRef) { 1002 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(), 1003 SemaRef.Context.VoidPtrTy, ".task_red."); 1004 TaskgroupReductionRef = 1005 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 1006 } 1007 } 1008 1009 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1010 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK, 1011 Expr *&TaskgroupDescriptor) const { 1012 D = getCanonicalDecl(D); 1013 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1014 if (Stack.back().first.empty()) 1015 return DSAVarData(); 1016 for (iterator I = std::next(Stack.back().first.rbegin(), 1), 1017 E = Stack.back().first.rend(); 1018 I != E; std::advance(I, 1)) { 1019 const DSAInfo &Data = I->SharingMap.lookup(D); 1020 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) 1021 continue; 1022 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1023 if (!ReductionData.ReductionOp || 1024 ReductionData.ReductionOp.is<const Expr *>()) 1025 return DSAVarData(); 1026 SR = ReductionData.ReductionRange; 1027 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>(); 1028 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1029 "expression for the descriptor is not " 1030 "set."); 1031 TaskgroupDescriptor = I->TaskgroupReductionRef; 1032 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), 1033 Data.PrivateCopy, I->DefaultAttrLoc); 1034 } 1035 return DSAVarData(); 1036 } 1037 1038 const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData( 1039 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef, 1040 Expr *&TaskgroupDescriptor) const { 1041 D = getCanonicalDecl(D); 1042 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 1043 if (Stack.back().first.empty()) 1044 return DSAVarData(); 1045 for (iterator I = std::next(Stack.back().first.rbegin(), 1), 1046 E = Stack.back().first.rend(); 1047 I != E; std::advance(I, 1)) { 1048 const DSAInfo &Data = I->SharingMap.lookup(D); 1049 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) 1050 continue; 1051 const ReductionData &ReductionData = I->ReductionMap.lookup(D); 1052 if (!ReductionData.ReductionOp || 1053 !ReductionData.ReductionOp.is<const Expr *>()) 1054 return DSAVarData(); 1055 SR = ReductionData.ReductionRange; 1056 ReductionRef = ReductionData.ReductionOp.get<const Expr *>(); 1057 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 1058 "expression for the descriptor is not " 1059 "set."); 1060 TaskgroupDescriptor = I->TaskgroupReductionRef; 1061 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), 1062 Data.PrivateCopy, I->DefaultAttrLoc); 1063 } 1064 return DSAVarData(); 1065 } 1066 1067 bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const { 1068 D = D->getCanonicalDecl(); 1069 if (!isStackEmpty()) { 1070 iterator I = Iter, E = Stack.back().first.rend(); 1071 Scope *TopScope = nullptr; 1072 while (I != E && !isImplicitOrExplicitTaskingRegion(I->Directive) && 1073 !isOpenMPTargetExecutionDirective(I->Directive)) 1074 ++I; 1075 if (I == E) 1076 return false; 1077 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; 1078 Scope *CurScope = getCurScope(); 1079 while (CurScope != TopScope && !CurScope->isDeclScope(D)) 1080 CurScope = CurScope->getParent(); 1081 return CurScope != TopScope; 1082 } 1083 return false; 1084 } 1085 1086 static bool isConstNotMutableType(Sema &SemaRef, QualType Type, 1087 bool AcceptIfMutable = true, 1088 bool *IsClassType = nullptr) { 1089 ASTContext &Context = SemaRef.getASTContext(); 1090 Type = Type.getNonReferenceType().getCanonicalType(); 1091 bool IsConstant = Type.isConstant(Context); 1092 Type = Context.getBaseElementType(Type); 1093 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus 1094 ? Type->getAsCXXRecordDecl() 1095 : nullptr; 1096 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 1097 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate()) 1098 RD = CTD->getTemplatedDecl(); 1099 if (IsClassType) 1100 *IsClassType = RD; 1101 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD && 1102 RD->hasDefinition() && RD->hasMutableFields()); 1103 } 1104 1105 static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D, 1106 QualType Type, OpenMPClauseKind CKind, 1107 SourceLocation ELoc, 1108 bool AcceptIfMutable = true, 1109 bool ListItemNotVar = false) { 1110 ASTContext &Context = SemaRef.getASTContext(); 1111 bool IsClassType; 1112 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) { 1113 unsigned Diag = ListItemNotVar 1114 ? diag::err_omp_const_list_item 1115 : IsClassType ? diag::err_omp_const_not_mutable_variable 1116 : diag::err_omp_const_variable; 1117 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind); 1118 if (!ListItemNotVar && D) { 1119 const VarDecl *VD = dyn_cast<VarDecl>(D); 1120 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 1121 VarDecl::DeclarationOnly; 1122 SemaRef.Diag(D->getLocation(), 1123 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1124 << D; 1125 } 1126 return true; 1127 } 1128 return false; 1129 } 1130 1131 const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, 1132 bool FromParent) { 1133 D = getCanonicalDecl(D); 1134 DSAVarData DVar; 1135 1136 auto *VD = dyn_cast<VarDecl>(D); 1137 auto TI = Threadprivates.find(D); 1138 if (TI != Threadprivates.end()) { 1139 DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); 1140 DVar.CKind = OMPC_threadprivate; 1141 return DVar; 1142 } 1143 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 1144 DVar.RefExpr = buildDeclRefExpr( 1145 SemaRef, VD, D->getType().getNonReferenceType(), 1146 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation()); 1147 DVar.CKind = OMPC_threadprivate; 1148 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1149 return DVar; 1150 } 1151 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1152 // in a Construct, C/C++, predetermined, p.1] 1153 // Variables appearing in threadprivate directives are threadprivate. 1154 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 1155 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1156 SemaRef.getLangOpts().OpenMPUseTLS && 1157 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 1158 (VD && VD->getStorageClass() == SC_Register && 1159 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 1160 DVar.RefExpr = buildDeclRefExpr( 1161 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation()); 1162 DVar.CKind = OMPC_threadprivate; 1163 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 1164 return DVar; 1165 } 1166 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD && 1167 VD->isLocalVarDeclOrParm() && !isStackEmpty() && 1168 !isLoopControlVariable(D).first) { 1169 iterator IterTarget = 1170 std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(), 1171 [](const SharingMapTy &Data) { 1172 return isOpenMPTargetExecutionDirective(Data.Directive); 1173 }); 1174 if (IterTarget != Stack.back().first.rend()) { 1175 iterator ParentIterTarget = std::next(IterTarget, 1); 1176 for (iterator Iter = Stack.back().first.rbegin(); 1177 Iter != ParentIterTarget; std::advance(Iter, 1)) { 1178 if (isOpenMPLocal(VD, Iter)) { 1179 DVar.RefExpr = 1180 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1181 D->getLocation()); 1182 DVar.CKind = OMPC_threadprivate; 1183 return DVar; 1184 } 1185 } 1186 if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) { 1187 auto DSAIter = IterTarget->SharingMap.find(D); 1188 if (DSAIter != IterTarget->SharingMap.end() && 1189 isOpenMPPrivate(DSAIter->getSecond().Attributes)) { 1190 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer(); 1191 DVar.CKind = OMPC_threadprivate; 1192 return DVar; 1193 } 1194 iterator End = Stack.back().first.rend(); 1195 if (!SemaRef.isOpenMPCapturedByRef( 1196 D, std::distance(ParentIterTarget, End))) { 1197 DVar.RefExpr = 1198 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1199 IterTarget->ConstructLoc); 1200 DVar.CKind = OMPC_threadprivate; 1201 return DVar; 1202 } 1203 } 1204 } 1205 } 1206 1207 if (isStackEmpty()) 1208 // Not in OpenMP execution region and top scope was already checked. 1209 return DVar; 1210 1211 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1212 // in a Construct, C/C++, predetermined, p.4] 1213 // Static data members are shared. 1214 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1215 // in a Construct, C/C++, predetermined, p.7] 1216 // Variables with static storage duration that are declared in a scope 1217 // inside the construct are shared. 1218 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; }; 1219 if (VD && VD->isStaticDataMember()) { 1220 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent); 1221 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 1222 return DVar; 1223 1224 DVar.CKind = OMPC_shared; 1225 return DVar; 1226 } 1227 1228 // The predetermined shared attribute for const-qualified types having no 1229 // mutable members was removed after OpenMP 3.1. 1230 if (SemaRef.LangOpts.OpenMP <= 31) { 1231 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1232 // in a Construct, C/C++, predetermined, p.6] 1233 // Variables with const qualified type having no mutable member are 1234 // shared. 1235 if (isConstNotMutableType(SemaRef, D->getType())) { 1236 // Variables with const-qualified type having no mutable member may be 1237 // listed in a firstprivate clause, even if they are static data members. 1238 DSAVarData DVarTemp = hasInnermostDSA( 1239 D, 1240 [](OpenMPClauseKind C) { 1241 return C == OMPC_firstprivate || C == OMPC_shared; 1242 }, 1243 MatchesAlways, FromParent); 1244 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 1245 return DVarTemp; 1246 1247 DVar.CKind = OMPC_shared; 1248 return DVar; 1249 } 1250 } 1251 1252 // Explicitly specified attributes and local variables with predetermined 1253 // attributes. 1254 iterator I = Stack.back().first.rbegin(); 1255 iterator EndI = Stack.back().first.rend(); 1256 if (FromParent && I != EndI) 1257 std::advance(I, 1); 1258 auto It = I->SharingMap.find(D); 1259 if (It != I->SharingMap.end()) { 1260 const DSAInfo &Data = It->getSecond(); 1261 DVar.RefExpr = Data.RefExpr.getPointer(); 1262 DVar.PrivateCopy = Data.PrivateCopy; 1263 DVar.CKind = Data.Attributes; 1264 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1265 DVar.DKind = I->Directive; 1266 } 1267 1268 return DVar; 1269 } 1270 1271 const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1272 bool FromParent) const { 1273 if (isStackEmpty()) { 1274 iterator I; 1275 return getDSA(I, D); 1276 } 1277 D = getCanonicalDecl(D); 1278 iterator StartI = Stack.back().first.rbegin(); 1279 iterator EndI = Stack.back().first.rend(); 1280 if (FromParent && StartI != EndI) 1281 std::advance(StartI, 1); 1282 return getDSA(StartI, D); 1283 } 1284 1285 const DSAStackTy::DSAVarData 1286 DSAStackTy::hasDSA(ValueDecl *D, 1287 const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1288 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1289 bool FromParent) const { 1290 if (isStackEmpty()) 1291 return {}; 1292 D = getCanonicalDecl(D); 1293 iterator I = Stack.back().first.rbegin(); 1294 iterator EndI = Stack.back().first.rend(); 1295 if (FromParent && I != EndI) 1296 std::advance(I, 1); 1297 for (; I != EndI; std::advance(I, 1)) { 1298 if (!DPred(I->Directive) && !isImplicitOrExplicitTaskingRegion(I->Directive)) 1299 continue; 1300 iterator NewI = I; 1301 DSAVarData DVar = getDSA(NewI, D); 1302 if (I == NewI && CPred(DVar.CKind)) 1303 return DVar; 1304 } 1305 return {}; 1306 } 1307 1308 const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 1309 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1310 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1311 bool FromParent) const { 1312 if (isStackEmpty()) 1313 return {}; 1314 D = getCanonicalDecl(D); 1315 iterator StartI = Stack.back().first.rbegin(); 1316 iterator EndI = Stack.back().first.rend(); 1317 if (FromParent && StartI != EndI) 1318 std::advance(StartI, 1); 1319 if (StartI == EndI || !DPred(StartI->Directive)) 1320 return {}; 1321 iterator NewI = StartI; 1322 DSAVarData DVar = getDSA(NewI, D); 1323 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData(); 1324 } 1325 1326 bool DSAStackTy::hasExplicitDSA( 1327 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred, 1328 unsigned Level, bool NotLastprivate) const { 1329 if (isStackEmpty()) 1330 return false; 1331 D = getCanonicalDecl(D); 1332 auto StartI = Stack.back().first.begin(); 1333 auto EndI = Stack.back().first.end(); 1334 if (std::distance(StartI, EndI) <= (int)Level) 1335 return false; 1336 std::advance(StartI, Level); 1337 auto I = StartI->SharingMap.find(D); 1338 if ((I != StartI->SharingMap.end()) && 1339 I->getSecond().RefExpr.getPointer() && 1340 CPred(I->getSecond().Attributes) && 1341 (!NotLastprivate || !I->getSecond().RefExpr.getInt())) 1342 return true; 1343 // Check predetermined rules for the loop control variables. 1344 auto LI = StartI->LCVMap.find(D); 1345 if (LI != StartI->LCVMap.end()) 1346 return CPred(OMPC_private); 1347 return false; 1348 } 1349 1350 bool DSAStackTy::hasExplicitDirective( 1351 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred, 1352 unsigned Level) const { 1353 if (isStackEmpty()) 1354 return false; 1355 auto StartI = Stack.back().first.begin(); 1356 auto EndI = Stack.back().first.end(); 1357 if (std::distance(StartI, EndI) <= (int)Level) 1358 return false; 1359 std::advance(StartI, Level); 1360 return DPred(StartI->Directive); 1361 } 1362 1363 bool DSAStackTy::hasDirective( 1364 const llvm::function_ref<bool(OpenMPDirectiveKind, 1365 const DeclarationNameInfo &, SourceLocation)> 1366 DPred, 1367 bool FromParent) const { 1368 // We look only in the enclosing region. 1369 if (isStackEmpty()) 1370 return false; 1371 auto StartI = std::next(Stack.back().first.rbegin()); 1372 auto EndI = Stack.back().first.rend(); 1373 if (FromParent && StartI != EndI) 1374 StartI = std::next(StartI); 1375 for (auto I = StartI, EE = EndI; I != EE; ++I) { 1376 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 1377 return true; 1378 } 1379 return false; 1380 } 1381 1382 void Sema::InitDataSharingAttributesStack() { 1383 VarDataSharingAttributesStack = new DSAStackTy(*this); 1384 } 1385 1386 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 1387 1388 void Sema::pushOpenMPFunctionRegion() { 1389 DSAStack->pushFunction(); 1390 } 1391 1392 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 1393 DSAStack->popFunction(OldFSI); 1394 } 1395 1396 static bool isOpenMPDeviceDelayedContext(Sema &S) { 1397 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && 1398 "Expected OpenMP device compilation."); 1399 return !S.isInOpenMPTargetExecutionDirective() && 1400 !S.isInOpenMPDeclareTargetContext(); 1401 } 1402 1403 /// Do we know that we will eventually codegen the given function? 1404 static bool isKnownEmitted(Sema &S, FunctionDecl *FD) { 1405 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice && 1406 "Expected OpenMP device compilation."); 1407 // Templates are emitted when they're instantiated. 1408 if (FD->isDependentContext()) 1409 return false; 1410 1411 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 1412 FD->getCanonicalDecl())) 1413 return true; 1414 1415 // Otherwise, the function is known-emitted if it's in our set of 1416 // known-emitted functions. 1417 return S.DeviceKnownEmittedFns.count(FD) > 0; 1418 } 1419 1420 Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc, 1421 unsigned DiagID) { 1422 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 1423 "Expected OpenMP device compilation."); 1424 return DeviceDiagBuilder((isOpenMPDeviceDelayedContext(*this) && 1425 !isKnownEmitted(*this, getCurFunctionDecl())) 1426 ? DeviceDiagBuilder::K_Deferred 1427 : DeviceDiagBuilder::K_Immediate, 1428 Loc, DiagID, getCurFunctionDecl(), *this); 1429 } 1430 1431 void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee) { 1432 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice && 1433 "Expected OpenMP device compilation."); 1434 assert(Callee && "Callee may not be null."); 1435 FunctionDecl *Caller = getCurFunctionDecl(); 1436 1437 // If the caller is known-emitted, mark the callee as known-emitted. 1438 // Otherwise, mark the call in our call graph so we can traverse it later. 1439 if (!isOpenMPDeviceDelayedContext(*this) || 1440 (Caller && isKnownEmitted(*this, Caller))) 1441 markKnownEmitted(*this, Caller, Callee, Loc, isKnownEmitted); 1442 else if (Caller) 1443 DeviceCallGraph[Caller].insert({Callee, Loc}); 1444 } 1445 1446 bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const { 1447 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1448 1449 ASTContext &Ctx = getASTContext(); 1450 bool IsByRef = true; 1451 1452 // Find the directive that is associated with the provided scope. 1453 D = cast<ValueDecl>(D->getCanonicalDecl()); 1454 QualType Ty = D->getType(); 1455 1456 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 1457 // This table summarizes how a given variable should be passed to the device 1458 // given its type and the clauses where it appears. This table is based on 1459 // the description in OpenMP 4.5 [2.10.4, target Construct] and 1460 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 1461 // 1462 // ========================================================================= 1463 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 1464 // | |(tofrom:scalar)| | pvt | | | | 1465 // ========================================================================= 1466 // | scl | | | | - | | bycopy| 1467 // | scl | | - | x | - | - | bycopy| 1468 // | scl | | x | - | - | - | null | 1469 // | scl | x | | | - | | byref | 1470 // | scl | x | - | x | - | - | bycopy| 1471 // | scl | x | x | - | - | - | null | 1472 // | scl | | - | - | - | x | byref | 1473 // | scl | x | - | - | - | x | byref | 1474 // 1475 // | agg | n.a. | | | - | | byref | 1476 // | agg | n.a. | - | x | - | - | byref | 1477 // | agg | n.a. | x | - | - | - | null | 1478 // | agg | n.a. | - | - | - | x | byref | 1479 // | agg | n.a. | - | - | - | x[] | byref | 1480 // 1481 // | ptr | n.a. | | | - | | bycopy| 1482 // | ptr | n.a. | - | x | - | - | bycopy| 1483 // | ptr | n.a. | x | - | - | - | null | 1484 // | ptr | n.a. | - | - | - | x | byref | 1485 // | ptr | n.a. | - | - | - | x[] | bycopy| 1486 // | ptr | n.a. | - | - | x | | bycopy| 1487 // | ptr | n.a. | - | - | x | x | bycopy| 1488 // | ptr | n.a. | - | - | x | x[] | bycopy| 1489 // ========================================================================= 1490 // Legend: 1491 // scl - scalar 1492 // ptr - pointer 1493 // agg - aggregate 1494 // x - applies 1495 // - - invalid in this combination 1496 // [] - mapped with an array section 1497 // byref - should be mapped by reference 1498 // byval - should be mapped by value 1499 // null - initialize a local variable to null on the device 1500 // 1501 // Observations: 1502 // - All scalar declarations that show up in a map clause have to be passed 1503 // by reference, because they may have been mapped in the enclosing data 1504 // environment. 1505 // - If the scalar value does not fit the size of uintptr, it has to be 1506 // passed by reference, regardless the result in the table above. 1507 // - For pointers mapped by value that have either an implicit map or an 1508 // array section, the runtime library may pass the NULL value to the 1509 // device instead of the value passed to it by the compiler. 1510 1511 if (Ty->isReferenceType()) 1512 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 1513 1514 // Locate map clauses and see if the variable being captured is referred to 1515 // in any of those clauses. Here we only care about variables, not fields, 1516 // because fields are part of aggregates. 1517 bool IsVariableUsedInMapClause = false; 1518 bool IsVariableAssociatedWithSection = false; 1519 1520 DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1521 D, Level, 1522 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D]( 1523 OMPClauseMappableExprCommon::MappableExprComponentListRef 1524 MapExprComponents, 1525 OpenMPClauseKind WhereFoundClauseKind) { 1526 // Only the map clause information influences how a variable is 1527 // captured. E.g. is_device_ptr does not require changing the default 1528 // behavior. 1529 if (WhereFoundClauseKind != OMPC_map) 1530 return false; 1531 1532 auto EI = MapExprComponents.rbegin(); 1533 auto EE = MapExprComponents.rend(); 1534 1535 assert(EI != EE && "Invalid map expression!"); 1536 1537 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 1538 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 1539 1540 ++EI; 1541 if (EI == EE) 1542 return false; 1543 1544 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 1545 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 1546 isa<MemberExpr>(EI->getAssociatedExpression())) { 1547 IsVariableAssociatedWithSection = true; 1548 // There is nothing more we need to know about this variable. 1549 return true; 1550 } 1551 1552 // Keep looking for more map info. 1553 return false; 1554 }); 1555 1556 if (IsVariableUsedInMapClause) { 1557 // If variable is identified in a map clause it is always captured by 1558 // reference except if it is a pointer that is dereferenced somehow. 1559 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 1560 } else { 1561 // By default, all the data that has a scalar type is mapped by copy 1562 // (except for reduction variables). 1563 IsByRef = 1564 (DSAStack->isForceCaptureByReferenceInTargetExecutable() && 1565 !Ty->isAnyPointerType()) || 1566 !Ty->isScalarType() || 1567 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar || 1568 DSAStack->hasExplicitDSA( 1569 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level); 1570 } 1571 } 1572 1573 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 1574 IsByRef = 1575 ((DSAStack->isForceCaptureByReferenceInTargetExecutable() && 1576 !Ty->isAnyPointerType()) || 1577 !DSAStack->hasExplicitDSA( 1578 D, 1579 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; }, 1580 Level, /*NotLastprivate=*/true)) && 1581 // If the variable is artificial and must be captured by value - try to 1582 // capture by value. 1583 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() && 1584 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()); 1585 } 1586 1587 // When passing data by copy, we need to make sure it fits the uintptr size 1588 // and alignment, because the runtime library only deals with uintptr types. 1589 // If it does not fit the uintptr size, we need to pass the data by reference 1590 // instead. 1591 if (!IsByRef && 1592 (Ctx.getTypeSizeInChars(Ty) > 1593 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 1594 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 1595 IsByRef = true; 1596 } 1597 1598 return IsByRef; 1599 } 1600 1601 unsigned Sema::getOpenMPNestingLevel() const { 1602 assert(getLangOpts().OpenMP); 1603 return DSAStack->getNestingLevel(); 1604 } 1605 1606 bool Sema::isInOpenMPTargetExecutionDirective() const { 1607 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) && 1608 !DSAStack->isClauseParsingMode()) || 1609 DSAStack->hasDirective( 1610 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 1611 SourceLocation) -> bool { 1612 return isOpenMPTargetExecutionDirective(K); 1613 }, 1614 false); 1615 } 1616 1617 VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) { 1618 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1619 D = getCanonicalDecl(D); 1620 1621 // If we are attempting to capture a global variable in a directive with 1622 // 'target' we return true so that this global is also mapped to the device. 1623 // 1624 auto *VD = dyn_cast<VarDecl>(D); 1625 if (VD && !VD->hasLocalStorage()) { 1626 if (isInOpenMPDeclareTargetContext() && 1627 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) { 1628 // Try to mark variable as declare target if it is used in capturing 1629 // regions. 1630 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 1631 checkDeclIsAllowedInOpenMPTarget(nullptr, VD); 1632 return nullptr; 1633 } else if (isInOpenMPTargetExecutionDirective()) { 1634 // If the declaration is enclosed in a 'declare target' directive, 1635 // then it should not be captured. 1636 // 1637 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 1638 return nullptr; 1639 return VD; 1640 } 1641 } 1642 // Capture variables captured by reference in lambdas for target-based 1643 // directives. 1644 if (VD && !DSAStack->isClauseParsingMode()) { 1645 if (const auto *RD = VD->getType() 1646 .getCanonicalType() 1647 .getNonReferenceType() 1648 ->getAsCXXRecordDecl()) { 1649 bool SavedForceCaptureByReferenceInTargetExecutable = 1650 DSAStack->isForceCaptureByReferenceInTargetExecutable(); 1651 DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true); 1652 if (RD->isLambda()) { 1653 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures; 1654 FieldDecl *ThisCapture; 1655 RD->getCaptureFields(Captures, ThisCapture); 1656 for (const LambdaCapture &LC : RD->captures()) { 1657 if (LC.getCaptureKind() == LCK_ByRef) { 1658 VarDecl *VD = LC.getCapturedVar(); 1659 DeclContext *VDC = VD->getDeclContext(); 1660 if (!VDC->Encloses(CurContext)) 1661 continue; 1662 DSAStackTy::DSAVarData DVarPrivate = 1663 DSAStack->getTopDSA(VD, /*FromParent=*/false); 1664 // Do not capture already captured variables. 1665 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) && 1666 DVarPrivate.CKind == OMPC_unknown && 1667 !DSAStack->checkMappableExprComponentListsForDecl( 1668 D, /*CurrentRegionOnly=*/true, 1669 [](OMPClauseMappableExprCommon:: 1670 MappableExprComponentListRef, 1671 OpenMPClauseKind) { return true; })) 1672 MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar()); 1673 } else if (LC.getCaptureKind() == LCK_This) { 1674 QualType ThisTy = getCurrentThisType(); 1675 if (!ThisTy.isNull() && 1676 Context.typesAreCompatible(ThisTy, ThisCapture->getType())) 1677 CheckCXXThisCapture(LC.getLocation()); 1678 } 1679 } 1680 } 1681 DSAStack->setForceCaptureByReferenceInTargetExecutable( 1682 SavedForceCaptureByReferenceInTargetExecutable); 1683 } 1684 } 1685 1686 if (DSAStack->getCurrentDirective() != OMPD_unknown && 1687 (!DSAStack->isClauseParsingMode() || 1688 DSAStack->getParentDirective() != OMPD_unknown)) { 1689 auto &&Info = DSAStack->isLoopControlVariable(D); 1690 if (Info.first || 1691 (VD && VD->hasLocalStorage() && 1692 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) || 1693 (VD && DSAStack->isForceVarCapturing())) 1694 return VD ? VD : Info.second; 1695 DSAStackTy::DSAVarData DVarPrivate = 1696 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 1697 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind)) 1698 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1699 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate, 1700 [](OpenMPDirectiveKind) { return true; }, 1701 DSAStack->isClauseParsingMode()); 1702 if (DVarPrivate.CKind != OMPC_unknown) 1703 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1704 } 1705 return nullptr; 1706 } 1707 1708 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 1709 unsigned Level) const { 1710 SmallVector<OpenMPDirectiveKind, 4> Regions; 1711 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level)); 1712 FunctionScopesIndex -= Regions.size(); 1713 } 1714 1715 void Sema::startOpenMPLoop() { 1716 assert(LangOpts.OpenMP && "OpenMP must be enabled."); 1717 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) 1718 DSAStack->loopInit(); 1719 } 1720 1721 bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const { 1722 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1723 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 1724 if (DSAStack->getAssociatedLoops() > 0 && 1725 !DSAStack->isLoopStarted()) { 1726 DSAStack->resetPossibleLoopCounter(D); 1727 DSAStack->loopStart(); 1728 return true; 1729 } 1730 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() || 1731 DSAStack->isLoopControlVariable(D).first) && 1732 !DSAStack->hasExplicitDSA( 1733 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) && 1734 !isOpenMPSimdDirective(DSAStack->getCurrentDirective())) 1735 return true; 1736 } 1737 return DSAStack->hasExplicitDSA( 1738 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) || 1739 (DSAStack->isClauseParsingMode() && 1740 DSAStack->getClauseParsingMode() == OMPC_private) || 1741 // Consider taskgroup reduction descriptor variable a private to avoid 1742 // possible capture in the region. 1743 (DSAStack->hasExplicitDirective( 1744 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; }, 1745 Level) && 1746 DSAStack->isTaskgroupReductionRef(D, Level)); 1747 } 1748 1749 void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D, 1750 unsigned Level) { 1751 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1752 D = getCanonicalDecl(D); 1753 OpenMPClauseKind OMPC = OMPC_unknown; 1754 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) { 1755 const unsigned NewLevel = I - 1; 1756 if (DSAStack->hasExplicitDSA(D, 1757 [&OMPC](const OpenMPClauseKind K) { 1758 if (isOpenMPPrivate(K)) { 1759 OMPC = K; 1760 return true; 1761 } 1762 return false; 1763 }, 1764 NewLevel)) 1765 break; 1766 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1767 D, NewLevel, 1768 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 1769 OpenMPClauseKind) { return true; })) { 1770 OMPC = OMPC_map; 1771 break; 1772 } 1773 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1774 NewLevel)) { 1775 OMPC = OMPC_map; 1776 if (D->getType()->isScalarType() && 1777 DSAStack->getDefaultDMAAtLevel(NewLevel) != 1778 DefaultMapAttributes::DMA_tofrom_scalar) 1779 OMPC = OMPC_firstprivate; 1780 break; 1781 } 1782 } 1783 if (OMPC != OMPC_unknown) 1784 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC)); 1785 } 1786 1787 bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, 1788 unsigned Level) const { 1789 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1790 // Return true if the current level is no longer enclosed in a target region. 1791 1792 const auto *VD = dyn_cast<VarDecl>(D); 1793 return VD && !VD->hasLocalStorage() && 1794 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1795 Level); 1796 } 1797 1798 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 1799 1800 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 1801 const DeclarationNameInfo &DirName, 1802 Scope *CurScope, SourceLocation Loc) { 1803 DSAStack->push(DKind, DirName, CurScope, Loc); 1804 PushExpressionEvaluationContext( 1805 ExpressionEvaluationContext::PotentiallyEvaluated); 1806 } 1807 1808 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 1809 DSAStack->setClauseParsingMode(K); 1810 } 1811 1812 void Sema::EndOpenMPClause() { 1813 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 1814 } 1815 1816 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 1817 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 1818 // A variable of class type (or array thereof) that appears in a lastprivate 1819 // clause requires an accessible, unambiguous default constructor for the 1820 // class type, unless the list item is also specified in a firstprivate 1821 // clause. 1822 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 1823 for (OMPClause *C : D->clauses()) { 1824 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 1825 SmallVector<Expr *, 8> PrivateCopies; 1826 for (Expr *DE : Clause->varlists()) { 1827 if (DE->isValueDependent() || DE->isTypeDependent()) { 1828 PrivateCopies.push_back(nullptr); 1829 continue; 1830 } 1831 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 1832 auto *VD = cast<VarDecl>(DRE->getDecl()); 1833 QualType Type = VD->getType().getNonReferenceType(); 1834 const DSAStackTy::DSAVarData DVar = 1835 DSAStack->getTopDSA(VD, /*FromParent=*/false); 1836 if (DVar.CKind == OMPC_lastprivate) { 1837 // Generate helper private variable and initialize it with the 1838 // default value. The address of the original variable is replaced 1839 // by the address of the new private variable in CodeGen. This new 1840 // variable is not added to IdResolver, so the code in the OpenMP 1841 // region uses original variable for proper diagnostics. 1842 VarDecl *VDPrivate = buildVarDecl( 1843 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 1844 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE); 1845 ActOnUninitializedDecl(VDPrivate); 1846 if (VDPrivate->isInvalidDecl()) 1847 continue; 1848 PrivateCopies.push_back(buildDeclRefExpr( 1849 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 1850 } else { 1851 // The variable is also a firstprivate, so initialization sequence 1852 // for private copy is generated already. 1853 PrivateCopies.push_back(nullptr); 1854 } 1855 } 1856 // Set initializers to private copies if no errors were found. 1857 if (PrivateCopies.size() == Clause->varlist_size()) 1858 Clause->setPrivateCopies(PrivateCopies); 1859 } 1860 } 1861 } 1862 1863 DSAStack->pop(); 1864 DiscardCleanupsInEvaluationContext(); 1865 PopExpressionEvaluationContext(); 1866 } 1867 1868 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 1869 Expr *NumIterations, Sema &SemaRef, 1870 Scope *S, DSAStackTy *Stack); 1871 1872 namespace { 1873 1874 class VarDeclFilterCCC final : public CorrectionCandidateCallback { 1875 private: 1876 Sema &SemaRef; 1877 1878 public: 1879 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 1880 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1881 NamedDecl *ND = Candidate.getCorrectionDecl(); 1882 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 1883 return VD->hasGlobalStorage() && 1884 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1885 SemaRef.getCurScope()); 1886 } 1887 return false; 1888 } 1889 }; 1890 1891 class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback { 1892 private: 1893 Sema &SemaRef; 1894 1895 public: 1896 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 1897 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1898 NamedDecl *ND = Candidate.getCorrectionDecl(); 1899 if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) { 1900 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1901 SemaRef.getCurScope()); 1902 } 1903 return false; 1904 } 1905 }; 1906 1907 } // namespace 1908 1909 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 1910 CXXScopeSpec &ScopeSpec, 1911 const DeclarationNameInfo &Id) { 1912 LookupResult Lookup(*this, Id, LookupOrdinaryName); 1913 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 1914 1915 if (Lookup.isAmbiguous()) 1916 return ExprError(); 1917 1918 VarDecl *VD; 1919 if (!Lookup.isSingleResult()) { 1920 if (TypoCorrection Corrected = CorrectTypo( 1921 Id, LookupOrdinaryName, CurScope, nullptr, 1922 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) { 1923 diagnoseTypo(Corrected, 1924 PDiag(Lookup.empty() 1925 ? diag::err_undeclared_var_use_suggest 1926 : diag::err_omp_expected_var_arg_suggest) 1927 << Id.getName()); 1928 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 1929 } else { 1930 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 1931 : diag::err_omp_expected_var_arg) 1932 << Id.getName(); 1933 return ExprError(); 1934 } 1935 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) { 1936 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 1937 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 1938 return ExprError(); 1939 } 1940 Lookup.suppressDiagnostics(); 1941 1942 // OpenMP [2.9.2, Syntax, C/C++] 1943 // Variables must be file-scope, namespace-scope, or static block-scope. 1944 if (!VD->hasGlobalStorage()) { 1945 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 1946 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal(); 1947 bool IsDecl = 1948 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1949 Diag(VD->getLocation(), 1950 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1951 << VD; 1952 return ExprError(); 1953 } 1954 1955 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 1956 NamedDecl *ND = CanonicalVD; 1957 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 1958 // A threadprivate directive for file-scope variables must appear outside 1959 // any definition or declaration. 1960 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 1961 !getCurLexicalContext()->isTranslationUnit()) { 1962 Diag(Id.getLoc(), diag::err_omp_var_scope) 1963 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1964 bool IsDecl = 1965 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1966 Diag(VD->getLocation(), 1967 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1968 << VD; 1969 return ExprError(); 1970 } 1971 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 1972 // A threadprivate directive for static class member variables must appear 1973 // in the class definition, in the same scope in which the member 1974 // variables are declared. 1975 if (CanonicalVD->isStaticDataMember() && 1976 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 1977 Diag(Id.getLoc(), diag::err_omp_var_scope) 1978 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1979 bool IsDecl = 1980 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1981 Diag(VD->getLocation(), 1982 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1983 << VD; 1984 return ExprError(); 1985 } 1986 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 1987 // A threadprivate directive for namespace-scope variables must appear 1988 // outside any definition or declaration other than the namespace 1989 // definition itself. 1990 if (CanonicalVD->getDeclContext()->isNamespace() && 1991 (!getCurLexicalContext()->isFileContext() || 1992 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 1993 Diag(Id.getLoc(), diag::err_omp_var_scope) 1994 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1995 bool IsDecl = 1996 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1997 Diag(VD->getLocation(), 1998 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1999 << VD; 2000 return ExprError(); 2001 } 2002 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 2003 // A threadprivate directive for static block-scope variables must appear 2004 // in the scope of the variable and not in a nested scope. 2005 if (CanonicalVD->isStaticLocal() && CurScope && 2006 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 2007 Diag(Id.getLoc(), diag::err_omp_var_scope) 2008 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 2009 bool IsDecl = 2010 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2011 Diag(VD->getLocation(), 2012 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2013 << VD; 2014 return ExprError(); 2015 } 2016 2017 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 2018 // A threadprivate directive must lexically precede all references to any 2019 // of the variables in its list. 2020 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) { 2021 Diag(Id.getLoc(), diag::err_omp_var_used) 2022 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 2023 return ExprError(); 2024 } 2025 2026 QualType ExprType = VD->getType().getNonReferenceType(); 2027 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 2028 SourceLocation(), VD, 2029 /*RefersToEnclosingVariableOrCapture=*/false, 2030 Id.getLoc(), ExprType, VK_LValue); 2031 } 2032 2033 Sema::DeclGroupPtrTy 2034 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 2035 ArrayRef<Expr *> VarList) { 2036 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 2037 CurContext->addDecl(D); 2038 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2039 } 2040 return nullptr; 2041 } 2042 2043 namespace { 2044 class LocalVarRefChecker final 2045 : public ConstStmtVisitor<LocalVarRefChecker, bool> { 2046 Sema &SemaRef; 2047 2048 public: 2049 bool VisitDeclRefExpr(const DeclRefExpr *E) { 2050 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 2051 if (VD->hasLocalStorage()) { 2052 SemaRef.Diag(E->getBeginLoc(), 2053 diag::err_omp_local_var_in_threadprivate_init) 2054 << E->getSourceRange(); 2055 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 2056 << VD << VD->getSourceRange(); 2057 return true; 2058 } 2059 } 2060 return false; 2061 } 2062 bool VisitStmt(const Stmt *S) { 2063 for (const Stmt *Child : S->children()) { 2064 if (Child && Visit(Child)) 2065 return true; 2066 } 2067 return false; 2068 } 2069 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 2070 }; 2071 } // namespace 2072 2073 OMPThreadPrivateDecl * 2074 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 2075 SmallVector<Expr *, 8> Vars; 2076 for (Expr *RefExpr : VarList) { 2077 auto *DE = cast<DeclRefExpr>(RefExpr); 2078 auto *VD = cast<VarDecl>(DE->getDecl()); 2079 SourceLocation ILoc = DE->getExprLoc(); 2080 2081 // Mark variable as used. 2082 VD->setReferenced(); 2083 VD->markUsed(Context); 2084 2085 QualType QType = VD->getType(); 2086 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 2087 // It will be analyzed later. 2088 Vars.push_back(DE); 2089 continue; 2090 } 2091 2092 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2093 // A threadprivate variable must not have an incomplete type. 2094 if (RequireCompleteType(ILoc, VD->getType(), 2095 diag::err_omp_threadprivate_incomplete_type)) { 2096 continue; 2097 } 2098 2099 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 2100 // A threadprivate variable must not have a reference type. 2101 if (VD->getType()->isReferenceType()) { 2102 Diag(ILoc, diag::err_omp_ref_type_arg) 2103 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 2104 bool IsDecl = 2105 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2106 Diag(VD->getLocation(), 2107 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2108 << VD; 2109 continue; 2110 } 2111 2112 // Check if this is a TLS variable. If TLS is not being supported, produce 2113 // the corresponding diagnostic. 2114 if ((VD->getTLSKind() != VarDecl::TLS_None && 2115 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 2116 getLangOpts().OpenMPUseTLS && 2117 getASTContext().getTargetInfo().isTLSSupported())) || 2118 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 2119 !VD->isLocalVarDecl())) { 2120 Diag(ILoc, diag::err_omp_var_thread_local) 2121 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 2122 bool IsDecl = 2123 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 2124 Diag(VD->getLocation(), 2125 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 2126 << VD; 2127 continue; 2128 } 2129 2130 // Check if initial value of threadprivate variable reference variable with 2131 // local storage (it is not supported by runtime). 2132 if (const Expr *Init = VD->getAnyInitializer()) { 2133 LocalVarRefChecker Checker(*this); 2134 if (Checker.Visit(Init)) 2135 continue; 2136 } 2137 2138 Vars.push_back(RefExpr); 2139 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 2140 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 2141 Context, SourceRange(Loc, Loc))); 2142 if (ASTMutationListener *ML = Context.getASTMutationListener()) 2143 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 2144 } 2145 OMPThreadPrivateDecl *D = nullptr; 2146 if (!Vars.empty()) { 2147 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 2148 Vars); 2149 D->setAccess(AS_public); 2150 } 2151 return D; 2152 } 2153 2154 Sema::DeclGroupPtrTy 2155 Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc, 2156 ArrayRef<OMPClause *> ClauseList) { 2157 OMPRequiresDecl *D = nullptr; 2158 if (!CurContext->isFileContext()) { 2159 Diag(Loc, diag::err_omp_invalid_scope) << "requires"; 2160 } else { 2161 D = CheckOMPRequiresDecl(Loc, ClauseList); 2162 if (D) { 2163 CurContext->addDecl(D); 2164 DSAStack->addRequiresDecl(D); 2165 } 2166 } 2167 return DeclGroupPtrTy::make(DeclGroupRef(D)); 2168 } 2169 2170 OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc, 2171 ArrayRef<OMPClause *> ClauseList) { 2172 if (!DSAStack->hasDuplicateRequiresClause(ClauseList)) 2173 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc, 2174 ClauseList); 2175 return nullptr; 2176 } 2177 2178 static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack, 2179 const ValueDecl *D, 2180 const DSAStackTy::DSAVarData &DVar, 2181 bool IsLoopIterVar = false) { 2182 if (DVar.RefExpr) { 2183 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 2184 << getOpenMPClauseName(DVar.CKind); 2185 return; 2186 } 2187 enum { 2188 PDSA_StaticMemberShared, 2189 PDSA_StaticLocalVarShared, 2190 PDSA_LoopIterVarPrivate, 2191 PDSA_LoopIterVarLinear, 2192 PDSA_LoopIterVarLastprivate, 2193 PDSA_ConstVarShared, 2194 PDSA_GlobalVarShared, 2195 PDSA_TaskVarFirstprivate, 2196 PDSA_LocalVarPrivate, 2197 PDSA_Implicit 2198 } Reason = PDSA_Implicit; 2199 bool ReportHint = false; 2200 auto ReportLoc = D->getLocation(); 2201 auto *VD = dyn_cast<VarDecl>(D); 2202 if (IsLoopIterVar) { 2203 if (DVar.CKind == OMPC_private) 2204 Reason = PDSA_LoopIterVarPrivate; 2205 else if (DVar.CKind == OMPC_lastprivate) 2206 Reason = PDSA_LoopIterVarLastprivate; 2207 else 2208 Reason = PDSA_LoopIterVarLinear; 2209 } else if (isOpenMPTaskingDirective(DVar.DKind) && 2210 DVar.CKind == OMPC_firstprivate) { 2211 Reason = PDSA_TaskVarFirstprivate; 2212 ReportLoc = DVar.ImplicitDSALoc; 2213 } else if (VD && VD->isStaticLocal()) 2214 Reason = PDSA_StaticLocalVarShared; 2215 else if (VD && VD->isStaticDataMember()) 2216 Reason = PDSA_StaticMemberShared; 2217 else if (VD && VD->isFileVarDecl()) 2218 Reason = PDSA_GlobalVarShared; 2219 else if (D->getType().isConstant(SemaRef.getASTContext())) 2220 Reason = PDSA_ConstVarShared; 2221 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 2222 ReportHint = true; 2223 Reason = PDSA_LocalVarPrivate; 2224 } 2225 if (Reason != PDSA_Implicit) { 2226 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 2227 << Reason << ReportHint 2228 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 2229 } else if (DVar.ImplicitDSALoc.isValid()) { 2230 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 2231 << getOpenMPClauseName(DVar.CKind); 2232 } 2233 } 2234 2235 namespace { 2236 class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> { 2237 DSAStackTy *Stack; 2238 Sema &SemaRef; 2239 bool ErrorFound = false; 2240 CapturedStmt *CS = nullptr; 2241 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate; 2242 llvm::SmallVector<Expr *, 4> ImplicitMap; 2243 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA; 2244 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations; 2245 2246 void VisitSubCaptures(OMPExecutableDirective *S) { 2247 // Check implicitly captured variables. 2248 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt()) 2249 return; 2250 for (const CapturedStmt::Capture &Cap : 2251 S->getInnermostCapturedStmt()->captures()) { 2252 if (!Cap.capturesVariable()) 2253 continue; 2254 VarDecl *VD = Cap.getCapturedVar(); 2255 // Do not try to map the variable if it or its sub-component was mapped 2256 // already. 2257 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) && 2258 Stack->checkMappableExprComponentListsForDecl( 2259 VD, /*CurrentRegionOnly=*/true, 2260 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 2261 OpenMPClauseKind) { return true; })) 2262 continue; 2263 DeclRefExpr *DRE = buildDeclRefExpr( 2264 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context), 2265 Cap.getLocation(), /*RefersToCapture=*/true); 2266 Visit(DRE); 2267 } 2268 } 2269 2270 public: 2271 void VisitDeclRefExpr(DeclRefExpr *E) { 2272 if (E->isTypeDependent() || E->isValueDependent() || 2273 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 2274 return; 2275 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 2276 VD = VD->getCanonicalDecl(); 2277 // Skip internally declared variables. 2278 if (VD->hasLocalStorage() && !CS->capturesVariable(VD)) 2279 return; 2280 2281 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 2282 // Check if the variable has explicit DSA set and stop analysis if it so. 2283 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second) 2284 return; 2285 2286 // Skip internally declared static variables. 2287 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 2288 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD); 2289 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) && 2290 (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link)) 2291 return; 2292 2293 SourceLocation ELoc = E->getExprLoc(); 2294 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 2295 // The default(none) clause requires that each variable that is referenced 2296 // in the construct, and does not have a predetermined data-sharing 2297 // attribute, must have its data-sharing attribute explicitly determined 2298 // by being listed in a data-sharing attribute clause. 2299 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && 2300 isImplicitOrExplicitTaskingRegion(DKind) && 2301 VarsWithInheritedDSA.count(VD) == 0) { 2302 VarsWithInheritedDSA[VD] = E; 2303 return; 2304 } 2305 2306 if (isOpenMPTargetExecutionDirective(DKind) && 2307 !Stack->isLoopControlVariable(VD).first) { 2308 if (!Stack->checkMappableExprComponentListsForDecl( 2309 VD, /*CurrentRegionOnly=*/true, 2310 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 2311 StackComponents, 2312 OpenMPClauseKind) { 2313 // Variable is used if it has been marked as an array, array 2314 // section or the variable iself. 2315 return StackComponents.size() == 1 || 2316 std::all_of( 2317 std::next(StackComponents.rbegin()), 2318 StackComponents.rend(), 2319 [](const OMPClauseMappableExprCommon:: 2320 MappableComponent &MC) { 2321 return MC.getAssociatedDeclaration() == 2322 nullptr && 2323 (isa<OMPArraySectionExpr>( 2324 MC.getAssociatedExpression()) || 2325 isa<ArraySubscriptExpr>( 2326 MC.getAssociatedExpression())); 2327 }); 2328 })) { 2329 bool IsFirstprivate = false; 2330 // By default lambdas are captured as firstprivates. 2331 if (const auto *RD = 2332 VD->getType().getNonReferenceType()->getAsCXXRecordDecl()) 2333 IsFirstprivate = RD->isLambda(); 2334 IsFirstprivate = 2335 IsFirstprivate || 2336 (VD->getType().getNonReferenceType()->isScalarType() && 2337 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res); 2338 if (IsFirstprivate) 2339 ImplicitFirstprivate.emplace_back(E); 2340 else 2341 ImplicitMap.emplace_back(E); 2342 return; 2343 } 2344 } 2345 2346 // OpenMP [2.9.3.6, Restrictions, p.2] 2347 // A list item that appears in a reduction clause of the innermost 2348 // enclosing worksharing or parallel construct may not be accessed in an 2349 // explicit task. 2350 DVar = Stack->hasInnermostDSA( 2351 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 2352 [](OpenMPDirectiveKind K) { 2353 return isOpenMPParallelDirective(K) || 2354 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 2355 }, 2356 /*FromParent=*/true); 2357 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 2358 ErrorFound = true; 2359 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 2360 reportOriginalDsa(SemaRef, Stack, VD, DVar); 2361 return; 2362 } 2363 2364 // Define implicit data-sharing attributes for task. 2365 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false); 2366 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 2367 !Stack->isLoopControlVariable(VD).first) 2368 ImplicitFirstprivate.push_back(E); 2369 } 2370 } 2371 void VisitMemberExpr(MemberExpr *E) { 2372 if (E->isTypeDependent() || E->isValueDependent() || 2373 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 2374 return; 2375 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 2376 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 2377 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) { 2378 if (!FD) 2379 return; 2380 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false); 2381 // Check if the variable has explicit DSA set and stop analysis if it 2382 // so. 2383 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second) 2384 return; 2385 2386 if (isOpenMPTargetExecutionDirective(DKind) && 2387 !Stack->isLoopControlVariable(FD).first && 2388 !Stack->checkMappableExprComponentListsForDecl( 2389 FD, /*CurrentRegionOnly=*/true, 2390 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 2391 StackComponents, 2392 OpenMPClauseKind) { 2393 return isa<CXXThisExpr>( 2394 cast<MemberExpr>( 2395 StackComponents.back().getAssociatedExpression()) 2396 ->getBase() 2397 ->IgnoreParens()); 2398 })) { 2399 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 2400 // A bit-field cannot appear in a map clause. 2401 // 2402 if (FD->isBitField()) 2403 return; 2404 2405 // Check to see if the member expression is referencing a class that 2406 // has already been explicitly mapped 2407 if (Stack->isClassPreviouslyMapped(TE->getType())) 2408 return; 2409 2410 ImplicitMap.emplace_back(E); 2411 return; 2412 } 2413 2414 SourceLocation ELoc = E->getExprLoc(); 2415 // OpenMP [2.9.3.6, Restrictions, p.2] 2416 // A list item that appears in a reduction clause of the innermost 2417 // enclosing worksharing or parallel construct may not be accessed in 2418 // an explicit task. 2419 DVar = Stack->hasInnermostDSA( 2420 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 2421 [](OpenMPDirectiveKind K) { 2422 return isOpenMPParallelDirective(K) || 2423 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 2424 }, 2425 /*FromParent=*/true); 2426 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 2427 ErrorFound = true; 2428 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 2429 reportOriginalDsa(SemaRef, Stack, FD, DVar); 2430 return; 2431 } 2432 2433 // Define implicit data-sharing attributes for task. 2434 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false); 2435 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 2436 !Stack->isLoopControlVariable(FD).first) { 2437 // Check if there is a captured expression for the current field in the 2438 // region. Do not mark it as firstprivate unless there is no captured 2439 // expression. 2440 // TODO: try to make it firstprivate. 2441 if (DVar.CKind != OMPC_unknown) 2442 ImplicitFirstprivate.push_back(E); 2443 } 2444 return; 2445 } 2446 if (isOpenMPTargetExecutionDirective(DKind)) { 2447 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 2448 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map, 2449 /*NoDiagnose=*/true)) 2450 return; 2451 const auto *VD = cast<ValueDecl>( 2452 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl()); 2453 if (!Stack->checkMappableExprComponentListsForDecl( 2454 VD, /*CurrentRegionOnly=*/true, 2455 [&CurComponents]( 2456 OMPClauseMappableExprCommon::MappableExprComponentListRef 2457 StackComponents, 2458 OpenMPClauseKind) { 2459 auto CCI = CurComponents.rbegin(); 2460 auto CCE = CurComponents.rend(); 2461 for (const auto &SC : llvm::reverse(StackComponents)) { 2462 // Do both expressions have the same kind? 2463 if (CCI->getAssociatedExpression()->getStmtClass() != 2464 SC.getAssociatedExpression()->getStmtClass()) 2465 if (!(isa<OMPArraySectionExpr>( 2466 SC.getAssociatedExpression()) && 2467 isa<ArraySubscriptExpr>( 2468 CCI->getAssociatedExpression()))) 2469 return false; 2470 2471 const Decl *CCD = CCI->getAssociatedDeclaration(); 2472 const Decl *SCD = SC.getAssociatedDeclaration(); 2473 CCD = CCD ? CCD->getCanonicalDecl() : nullptr; 2474 SCD = SCD ? SCD->getCanonicalDecl() : nullptr; 2475 if (SCD != CCD) 2476 return false; 2477 std::advance(CCI, 1); 2478 if (CCI == CCE) 2479 break; 2480 } 2481 return true; 2482 })) { 2483 Visit(E->getBase()); 2484 } 2485 } else { 2486 Visit(E->getBase()); 2487 } 2488 } 2489 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 2490 for (OMPClause *C : S->clauses()) { 2491 // Skip analysis of arguments of implicitly defined firstprivate clause 2492 // for task|target directives. 2493 // Skip analysis of arguments of implicitly defined map clause for target 2494 // directives. 2495 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) && 2496 C->isImplicit())) { 2497 for (Stmt *CC : C->children()) { 2498 if (CC) 2499 Visit(CC); 2500 } 2501 } 2502 } 2503 // Check implicitly captured variables. 2504 VisitSubCaptures(S); 2505 } 2506 void VisitStmt(Stmt *S) { 2507 for (Stmt *C : S->children()) { 2508 if (C) { 2509 // Check implicitly captured variables in the task-based directives to 2510 // check if they must be firstprivatized. 2511 Visit(C); 2512 } 2513 } 2514 } 2515 2516 bool isErrorFound() const { return ErrorFound; } 2517 ArrayRef<Expr *> getImplicitFirstprivate() const { 2518 return ImplicitFirstprivate; 2519 } 2520 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; } 2521 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const { 2522 return VarsWithInheritedDSA; 2523 } 2524 2525 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 2526 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {} 2527 }; 2528 } // namespace 2529 2530 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 2531 switch (DKind) { 2532 case OMPD_parallel: 2533 case OMPD_parallel_for: 2534 case OMPD_parallel_for_simd: 2535 case OMPD_parallel_sections: 2536 case OMPD_teams: 2537 case OMPD_teams_distribute: 2538 case OMPD_teams_distribute_simd: { 2539 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2540 QualType KmpInt32PtrTy = 2541 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2542 Sema::CapturedParamNameType Params[] = { 2543 std::make_pair(".global_tid.", KmpInt32PtrTy), 2544 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2545 std::make_pair(StringRef(), QualType()) // __context with shared vars 2546 }; 2547 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2548 Params); 2549 break; 2550 } 2551 case OMPD_target_teams: 2552 case OMPD_target_parallel: 2553 case OMPD_target_parallel_for: 2554 case OMPD_target_parallel_for_simd: 2555 case OMPD_target_teams_distribute: 2556 case OMPD_target_teams_distribute_simd: { 2557 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2558 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2559 QualType KmpInt32PtrTy = 2560 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2561 QualType Args[] = {VoidPtrTy}; 2562 FunctionProtoType::ExtProtoInfo EPI; 2563 EPI.Variadic = true; 2564 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2565 Sema::CapturedParamNameType Params[] = { 2566 std::make_pair(".global_tid.", KmpInt32Ty), 2567 std::make_pair(".part_id.", KmpInt32PtrTy), 2568 std::make_pair(".privates.", VoidPtrTy), 2569 std::make_pair( 2570 ".copy_fn.", 2571 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2572 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2573 std::make_pair(StringRef(), QualType()) // __context with shared vars 2574 }; 2575 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2576 Params); 2577 // Mark this captured region as inlined, because we don't use outlined 2578 // function directly. 2579 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2580 AlwaysInlineAttr::CreateImplicit( 2581 Context, AlwaysInlineAttr::Keyword_forceinline)); 2582 Sema::CapturedParamNameType ParamsTarget[] = { 2583 std::make_pair(StringRef(), QualType()) // __context with shared vars 2584 }; 2585 // Start a captured region for 'target' with no implicit parameters. 2586 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2587 ParamsTarget); 2588 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 2589 std::make_pair(".global_tid.", KmpInt32PtrTy), 2590 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2591 std::make_pair(StringRef(), QualType()) // __context with shared vars 2592 }; 2593 // Start a captured region for 'teams' or 'parallel'. Both regions have 2594 // the same implicit parameters. 2595 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2596 ParamsTeamsOrParallel); 2597 break; 2598 } 2599 case OMPD_target: 2600 case OMPD_target_simd: { 2601 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2602 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2603 QualType KmpInt32PtrTy = 2604 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2605 QualType Args[] = {VoidPtrTy}; 2606 FunctionProtoType::ExtProtoInfo EPI; 2607 EPI.Variadic = true; 2608 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2609 Sema::CapturedParamNameType Params[] = { 2610 std::make_pair(".global_tid.", KmpInt32Ty), 2611 std::make_pair(".part_id.", KmpInt32PtrTy), 2612 std::make_pair(".privates.", VoidPtrTy), 2613 std::make_pair( 2614 ".copy_fn.", 2615 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2616 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2617 std::make_pair(StringRef(), QualType()) // __context with shared vars 2618 }; 2619 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2620 Params); 2621 // Mark this captured region as inlined, because we don't use outlined 2622 // function directly. 2623 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2624 AlwaysInlineAttr::CreateImplicit( 2625 Context, AlwaysInlineAttr::Keyword_forceinline)); 2626 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2627 std::make_pair(StringRef(), QualType())); 2628 break; 2629 } 2630 case OMPD_simd: 2631 case OMPD_for: 2632 case OMPD_for_simd: 2633 case OMPD_sections: 2634 case OMPD_section: 2635 case OMPD_single: 2636 case OMPD_master: 2637 case OMPD_critical: 2638 case OMPD_taskgroup: 2639 case OMPD_distribute: 2640 case OMPD_distribute_simd: 2641 case OMPD_ordered: 2642 case OMPD_atomic: 2643 case OMPD_target_data: { 2644 Sema::CapturedParamNameType Params[] = { 2645 std::make_pair(StringRef(), QualType()) // __context with shared vars 2646 }; 2647 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2648 Params); 2649 break; 2650 } 2651 case OMPD_task: { 2652 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2653 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2654 QualType KmpInt32PtrTy = 2655 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2656 QualType Args[] = {VoidPtrTy}; 2657 FunctionProtoType::ExtProtoInfo EPI; 2658 EPI.Variadic = true; 2659 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2660 Sema::CapturedParamNameType Params[] = { 2661 std::make_pair(".global_tid.", KmpInt32Ty), 2662 std::make_pair(".part_id.", KmpInt32PtrTy), 2663 std::make_pair(".privates.", VoidPtrTy), 2664 std::make_pair( 2665 ".copy_fn.", 2666 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2667 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2668 std::make_pair(StringRef(), QualType()) // __context with shared vars 2669 }; 2670 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2671 Params); 2672 // Mark this captured region as inlined, because we don't use outlined 2673 // function directly. 2674 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2675 AlwaysInlineAttr::CreateImplicit( 2676 Context, AlwaysInlineAttr::Keyword_forceinline)); 2677 break; 2678 } 2679 case OMPD_taskloop: 2680 case OMPD_taskloop_simd: { 2681 QualType KmpInt32Ty = 2682 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1) 2683 .withConst(); 2684 QualType KmpUInt64Ty = 2685 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0) 2686 .withConst(); 2687 QualType KmpInt64Ty = 2688 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1) 2689 .withConst(); 2690 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2691 QualType KmpInt32PtrTy = 2692 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2693 QualType Args[] = {VoidPtrTy}; 2694 FunctionProtoType::ExtProtoInfo EPI; 2695 EPI.Variadic = true; 2696 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2697 Sema::CapturedParamNameType Params[] = { 2698 std::make_pair(".global_tid.", KmpInt32Ty), 2699 std::make_pair(".part_id.", KmpInt32PtrTy), 2700 std::make_pair(".privates.", VoidPtrTy), 2701 std::make_pair( 2702 ".copy_fn.", 2703 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2704 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2705 std::make_pair(".lb.", KmpUInt64Ty), 2706 std::make_pair(".ub.", KmpUInt64Ty), 2707 std::make_pair(".st.", KmpInt64Ty), 2708 std::make_pair(".liter.", KmpInt32Ty), 2709 std::make_pair(".reductions.", VoidPtrTy), 2710 std::make_pair(StringRef(), QualType()) // __context with shared vars 2711 }; 2712 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2713 Params); 2714 // Mark this captured region as inlined, because we don't use outlined 2715 // function directly. 2716 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2717 AlwaysInlineAttr::CreateImplicit( 2718 Context, AlwaysInlineAttr::Keyword_forceinline)); 2719 break; 2720 } 2721 case OMPD_distribute_parallel_for_simd: 2722 case OMPD_distribute_parallel_for: { 2723 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2724 QualType KmpInt32PtrTy = 2725 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2726 Sema::CapturedParamNameType Params[] = { 2727 std::make_pair(".global_tid.", KmpInt32PtrTy), 2728 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2729 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 2730 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 2731 std::make_pair(StringRef(), QualType()) // __context with shared vars 2732 }; 2733 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2734 Params); 2735 break; 2736 } 2737 case OMPD_target_teams_distribute_parallel_for: 2738 case OMPD_target_teams_distribute_parallel_for_simd: { 2739 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2740 QualType KmpInt32PtrTy = 2741 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2742 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2743 2744 QualType Args[] = {VoidPtrTy}; 2745 FunctionProtoType::ExtProtoInfo EPI; 2746 EPI.Variadic = true; 2747 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2748 Sema::CapturedParamNameType Params[] = { 2749 std::make_pair(".global_tid.", KmpInt32Ty), 2750 std::make_pair(".part_id.", KmpInt32PtrTy), 2751 std::make_pair(".privates.", VoidPtrTy), 2752 std::make_pair( 2753 ".copy_fn.", 2754 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2755 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2756 std::make_pair(StringRef(), QualType()) // __context with shared vars 2757 }; 2758 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2759 Params); 2760 // Mark this captured region as inlined, because we don't use outlined 2761 // function directly. 2762 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2763 AlwaysInlineAttr::CreateImplicit( 2764 Context, AlwaysInlineAttr::Keyword_forceinline)); 2765 Sema::CapturedParamNameType ParamsTarget[] = { 2766 std::make_pair(StringRef(), QualType()) // __context with shared vars 2767 }; 2768 // Start a captured region for 'target' with no implicit parameters. 2769 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2770 ParamsTarget); 2771 2772 Sema::CapturedParamNameType ParamsTeams[] = { 2773 std::make_pair(".global_tid.", KmpInt32PtrTy), 2774 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2775 std::make_pair(StringRef(), QualType()) // __context with shared vars 2776 }; 2777 // Start a captured region for 'target' with no implicit parameters. 2778 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2779 ParamsTeams); 2780 2781 Sema::CapturedParamNameType ParamsParallel[] = { 2782 std::make_pair(".global_tid.", KmpInt32PtrTy), 2783 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2784 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 2785 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 2786 std::make_pair(StringRef(), QualType()) // __context with shared vars 2787 }; 2788 // Start a captured region for 'teams' or 'parallel'. Both regions have 2789 // the same implicit parameters. 2790 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2791 ParamsParallel); 2792 break; 2793 } 2794 2795 case OMPD_teams_distribute_parallel_for: 2796 case OMPD_teams_distribute_parallel_for_simd: { 2797 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2798 QualType KmpInt32PtrTy = 2799 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2800 2801 Sema::CapturedParamNameType ParamsTeams[] = { 2802 std::make_pair(".global_tid.", KmpInt32PtrTy), 2803 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2804 std::make_pair(StringRef(), QualType()) // __context with shared vars 2805 }; 2806 // Start a captured region for 'target' with no implicit parameters. 2807 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2808 ParamsTeams); 2809 2810 Sema::CapturedParamNameType ParamsParallel[] = { 2811 std::make_pair(".global_tid.", KmpInt32PtrTy), 2812 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2813 std::make_pair(".previous.lb.", Context.getSizeType().withConst()), 2814 std::make_pair(".previous.ub.", Context.getSizeType().withConst()), 2815 std::make_pair(StringRef(), QualType()) // __context with shared vars 2816 }; 2817 // Start a captured region for 'teams' or 'parallel'. Both regions have 2818 // the same implicit parameters. 2819 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2820 ParamsParallel); 2821 break; 2822 } 2823 case OMPD_target_update: 2824 case OMPD_target_enter_data: 2825 case OMPD_target_exit_data: { 2826 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst(); 2827 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict(); 2828 QualType KmpInt32PtrTy = 2829 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2830 QualType Args[] = {VoidPtrTy}; 2831 FunctionProtoType::ExtProtoInfo EPI; 2832 EPI.Variadic = true; 2833 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2834 Sema::CapturedParamNameType Params[] = { 2835 std::make_pair(".global_tid.", KmpInt32Ty), 2836 std::make_pair(".part_id.", KmpInt32PtrTy), 2837 std::make_pair(".privates.", VoidPtrTy), 2838 std::make_pair( 2839 ".copy_fn.", 2840 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2841 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2842 std::make_pair(StringRef(), QualType()) // __context with shared vars 2843 }; 2844 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2845 Params); 2846 // Mark this captured region as inlined, because we don't use outlined 2847 // function directly. 2848 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2849 AlwaysInlineAttr::CreateImplicit( 2850 Context, AlwaysInlineAttr::Keyword_forceinline)); 2851 break; 2852 } 2853 case OMPD_threadprivate: 2854 case OMPD_taskyield: 2855 case OMPD_barrier: 2856 case OMPD_taskwait: 2857 case OMPD_cancellation_point: 2858 case OMPD_cancel: 2859 case OMPD_flush: 2860 case OMPD_declare_reduction: 2861 case OMPD_declare_mapper: 2862 case OMPD_declare_simd: 2863 case OMPD_declare_target: 2864 case OMPD_end_declare_target: 2865 case OMPD_requires: 2866 llvm_unreachable("OpenMP Directive is not allowed"); 2867 case OMPD_unknown: 2868 llvm_unreachable("Unknown OpenMP directive"); 2869 } 2870 } 2871 2872 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 2873 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2874 getOpenMPCaptureRegions(CaptureRegions, DKind); 2875 return CaptureRegions.size(); 2876 } 2877 2878 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 2879 Expr *CaptureExpr, bool WithInit, 2880 bool AsExpression) { 2881 assert(CaptureExpr); 2882 ASTContext &C = S.getASTContext(); 2883 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 2884 QualType Ty = Init->getType(); 2885 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 2886 if (S.getLangOpts().CPlusPlus) { 2887 Ty = C.getLValueReferenceType(Ty); 2888 } else { 2889 Ty = C.getPointerType(Ty); 2890 ExprResult Res = 2891 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 2892 if (!Res.isUsable()) 2893 return nullptr; 2894 Init = Res.get(); 2895 } 2896 WithInit = true; 2897 } 2898 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 2899 CaptureExpr->getBeginLoc()); 2900 if (!WithInit) 2901 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C)); 2902 S.CurContext->addHiddenDecl(CED); 2903 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 2904 return CED; 2905 } 2906 2907 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 2908 bool WithInit) { 2909 OMPCapturedExprDecl *CD; 2910 if (VarDecl *VD = S.isOpenMPCapturedDecl(D)) 2911 CD = cast<OMPCapturedExprDecl>(VD); 2912 else 2913 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 2914 /*AsExpression=*/false); 2915 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 2916 CaptureExpr->getExprLoc()); 2917 } 2918 2919 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 2920 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get(); 2921 if (!Ref) { 2922 OMPCapturedExprDecl *CD = buildCaptureDecl( 2923 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr, 2924 /*WithInit=*/true, /*AsExpression=*/true); 2925 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 2926 CaptureExpr->getExprLoc()); 2927 } 2928 ExprResult Res = Ref; 2929 if (!S.getLangOpts().CPlusPlus && 2930 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 2931 Ref->getType()->isPointerType()) { 2932 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 2933 if (!Res.isUsable()) 2934 return ExprError(); 2935 } 2936 return S.DefaultLvalueConversion(Res.get()); 2937 } 2938 2939 namespace { 2940 // OpenMP directives parsed in this section are represented as a 2941 // CapturedStatement with an associated statement. If a syntax error 2942 // is detected during the parsing of the associated statement, the 2943 // compiler must abort processing and close the CapturedStatement. 2944 // 2945 // Combined directives such as 'target parallel' have more than one 2946 // nested CapturedStatements. This RAII ensures that we unwind out 2947 // of all the nested CapturedStatements when an error is found. 2948 class CaptureRegionUnwinderRAII { 2949 private: 2950 Sema &S; 2951 bool &ErrorFound; 2952 OpenMPDirectiveKind DKind = OMPD_unknown; 2953 2954 public: 2955 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 2956 OpenMPDirectiveKind DKind) 2957 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 2958 ~CaptureRegionUnwinderRAII() { 2959 if (ErrorFound) { 2960 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 2961 while (--ThisCaptureLevel >= 0) 2962 S.ActOnCapturedRegionError(); 2963 } 2964 } 2965 }; 2966 } // namespace 2967 2968 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 2969 ArrayRef<OMPClause *> Clauses) { 2970 bool ErrorFound = false; 2971 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 2972 *this, ErrorFound, DSAStack->getCurrentDirective()); 2973 if (!S.isUsable()) { 2974 ErrorFound = true; 2975 return StmtError(); 2976 } 2977 2978 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2979 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 2980 OMPOrderedClause *OC = nullptr; 2981 OMPScheduleClause *SC = nullptr; 2982 SmallVector<const OMPLinearClause *, 4> LCs; 2983 SmallVector<const OMPClauseWithPreInit *, 4> PICs; 2984 // This is required for proper codegen. 2985 for (OMPClause *Clause : Clauses) { 2986 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) && 2987 Clause->getClauseKind() == OMPC_in_reduction) { 2988 // Capture taskgroup task_reduction descriptors inside the tasking regions 2989 // with the corresponding in_reduction items. 2990 auto *IRC = cast<OMPInReductionClause>(Clause); 2991 for (Expr *E : IRC->taskgroup_descriptors()) 2992 if (E) 2993 MarkDeclarationsReferencedInExpr(E); 2994 } 2995 if (isOpenMPPrivate(Clause->getClauseKind()) || 2996 Clause->getClauseKind() == OMPC_copyprivate || 2997 (getLangOpts().OpenMPUseTLS && 2998 getASTContext().getTargetInfo().isTLSSupported() && 2999 Clause->getClauseKind() == OMPC_copyin)) { 3000 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 3001 // Mark all variables in private list clauses as used in inner region. 3002 for (Stmt *VarRef : Clause->children()) { 3003 if (auto *E = cast_or_null<Expr>(VarRef)) { 3004 MarkDeclarationsReferencedInExpr(E); 3005 } 3006 } 3007 DSAStack->setForceVarCapturing(/*V=*/false); 3008 } else if (CaptureRegions.size() > 1 || 3009 CaptureRegions.back() != OMPD_unknown) { 3010 if (auto *C = OMPClauseWithPreInit::get(Clause)) 3011 PICs.push_back(C); 3012 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 3013 if (Expr *E = C->getPostUpdateExpr()) 3014 MarkDeclarationsReferencedInExpr(E); 3015 } 3016 } 3017 if (Clause->getClauseKind() == OMPC_schedule) 3018 SC = cast<OMPScheduleClause>(Clause); 3019 else if (Clause->getClauseKind() == OMPC_ordered) 3020 OC = cast<OMPOrderedClause>(Clause); 3021 else if (Clause->getClauseKind() == OMPC_linear) 3022 LCs.push_back(cast<OMPLinearClause>(Clause)); 3023 } 3024 // OpenMP, 2.7.1 Loop Construct, Restrictions 3025 // The nonmonotonic modifier cannot be specified if an ordered clause is 3026 // specified. 3027 if (SC && 3028 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 3029 SC->getSecondScheduleModifier() == 3030 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 3031 OC) { 3032 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 3033 ? SC->getFirstScheduleModifierLoc() 3034 : SC->getSecondScheduleModifierLoc(), 3035 diag::err_omp_schedule_nonmonotonic_ordered) 3036 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 3037 ErrorFound = true; 3038 } 3039 if (!LCs.empty() && OC && OC->getNumForLoops()) { 3040 for (const OMPLinearClause *C : LCs) { 3041 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered) 3042 << SourceRange(OC->getBeginLoc(), OC->getEndLoc()); 3043 } 3044 ErrorFound = true; 3045 } 3046 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 3047 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 3048 OC->getNumForLoops()) { 3049 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd) 3050 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 3051 ErrorFound = true; 3052 } 3053 if (ErrorFound) { 3054 return StmtError(); 3055 } 3056 StmtResult SR = S; 3057 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 3058 // Mark all variables in private list clauses as used in inner region. 3059 // Required for proper codegen of combined directives. 3060 // TODO: add processing for other clauses. 3061 if (ThisCaptureRegion != OMPD_unknown) { 3062 for (const clang::OMPClauseWithPreInit *C : PICs) { 3063 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 3064 // Find the particular capture region for the clause if the 3065 // directive is a combined one with multiple capture regions. 3066 // If the directive is not a combined one, the capture region 3067 // associated with the clause is OMPD_unknown and is generated 3068 // only once. 3069 if (CaptureRegion == ThisCaptureRegion || 3070 CaptureRegion == OMPD_unknown) { 3071 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 3072 for (Decl *D : DS->decls()) 3073 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 3074 } 3075 } 3076 } 3077 } 3078 SR = ActOnCapturedRegionEnd(SR.get()); 3079 } 3080 return SR; 3081 } 3082 3083 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 3084 OpenMPDirectiveKind CancelRegion, 3085 SourceLocation StartLoc) { 3086 // CancelRegion is only needed for cancel and cancellation_point. 3087 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 3088 return false; 3089 3090 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 3091 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 3092 return false; 3093 3094 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 3095 << getOpenMPDirectiveName(CancelRegion); 3096 return true; 3097 } 3098 3099 static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack, 3100 OpenMPDirectiveKind CurrentRegion, 3101 const DeclarationNameInfo &CurrentName, 3102 OpenMPDirectiveKind CancelRegion, 3103 SourceLocation StartLoc) { 3104 if (Stack->getCurScope()) { 3105 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective(); 3106 OpenMPDirectiveKind OffendingRegion = ParentRegion; 3107 bool NestingProhibited = false; 3108 bool CloseNesting = true; 3109 bool OrphanSeen = false; 3110 enum { 3111 NoRecommend, 3112 ShouldBeInParallelRegion, 3113 ShouldBeInOrderedRegion, 3114 ShouldBeInTargetRegion, 3115 ShouldBeInTeamsRegion 3116 } Recommend = NoRecommend; 3117 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { 3118 // OpenMP [2.16, Nesting of Regions] 3119 // OpenMP constructs may not be nested inside a simd region. 3120 // OpenMP [2.8.1,simd Construct, Restrictions] 3121 // An ordered construct with the simd clause is the only OpenMP 3122 // construct that can appear in the simd region. 3123 // Allowing a SIMD construct nested in another SIMD construct is an 3124 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 3125 // message. 3126 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 3127 ? diag::err_omp_prohibited_region_simd 3128 : diag::warn_omp_nesting_simd); 3129 return CurrentRegion != OMPD_simd; 3130 } 3131 if (ParentRegion == OMPD_atomic) { 3132 // OpenMP [2.16, Nesting of Regions] 3133 // OpenMP constructs may not be nested inside an atomic region. 3134 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 3135 return true; 3136 } 3137 if (CurrentRegion == OMPD_section) { 3138 // OpenMP [2.7.2, sections Construct, Restrictions] 3139 // Orphaned section directives are prohibited. That is, the section 3140 // directives must appear within the sections construct and must not be 3141 // encountered elsewhere in the sections region. 3142 if (ParentRegion != OMPD_sections && 3143 ParentRegion != OMPD_parallel_sections) { 3144 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 3145 << (ParentRegion != OMPD_unknown) 3146 << getOpenMPDirectiveName(ParentRegion); 3147 return true; 3148 } 3149 return false; 3150 } 3151 // Allow some constructs (except teams and cancellation constructs) to be 3152 // orphaned (they could be used in functions, called from OpenMP regions 3153 // with the required preconditions). 3154 if (ParentRegion == OMPD_unknown && 3155 !isOpenMPNestingTeamsDirective(CurrentRegion) && 3156 CurrentRegion != OMPD_cancellation_point && 3157 CurrentRegion != OMPD_cancel) 3158 return false; 3159 if (CurrentRegion == OMPD_cancellation_point || 3160 CurrentRegion == OMPD_cancel) { 3161 // OpenMP [2.16, Nesting of Regions] 3162 // A cancellation point construct for which construct-type-clause is 3163 // taskgroup must be nested inside a task construct. A cancellation 3164 // point construct for which construct-type-clause is not taskgroup must 3165 // be closely nested inside an OpenMP construct that matches the type 3166 // specified in construct-type-clause. 3167 // A cancel construct for which construct-type-clause is taskgroup must be 3168 // nested inside a task construct. A cancel construct for which 3169 // construct-type-clause is not taskgroup must be closely nested inside an 3170 // OpenMP construct that matches the type specified in 3171 // construct-type-clause. 3172 NestingProhibited = 3173 !((CancelRegion == OMPD_parallel && 3174 (ParentRegion == OMPD_parallel || 3175 ParentRegion == OMPD_target_parallel)) || 3176 (CancelRegion == OMPD_for && 3177 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 3178 ParentRegion == OMPD_target_parallel_for || 3179 ParentRegion == OMPD_distribute_parallel_for || 3180 ParentRegion == OMPD_teams_distribute_parallel_for || 3181 ParentRegion == OMPD_target_teams_distribute_parallel_for)) || 3182 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || 3183 (CancelRegion == OMPD_sections && 3184 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 3185 ParentRegion == OMPD_parallel_sections))); 3186 OrphanSeen = ParentRegion == OMPD_unknown; 3187 } else if (CurrentRegion == OMPD_master) { 3188 // OpenMP [2.16, Nesting of Regions] 3189 // A master region may not be closely nested inside a worksharing, 3190 // atomic, or explicit task region. 3191 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 3192 isOpenMPTaskingDirective(ParentRegion); 3193 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 3194 // OpenMP [2.16, Nesting of Regions] 3195 // A critical region may not be nested (closely or otherwise) inside a 3196 // critical region with the same name. Note that this restriction is not 3197 // sufficient to prevent deadlock. 3198 SourceLocation PreviousCriticalLoc; 3199 bool DeadLock = Stack->hasDirective( 3200 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 3201 const DeclarationNameInfo &DNI, 3202 SourceLocation Loc) { 3203 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 3204 PreviousCriticalLoc = Loc; 3205 return true; 3206 } 3207 return false; 3208 }, 3209 false /* skip top directive */); 3210 if (DeadLock) { 3211 SemaRef.Diag(StartLoc, 3212 diag::err_omp_prohibited_region_critical_same_name) 3213 << CurrentName.getName(); 3214 if (PreviousCriticalLoc.isValid()) 3215 SemaRef.Diag(PreviousCriticalLoc, 3216 diag::note_omp_previous_critical_region); 3217 return true; 3218 } 3219 } else if (CurrentRegion == OMPD_barrier) { 3220 // OpenMP [2.16, Nesting of Regions] 3221 // A barrier region may not be closely nested inside a worksharing, 3222 // explicit task, critical, ordered, atomic, or master region. 3223 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 3224 isOpenMPTaskingDirective(ParentRegion) || 3225 ParentRegion == OMPD_master || 3226 ParentRegion == OMPD_critical || 3227 ParentRegion == OMPD_ordered; 3228 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 3229 !isOpenMPParallelDirective(CurrentRegion) && 3230 !isOpenMPTeamsDirective(CurrentRegion)) { 3231 // OpenMP [2.16, Nesting of Regions] 3232 // A worksharing region may not be closely nested inside a worksharing, 3233 // explicit task, critical, ordered, atomic, or master region. 3234 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 3235 isOpenMPTaskingDirective(ParentRegion) || 3236 ParentRegion == OMPD_master || 3237 ParentRegion == OMPD_critical || 3238 ParentRegion == OMPD_ordered; 3239 Recommend = ShouldBeInParallelRegion; 3240 } else if (CurrentRegion == OMPD_ordered) { 3241 // OpenMP [2.16, Nesting of Regions] 3242 // An ordered region may not be closely nested inside a critical, 3243 // atomic, or explicit task region. 3244 // An ordered region must be closely nested inside a loop region (or 3245 // parallel loop region) with an ordered clause. 3246 // OpenMP [2.8.1,simd Construct, Restrictions] 3247 // An ordered construct with the simd clause is the only OpenMP construct 3248 // that can appear in the simd region. 3249 NestingProhibited = ParentRegion == OMPD_critical || 3250 isOpenMPTaskingDirective(ParentRegion) || 3251 !(isOpenMPSimdDirective(ParentRegion) || 3252 Stack->isParentOrderedRegion()); 3253 Recommend = ShouldBeInOrderedRegion; 3254 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 3255 // OpenMP [2.16, Nesting of Regions] 3256 // If specified, a teams construct must be contained within a target 3257 // construct. 3258 NestingProhibited = ParentRegion != OMPD_target; 3259 OrphanSeen = ParentRegion == OMPD_unknown; 3260 Recommend = ShouldBeInTargetRegion; 3261 } 3262 if (!NestingProhibited && 3263 !isOpenMPTargetExecutionDirective(CurrentRegion) && 3264 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 3265 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 3266 // OpenMP [2.16, Nesting of Regions] 3267 // distribute, parallel, parallel sections, parallel workshare, and the 3268 // parallel loop and parallel loop SIMD constructs are the only OpenMP 3269 // constructs that can be closely nested in the teams region. 3270 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 3271 !isOpenMPDistributeDirective(CurrentRegion); 3272 Recommend = ShouldBeInParallelRegion; 3273 } 3274 if (!NestingProhibited && 3275 isOpenMPNestingDistributeDirective(CurrentRegion)) { 3276 // OpenMP 4.5 [2.17 Nesting of Regions] 3277 // The region associated with the distribute construct must be strictly 3278 // nested inside a teams region 3279 NestingProhibited = 3280 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 3281 Recommend = ShouldBeInTeamsRegion; 3282 } 3283 if (!NestingProhibited && 3284 (isOpenMPTargetExecutionDirective(CurrentRegion) || 3285 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 3286 // OpenMP 4.5 [2.17 Nesting of Regions] 3287 // If a target, target update, target data, target enter data, or 3288 // target exit data construct is encountered during execution of a 3289 // target region, the behavior is unspecified. 3290 NestingProhibited = Stack->hasDirective( 3291 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 3292 SourceLocation) { 3293 if (isOpenMPTargetExecutionDirective(K)) { 3294 OffendingRegion = K; 3295 return true; 3296 } 3297 return false; 3298 }, 3299 false /* don't skip top directive */); 3300 CloseNesting = false; 3301 } 3302 if (NestingProhibited) { 3303 if (OrphanSeen) { 3304 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 3305 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 3306 } else { 3307 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 3308 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 3309 << Recommend << getOpenMPDirectiveName(CurrentRegion); 3310 } 3311 return true; 3312 } 3313 } 3314 return false; 3315 } 3316 3317 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 3318 ArrayRef<OMPClause *> Clauses, 3319 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 3320 bool ErrorFound = false; 3321 unsigned NamedModifiersNumber = 0; 3322 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers( 3323 OMPD_unknown + 1); 3324 SmallVector<SourceLocation, 4> NameModifierLoc; 3325 for (const OMPClause *C : Clauses) { 3326 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 3327 // At most one if clause without a directive-name-modifier can appear on 3328 // the directive. 3329 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 3330 if (FoundNameModifiers[CurNM]) { 3331 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 3332 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 3333 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 3334 ErrorFound = true; 3335 } else if (CurNM != OMPD_unknown) { 3336 NameModifierLoc.push_back(IC->getNameModifierLoc()); 3337 ++NamedModifiersNumber; 3338 } 3339 FoundNameModifiers[CurNM] = IC; 3340 if (CurNM == OMPD_unknown) 3341 continue; 3342 // Check if the specified name modifier is allowed for the current 3343 // directive. 3344 // At most one if clause with the particular directive-name-modifier can 3345 // appear on the directive. 3346 bool MatchFound = false; 3347 for (auto NM : AllowedNameModifiers) { 3348 if (CurNM == NM) { 3349 MatchFound = true; 3350 break; 3351 } 3352 } 3353 if (!MatchFound) { 3354 S.Diag(IC->getNameModifierLoc(), 3355 diag::err_omp_wrong_if_directive_name_modifier) 3356 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 3357 ErrorFound = true; 3358 } 3359 } 3360 } 3361 // If any if clause on the directive includes a directive-name-modifier then 3362 // all if clauses on the directive must include a directive-name-modifier. 3363 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 3364 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 3365 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(), 3366 diag::err_omp_no_more_if_clause); 3367 } else { 3368 std::string Values; 3369 std::string Sep(", "); 3370 unsigned AllowedCnt = 0; 3371 unsigned TotalAllowedNum = 3372 AllowedNameModifiers.size() - NamedModifiersNumber; 3373 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 3374 ++Cnt) { 3375 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 3376 if (!FoundNameModifiers[NM]) { 3377 Values += "'"; 3378 Values += getOpenMPDirectiveName(NM); 3379 Values += "'"; 3380 if (AllowedCnt + 2 == TotalAllowedNum) 3381 Values += " or "; 3382 else if (AllowedCnt + 1 != TotalAllowedNum) 3383 Values += Sep; 3384 ++AllowedCnt; 3385 } 3386 } 3387 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(), 3388 diag::err_omp_unnamed_if_clause) 3389 << (TotalAllowedNum > 1) << Values; 3390 } 3391 for (SourceLocation Loc : NameModifierLoc) { 3392 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 3393 } 3394 ErrorFound = true; 3395 } 3396 return ErrorFound; 3397 } 3398 3399 StmtResult Sema::ActOnOpenMPExecutableDirective( 3400 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 3401 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 3402 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 3403 StmtResult Res = StmtError(); 3404 // First check CancelRegion which is then used in checkNestingOfRegions. 3405 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 3406 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 3407 StartLoc)) 3408 return StmtError(); 3409 3410 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 3411 VarsWithInheritedDSAType VarsWithInheritedDSA; 3412 bool ErrorFound = false; 3413 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 3414 if (AStmt && !CurContext->isDependentContext()) { 3415 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3416 3417 // Check default data sharing attributes for referenced variables. 3418 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 3419 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 3420 Stmt *S = AStmt; 3421 while (--ThisCaptureLevel >= 0) 3422 S = cast<CapturedStmt>(S)->getCapturedStmt(); 3423 DSAChecker.Visit(S); 3424 if (DSAChecker.isErrorFound()) 3425 return StmtError(); 3426 // Generate list of implicitly defined firstprivate variables. 3427 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 3428 3429 SmallVector<Expr *, 4> ImplicitFirstprivates( 3430 DSAChecker.getImplicitFirstprivate().begin(), 3431 DSAChecker.getImplicitFirstprivate().end()); 3432 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(), 3433 DSAChecker.getImplicitMap().end()); 3434 // Mark taskgroup task_reduction descriptors as implicitly firstprivate. 3435 for (OMPClause *C : Clauses) { 3436 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) { 3437 for (Expr *E : IRC->taskgroup_descriptors()) 3438 if (E) 3439 ImplicitFirstprivates.emplace_back(E); 3440 } 3441 } 3442 if (!ImplicitFirstprivates.empty()) { 3443 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 3444 ImplicitFirstprivates, SourceLocation(), SourceLocation(), 3445 SourceLocation())) { 3446 ClausesWithImplicit.push_back(Implicit); 3447 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 3448 ImplicitFirstprivates.size(); 3449 } else { 3450 ErrorFound = true; 3451 } 3452 } 3453 if (!ImplicitMaps.empty()) { 3454 if (OMPClause *Implicit = ActOnOpenMPMapClause( 3455 llvm::None, llvm::None, OMPC_MAP_tofrom, 3456 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(), 3457 ImplicitMaps, SourceLocation(), SourceLocation(), 3458 SourceLocation())) { 3459 ClausesWithImplicit.emplace_back(Implicit); 3460 ErrorFound |= 3461 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size(); 3462 } else { 3463 ErrorFound = true; 3464 } 3465 } 3466 } 3467 3468 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 3469 switch (Kind) { 3470 case OMPD_parallel: 3471 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 3472 EndLoc); 3473 AllowedNameModifiers.push_back(OMPD_parallel); 3474 break; 3475 case OMPD_simd: 3476 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 3477 VarsWithInheritedDSA); 3478 break; 3479 case OMPD_for: 3480 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 3481 VarsWithInheritedDSA); 3482 break; 3483 case OMPD_for_simd: 3484 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3485 EndLoc, VarsWithInheritedDSA); 3486 break; 3487 case OMPD_sections: 3488 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 3489 EndLoc); 3490 break; 3491 case OMPD_section: 3492 assert(ClausesWithImplicit.empty() && 3493 "No clauses are allowed for 'omp section' directive"); 3494 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 3495 break; 3496 case OMPD_single: 3497 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 3498 EndLoc); 3499 break; 3500 case OMPD_master: 3501 assert(ClausesWithImplicit.empty() && 3502 "No clauses are allowed for 'omp master' directive"); 3503 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 3504 break; 3505 case OMPD_critical: 3506 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 3507 StartLoc, EndLoc); 3508 break; 3509 case OMPD_parallel_for: 3510 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 3511 EndLoc, VarsWithInheritedDSA); 3512 AllowedNameModifiers.push_back(OMPD_parallel); 3513 break; 3514 case OMPD_parallel_for_simd: 3515 Res = ActOnOpenMPParallelForSimdDirective( 3516 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3517 AllowedNameModifiers.push_back(OMPD_parallel); 3518 break; 3519 case OMPD_parallel_sections: 3520 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 3521 StartLoc, EndLoc); 3522 AllowedNameModifiers.push_back(OMPD_parallel); 3523 break; 3524 case OMPD_task: 3525 Res = 3526 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 3527 AllowedNameModifiers.push_back(OMPD_task); 3528 break; 3529 case OMPD_taskyield: 3530 assert(ClausesWithImplicit.empty() && 3531 "No clauses are allowed for 'omp taskyield' directive"); 3532 assert(AStmt == nullptr && 3533 "No associated statement allowed for 'omp taskyield' directive"); 3534 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 3535 break; 3536 case OMPD_barrier: 3537 assert(ClausesWithImplicit.empty() && 3538 "No clauses are allowed for 'omp barrier' directive"); 3539 assert(AStmt == nullptr && 3540 "No associated statement allowed for 'omp barrier' directive"); 3541 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 3542 break; 3543 case OMPD_taskwait: 3544 assert(ClausesWithImplicit.empty() && 3545 "No clauses are allowed for 'omp taskwait' directive"); 3546 assert(AStmt == nullptr && 3547 "No associated statement allowed for 'omp taskwait' directive"); 3548 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 3549 break; 3550 case OMPD_taskgroup: 3551 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, 3552 EndLoc); 3553 break; 3554 case OMPD_flush: 3555 assert(AStmt == nullptr && 3556 "No associated statement allowed for 'omp flush' directive"); 3557 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 3558 break; 3559 case OMPD_ordered: 3560 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 3561 EndLoc); 3562 break; 3563 case OMPD_atomic: 3564 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 3565 EndLoc); 3566 break; 3567 case OMPD_teams: 3568 Res = 3569 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 3570 break; 3571 case OMPD_target: 3572 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 3573 EndLoc); 3574 AllowedNameModifiers.push_back(OMPD_target); 3575 break; 3576 case OMPD_target_parallel: 3577 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 3578 StartLoc, EndLoc); 3579 AllowedNameModifiers.push_back(OMPD_target); 3580 AllowedNameModifiers.push_back(OMPD_parallel); 3581 break; 3582 case OMPD_target_parallel_for: 3583 Res = ActOnOpenMPTargetParallelForDirective( 3584 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3585 AllowedNameModifiers.push_back(OMPD_target); 3586 AllowedNameModifiers.push_back(OMPD_parallel); 3587 break; 3588 case OMPD_cancellation_point: 3589 assert(ClausesWithImplicit.empty() && 3590 "No clauses are allowed for 'omp cancellation point' directive"); 3591 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 3592 "cancellation point' directive"); 3593 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 3594 break; 3595 case OMPD_cancel: 3596 assert(AStmt == nullptr && 3597 "No associated statement allowed for 'omp cancel' directive"); 3598 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 3599 CancelRegion); 3600 AllowedNameModifiers.push_back(OMPD_cancel); 3601 break; 3602 case OMPD_target_data: 3603 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 3604 EndLoc); 3605 AllowedNameModifiers.push_back(OMPD_target_data); 3606 break; 3607 case OMPD_target_enter_data: 3608 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 3609 EndLoc, AStmt); 3610 AllowedNameModifiers.push_back(OMPD_target_enter_data); 3611 break; 3612 case OMPD_target_exit_data: 3613 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 3614 EndLoc, AStmt); 3615 AllowedNameModifiers.push_back(OMPD_target_exit_data); 3616 break; 3617 case OMPD_taskloop: 3618 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 3619 EndLoc, VarsWithInheritedDSA); 3620 AllowedNameModifiers.push_back(OMPD_taskloop); 3621 break; 3622 case OMPD_taskloop_simd: 3623 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3624 EndLoc, VarsWithInheritedDSA); 3625 AllowedNameModifiers.push_back(OMPD_taskloop); 3626 break; 3627 case OMPD_distribute: 3628 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 3629 EndLoc, VarsWithInheritedDSA); 3630 break; 3631 case OMPD_target_update: 3632 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, 3633 EndLoc, AStmt); 3634 AllowedNameModifiers.push_back(OMPD_target_update); 3635 break; 3636 case OMPD_distribute_parallel_for: 3637 Res = ActOnOpenMPDistributeParallelForDirective( 3638 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3639 AllowedNameModifiers.push_back(OMPD_parallel); 3640 break; 3641 case OMPD_distribute_parallel_for_simd: 3642 Res = ActOnOpenMPDistributeParallelForSimdDirective( 3643 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3644 AllowedNameModifiers.push_back(OMPD_parallel); 3645 break; 3646 case OMPD_distribute_simd: 3647 Res = ActOnOpenMPDistributeSimdDirective( 3648 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3649 break; 3650 case OMPD_target_parallel_for_simd: 3651 Res = ActOnOpenMPTargetParallelForSimdDirective( 3652 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3653 AllowedNameModifiers.push_back(OMPD_target); 3654 AllowedNameModifiers.push_back(OMPD_parallel); 3655 break; 3656 case OMPD_target_simd: 3657 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3658 EndLoc, VarsWithInheritedDSA); 3659 AllowedNameModifiers.push_back(OMPD_target); 3660 break; 3661 case OMPD_teams_distribute: 3662 Res = ActOnOpenMPTeamsDistributeDirective( 3663 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3664 break; 3665 case OMPD_teams_distribute_simd: 3666 Res = ActOnOpenMPTeamsDistributeSimdDirective( 3667 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3668 break; 3669 case OMPD_teams_distribute_parallel_for_simd: 3670 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 3671 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3672 AllowedNameModifiers.push_back(OMPD_parallel); 3673 break; 3674 case OMPD_teams_distribute_parallel_for: 3675 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 3676 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3677 AllowedNameModifiers.push_back(OMPD_parallel); 3678 break; 3679 case OMPD_target_teams: 3680 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 3681 EndLoc); 3682 AllowedNameModifiers.push_back(OMPD_target); 3683 break; 3684 case OMPD_target_teams_distribute: 3685 Res = ActOnOpenMPTargetTeamsDistributeDirective( 3686 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3687 AllowedNameModifiers.push_back(OMPD_target); 3688 break; 3689 case OMPD_target_teams_distribute_parallel_for: 3690 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 3691 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3692 AllowedNameModifiers.push_back(OMPD_target); 3693 AllowedNameModifiers.push_back(OMPD_parallel); 3694 break; 3695 case OMPD_target_teams_distribute_parallel_for_simd: 3696 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 3697 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3698 AllowedNameModifiers.push_back(OMPD_target); 3699 AllowedNameModifiers.push_back(OMPD_parallel); 3700 break; 3701 case OMPD_target_teams_distribute_simd: 3702 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 3703 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3704 AllowedNameModifiers.push_back(OMPD_target); 3705 break; 3706 case OMPD_declare_target: 3707 case OMPD_end_declare_target: 3708 case OMPD_threadprivate: 3709 case OMPD_declare_reduction: 3710 case OMPD_declare_mapper: 3711 case OMPD_declare_simd: 3712 case OMPD_requires: 3713 llvm_unreachable("OpenMP Directive is not allowed"); 3714 case OMPD_unknown: 3715 llvm_unreachable("Unknown OpenMP directive"); 3716 } 3717 3718 for (const auto &P : VarsWithInheritedDSA) { 3719 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 3720 << P.first << P.second->getSourceRange(); 3721 } 3722 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound; 3723 3724 if (!AllowedNameModifiers.empty()) 3725 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 3726 ErrorFound; 3727 3728 if (ErrorFound) 3729 return StmtError(); 3730 return Res; 3731 } 3732 3733 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 3734 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 3735 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 3736 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 3737 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 3738 assert(Aligneds.size() == Alignments.size()); 3739 assert(Linears.size() == LinModifiers.size()); 3740 assert(Linears.size() == Steps.size()); 3741 if (!DG || DG.get().isNull()) 3742 return DeclGroupPtrTy(); 3743 3744 if (!DG.get().isSingleDecl()) { 3745 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd); 3746 return DG; 3747 } 3748 Decl *ADecl = DG.get().getSingleDecl(); 3749 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 3750 ADecl = FTD->getTemplatedDecl(); 3751 3752 auto *FD = dyn_cast<FunctionDecl>(ADecl); 3753 if (!FD) { 3754 Diag(ADecl->getLocation(), diag::err_omp_function_expected); 3755 return DeclGroupPtrTy(); 3756 } 3757 3758 // OpenMP [2.8.2, declare simd construct, Description] 3759 // The parameter of the simdlen clause must be a constant positive integer 3760 // expression. 3761 ExprResult SL; 3762 if (Simdlen) 3763 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 3764 // OpenMP [2.8.2, declare simd construct, Description] 3765 // The special this pointer can be used as if was one of the arguments to the 3766 // function in any of the linear, aligned, or uniform clauses. 3767 // The uniform clause declares one or more arguments to have an invariant 3768 // value for all concurrent invocations of the function in the execution of a 3769 // single SIMD loop. 3770 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs; 3771 const Expr *UniformedLinearThis = nullptr; 3772 for (const Expr *E : Uniforms) { 3773 E = E->IgnoreParenImpCasts(); 3774 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 3775 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 3776 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3777 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3778 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 3779 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E); 3780 continue; 3781 } 3782 if (isa<CXXThisExpr>(E)) { 3783 UniformedLinearThis = E; 3784 continue; 3785 } 3786 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3787 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3788 } 3789 // OpenMP [2.8.2, declare simd construct, Description] 3790 // The aligned clause declares that the object to which each list item points 3791 // is aligned to the number of bytes expressed in the optional parameter of 3792 // the aligned clause. 3793 // The special this pointer can be used as if was one of the arguments to the 3794 // function in any of the linear, aligned, or uniform clauses. 3795 // The type of list items appearing in the aligned clause must be array, 3796 // pointer, reference to array, or reference to pointer. 3797 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs; 3798 const Expr *AlignedThis = nullptr; 3799 for (const Expr *E : Aligneds) { 3800 E = E->IgnoreParenImpCasts(); 3801 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 3802 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3803 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 3804 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3805 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3806 ->getCanonicalDecl() == CanonPVD) { 3807 // OpenMP [2.8.1, simd construct, Restrictions] 3808 // A list-item cannot appear in more than one aligned clause. 3809 if (AlignedArgs.count(CanonPVD) > 0) { 3810 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3811 << 1 << E->getSourceRange(); 3812 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 3813 diag::note_omp_explicit_dsa) 3814 << getOpenMPClauseName(OMPC_aligned); 3815 continue; 3816 } 3817 AlignedArgs[CanonPVD] = E; 3818 QualType QTy = PVD->getType() 3819 .getNonReferenceType() 3820 .getUnqualifiedType() 3821 .getCanonicalType(); 3822 const Type *Ty = QTy.getTypePtrOrNull(); 3823 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 3824 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 3825 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 3826 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 3827 } 3828 continue; 3829 } 3830 } 3831 if (isa<CXXThisExpr>(E)) { 3832 if (AlignedThis) { 3833 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3834 << 2 << E->getSourceRange(); 3835 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 3836 << getOpenMPClauseName(OMPC_aligned); 3837 } 3838 AlignedThis = E; 3839 continue; 3840 } 3841 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3842 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3843 } 3844 // The optional parameter of the aligned clause, alignment, must be a constant 3845 // positive integer expression. If no optional parameter is specified, 3846 // implementation-defined default alignments for SIMD instructions on the 3847 // target platforms are assumed. 3848 SmallVector<const Expr *, 4> NewAligns; 3849 for (Expr *E : Alignments) { 3850 ExprResult Align; 3851 if (E) 3852 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 3853 NewAligns.push_back(Align.get()); 3854 } 3855 // OpenMP [2.8.2, declare simd construct, Description] 3856 // The linear clause declares one or more list items to be private to a SIMD 3857 // lane and to have a linear relationship with respect to the iteration space 3858 // of a loop. 3859 // The special this pointer can be used as if was one of the arguments to the 3860 // function in any of the linear, aligned, or uniform clauses. 3861 // When a linear-step expression is specified in a linear clause it must be 3862 // either a constant integer expression or an integer-typed parameter that is 3863 // specified in a uniform clause on the directive. 3864 llvm::DenseMap<const Decl *, const Expr *> LinearArgs; 3865 const bool IsUniformedThis = UniformedLinearThis != nullptr; 3866 auto MI = LinModifiers.begin(); 3867 for (const Expr *E : Linears) { 3868 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 3869 ++MI; 3870 E = E->IgnoreParenImpCasts(); 3871 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 3872 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3873 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 3874 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3875 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3876 ->getCanonicalDecl() == CanonPVD) { 3877 // OpenMP [2.15.3.7, linear Clause, Restrictions] 3878 // A list-item cannot appear in more than one linear clause. 3879 if (LinearArgs.count(CanonPVD) > 0) { 3880 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3881 << getOpenMPClauseName(OMPC_linear) 3882 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 3883 Diag(LinearArgs[CanonPVD]->getExprLoc(), 3884 diag::note_omp_explicit_dsa) 3885 << getOpenMPClauseName(OMPC_linear); 3886 continue; 3887 } 3888 // Each argument can appear in at most one uniform or linear clause. 3889 if (UniformedArgs.count(CanonPVD) > 0) { 3890 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3891 << getOpenMPClauseName(OMPC_linear) 3892 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 3893 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 3894 diag::note_omp_explicit_dsa) 3895 << getOpenMPClauseName(OMPC_uniform); 3896 continue; 3897 } 3898 LinearArgs[CanonPVD] = E; 3899 if (E->isValueDependent() || E->isTypeDependent() || 3900 E->isInstantiationDependent() || 3901 E->containsUnexpandedParameterPack()) 3902 continue; 3903 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 3904 PVD->getOriginalType()); 3905 continue; 3906 } 3907 } 3908 if (isa<CXXThisExpr>(E)) { 3909 if (UniformedLinearThis) { 3910 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3911 << getOpenMPClauseName(OMPC_linear) 3912 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 3913 << E->getSourceRange(); 3914 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 3915 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 3916 : OMPC_linear); 3917 continue; 3918 } 3919 UniformedLinearThis = E; 3920 if (E->isValueDependent() || E->isTypeDependent() || 3921 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 3922 continue; 3923 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 3924 E->getType()); 3925 continue; 3926 } 3927 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3928 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3929 } 3930 Expr *Step = nullptr; 3931 Expr *NewStep = nullptr; 3932 SmallVector<Expr *, 4> NewSteps; 3933 for (Expr *E : Steps) { 3934 // Skip the same step expression, it was checked already. 3935 if (Step == E || !E) { 3936 NewSteps.push_back(E ? NewStep : nullptr); 3937 continue; 3938 } 3939 Step = E; 3940 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step)) 3941 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3942 const VarDecl *CanonPVD = PVD->getCanonicalDecl(); 3943 if (UniformedArgs.count(CanonPVD) == 0) { 3944 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 3945 << Step->getSourceRange(); 3946 } else if (E->isValueDependent() || E->isTypeDependent() || 3947 E->isInstantiationDependent() || 3948 E->containsUnexpandedParameterPack() || 3949 CanonPVD->getType()->hasIntegerRepresentation()) { 3950 NewSteps.push_back(Step); 3951 } else { 3952 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 3953 << Step->getSourceRange(); 3954 } 3955 continue; 3956 } 3957 NewStep = Step; 3958 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 3959 !Step->isInstantiationDependent() && 3960 !Step->containsUnexpandedParameterPack()) { 3961 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 3962 .get(); 3963 if (NewStep) 3964 NewStep = VerifyIntegerConstantExpression(NewStep).get(); 3965 } 3966 NewSteps.push_back(NewStep); 3967 } 3968 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 3969 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 3970 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 3971 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 3972 const_cast<Expr **>(Linears.data()), Linears.size(), 3973 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 3974 NewSteps.data(), NewSteps.size(), SR); 3975 ADecl->addAttr(NewAttr); 3976 return ConvertDeclToDeclGroup(ADecl); 3977 } 3978 3979 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 3980 Stmt *AStmt, 3981 SourceLocation StartLoc, 3982 SourceLocation EndLoc) { 3983 if (!AStmt) 3984 return StmtError(); 3985 3986 auto *CS = cast<CapturedStmt>(AStmt); 3987 // 1.2.2 OpenMP Language Terminology 3988 // Structured block - An executable statement with a single entry at the 3989 // top and a single exit at the bottom. 3990 // The point of exit cannot be a branch out of the structured block. 3991 // longjmp() and throw() must not violate the entry/exit criteria. 3992 CS->getCapturedDecl()->setNothrow(); 3993 3994 setFunctionHasBranchProtectedScope(); 3995 3996 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 3997 DSAStack->isCancelRegion()); 3998 } 3999 4000 namespace { 4001 /// Helper class for checking canonical form of the OpenMP loops and 4002 /// extracting iteration space of each loop in the loop nest, that will be used 4003 /// for IR generation. 4004 class OpenMPIterationSpaceChecker { 4005 /// Reference to Sema. 4006 Sema &SemaRef; 4007 /// A location for diagnostics (when there is no some better location). 4008 SourceLocation DefaultLoc; 4009 /// A location for diagnostics (when increment is not compatible). 4010 SourceLocation ConditionLoc; 4011 /// A source location for referring to loop init later. 4012 SourceRange InitSrcRange; 4013 /// A source location for referring to condition later. 4014 SourceRange ConditionSrcRange; 4015 /// A source location for referring to increment later. 4016 SourceRange IncrementSrcRange; 4017 /// Loop variable. 4018 ValueDecl *LCDecl = nullptr; 4019 /// Reference to loop variable. 4020 Expr *LCRef = nullptr; 4021 /// Lower bound (initializer for the var). 4022 Expr *LB = nullptr; 4023 /// Upper bound. 4024 Expr *UB = nullptr; 4025 /// Loop step (increment). 4026 Expr *Step = nullptr; 4027 /// This flag is true when condition is one of: 4028 /// Var < UB 4029 /// Var <= UB 4030 /// UB > Var 4031 /// UB >= Var 4032 /// This will have no value when the condition is != 4033 llvm::Optional<bool> TestIsLessOp; 4034 /// This flag is true when condition is strict ( < or > ). 4035 bool TestIsStrictOp = false; 4036 /// This flag is true when step is subtracted on each iteration. 4037 bool SubtractStep = false; 4038 4039 public: 4040 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) 4041 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 4042 /// Check init-expr for canonical loop form and save loop counter 4043 /// variable - #Var and its initialization value - #LB. 4044 bool checkAndSetInit(Stmt *S, bool EmitDiags = true); 4045 /// Check test-expr for canonical form, save upper-bound (#UB), flags 4046 /// for less/greater and for strict/non-strict comparison. 4047 bool checkAndSetCond(Expr *S); 4048 /// Check incr-expr for canonical loop form and return true if it 4049 /// does not conform, otherwise save loop step (#Step). 4050 bool checkAndSetInc(Expr *S); 4051 /// Return the loop counter variable. 4052 ValueDecl *getLoopDecl() const { return LCDecl; } 4053 /// Return the reference expression to loop counter variable. 4054 Expr *getLoopDeclRefExpr() const { return LCRef; } 4055 /// Source range of the loop init. 4056 SourceRange getInitSrcRange() const { return InitSrcRange; } 4057 /// Source range of the loop condition. 4058 SourceRange getConditionSrcRange() const { return ConditionSrcRange; } 4059 /// Source range of the loop increment. 4060 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; } 4061 /// True if the step should be subtracted. 4062 bool shouldSubtractStep() const { return SubtractStep; } 4063 /// True, if the compare operator is strict (<, > or !=). 4064 bool isStrictTestOp() const { return TestIsStrictOp; } 4065 /// Build the expression to calculate the number of iterations. 4066 Expr *buildNumIterations( 4067 Scope *S, const bool LimitedType, 4068 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 4069 /// Build the precondition expression for the loops. 4070 Expr * 4071 buildPreCond(Scope *S, Expr *Cond, 4072 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const; 4073 /// Build reference expression to the counter be used for codegen. 4074 DeclRefExpr * 4075 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 4076 DSAStackTy &DSA) const; 4077 /// Build reference expression to the private counter be used for 4078 /// codegen. 4079 Expr *buildPrivateCounterVar() const; 4080 /// Build initialization of the counter be used for codegen. 4081 Expr *buildCounterInit() const; 4082 /// Build step of the counter be used for codegen. 4083 Expr *buildCounterStep() const; 4084 /// Build loop data with counter value for depend clauses in ordered 4085 /// directives. 4086 Expr * 4087 buildOrderedLoopData(Scope *S, Expr *Counter, 4088 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 4089 SourceLocation Loc, Expr *Inc = nullptr, 4090 OverloadedOperatorKind OOK = OO_Amp); 4091 /// Return true if any expression is dependent. 4092 bool dependent() const; 4093 4094 private: 4095 /// Check the right-hand side of an assignment in the increment 4096 /// expression. 4097 bool checkAndSetIncRHS(Expr *RHS); 4098 /// Helper to set loop counter variable and its initializer. 4099 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB); 4100 /// Helper to set upper bound. 4101 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp, 4102 SourceRange SR, SourceLocation SL); 4103 /// Helper to set loop increment. 4104 bool setStep(Expr *NewStep, bool Subtract); 4105 }; 4106 4107 bool OpenMPIterationSpaceChecker::dependent() const { 4108 if (!LCDecl) { 4109 assert(!LB && !UB && !Step); 4110 return false; 4111 } 4112 return LCDecl->getType()->isDependentType() || 4113 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 4114 (Step && Step->isValueDependent()); 4115 } 4116 4117 bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl, 4118 Expr *NewLCRefExpr, 4119 Expr *NewLB) { 4120 // State consistency checking to ensure correct usage. 4121 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 4122 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 4123 if (!NewLCDecl || !NewLB) 4124 return true; 4125 LCDecl = getCanonicalDecl(NewLCDecl); 4126 LCRef = NewLCRefExpr; 4127 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 4128 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 4129 if ((Ctor->isCopyOrMoveConstructor() || 4130 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 4131 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 4132 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 4133 LB = NewLB; 4134 return false; 4135 } 4136 4137 bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, 4138 llvm::Optional<bool> LessOp, 4139 bool StrictOp, SourceRange SR, 4140 SourceLocation SL) { 4141 // State consistency checking to ensure correct usage. 4142 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 4143 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 4144 if (!NewUB) 4145 return true; 4146 UB = NewUB; 4147 if (LessOp) 4148 TestIsLessOp = LessOp; 4149 TestIsStrictOp = StrictOp; 4150 ConditionSrcRange = SR; 4151 ConditionLoc = SL; 4152 return false; 4153 } 4154 4155 bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) { 4156 // State consistency checking to ensure correct usage. 4157 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 4158 if (!NewStep) 4159 return true; 4160 if (!NewStep->isValueDependent()) { 4161 // Check that the step is integer expression. 4162 SourceLocation StepLoc = NewStep->getBeginLoc(); 4163 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( 4164 StepLoc, getExprAsWritten(NewStep)); 4165 if (Val.isInvalid()) 4166 return true; 4167 NewStep = Val.get(); 4168 4169 // OpenMP [2.6, Canonical Loop Form, Restrictions] 4170 // If test-expr is of form var relational-op b and relational-op is < or 4171 // <= then incr-expr must cause var to increase on each iteration of the 4172 // loop. If test-expr is of form var relational-op b and relational-op is 4173 // > or >= then incr-expr must cause var to decrease on each iteration of 4174 // the loop. 4175 // If test-expr is of form b relational-op var and relational-op is < or 4176 // <= then incr-expr must cause var to decrease on each iteration of the 4177 // loop. If test-expr is of form b relational-op var and relational-op is 4178 // > or >= then incr-expr must cause var to increase on each iteration of 4179 // the loop. 4180 llvm::APSInt Result; 4181 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 4182 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 4183 bool IsConstNeg = 4184 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 4185 bool IsConstPos = 4186 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 4187 bool IsConstZero = IsConstant && !Result.getBoolValue(); 4188 4189 // != with increment is treated as <; != with decrement is treated as > 4190 if (!TestIsLessOp.hasValue()) 4191 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract); 4192 if (UB && (IsConstZero || 4193 (TestIsLessOp.getValue() ? 4194 (IsConstNeg || (IsUnsigned && Subtract)) : 4195 (IsConstPos || (IsUnsigned && !Subtract))))) { 4196 SemaRef.Diag(NewStep->getExprLoc(), 4197 diag::err_omp_loop_incr_not_compatible) 4198 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange(); 4199 SemaRef.Diag(ConditionLoc, 4200 diag::note_omp_loop_cond_requres_compatible_incr) 4201 << TestIsLessOp.getValue() << ConditionSrcRange; 4202 return true; 4203 } 4204 if (TestIsLessOp.getValue() == Subtract) { 4205 NewStep = 4206 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 4207 .get(); 4208 Subtract = !Subtract; 4209 } 4210 } 4211 4212 Step = NewStep; 4213 SubtractStep = Subtract; 4214 return false; 4215 } 4216 4217 bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) { 4218 // Check init-expr for canonical loop form and save loop counter 4219 // variable - #Var and its initialization value - #LB. 4220 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 4221 // var = lb 4222 // integer-type var = lb 4223 // random-access-iterator-type var = lb 4224 // pointer-type var = lb 4225 // 4226 if (!S) { 4227 if (EmitDiags) { 4228 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 4229 } 4230 return true; 4231 } 4232 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 4233 if (!ExprTemp->cleanupsHaveSideEffects()) 4234 S = ExprTemp->getSubExpr(); 4235 4236 InitSrcRange = S->getSourceRange(); 4237 if (Expr *E = dyn_cast<Expr>(S)) 4238 S = E->IgnoreParens(); 4239 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 4240 if (BO->getOpcode() == BO_Assign) { 4241 Expr *LHS = BO->getLHS()->IgnoreParens(); 4242 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 4243 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 4244 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 4245 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4246 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS()); 4247 } 4248 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 4249 if (ME->isArrow() && 4250 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 4251 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4252 } 4253 } 4254 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 4255 if (DS->isSingleDecl()) { 4256 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 4257 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 4258 // Accept non-canonical init form here but emit ext. warning. 4259 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 4260 SemaRef.Diag(S->getBeginLoc(), 4261 diag::ext_omp_loop_not_canonical_init) 4262 << S->getSourceRange(); 4263 return setLCDeclAndLB( 4264 Var, 4265 buildDeclRefExpr(SemaRef, Var, 4266 Var->getType().getNonReferenceType(), 4267 DS->getBeginLoc()), 4268 Var->getInit()); 4269 } 4270 } 4271 } 4272 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 4273 if (CE->getOperator() == OO_Equal) { 4274 Expr *LHS = CE->getArg(0); 4275 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 4276 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 4277 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 4278 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4279 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1)); 4280 } 4281 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 4282 if (ME->isArrow() && 4283 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 4284 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 4285 } 4286 } 4287 } 4288 4289 if (dependent() || SemaRef.CurContext->isDependentContext()) 4290 return false; 4291 if (EmitDiags) { 4292 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init) 4293 << S->getSourceRange(); 4294 } 4295 return true; 4296 } 4297 4298 /// Ignore parenthesizes, implicit casts, copy constructor and return the 4299 /// variable (which may be the loop variable) if possible. 4300 static const ValueDecl *getInitLCDecl(const Expr *E) { 4301 if (!E) 4302 return nullptr; 4303 E = getExprAsWritten(E); 4304 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 4305 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 4306 if ((Ctor->isCopyOrMoveConstructor() || 4307 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 4308 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 4309 E = CE->getArg(0)->IgnoreParenImpCasts(); 4310 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 4311 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 4312 return getCanonicalDecl(VD); 4313 } 4314 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E)) 4315 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 4316 return getCanonicalDecl(ME->getMemberDecl()); 4317 return nullptr; 4318 } 4319 4320 bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) { 4321 // Check test-expr for canonical form, save upper-bound UB, flags for 4322 // less/greater and for strict/non-strict comparison. 4323 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 4324 // var relational-op b 4325 // b relational-op var 4326 // 4327 if (!S) { 4328 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl; 4329 return true; 4330 } 4331 S = getExprAsWritten(S); 4332 SourceLocation CondLoc = S->getBeginLoc(); 4333 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 4334 if (BO->isRelationalOp()) { 4335 if (getInitLCDecl(BO->getLHS()) == LCDecl) 4336 return setUB(BO->getRHS(), 4337 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 4338 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 4339 BO->getSourceRange(), BO->getOperatorLoc()); 4340 if (getInitLCDecl(BO->getRHS()) == LCDecl) 4341 return setUB(BO->getLHS(), 4342 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 4343 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 4344 BO->getSourceRange(), BO->getOperatorLoc()); 4345 } else if (BO->getOpcode() == BO_NE) 4346 return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ? 4347 BO->getRHS() : BO->getLHS(), 4348 /*LessOp=*/llvm::None, 4349 /*StrictOp=*/true, 4350 BO->getSourceRange(), BO->getOperatorLoc()); 4351 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 4352 if (CE->getNumArgs() == 2) { 4353 auto Op = CE->getOperator(); 4354 switch (Op) { 4355 case OO_Greater: 4356 case OO_GreaterEqual: 4357 case OO_Less: 4358 case OO_LessEqual: 4359 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 4360 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 4361 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 4362 CE->getOperatorLoc()); 4363 if (getInitLCDecl(CE->getArg(1)) == LCDecl) 4364 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 4365 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 4366 CE->getOperatorLoc()); 4367 break; 4368 case OO_ExclaimEqual: 4369 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? 4370 CE->getArg(1) : CE->getArg(0), 4371 /*LessOp=*/llvm::None, 4372 /*StrictOp=*/true, 4373 CE->getSourceRange(), 4374 CE->getOperatorLoc()); 4375 break; 4376 default: 4377 break; 4378 } 4379 } 4380 } 4381 if (dependent() || SemaRef.CurContext->isDependentContext()) 4382 return false; 4383 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 4384 << S->getSourceRange() << LCDecl; 4385 return true; 4386 } 4387 4388 bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) { 4389 // RHS of canonical loop form increment can be: 4390 // var + incr 4391 // incr + var 4392 // var - incr 4393 // 4394 RHS = RHS->IgnoreParenImpCasts(); 4395 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 4396 if (BO->isAdditiveOp()) { 4397 bool IsAdd = BO->getOpcode() == BO_Add; 4398 if (getInitLCDecl(BO->getLHS()) == LCDecl) 4399 return setStep(BO->getRHS(), !IsAdd); 4400 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl) 4401 return setStep(BO->getLHS(), /*Subtract=*/false); 4402 } 4403 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 4404 bool IsAdd = CE->getOperator() == OO_Plus; 4405 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 4406 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 4407 return setStep(CE->getArg(1), !IsAdd); 4408 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl) 4409 return setStep(CE->getArg(0), /*Subtract=*/false); 4410 } 4411 } 4412 if (dependent() || SemaRef.CurContext->isDependentContext()) 4413 return false; 4414 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 4415 << RHS->getSourceRange() << LCDecl; 4416 return true; 4417 } 4418 4419 bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) { 4420 // Check incr-expr for canonical loop form and return true if it 4421 // does not conform. 4422 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 4423 // ++var 4424 // var++ 4425 // --var 4426 // var-- 4427 // var += incr 4428 // var -= incr 4429 // var = var + incr 4430 // var = incr + var 4431 // var = var - incr 4432 // 4433 if (!S) { 4434 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 4435 return true; 4436 } 4437 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 4438 if (!ExprTemp->cleanupsHaveSideEffects()) 4439 S = ExprTemp->getSubExpr(); 4440 4441 IncrementSrcRange = S->getSourceRange(); 4442 S = S->IgnoreParens(); 4443 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 4444 if (UO->isIncrementDecrementOp() && 4445 getInitLCDecl(UO->getSubExpr()) == LCDecl) 4446 return setStep(SemaRef 4447 .ActOnIntegerConstant(UO->getBeginLoc(), 4448 (UO->isDecrementOp() ? -1 : 1)) 4449 .get(), 4450 /*Subtract=*/false); 4451 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 4452 switch (BO->getOpcode()) { 4453 case BO_AddAssign: 4454 case BO_SubAssign: 4455 if (getInitLCDecl(BO->getLHS()) == LCDecl) 4456 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 4457 break; 4458 case BO_Assign: 4459 if (getInitLCDecl(BO->getLHS()) == LCDecl) 4460 return checkAndSetIncRHS(BO->getRHS()); 4461 break; 4462 default: 4463 break; 4464 } 4465 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 4466 switch (CE->getOperator()) { 4467 case OO_PlusPlus: 4468 case OO_MinusMinus: 4469 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 4470 return setStep(SemaRef 4471 .ActOnIntegerConstant( 4472 CE->getBeginLoc(), 4473 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 4474 .get(), 4475 /*Subtract=*/false); 4476 break; 4477 case OO_PlusEqual: 4478 case OO_MinusEqual: 4479 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 4480 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 4481 break; 4482 case OO_Equal: 4483 if (getInitLCDecl(CE->getArg(0)) == LCDecl) 4484 return checkAndSetIncRHS(CE->getArg(1)); 4485 break; 4486 default: 4487 break; 4488 } 4489 } 4490 if (dependent() || SemaRef.CurContext->isDependentContext()) 4491 return false; 4492 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr) 4493 << S->getSourceRange() << LCDecl; 4494 return true; 4495 } 4496 4497 static ExprResult 4498 tryBuildCapture(Sema &SemaRef, Expr *Capture, 4499 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 4500 if (SemaRef.CurContext->isDependentContext()) 4501 return ExprResult(Capture); 4502 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 4503 return SemaRef.PerformImplicitConversion( 4504 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 4505 /*AllowExplicit=*/true); 4506 auto I = Captures.find(Capture); 4507 if (I != Captures.end()) 4508 return buildCapture(SemaRef, Capture, I->second); 4509 DeclRefExpr *Ref = nullptr; 4510 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 4511 Captures[Capture] = Ref; 4512 return Res; 4513 } 4514 4515 /// Build the expression to calculate the number of iterations. 4516 Expr *OpenMPIterationSpaceChecker::buildNumIterations( 4517 Scope *S, const bool LimitedType, 4518 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 4519 ExprResult Diff; 4520 QualType VarType = LCDecl->getType().getNonReferenceType(); 4521 if (VarType->isIntegerType() || VarType->isPointerType() || 4522 SemaRef.getLangOpts().CPlusPlus) { 4523 // Upper - Lower 4524 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB; 4525 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB; 4526 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 4527 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 4528 if (!Upper || !Lower) 4529 return nullptr; 4530 4531 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 4532 4533 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 4534 // BuildBinOp already emitted error, this one is to point user to upper 4535 // and lower bound, and to tell what is passed to 'operator-'. 4536 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx) 4537 << Upper->getSourceRange() << Lower->getSourceRange(); 4538 return nullptr; 4539 } 4540 } 4541 4542 if (!Diff.isUsable()) 4543 return nullptr; 4544 4545 // Upper - Lower [- 1] 4546 if (TestIsStrictOp) 4547 Diff = SemaRef.BuildBinOp( 4548 S, DefaultLoc, BO_Sub, Diff.get(), 4549 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4550 if (!Diff.isUsable()) 4551 return nullptr; 4552 4553 // Upper - Lower [- 1] + Step 4554 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 4555 if (!NewStep.isUsable()) 4556 return nullptr; 4557 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 4558 if (!Diff.isUsable()) 4559 return nullptr; 4560 4561 // Parentheses (for dumping/debugging purposes only). 4562 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 4563 if (!Diff.isUsable()) 4564 return nullptr; 4565 4566 // (Upper - Lower [- 1] + Step) / Step 4567 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 4568 if (!Diff.isUsable()) 4569 return nullptr; 4570 4571 // OpenMP runtime requires 32-bit or 64-bit loop variables. 4572 QualType Type = Diff.get()->getType(); 4573 ASTContext &C = SemaRef.Context; 4574 bool UseVarType = VarType->hasIntegerRepresentation() && 4575 C.getTypeSize(Type) > C.getTypeSize(VarType); 4576 if (!Type->isIntegerType() || UseVarType) { 4577 unsigned NewSize = 4578 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 4579 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 4580 : Type->hasSignedIntegerRepresentation(); 4581 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 4582 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 4583 Diff = SemaRef.PerformImplicitConversion( 4584 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 4585 if (!Diff.isUsable()) 4586 return nullptr; 4587 } 4588 } 4589 if (LimitedType) { 4590 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 4591 if (NewSize != C.getTypeSize(Type)) { 4592 if (NewSize < C.getTypeSize(Type)) { 4593 assert(NewSize == 64 && "incorrect loop var size"); 4594 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 4595 << InitSrcRange << ConditionSrcRange; 4596 } 4597 QualType NewType = C.getIntTypeForBitwidth( 4598 NewSize, Type->hasSignedIntegerRepresentation() || 4599 C.getTypeSize(Type) < NewSize); 4600 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 4601 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 4602 Sema::AA_Converting, true); 4603 if (!Diff.isUsable()) 4604 return nullptr; 4605 } 4606 } 4607 } 4608 4609 return Diff.get(); 4610 } 4611 4612 Expr *OpenMPIterationSpaceChecker::buildPreCond( 4613 Scope *S, Expr *Cond, 4614 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const { 4615 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 4616 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 4617 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 4618 4619 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures); 4620 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures); 4621 if (!NewLB.isUsable() || !NewUB.isUsable()) 4622 return nullptr; 4623 4624 ExprResult CondExpr = 4625 SemaRef.BuildBinOp(S, DefaultLoc, 4626 TestIsLessOp.getValue() ? 4627 (TestIsStrictOp ? BO_LT : BO_LE) : 4628 (TestIsStrictOp ? BO_GT : BO_GE), 4629 NewLB.get(), NewUB.get()); 4630 if (CondExpr.isUsable()) { 4631 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 4632 SemaRef.Context.BoolTy)) 4633 CondExpr = SemaRef.PerformImplicitConversion( 4634 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 4635 /*AllowExplicit=*/true); 4636 } 4637 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 4638 // Otherwise use original loop condition and evaluate it in runtime. 4639 return CondExpr.isUsable() ? CondExpr.get() : Cond; 4640 } 4641 4642 /// Build reference expression to the counter be used for codegen. 4643 DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar( 4644 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, 4645 DSAStackTy &DSA) const { 4646 auto *VD = dyn_cast<VarDecl>(LCDecl); 4647 if (!VD) { 4648 VD = SemaRef.isOpenMPCapturedDecl(LCDecl); 4649 DeclRefExpr *Ref = buildDeclRefExpr( 4650 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 4651 const DSAStackTy::DSAVarData Data = 4652 DSA.getTopDSA(LCDecl, /*FromParent=*/false); 4653 // If the loop control decl is explicitly marked as private, do not mark it 4654 // as captured again. 4655 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 4656 Captures.insert(std::make_pair(LCRef, Ref)); 4657 return Ref; 4658 } 4659 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(), 4660 DefaultLoc); 4661 } 4662 4663 Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const { 4664 if (LCDecl && !LCDecl->isInvalidDecl()) { 4665 QualType Type = LCDecl->getType().getNonReferenceType(); 4666 VarDecl *PrivateVar = buildVarDecl( 4667 SemaRef, DefaultLoc, Type, LCDecl->getName(), 4668 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr, 4669 isa<VarDecl>(LCDecl) 4670 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc) 4671 : nullptr); 4672 if (PrivateVar->isInvalidDecl()) 4673 return nullptr; 4674 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 4675 } 4676 return nullptr; 4677 } 4678 4679 /// Build initialization of the counter to be used for codegen. 4680 Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; } 4681 4682 /// Build step of the counter be used for codegen. 4683 Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; } 4684 4685 Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData( 4686 Scope *S, Expr *Counter, 4687 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc, 4688 Expr *Inc, OverloadedOperatorKind OOK) { 4689 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get(); 4690 if (!Cnt) 4691 return nullptr; 4692 if (Inc) { 4693 assert((OOK == OO_Plus || OOK == OO_Minus) && 4694 "Expected only + or - operations for depend clauses."); 4695 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub; 4696 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get(); 4697 if (!Cnt) 4698 return nullptr; 4699 } 4700 ExprResult Diff; 4701 QualType VarType = LCDecl->getType().getNonReferenceType(); 4702 if (VarType->isIntegerType() || VarType->isPointerType() || 4703 SemaRef.getLangOpts().CPlusPlus) { 4704 // Upper - Lower 4705 Expr *Upper = TestIsLessOp.getValue() 4706 ? Cnt 4707 : tryBuildCapture(SemaRef, UB, Captures).get(); 4708 Expr *Lower = TestIsLessOp.getValue() 4709 ? tryBuildCapture(SemaRef, LB, Captures).get() 4710 : Cnt; 4711 if (!Upper || !Lower) 4712 return nullptr; 4713 4714 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 4715 4716 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 4717 // BuildBinOp already emitted error, this one is to point user to upper 4718 // and lower bound, and to tell what is passed to 'operator-'. 4719 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx) 4720 << Upper->getSourceRange() << Lower->getSourceRange(); 4721 return nullptr; 4722 } 4723 } 4724 4725 if (!Diff.isUsable()) 4726 return nullptr; 4727 4728 // Parentheses (for dumping/debugging purposes only). 4729 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 4730 if (!Diff.isUsable()) 4731 return nullptr; 4732 4733 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures); 4734 if (!NewStep.isUsable()) 4735 return nullptr; 4736 // (Upper - Lower) / Step 4737 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 4738 if (!Diff.isUsable()) 4739 return nullptr; 4740 4741 return Diff.get(); 4742 } 4743 4744 /// Iteration space of a single for loop. 4745 struct LoopIterationSpace final { 4746 /// True if the condition operator is the strict compare operator (<, > or 4747 /// !=). 4748 bool IsStrictCompare = false; 4749 /// Condition of the loop. 4750 Expr *PreCond = nullptr; 4751 /// This expression calculates the number of iterations in the loop. 4752 /// It is always possible to calculate it before starting the loop. 4753 Expr *NumIterations = nullptr; 4754 /// The loop counter variable. 4755 Expr *CounterVar = nullptr; 4756 /// Private loop counter variable. 4757 Expr *PrivateCounterVar = nullptr; 4758 /// This is initializer for the initial value of #CounterVar. 4759 Expr *CounterInit = nullptr; 4760 /// This is step for the #CounterVar used to generate its update: 4761 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 4762 Expr *CounterStep = nullptr; 4763 /// Should step be subtracted? 4764 bool Subtract = false; 4765 /// Source range of the loop init. 4766 SourceRange InitSrcRange; 4767 /// Source range of the loop condition. 4768 SourceRange CondSrcRange; 4769 /// Source range of the loop increment. 4770 SourceRange IncSrcRange; 4771 }; 4772 4773 } // namespace 4774 4775 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 4776 assert(getLangOpts().OpenMP && "OpenMP is not active."); 4777 assert(Init && "Expected loop in canonical form."); 4778 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 4779 if (AssociatedLoops > 0 && 4780 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 4781 DSAStack->loopStart(); 4782 OpenMPIterationSpaceChecker ISC(*this, ForLoc); 4783 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) { 4784 if (ValueDecl *D = ISC.getLoopDecl()) { 4785 auto *VD = dyn_cast<VarDecl>(D); 4786 if (!VD) { 4787 if (VarDecl *Private = isOpenMPCapturedDecl(D)) { 4788 VD = Private; 4789 } else { 4790 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(), 4791 /*WithInit=*/false); 4792 VD = cast<VarDecl>(Ref->getDecl()); 4793 } 4794 } 4795 DSAStack->addLoopControlVariable(D, VD); 4796 const Decl *LD = DSAStack->getPossiblyLoopCunter(); 4797 if (LD != D->getCanonicalDecl()) { 4798 DSAStack->resetPossibleLoopCounter(); 4799 if (auto *Var = dyn_cast_or_null<VarDecl>(LD)) 4800 MarkDeclarationsReferencedInExpr( 4801 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var), 4802 Var->getType().getNonLValueExprType(Context), 4803 ForLoc, /*RefersToCapture=*/true)); 4804 } 4805 } 4806 } 4807 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 4808 } 4809 } 4810 4811 /// Called on a for stmt to check and extract its iteration space 4812 /// for further processing (such as collapsing). 4813 static bool checkOpenMPIterationSpace( 4814 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 4815 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 4816 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr, 4817 Expr *OrderedLoopCountExpr, 4818 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 4819 LoopIterationSpace &ResultIterSpace, 4820 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 4821 // OpenMP [2.6, Canonical Loop Form] 4822 // for (init-expr; test-expr; incr-expr) structured-block 4823 auto *For = dyn_cast_or_null<ForStmt>(S); 4824 if (!For) { 4825 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for) 4826 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 4827 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount 4828 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 4829 if (TotalNestedLoopCount > 1) { 4830 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 4831 SemaRef.Diag(DSA.getConstructLoc(), 4832 diag::note_omp_collapse_ordered_expr) 4833 << 2 << CollapseLoopCountExpr->getSourceRange() 4834 << OrderedLoopCountExpr->getSourceRange(); 4835 else if (CollapseLoopCountExpr) 4836 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 4837 diag::note_omp_collapse_ordered_expr) 4838 << 0 << CollapseLoopCountExpr->getSourceRange(); 4839 else 4840 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 4841 diag::note_omp_collapse_ordered_expr) 4842 << 1 << OrderedLoopCountExpr->getSourceRange(); 4843 } 4844 return true; 4845 } 4846 assert(For->getBody()); 4847 4848 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); 4849 4850 // Check init. 4851 Stmt *Init = For->getInit(); 4852 if (ISC.checkAndSetInit(Init)) 4853 return true; 4854 4855 bool HasErrors = false; 4856 4857 // Check loop variable's type. 4858 if (ValueDecl *LCDecl = ISC.getLoopDecl()) { 4859 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr(); 4860 4861 // OpenMP [2.6, Canonical Loop Form] 4862 // Var is one of the following: 4863 // A variable of signed or unsigned integer type. 4864 // For C++, a variable of a random access iterator type. 4865 // For C, a variable of a pointer type. 4866 QualType VarType = LCDecl->getType().getNonReferenceType(); 4867 if (!VarType->isDependentType() && !VarType->isIntegerType() && 4868 !VarType->isPointerType() && 4869 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 4870 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type) 4871 << SemaRef.getLangOpts().CPlusPlus; 4872 HasErrors = true; 4873 } 4874 4875 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 4876 // a Construct 4877 // The loop iteration variable(s) in the associated for-loop(s) of a for or 4878 // parallel for construct is (are) private. 4879 // The loop iteration variable in the associated for-loop of a simd 4880 // construct with just one associated for-loop is linear with a 4881 // constant-linear-step that is the increment of the associated for-loop. 4882 // Exclude loop var from the list of variables with implicitly defined data 4883 // sharing attributes. 4884 VarsWithImplicitDSA.erase(LCDecl); 4885 4886 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 4887 // in a Construct, C/C++]. 4888 // The loop iteration variable in the associated for-loop of a simd 4889 // construct with just one associated for-loop may be listed in a linear 4890 // clause with a constant-linear-step that is the increment of the 4891 // associated for-loop. 4892 // The loop iteration variable(s) in the associated for-loop(s) of a for or 4893 // parallel for construct may be listed in a private or lastprivate clause. 4894 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false); 4895 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 4896 // declared in the loop and it is predetermined as a private. 4897 OpenMPClauseKind PredeterminedCKind = 4898 isOpenMPSimdDirective(DKind) 4899 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 4900 : OMPC_private; 4901 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 4902 DVar.CKind != PredeterminedCKind) || 4903 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 4904 isOpenMPDistributeDirective(DKind)) && 4905 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 4906 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 4907 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 4908 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa) 4909 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 4910 << getOpenMPClauseName(PredeterminedCKind); 4911 if (DVar.RefExpr == nullptr) 4912 DVar.CKind = PredeterminedCKind; 4913 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true); 4914 HasErrors = true; 4915 } else if (LoopDeclRefExpr != nullptr) { 4916 // Make the loop iteration variable private (for worksharing constructs), 4917 // linear (for simd directives with the only one associated loop) or 4918 // lastprivate (for simd directives with several collapsed or ordered 4919 // loops). 4920 if (DVar.CKind == OMPC_unknown) 4921 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind); 4922 } 4923 4924 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 4925 4926 // Check test-expr. 4927 HasErrors |= ISC.checkAndSetCond(For->getCond()); 4928 4929 // Check incr-expr. 4930 HasErrors |= ISC.checkAndSetInc(For->getInc()); 4931 } 4932 4933 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 4934 return HasErrors; 4935 4936 // Build the loop's iteration space representation. 4937 ResultIterSpace.PreCond = 4938 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures); 4939 ResultIterSpace.NumIterations = ISC.buildNumIterations( 4940 DSA.getCurScope(), 4941 (isOpenMPWorksharingDirective(DKind) || 4942 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)), 4943 Captures); 4944 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA); 4945 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar(); 4946 ResultIterSpace.CounterInit = ISC.buildCounterInit(); 4947 ResultIterSpace.CounterStep = ISC.buildCounterStep(); 4948 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange(); 4949 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange(); 4950 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange(); 4951 ResultIterSpace.Subtract = ISC.shouldSubtractStep(); 4952 ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp(); 4953 4954 HasErrors |= (ResultIterSpace.PreCond == nullptr || 4955 ResultIterSpace.NumIterations == nullptr || 4956 ResultIterSpace.CounterVar == nullptr || 4957 ResultIterSpace.PrivateCounterVar == nullptr || 4958 ResultIterSpace.CounterInit == nullptr || 4959 ResultIterSpace.CounterStep == nullptr); 4960 if (!HasErrors && DSA.isOrderedRegion()) { 4961 if (DSA.getOrderedRegionParam().second->getNumForLoops()) { 4962 if (CurrentNestedLoopCount < 4963 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) { 4964 DSA.getOrderedRegionParam().second->setLoopNumIterations( 4965 CurrentNestedLoopCount, ResultIterSpace.NumIterations); 4966 DSA.getOrderedRegionParam().second->setLoopCounter( 4967 CurrentNestedLoopCount, ResultIterSpace.CounterVar); 4968 } 4969 } 4970 for (auto &Pair : DSA.getDoacrossDependClauses()) { 4971 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) { 4972 // Erroneous case - clause has some problems. 4973 continue; 4974 } 4975 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink && 4976 Pair.second.size() <= CurrentNestedLoopCount) { 4977 // Erroneous case - clause has some problems. 4978 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr); 4979 continue; 4980 } 4981 Expr *CntValue; 4982 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 4983 CntValue = ISC.buildOrderedLoopData( 4984 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures, 4985 Pair.first->getDependencyLoc()); 4986 else 4987 CntValue = ISC.buildOrderedLoopData( 4988 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures, 4989 Pair.first->getDependencyLoc(), 4990 Pair.second[CurrentNestedLoopCount].first, 4991 Pair.second[CurrentNestedLoopCount].second); 4992 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue); 4993 } 4994 } 4995 4996 return HasErrors; 4997 } 4998 4999 /// Build 'VarRef = Start. 5000 static ExprResult 5001 buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 5002 ExprResult Start, 5003 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 5004 // Build 'VarRef = Start. 5005 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures); 5006 if (!NewStart.isUsable()) 5007 return ExprError(); 5008 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 5009 VarRef.get()->getType())) { 5010 NewStart = SemaRef.PerformImplicitConversion( 5011 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 5012 /*AllowExplicit=*/true); 5013 if (!NewStart.isUsable()) 5014 return ExprError(); 5015 } 5016 5017 ExprResult Init = 5018 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 5019 return Init; 5020 } 5021 5022 /// Build 'VarRef = Start + Iter * Step'. 5023 static ExprResult buildCounterUpdate( 5024 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 5025 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract, 5026 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) { 5027 // Add parentheses (for debugging purposes only). 5028 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 5029 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 5030 !Step.isUsable()) 5031 return ExprError(); 5032 5033 ExprResult NewStep = Step; 5034 if (Captures) 5035 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 5036 if (NewStep.isInvalid()) 5037 return ExprError(); 5038 ExprResult Update = 5039 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 5040 if (!Update.isUsable()) 5041 return ExprError(); 5042 5043 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 5044 // 'VarRef = Start (+|-) Iter * Step'. 5045 ExprResult NewStart = Start; 5046 if (Captures) 5047 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 5048 if (NewStart.isInvalid()) 5049 return ExprError(); 5050 5051 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 5052 ExprResult SavedUpdate = Update; 5053 ExprResult UpdateVal; 5054 if (VarRef.get()->getType()->isOverloadableType() || 5055 NewStart.get()->getType()->isOverloadableType() || 5056 Update.get()->getType()->isOverloadableType()) { 5057 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 5058 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 5059 Update = 5060 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 5061 if (Update.isUsable()) { 5062 UpdateVal = 5063 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 5064 VarRef.get(), SavedUpdate.get()); 5065 if (UpdateVal.isUsable()) { 5066 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 5067 UpdateVal.get()); 5068 } 5069 } 5070 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 5071 } 5072 5073 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 5074 if (!Update.isUsable() || !UpdateVal.isUsable()) { 5075 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 5076 NewStart.get(), SavedUpdate.get()); 5077 if (!Update.isUsable()) 5078 return ExprError(); 5079 5080 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 5081 VarRef.get()->getType())) { 5082 Update = SemaRef.PerformImplicitConversion( 5083 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 5084 if (!Update.isUsable()) 5085 return ExprError(); 5086 } 5087 5088 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 5089 } 5090 return Update; 5091 } 5092 5093 /// Convert integer expression \a E to make it have at least \a Bits 5094 /// bits. 5095 static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 5096 if (E == nullptr) 5097 return ExprError(); 5098 ASTContext &C = SemaRef.Context; 5099 QualType OldType = E->getType(); 5100 unsigned HasBits = C.getTypeSize(OldType); 5101 if (HasBits >= Bits) 5102 return ExprResult(E); 5103 // OK to convert to signed, because new type has more bits than old. 5104 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 5105 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 5106 true); 5107 } 5108 5109 /// Check if the given expression \a E is a constant integer that fits 5110 /// into \a Bits bits. 5111 static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) { 5112 if (E == nullptr) 5113 return false; 5114 llvm::APSInt Result; 5115 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 5116 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 5117 return false; 5118 } 5119 5120 /// Build preinits statement for the given declarations. 5121 static Stmt *buildPreInits(ASTContext &Context, 5122 MutableArrayRef<Decl *> PreInits) { 5123 if (!PreInits.empty()) { 5124 return new (Context) DeclStmt( 5125 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 5126 SourceLocation(), SourceLocation()); 5127 } 5128 return nullptr; 5129 } 5130 5131 /// Build preinits statement for the given declarations. 5132 static Stmt * 5133 buildPreInits(ASTContext &Context, 5134 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) { 5135 if (!Captures.empty()) { 5136 SmallVector<Decl *, 16> PreInits; 5137 for (const auto &Pair : Captures) 5138 PreInits.push_back(Pair.second->getDecl()); 5139 return buildPreInits(Context, PreInits); 5140 } 5141 return nullptr; 5142 } 5143 5144 /// Build postupdate expression for the given list of postupdates expressions. 5145 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 5146 Expr *PostUpdate = nullptr; 5147 if (!PostUpdates.empty()) { 5148 for (Expr *E : PostUpdates) { 5149 Expr *ConvE = S.BuildCStyleCastExpr( 5150 E->getExprLoc(), 5151 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 5152 E->getExprLoc(), E) 5153 .get(); 5154 PostUpdate = PostUpdate 5155 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 5156 PostUpdate, ConvE) 5157 .get() 5158 : ConvE; 5159 } 5160 } 5161 return PostUpdate; 5162 } 5163 5164 /// Called on a for stmt to check itself and nested loops (if any). 5165 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 5166 /// number of collapsed loops otherwise. 5167 static unsigned 5168 checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 5169 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 5170 DSAStackTy &DSA, 5171 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA, 5172 OMPLoopDirective::HelperExprs &Built) { 5173 unsigned NestedLoopCount = 1; 5174 if (CollapseLoopCountExpr) { 5175 // Found 'collapse' clause - calculate collapse number. 5176 Expr::EvalResult Result; 5177 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) 5178 NestedLoopCount = Result.Val.getInt().getLimitedValue(); 5179 } 5180 unsigned OrderedLoopCount = 1; 5181 if (OrderedLoopCountExpr) { 5182 // Found 'ordered' clause - calculate collapse number. 5183 Expr::EvalResult EVResult; 5184 if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) { 5185 llvm::APSInt Result = EVResult.Val.getInt(); 5186 if (Result.getLimitedValue() < NestedLoopCount) { 5187 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 5188 diag::err_omp_wrong_ordered_loop_count) 5189 << OrderedLoopCountExpr->getSourceRange(); 5190 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 5191 diag::note_collapse_loop_count) 5192 << CollapseLoopCountExpr->getSourceRange(); 5193 } 5194 OrderedLoopCount = Result.getLimitedValue(); 5195 } 5196 } 5197 // This is helper routine for loop directives (e.g., 'for', 'simd', 5198 // 'for simd', etc.). 5199 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 5200 SmallVector<LoopIterationSpace, 4> IterSpaces( 5201 std::max(OrderedLoopCount, NestedLoopCount)); 5202 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 5203 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 5204 if (checkOpenMPIterationSpace( 5205 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 5206 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr, 5207 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt], 5208 Captures)) 5209 return 0; 5210 // Move on to the next nested for loop, or to the loop body. 5211 // OpenMP [2.8.1, simd construct, Restrictions] 5212 // All loops associated with the construct must be perfectly nested; that 5213 // is, there must be no intervening code nor any OpenMP directive between 5214 // any two loops. 5215 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 5216 } 5217 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) { 5218 if (checkOpenMPIterationSpace( 5219 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount, 5220 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr, 5221 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt], 5222 Captures)) 5223 return 0; 5224 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) { 5225 // Handle initialization of captured loop iterator variables. 5226 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar); 5227 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) { 5228 Captures[DRE] = DRE; 5229 } 5230 } 5231 // Move on to the next nested for loop, or to the loop body. 5232 // OpenMP [2.8.1, simd construct, Restrictions] 5233 // All loops associated with the construct must be perfectly nested; that 5234 // is, there must be no intervening code nor any OpenMP directive between 5235 // any two loops. 5236 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 5237 } 5238 5239 Built.clear(/* size */ NestedLoopCount); 5240 5241 if (SemaRef.CurContext->isDependentContext()) 5242 return NestedLoopCount; 5243 5244 // An example of what is generated for the following code: 5245 // 5246 // #pragma omp simd collapse(2) ordered(2) 5247 // for (i = 0; i < NI; ++i) 5248 // for (k = 0; k < NK; ++k) 5249 // for (j = J0; j < NJ; j+=2) { 5250 // <loop body> 5251 // } 5252 // 5253 // We generate the code below. 5254 // Note: the loop body may be outlined in CodeGen. 5255 // Note: some counters may be C++ classes, operator- is used to find number of 5256 // iterations and operator+= to calculate counter value. 5257 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 5258 // or i64 is currently supported). 5259 // 5260 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 5261 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 5262 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 5263 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 5264 // // similar updates for vars in clauses (e.g. 'linear') 5265 // <loop body (using local i and j)> 5266 // } 5267 // i = NI; // assign final values of counters 5268 // j = NJ; 5269 // 5270 5271 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 5272 // the iteration counts of the collapsed for loops. 5273 // Precondition tests if there is at least one iteration (all conditions are 5274 // true). 5275 auto PreCond = ExprResult(IterSpaces[0].PreCond); 5276 Expr *N0 = IterSpaces[0].NumIterations; 5277 ExprResult LastIteration32 = 5278 widenIterationCount(/*Bits=*/32, 5279 SemaRef 5280 .PerformImplicitConversion( 5281 N0->IgnoreImpCasts(), N0->getType(), 5282 Sema::AA_Converting, /*AllowExplicit=*/true) 5283 .get(), 5284 SemaRef); 5285 ExprResult LastIteration64 = widenIterationCount( 5286 /*Bits=*/64, 5287 SemaRef 5288 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(), 5289 Sema::AA_Converting, 5290 /*AllowExplicit=*/true) 5291 .get(), 5292 SemaRef); 5293 5294 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 5295 return NestedLoopCount; 5296 5297 ASTContext &C = SemaRef.Context; 5298 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 5299 5300 Scope *CurScope = DSA.getCurScope(); 5301 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 5302 if (PreCond.isUsable()) { 5303 PreCond = 5304 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 5305 PreCond.get(), IterSpaces[Cnt].PreCond); 5306 } 5307 Expr *N = IterSpaces[Cnt].NumIterations; 5308 SourceLocation Loc = N->getExprLoc(); 5309 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 5310 if (LastIteration32.isUsable()) 5311 LastIteration32 = SemaRef.BuildBinOp( 5312 CurScope, Loc, BO_Mul, LastIteration32.get(), 5313 SemaRef 5314 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 5315 Sema::AA_Converting, 5316 /*AllowExplicit=*/true) 5317 .get()); 5318 if (LastIteration64.isUsable()) 5319 LastIteration64 = SemaRef.BuildBinOp( 5320 CurScope, Loc, BO_Mul, LastIteration64.get(), 5321 SemaRef 5322 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 5323 Sema::AA_Converting, 5324 /*AllowExplicit=*/true) 5325 .get()); 5326 } 5327 5328 // Choose either the 32-bit or 64-bit version. 5329 ExprResult LastIteration = LastIteration64; 5330 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse || 5331 (LastIteration32.isUsable() && 5332 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 5333 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 5334 fitsInto( 5335 /*Bits=*/32, 5336 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 5337 LastIteration64.get(), SemaRef)))) 5338 LastIteration = LastIteration32; 5339 QualType VType = LastIteration.get()->getType(); 5340 QualType RealVType = VType; 5341 QualType StrideVType = VType; 5342 if (isOpenMPTaskLoopDirective(DKind)) { 5343 VType = 5344 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 5345 StrideVType = 5346 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 5347 } 5348 5349 if (!LastIteration.isUsable()) 5350 return 0; 5351 5352 // Save the number of iterations. 5353 ExprResult NumIterations = LastIteration; 5354 { 5355 LastIteration = SemaRef.BuildBinOp( 5356 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 5357 LastIteration.get(), 5358 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 5359 if (!LastIteration.isUsable()) 5360 return 0; 5361 } 5362 5363 // Calculate the last iteration number beforehand instead of doing this on 5364 // each iteration. Do not do this if the number of iterations may be kfold-ed. 5365 llvm::APSInt Result; 5366 bool IsConstant = 5367 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 5368 ExprResult CalcLastIteration; 5369 if (!IsConstant) { 5370 ExprResult SaveRef = 5371 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 5372 LastIteration = SaveRef; 5373 5374 // Prepare SaveRef + 1. 5375 NumIterations = SemaRef.BuildBinOp( 5376 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 5377 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 5378 if (!NumIterations.isUsable()) 5379 return 0; 5380 } 5381 5382 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 5383 5384 // Build variables passed into runtime, necessary for worksharing directives. 5385 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 5386 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 5387 isOpenMPDistributeDirective(DKind)) { 5388 // Lower bound variable, initialized with zero. 5389 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 5390 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 5391 SemaRef.AddInitializerToDecl(LBDecl, 5392 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 5393 /*DirectInit*/ false); 5394 5395 // Upper bound variable, initialized with last iteration number. 5396 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 5397 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 5398 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 5399 /*DirectInit*/ false); 5400 5401 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 5402 // This will be used to implement clause 'lastprivate'. 5403 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 5404 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 5405 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 5406 SemaRef.AddInitializerToDecl(ILDecl, 5407 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 5408 /*DirectInit*/ false); 5409 5410 // Stride variable returned by runtime (we initialize it to 1 by default). 5411 VarDecl *STDecl = 5412 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 5413 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 5414 SemaRef.AddInitializerToDecl(STDecl, 5415 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 5416 /*DirectInit*/ false); 5417 5418 // Build expression: UB = min(UB, LastIteration) 5419 // It is necessary for CodeGen of directives with static scheduling. 5420 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 5421 UB.get(), LastIteration.get()); 5422 ExprResult CondOp = SemaRef.ActOnConditionalOp( 5423 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(), 5424 LastIteration.get(), UB.get()); 5425 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 5426 CondOp.get()); 5427 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false); 5428 5429 // If we have a combined directive that combines 'distribute', 'for' or 5430 // 'simd' we need to be able to access the bounds of the schedule of the 5431 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 5432 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 5433 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5434 // Lower bound variable, initialized with zero. 5435 VarDecl *CombLBDecl = 5436 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 5437 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 5438 SemaRef.AddInitializerToDecl( 5439 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 5440 /*DirectInit*/ false); 5441 5442 // Upper bound variable, initialized with last iteration number. 5443 VarDecl *CombUBDecl = 5444 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 5445 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 5446 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 5447 /*DirectInit*/ false); 5448 5449 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 5450 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 5451 ExprResult CombCondOp = 5452 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 5453 LastIteration.get(), CombUB.get()); 5454 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 5455 CombCondOp.get()); 5456 CombEUB = 5457 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false); 5458 5459 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 5460 // We expect to have at least 2 more parameters than the 'parallel' 5461 // directive does - the lower and upper bounds of the previous schedule. 5462 assert(CD->getNumParams() >= 4 && 5463 "Unexpected number of parameters in loop combined directive"); 5464 5465 // Set the proper type for the bounds given what we learned from the 5466 // enclosed loops. 5467 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 5468 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 5469 5470 // Previous lower and upper bounds are obtained from the region 5471 // parameters. 5472 PrevLB = 5473 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 5474 PrevUB = 5475 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 5476 } 5477 } 5478 5479 // Build the iteration variable and its initialization before loop. 5480 ExprResult IV; 5481 ExprResult Init, CombInit; 5482 { 5483 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 5484 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 5485 Expr *RHS = 5486 (isOpenMPWorksharingDirective(DKind) || 5487 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 5488 ? LB.get() 5489 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 5490 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 5491 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false); 5492 5493 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5494 Expr *CombRHS = 5495 (isOpenMPWorksharingDirective(DKind) || 5496 isOpenMPTaskLoopDirective(DKind) || 5497 isOpenMPDistributeDirective(DKind)) 5498 ? CombLB.get() 5499 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 5500 CombInit = 5501 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 5502 CombInit = 5503 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false); 5504 } 5505 } 5506 5507 bool UseStrictCompare = 5508 RealVType->hasUnsignedIntegerRepresentation() && 5509 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) { 5510 return LIS.IsStrictCompare; 5511 }); 5512 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for 5513 // unsigned IV)) for worksharing loops. 5514 SourceLocation CondLoc = AStmt->getBeginLoc(); 5515 Expr *BoundUB = UB.get(); 5516 if (UseStrictCompare) { 5517 BoundUB = 5518 SemaRef 5519 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB, 5520 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 5521 .get(); 5522 BoundUB = 5523 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get(); 5524 } 5525 ExprResult Cond = 5526 (isOpenMPWorksharingDirective(DKind) || 5527 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 5528 ? SemaRef.BuildBinOp(CurScope, CondLoc, 5529 UseStrictCompare ? BO_LT : BO_LE, IV.get(), 5530 BoundUB) 5531 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 5532 NumIterations.get()); 5533 ExprResult CombDistCond; 5534 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5535 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 5536 NumIterations.get()); 5537 } 5538 5539 ExprResult CombCond; 5540 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5541 Expr *BoundCombUB = CombUB.get(); 5542 if (UseStrictCompare) { 5543 BoundCombUB = 5544 SemaRef 5545 .BuildBinOp( 5546 CurScope, CondLoc, BO_Add, BoundCombUB, 5547 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 5548 .get(); 5549 BoundCombUB = 5550 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false) 5551 .get(); 5552 } 5553 CombCond = 5554 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 5555 IV.get(), BoundCombUB); 5556 } 5557 // Loop increment (IV = IV + 1) 5558 SourceLocation IncLoc = AStmt->getBeginLoc(); 5559 ExprResult Inc = 5560 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 5561 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 5562 if (!Inc.isUsable()) 5563 return 0; 5564 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 5565 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false); 5566 if (!Inc.isUsable()) 5567 return 0; 5568 5569 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 5570 // Used for directives with static scheduling. 5571 // In combined construct, add combined version that use CombLB and CombUB 5572 // base variables for the update 5573 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 5574 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 5575 isOpenMPDistributeDirective(DKind)) { 5576 // LB + ST 5577 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 5578 if (!NextLB.isUsable()) 5579 return 0; 5580 // LB = LB + ST 5581 NextLB = 5582 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 5583 NextLB = 5584 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false); 5585 if (!NextLB.isUsable()) 5586 return 0; 5587 // UB + ST 5588 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 5589 if (!NextUB.isUsable()) 5590 return 0; 5591 // UB = UB + ST 5592 NextUB = 5593 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 5594 NextUB = 5595 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false); 5596 if (!NextUB.isUsable()) 5597 return 0; 5598 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5599 CombNextLB = 5600 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 5601 if (!NextLB.isUsable()) 5602 return 0; 5603 // LB = LB + ST 5604 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 5605 CombNextLB.get()); 5606 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(), 5607 /*DiscardedValue*/ false); 5608 if (!CombNextLB.isUsable()) 5609 return 0; 5610 // UB + ST 5611 CombNextUB = 5612 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 5613 if (!CombNextUB.isUsable()) 5614 return 0; 5615 // UB = UB + ST 5616 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 5617 CombNextUB.get()); 5618 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(), 5619 /*DiscardedValue*/ false); 5620 if (!CombNextUB.isUsable()) 5621 return 0; 5622 } 5623 } 5624 5625 // Create increment expression for distribute loop when combined in a same 5626 // directive with for as IV = IV + ST; ensure upper bound expression based 5627 // on PrevUB instead of NumIterations - used to implement 'for' when found 5628 // in combination with 'distribute', like in 'distribute parallel for' 5629 SourceLocation DistIncLoc = AStmt->getBeginLoc(); 5630 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond; 5631 if (isOpenMPLoopBoundSharingDirective(DKind)) { 5632 DistCond = SemaRef.BuildBinOp( 5633 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB); 5634 assert(DistCond.isUsable() && "distribute cond expr was not built"); 5635 5636 DistInc = 5637 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 5638 assert(DistInc.isUsable() && "distribute inc expr was not built"); 5639 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 5640 DistInc.get()); 5641 DistInc = 5642 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false); 5643 assert(DistInc.isUsable() && "distribute inc expr was not built"); 5644 5645 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 5646 // construct 5647 SourceLocation DistEUBLoc = AStmt->getBeginLoc(); 5648 ExprResult IsUBGreater = 5649 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get()); 5650 ExprResult CondOp = SemaRef.ActOnConditionalOp( 5651 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get()); 5652 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 5653 CondOp.get()); 5654 PrevEUB = 5655 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false); 5656 5657 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in 5658 // parallel for is in combination with a distribute directive with 5659 // schedule(static, 1) 5660 Expr *BoundPrevUB = PrevUB.get(); 5661 if (UseStrictCompare) { 5662 BoundPrevUB = 5663 SemaRef 5664 .BuildBinOp( 5665 CurScope, CondLoc, BO_Add, BoundPrevUB, 5666 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()) 5667 .get(); 5668 BoundPrevUB = 5669 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false) 5670 .get(); 5671 } 5672 ParForInDistCond = 5673 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, 5674 IV.get(), BoundPrevUB); 5675 } 5676 5677 // Build updates and final values of the loop counters. 5678 bool HasErrors = false; 5679 Built.Counters.resize(NestedLoopCount); 5680 Built.Inits.resize(NestedLoopCount); 5681 Built.Updates.resize(NestedLoopCount); 5682 Built.Finals.resize(NestedLoopCount); 5683 { 5684 // We implement the following algorithm for obtaining the 5685 // original loop iteration variable values based on the 5686 // value of the collapsed loop iteration variable IV. 5687 // 5688 // Let n+1 be the number of collapsed loops in the nest. 5689 // Iteration variables (I0, I1, .... In) 5690 // Iteration counts (N0, N1, ... Nn) 5691 // 5692 // Acc = IV; 5693 // 5694 // To compute Ik for loop k, 0 <= k <= n, generate: 5695 // Prod = N(k+1) * N(k+2) * ... * Nn; 5696 // Ik = Acc / Prod; 5697 // Acc -= Ik * Prod; 5698 // 5699 ExprResult Acc = IV; 5700 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 5701 LoopIterationSpace &IS = IterSpaces[Cnt]; 5702 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 5703 ExprResult Iter; 5704 5705 // Compute prod 5706 ExprResult Prod = 5707 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 5708 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K) 5709 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(), 5710 IterSpaces[K].NumIterations); 5711 5712 // Iter = Acc / Prod 5713 // If there is at least one more inner loop to avoid 5714 // multiplication by 1. 5715 if (Cnt + 1 < NestedLoopCount) 5716 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, 5717 Acc.get(), Prod.get()); 5718 else 5719 Iter = Acc; 5720 if (!Iter.isUsable()) { 5721 HasErrors = true; 5722 break; 5723 } 5724 5725 // Update Acc: 5726 // Acc -= Iter * Prod 5727 // Check if there is at least one more inner loop to avoid 5728 // multiplication by 1. 5729 if (Cnt + 1 < NestedLoopCount) 5730 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, 5731 Iter.get(), Prod.get()); 5732 else 5733 Prod = Iter; 5734 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub, 5735 Acc.get(), Prod.get()); 5736 5737 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 5738 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 5739 DeclRefExpr *CounterVar = buildDeclRefExpr( 5740 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(), 5741 /*RefersToCapture=*/true); 5742 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 5743 IS.CounterInit, Captures); 5744 if (!Init.isUsable()) { 5745 HasErrors = true; 5746 break; 5747 } 5748 ExprResult Update = buildCounterUpdate( 5749 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 5750 IS.CounterStep, IS.Subtract, &Captures); 5751 if (!Update.isUsable()) { 5752 HasErrors = true; 5753 break; 5754 } 5755 5756 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 5757 ExprResult Final = buildCounterUpdate( 5758 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, 5759 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures); 5760 if (!Final.isUsable()) { 5761 HasErrors = true; 5762 break; 5763 } 5764 5765 if (!Update.isUsable() || !Final.isUsable()) { 5766 HasErrors = true; 5767 break; 5768 } 5769 // Save results 5770 Built.Counters[Cnt] = IS.CounterVar; 5771 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 5772 Built.Inits[Cnt] = Init.get(); 5773 Built.Updates[Cnt] = Update.get(); 5774 Built.Finals[Cnt] = Final.get(); 5775 } 5776 } 5777 5778 if (HasErrors) 5779 return 0; 5780 5781 // Save results 5782 Built.IterationVarRef = IV.get(); 5783 Built.LastIteration = LastIteration.get(); 5784 Built.NumIterations = NumIterations.get(); 5785 Built.CalcLastIteration = SemaRef 5786 .ActOnFinishFullExpr(CalcLastIteration.get(), 5787 /*DiscardedValue*/ false) 5788 .get(); 5789 Built.PreCond = PreCond.get(); 5790 Built.PreInits = buildPreInits(C, Captures); 5791 Built.Cond = Cond.get(); 5792 Built.Init = Init.get(); 5793 Built.Inc = Inc.get(); 5794 Built.LB = LB.get(); 5795 Built.UB = UB.get(); 5796 Built.IL = IL.get(); 5797 Built.ST = ST.get(); 5798 Built.EUB = EUB.get(); 5799 Built.NLB = NextLB.get(); 5800 Built.NUB = NextUB.get(); 5801 Built.PrevLB = PrevLB.get(); 5802 Built.PrevUB = PrevUB.get(); 5803 Built.DistInc = DistInc.get(); 5804 Built.PrevEUB = PrevEUB.get(); 5805 Built.DistCombinedFields.LB = CombLB.get(); 5806 Built.DistCombinedFields.UB = CombUB.get(); 5807 Built.DistCombinedFields.EUB = CombEUB.get(); 5808 Built.DistCombinedFields.Init = CombInit.get(); 5809 Built.DistCombinedFields.Cond = CombCond.get(); 5810 Built.DistCombinedFields.NLB = CombNextLB.get(); 5811 Built.DistCombinedFields.NUB = CombNextUB.get(); 5812 Built.DistCombinedFields.DistCond = CombDistCond.get(); 5813 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get(); 5814 5815 return NestedLoopCount; 5816 } 5817 5818 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 5819 auto CollapseClauses = 5820 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 5821 if (CollapseClauses.begin() != CollapseClauses.end()) 5822 return (*CollapseClauses.begin())->getNumForLoops(); 5823 return nullptr; 5824 } 5825 5826 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 5827 auto OrderedClauses = 5828 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 5829 if (OrderedClauses.begin() != OrderedClauses.end()) 5830 return (*OrderedClauses.begin())->getNumForLoops(); 5831 return nullptr; 5832 } 5833 5834 static bool checkSimdlenSafelenSpecified(Sema &S, 5835 const ArrayRef<OMPClause *> Clauses) { 5836 const OMPSafelenClause *Safelen = nullptr; 5837 const OMPSimdlenClause *Simdlen = nullptr; 5838 5839 for (const OMPClause *Clause : Clauses) { 5840 if (Clause->getClauseKind() == OMPC_safelen) 5841 Safelen = cast<OMPSafelenClause>(Clause); 5842 else if (Clause->getClauseKind() == OMPC_simdlen) 5843 Simdlen = cast<OMPSimdlenClause>(Clause); 5844 if (Safelen && Simdlen) 5845 break; 5846 } 5847 5848 if (Simdlen && Safelen) { 5849 const Expr *SimdlenLength = Simdlen->getSimdlen(); 5850 const Expr *SafelenLength = Safelen->getSafelen(); 5851 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 5852 SimdlenLength->isInstantiationDependent() || 5853 SimdlenLength->containsUnexpandedParameterPack()) 5854 return false; 5855 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 5856 SafelenLength->isInstantiationDependent() || 5857 SafelenLength->containsUnexpandedParameterPack()) 5858 return false; 5859 Expr::EvalResult SimdlenResult, SafelenResult; 5860 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context); 5861 SafelenLength->EvaluateAsInt(SafelenResult, S.Context); 5862 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt(); 5863 llvm::APSInt SafelenRes = SafelenResult.Val.getInt(); 5864 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 5865 // If both simdlen and safelen clauses are specified, the value of the 5866 // simdlen parameter must be less than or equal to the value of the safelen 5867 // parameter. 5868 if (SimdlenRes > SafelenRes) { 5869 S.Diag(SimdlenLength->getExprLoc(), 5870 diag::err_omp_wrong_simdlen_safelen_values) 5871 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 5872 return true; 5873 } 5874 } 5875 return false; 5876 } 5877 5878 StmtResult 5879 Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 5880 SourceLocation StartLoc, SourceLocation EndLoc, 5881 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 5882 if (!AStmt) 5883 return StmtError(); 5884 5885 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5886 OMPLoopDirective::HelperExprs B; 5887 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5888 // define the nested loops number. 5889 unsigned NestedLoopCount = checkOpenMPLoop( 5890 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 5891 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 5892 if (NestedLoopCount == 0) 5893 return StmtError(); 5894 5895 assert((CurContext->isDependentContext() || B.builtAll()) && 5896 "omp simd loop exprs were not built"); 5897 5898 if (!CurContext->isDependentContext()) { 5899 // Finalize the clauses that need pre-built expressions for CodeGen. 5900 for (OMPClause *C : Clauses) { 5901 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5902 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5903 B.NumIterations, *this, CurScope, 5904 DSAStack)) 5905 return StmtError(); 5906 } 5907 } 5908 5909 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5910 return StmtError(); 5911 5912 setFunctionHasBranchProtectedScope(); 5913 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5914 Clauses, AStmt, B); 5915 } 5916 5917 StmtResult 5918 Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt, 5919 SourceLocation StartLoc, SourceLocation EndLoc, 5920 VarsWithInheritedDSAType &VarsWithImplicitDSA) { 5921 if (!AStmt) 5922 return StmtError(); 5923 5924 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5925 OMPLoopDirective::HelperExprs B; 5926 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5927 // define the nested loops number. 5928 unsigned NestedLoopCount = checkOpenMPLoop( 5929 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 5930 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 5931 if (NestedLoopCount == 0) 5932 return StmtError(); 5933 5934 assert((CurContext->isDependentContext() || B.builtAll()) && 5935 "omp for loop exprs were not built"); 5936 5937 if (!CurContext->isDependentContext()) { 5938 // Finalize the clauses that need pre-built expressions for CodeGen. 5939 for (OMPClause *C : Clauses) { 5940 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5941 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5942 B.NumIterations, *this, CurScope, 5943 DSAStack)) 5944 return StmtError(); 5945 } 5946 } 5947 5948 setFunctionHasBranchProtectedScope(); 5949 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5950 Clauses, AStmt, B, DSAStack->isCancelRegion()); 5951 } 5952 5953 StmtResult Sema::ActOnOpenMPForSimdDirective( 5954 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5955 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 5956 if (!AStmt) 5957 return StmtError(); 5958 5959 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5960 OMPLoopDirective::HelperExprs B; 5961 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5962 // define the nested loops number. 5963 unsigned NestedLoopCount = 5964 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 5965 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5966 VarsWithImplicitDSA, B); 5967 if (NestedLoopCount == 0) 5968 return StmtError(); 5969 5970 assert((CurContext->isDependentContext() || B.builtAll()) && 5971 "omp for simd loop exprs were not built"); 5972 5973 if (!CurContext->isDependentContext()) { 5974 // Finalize the clauses that need pre-built expressions for CodeGen. 5975 for (OMPClause *C : Clauses) { 5976 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5977 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5978 B.NumIterations, *this, CurScope, 5979 DSAStack)) 5980 return StmtError(); 5981 } 5982 } 5983 5984 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5985 return StmtError(); 5986 5987 setFunctionHasBranchProtectedScope(); 5988 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5989 Clauses, AStmt, B); 5990 } 5991 5992 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 5993 Stmt *AStmt, 5994 SourceLocation StartLoc, 5995 SourceLocation EndLoc) { 5996 if (!AStmt) 5997 return StmtError(); 5998 5999 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6000 auto BaseStmt = AStmt; 6001 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 6002 BaseStmt = CS->getCapturedStmt(); 6003 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 6004 auto S = C->children(); 6005 if (S.begin() == S.end()) 6006 return StmtError(); 6007 // All associated statements must be '#pragma omp section' except for 6008 // the first one. 6009 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 6010 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 6011 if (SectionStmt) 6012 Diag(SectionStmt->getBeginLoc(), 6013 diag::err_omp_sections_substmt_not_section); 6014 return StmtError(); 6015 } 6016 cast<OMPSectionDirective>(SectionStmt) 6017 ->setHasCancel(DSAStack->isCancelRegion()); 6018 } 6019 } else { 6020 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt); 6021 return StmtError(); 6022 } 6023 6024 setFunctionHasBranchProtectedScope(); 6025 6026 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 6027 DSAStack->isCancelRegion()); 6028 } 6029 6030 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 6031 SourceLocation StartLoc, 6032 SourceLocation EndLoc) { 6033 if (!AStmt) 6034 return StmtError(); 6035 6036 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6037 6038 setFunctionHasBranchProtectedScope(); 6039 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 6040 6041 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 6042 DSAStack->isCancelRegion()); 6043 } 6044 6045 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 6046 Stmt *AStmt, 6047 SourceLocation StartLoc, 6048 SourceLocation EndLoc) { 6049 if (!AStmt) 6050 return StmtError(); 6051 6052 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6053 6054 setFunctionHasBranchProtectedScope(); 6055 6056 // OpenMP [2.7.3, single Construct, Restrictions] 6057 // The copyprivate clause must not be used with the nowait clause. 6058 const OMPClause *Nowait = nullptr; 6059 const OMPClause *Copyprivate = nullptr; 6060 for (const OMPClause *Clause : Clauses) { 6061 if (Clause->getClauseKind() == OMPC_nowait) 6062 Nowait = Clause; 6063 else if (Clause->getClauseKind() == OMPC_copyprivate) 6064 Copyprivate = Clause; 6065 if (Copyprivate && Nowait) { 6066 Diag(Copyprivate->getBeginLoc(), 6067 diag::err_omp_single_copyprivate_with_nowait); 6068 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here); 6069 return StmtError(); 6070 } 6071 } 6072 6073 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6074 } 6075 6076 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 6077 SourceLocation StartLoc, 6078 SourceLocation EndLoc) { 6079 if (!AStmt) 6080 return StmtError(); 6081 6082 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6083 6084 setFunctionHasBranchProtectedScope(); 6085 6086 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 6087 } 6088 6089 StmtResult Sema::ActOnOpenMPCriticalDirective( 6090 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 6091 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 6092 if (!AStmt) 6093 return StmtError(); 6094 6095 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6096 6097 bool ErrorFound = false; 6098 llvm::APSInt Hint; 6099 SourceLocation HintLoc; 6100 bool DependentHint = false; 6101 for (const OMPClause *C : Clauses) { 6102 if (C->getClauseKind() == OMPC_hint) { 6103 if (!DirName.getName()) { 6104 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name); 6105 ErrorFound = true; 6106 } 6107 Expr *E = cast<OMPHintClause>(C)->getHint(); 6108 if (E->isTypeDependent() || E->isValueDependent() || 6109 E->isInstantiationDependent()) { 6110 DependentHint = true; 6111 } else { 6112 Hint = E->EvaluateKnownConstInt(Context); 6113 HintLoc = C->getBeginLoc(); 6114 } 6115 } 6116 } 6117 if (ErrorFound) 6118 return StmtError(); 6119 const auto Pair = DSAStack->getCriticalWithHint(DirName); 6120 if (Pair.first && DirName.getName() && !DependentHint) { 6121 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 6122 Diag(StartLoc, diag::err_omp_critical_with_hint); 6123 if (HintLoc.isValid()) 6124 Diag(HintLoc, diag::note_omp_critical_hint_here) 6125 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 6126 else 6127 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 6128 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 6129 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here) 6130 << 1 6131 << C->getHint()->EvaluateKnownConstInt(Context).toString( 6132 /*Radix=*/10, /*Signed=*/false); 6133 } else { 6134 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1; 6135 } 6136 } 6137 } 6138 6139 setFunctionHasBranchProtectedScope(); 6140 6141 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 6142 Clauses, AStmt); 6143 if (!Pair.first && DirName.getName() && !DependentHint) 6144 DSAStack->addCriticalWithHint(Dir, Hint); 6145 return Dir; 6146 } 6147 6148 StmtResult Sema::ActOnOpenMPParallelForDirective( 6149 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6150 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 6151 if (!AStmt) 6152 return StmtError(); 6153 6154 auto *CS = cast<CapturedStmt>(AStmt); 6155 // 1.2.2 OpenMP Language Terminology 6156 // Structured block - An executable statement with a single entry at the 6157 // top and a single exit at the bottom. 6158 // The point of exit cannot be a branch out of the structured block. 6159 // longjmp() and throw() must not violate the entry/exit criteria. 6160 CS->getCapturedDecl()->setNothrow(); 6161 6162 OMPLoopDirective::HelperExprs B; 6163 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6164 // define the nested loops number. 6165 unsigned NestedLoopCount = 6166 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 6167 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6168 VarsWithImplicitDSA, B); 6169 if (NestedLoopCount == 0) 6170 return StmtError(); 6171 6172 assert((CurContext->isDependentContext() || B.builtAll()) && 6173 "omp parallel for loop exprs were not built"); 6174 6175 if (!CurContext->isDependentContext()) { 6176 // Finalize the clauses that need pre-built expressions for CodeGen. 6177 for (OMPClause *C : Clauses) { 6178 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6179 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6180 B.NumIterations, *this, CurScope, 6181 DSAStack)) 6182 return StmtError(); 6183 } 6184 } 6185 6186 setFunctionHasBranchProtectedScope(); 6187 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, 6188 NestedLoopCount, Clauses, AStmt, B, 6189 DSAStack->isCancelRegion()); 6190 } 6191 6192 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 6193 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6194 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 6195 if (!AStmt) 6196 return StmtError(); 6197 6198 auto *CS = cast<CapturedStmt>(AStmt); 6199 // 1.2.2 OpenMP Language Terminology 6200 // Structured block - An executable statement with a single entry at the 6201 // top and a single exit at the bottom. 6202 // The point of exit cannot be a branch out of the structured block. 6203 // longjmp() and throw() must not violate the entry/exit criteria. 6204 CS->getCapturedDecl()->setNothrow(); 6205 6206 OMPLoopDirective::HelperExprs B; 6207 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6208 // define the nested loops number. 6209 unsigned NestedLoopCount = 6210 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 6211 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6212 VarsWithImplicitDSA, B); 6213 if (NestedLoopCount == 0) 6214 return StmtError(); 6215 6216 if (!CurContext->isDependentContext()) { 6217 // Finalize the clauses that need pre-built expressions for CodeGen. 6218 for (OMPClause *C : Clauses) { 6219 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6220 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6221 B.NumIterations, *this, CurScope, 6222 DSAStack)) 6223 return StmtError(); 6224 } 6225 } 6226 6227 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6228 return StmtError(); 6229 6230 setFunctionHasBranchProtectedScope(); 6231 return OMPParallelForSimdDirective::Create( 6232 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6233 } 6234 6235 StmtResult 6236 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 6237 Stmt *AStmt, SourceLocation StartLoc, 6238 SourceLocation EndLoc) { 6239 if (!AStmt) 6240 return StmtError(); 6241 6242 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6243 auto BaseStmt = AStmt; 6244 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 6245 BaseStmt = CS->getCapturedStmt(); 6246 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 6247 auto S = C->children(); 6248 if (S.begin() == S.end()) 6249 return StmtError(); 6250 // All associated statements must be '#pragma omp section' except for 6251 // the first one. 6252 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 6253 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 6254 if (SectionStmt) 6255 Diag(SectionStmt->getBeginLoc(), 6256 diag::err_omp_parallel_sections_substmt_not_section); 6257 return StmtError(); 6258 } 6259 cast<OMPSectionDirective>(SectionStmt) 6260 ->setHasCancel(DSAStack->isCancelRegion()); 6261 } 6262 } else { 6263 Diag(AStmt->getBeginLoc(), 6264 diag::err_omp_parallel_sections_not_compound_stmt); 6265 return StmtError(); 6266 } 6267 6268 setFunctionHasBranchProtectedScope(); 6269 6270 return OMPParallelSectionsDirective::Create( 6271 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); 6272 } 6273 6274 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 6275 Stmt *AStmt, SourceLocation StartLoc, 6276 SourceLocation EndLoc) { 6277 if (!AStmt) 6278 return StmtError(); 6279 6280 auto *CS = cast<CapturedStmt>(AStmt); 6281 // 1.2.2 OpenMP Language Terminology 6282 // Structured block - An executable statement with a single entry at the 6283 // top and a single exit at the bottom. 6284 // The point of exit cannot be a branch out of the structured block. 6285 // longjmp() and throw() must not violate the entry/exit criteria. 6286 CS->getCapturedDecl()->setNothrow(); 6287 6288 setFunctionHasBranchProtectedScope(); 6289 6290 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 6291 DSAStack->isCancelRegion()); 6292 } 6293 6294 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 6295 SourceLocation EndLoc) { 6296 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 6297 } 6298 6299 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 6300 SourceLocation EndLoc) { 6301 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 6302 } 6303 6304 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 6305 SourceLocation EndLoc) { 6306 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 6307 } 6308 6309 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 6310 Stmt *AStmt, 6311 SourceLocation StartLoc, 6312 SourceLocation EndLoc) { 6313 if (!AStmt) 6314 return StmtError(); 6315 6316 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6317 6318 setFunctionHasBranchProtectedScope(); 6319 6320 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, 6321 AStmt, 6322 DSAStack->getTaskgroupReductionRef()); 6323 } 6324 6325 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 6326 SourceLocation StartLoc, 6327 SourceLocation EndLoc) { 6328 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 6329 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 6330 } 6331 6332 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 6333 Stmt *AStmt, 6334 SourceLocation StartLoc, 6335 SourceLocation EndLoc) { 6336 const OMPClause *DependFound = nullptr; 6337 const OMPClause *DependSourceClause = nullptr; 6338 const OMPClause *DependSinkClause = nullptr; 6339 bool ErrorFound = false; 6340 const OMPThreadsClause *TC = nullptr; 6341 const OMPSIMDClause *SC = nullptr; 6342 for (const OMPClause *C : Clauses) { 6343 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 6344 DependFound = C; 6345 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 6346 if (DependSourceClause) { 6347 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause) 6348 << getOpenMPDirectiveName(OMPD_ordered) 6349 << getOpenMPClauseName(OMPC_depend) << 2; 6350 ErrorFound = true; 6351 } else { 6352 DependSourceClause = C; 6353 } 6354 if (DependSinkClause) { 6355 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 6356 << 0; 6357 ErrorFound = true; 6358 } 6359 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 6360 if (DependSourceClause) { 6361 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed) 6362 << 1; 6363 ErrorFound = true; 6364 } 6365 DependSinkClause = C; 6366 } 6367 } else if (C->getClauseKind() == OMPC_threads) { 6368 TC = cast<OMPThreadsClause>(C); 6369 } else if (C->getClauseKind() == OMPC_simd) { 6370 SC = cast<OMPSIMDClause>(C); 6371 } 6372 } 6373 if (!ErrorFound && !SC && 6374 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 6375 // OpenMP [2.8.1,simd Construct, Restrictions] 6376 // An ordered construct with the simd clause is the only OpenMP construct 6377 // that can appear in the simd region. 6378 Diag(StartLoc, diag::err_omp_prohibited_region_simd); 6379 ErrorFound = true; 6380 } else if (DependFound && (TC || SC)) { 6381 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd) 6382 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 6383 ErrorFound = true; 6384 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) { 6385 Diag(DependFound->getBeginLoc(), 6386 diag::err_omp_ordered_directive_without_param); 6387 ErrorFound = true; 6388 } else if (TC || Clauses.empty()) { 6389 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) { 6390 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc; 6391 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 6392 << (TC != nullptr); 6393 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param); 6394 ErrorFound = true; 6395 } 6396 } 6397 if ((!AStmt && !DependFound) || ErrorFound) 6398 return StmtError(); 6399 6400 if (AStmt) { 6401 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6402 6403 setFunctionHasBranchProtectedScope(); 6404 } 6405 6406 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6407 } 6408 6409 namespace { 6410 /// Helper class for checking expression in 'omp atomic [update]' 6411 /// construct. 6412 class OpenMPAtomicUpdateChecker { 6413 /// Error results for atomic update expressions. 6414 enum ExprAnalysisErrorCode { 6415 /// A statement is not an expression statement. 6416 NotAnExpression, 6417 /// Expression is not builtin binary or unary operation. 6418 NotABinaryOrUnaryExpression, 6419 /// Unary operation is not post-/pre- increment/decrement operation. 6420 NotAnUnaryIncDecExpression, 6421 /// An expression is not of scalar type. 6422 NotAScalarType, 6423 /// A binary operation is not an assignment operation. 6424 NotAnAssignmentOp, 6425 /// RHS part of the binary operation is not a binary expression. 6426 NotABinaryExpression, 6427 /// RHS part is not additive/multiplicative/shift/biwise binary 6428 /// expression. 6429 NotABinaryOperator, 6430 /// RHS binary operation does not have reference to the updated LHS 6431 /// part. 6432 NotAnUpdateExpression, 6433 /// No errors is found. 6434 NoError 6435 }; 6436 /// Reference to Sema. 6437 Sema &SemaRef; 6438 /// A location for note diagnostics (when error is found). 6439 SourceLocation NoteLoc; 6440 /// 'x' lvalue part of the source atomic expression. 6441 Expr *X; 6442 /// 'expr' rvalue part of the source atomic expression. 6443 Expr *E; 6444 /// Helper expression of the form 6445 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 6446 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 6447 Expr *UpdateExpr; 6448 /// Is 'x' a LHS in a RHS part of full update expression. It is 6449 /// important for non-associative operations. 6450 bool IsXLHSInRHSPart; 6451 BinaryOperatorKind Op; 6452 SourceLocation OpLoc; 6453 /// true if the source expression is a postfix unary operation, false 6454 /// if it is a prefix unary operation. 6455 bool IsPostfixUpdate; 6456 6457 public: 6458 OpenMPAtomicUpdateChecker(Sema &SemaRef) 6459 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 6460 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 6461 /// Check specified statement that it is suitable for 'atomic update' 6462 /// constructs and extract 'x', 'expr' and Operation from the original 6463 /// expression. If DiagId and NoteId == 0, then only check is performed 6464 /// without error notification. 6465 /// \param DiagId Diagnostic which should be emitted if error is found. 6466 /// \param NoteId Diagnostic note for the main error message. 6467 /// \return true if statement is not an update expression, false otherwise. 6468 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 6469 /// Return the 'x' lvalue part of the source atomic expression. 6470 Expr *getX() const { return X; } 6471 /// Return the 'expr' rvalue part of the source atomic expression. 6472 Expr *getExpr() const { return E; } 6473 /// Return the update expression used in calculation of the updated 6474 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 6475 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 6476 Expr *getUpdateExpr() const { return UpdateExpr; } 6477 /// Return true if 'x' is LHS in RHS part of full update expression, 6478 /// false otherwise. 6479 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 6480 6481 /// true if the source expression is a postfix unary operation, false 6482 /// if it is a prefix unary operation. 6483 bool isPostfixUpdate() const { return IsPostfixUpdate; } 6484 6485 private: 6486 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 6487 unsigned NoteId = 0); 6488 }; 6489 } // namespace 6490 6491 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 6492 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 6493 ExprAnalysisErrorCode ErrorFound = NoError; 6494 SourceLocation ErrorLoc, NoteLoc; 6495 SourceRange ErrorRange, NoteRange; 6496 // Allowed constructs are: 6497 // x = x binop expr; 6498 // x = expr binop x; 6499 if (AtomicBinOp->getOpcode() == BO_Assign) { 6500 X = AtomicBinOp->getLHS(); 6501 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 6502 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 6503 if (AtomicInnerBinOp->isMultiplicativeOp() || 6504 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 6505 AtomicInnerBinOp->isBitwiseOp()) { 6506 Op = AtomicInnerBinOp->getOpcode(); 6507 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 6508 Expr *LHS = AtomicInnerBinOp->getLHS(); 6509 Expr *RHS = AtomicInnerBinOp->getRHS(); 6510 llvm::FoldingSetNodeID XId, LHSId, RHSId; 6511 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 6512 /*Canonical=*/true); 6513 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 6514 /*Canonical=*/true); 6515 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 6516 /*Canonical=*/true); 6517 if (XId == LHSId) { 6518 E = RHS; 6519 IsXLHSInRHSPart = true; 6520 } else if (XId == RHSId) { 6521 E = LHS; 6522 IsXLHSInRHSPart = false; 6523 } else { 6524 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 6525 ErrorRange = AtomicInnerBinOp->getSourceRange(); 6526 NoteLoc = X->getExprLoc(); 6527 NoteRange = X->getSourceRange(); 6528 ErrorFound = NotAnUpdateExpression; 6529 } 6530 } else { 6531 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 6532 ErrorRange = AtomicInnerBinOp->getSourceRange(); 6533 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 6534 NoteRange = SourceRange(NoteLoc, NoteLoc); 6535 ErrorFound = NotABinaryOperator; 6536 } 6537 } else { 6538 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 6539 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 6540 ErrorFound = NotABinaryExpression; 6541 } 6542 } else { 6543 ErrorLoc = AtomicBinOp->getExprLoc(); 6544 ErrorRange = AtomicBinOp->getSourceRange(); 6545 NoteLoc = AtomicBinOp->getOperatorLoc(); 6546 NoteRange = SourceRange(NoteLoc, NoteLoc); 6547 ErrorFound = NotAnAssignmentOp; 6548 } 6549 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 6550 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 6551 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 6552 return true; 6553 } 6554 if (SemaRef.CurContext->isDependentContext()) 6555 E = X = UpdateExpr = nullptr; 6556 return ErrorFound != NoError; 6557 } 6558 6559 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 6560 unsigned NoteId) { 6561 ExprAnalysisErrorCode ErrorFound = NoError; 6562 SourceLocation ErrorLoc, NoteLoc; 6563 SourceRange ErrorRange, NoteRange; 6564 // Allowed constructs are: 6565 // x++; 6566 // x--; 6567 // ++x; 6568 // --x; 6569 // x binop= expr; 6570 // x = x binop expr; 6571 // x = expr binop x; 6572 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 6573 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 6574 if (AtomicBody->getType()->isScalarType() || 6575 AtomicBody->isInstantiationDependent()) { 6576 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 6577 AtomicBody->IgnoreParenImpCasts())) { 6578 // Check for Compound Assignment Operation 6579 Op = BinaryOperator::getOpForCompoundAssignment( 6580 AtomicCompAssignOp->getOpcode()); 6581 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 6582 E = AtomicCompAssignOp->getRHS(); 6583 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 6584 IsXLHSInRHSPart = true; 6585 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 6586 AtomicBody->IgnoreParenImpCasts())) { 6587 // Check for Binary Operation 6588 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 6589 return true; 6590 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 6591 AtomicBody->IgnoreParenImpCasts())) { 6592 // Check for Unary Operation 6593 if (AtomicUnaryOp->isIncrementDecrementOp()) { 6594 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 6595 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 6596 OpLoc = AtomicUnaryOp->getOperatorLoc(); 6597 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 6598 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 6599 IsXLHSInRHSPart = true; 6600 } else { 6601 ErrorFound = NotAnUnaryIncDecExpression; 6602 ErrorLoc = AtomicUnaryOp->getExprLoc(); 6603 ErrorRange = AtomicUnaryOp->getSourceRange(); 6604 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 6605 NoteRange = SourceRange(NoteLoc, NoteLoc); 6606 } 6607 } else if (!AtomicBody->isInstantiationDependent()) { 6608 ErrorFound = NotABinaryOrUnaryExpression; 6609 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 6610 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 6611 } 6612 } else { 6613 ErrorFound = NotAScalarType; 6614 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc(); 6615 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6616 } 6617 } else { 6618 ErrorFound = NotAnExpression; 6619 NoteLoc = ErrorLoc = S->getBeginLoc(); 6620 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6621 } 6622 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 6623 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 6624 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 6625 return true; 6626 } 6627 if (SemaRef.CurContext->isDependentContext()) 6628 E = X = UpdateExpr = nullptr; 6629 if (ErrorFound == NoError && E && X) { 6630 // Build an update expression of form 'OpaqueValueExpr(x) binop 6631 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 6632 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 6633 auto *OVEX = new (SemaRef.getASTContext()) 6634 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 6635 auto *OVEExpr = new (SemaRef.getASTContext()) 6636 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 6637 ExprResult Update = 6638 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 6639 IsXLHSInRHSPart ? OVEExpr : OVEX); 6640 if (Update.isInvalid()) 6641 return true; 6642 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 6643 Sema::AA_Casting); 6644 if (Update.isInvalid()) 6645 return true; 6646 UpdateExpr = Update.get(); 6647 } 6648 return ErrorFound != NoError; 6649 } 6650 6651 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 6652 Stmt *AStmt, 6653 SourceLocation StartLoc, 6654 SourceLocation EndLoc) { 6655 if (!AStmt) 6656 return StmtError(); 6657 6658 auto *CS = cast<CapturedStmt>(AStmt); 6659 // 1.2.2 OpenMP Language Terminology 6660 // Structured block - An executable statement with a single entry at the 6661 // top and a single exit at the bottom. 6662 // The point of exit cannot be a branch out of the structured block. 6663 // longjmp() and throw() must not violate the entry/exit criteria. 6664 OpenMPClauseKind AtomicKind = OMPC_unknown; 6665 SourceLocation AtomicKindLoc; 6666 for (const OMPClause *C : Clauses) { 6667 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 6668 C->getClauseKind() == OMPC_update || 6669 C->getClauseKind() == OMPC_capture) { 6670 if (AtomicKind != OMPC_unknown) { 6671 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses) 6672 << SourceRange(C->getBeginLoc(), C->getEndLoc()); 6673 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 6674 << getOpenMPClauseName(AtomicKind); 6675 } else { 6676 AtomicKind = C->getClauseKind(); 6677 AtomicKindLoc = C->getBeginLoc(); 6678 } 6679 } 6680 } 6681 6682 Stmt *Body = CS->getCapturedStmt(); 6683 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 6684 Body = EWC->getSubExpr(); 6685 6686 Expr *X = nullptr; 6687 Expr *V = nullptr; 6688 Expr *E = nullptr; 6689 Expr *UE = nullptr; 6690 bool IsXLHSInRHSPart = false; 6691 bool IsPostfixUpdate = false; 6692 // OpenMP [2.12.6, atomic Construct] 6693 // In the next expressions: 6694 // * x and v (as applicable) are both l-value expressions with scalar type. 6695 // * During the execution of an atomic region, multiple syntactic 6696 // occurrences of x must designate the same storage location. 6697 // * Neither of v and expr (as applicable) may access the storage location 6698 // designated by x. 6699 // * Neither of x and expr (as applicable) may access the storage location 6700 // designated by v. 6701 // * expr is an expression with scalar type. 6702 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 6703 // * binop, binop=, ++, and -- are not overloaded operators. 6704 // * The expression x binop expr must be numerically equivalent to x binop 6705 // (expr). This requirement is satisfied if the operators in expr have 6706 // precedence greater than binop, or by using parentheses around expr or 6707 // subexpressions of expr. 6708 // * The expression expr binop x must be numerically equivalent to (expr) 6709 // binop x. This requirement is satisfied if the operators in expr have 6710 // precedence equal to or greater than binop, or by using parentheses around 6711 // expr or subexpressions of expr. 6712 // * For forms that allow multiple occurrences of x, the number of times 6713 // that x is evaluated is unspecified. 6714 if (AtomicKind == OMPC_read) { 6715 enum { 6716 NotAnExpression, 6717 NotAnAssignmentOp, 6718 NotAScalarType, 6719 NotAnLValue, 6720 NoError 6721 } ErrorFound = NoError; 6722 SourceLocation ErrorLoc, NoteLoc; 6723 SourceRange ErrorRange, NoteRange; 6724 // If clause is read: 6725 // v = x; 6726 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 6727 const auto *AtomicBinOp = 6728 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6729 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6730 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 6731 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 6732 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 6733 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 6734 if (!X->isLValue() || !V->isLValue()) { 6735 const Expr *NotLValueExpr = X->isLValue() ? V : X; 6736 ErrorFound = NotAnLValue; 6737 ErrorLoc = AtomicBinOp->getExprLoc(); 6738 ErrorRange = AtomicBinOp->getSourceRange(); 6739 NoteLoc = NotLValueExpr->getExprLoc(); 6740 NoteRange = NotLValueExpr->getSourceRange(); 6741 } 6742 } else if (!X->isInstantiationDependent() || 6743 !V->isInstantiationDependent()) { 6744 const Expr *NotScalarExpr = 6745 (X->isInstantiationDependent() || X->getType()->isScalarType()) 6746 ? V 6747 : X; 6748 ErrorFound = NotAScalarType; 6749 ErrorLoc = AtomicBinOp->getExprLoc(); 6750 ErrorRange = AtomicBinOp->getSourceRange(); 6751 NoteLoc = NotScalarExpr->getExprLoc(); 6752 NoteRange = NotScalarExpr->getSourceRange(); 6753 } 6754 } else if (!AtomicBody->isInstantiationDependent()) { 6755 ErrorFound = NotAnAssignmentOp; 6756 ErrorLoc = AtomicBody->getExprLoc(); 6757 ErrorRange = AtomicBody->getSourceRange(); 6758 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6759 : AtomicBody->getExprLoc(); 6760 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6761 : AtomicBody->getSourceRange(); 6762 } 6763 } else { 6764 ErrorFound = NotAnExpression; 6765 NoteLoc = ErrorLoc = Body->getBeginLoc(); 6766 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6767 } 6768 if (ErrorFound != NoError) { 6769 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 6770 << ErrorRange; 6771 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 6772 << NoteRange; 6773 return StmtError(); 6774 } 6775 if (CurContext->isDependentContext()) 6776 V = X = nullptr; 6777 } else if (AtomicKind == OMPC_write) { 6778 enum { 6779 NotAnExpression, 6780 NotAnAssignmentOp, 6781 NotAScalarType, 6782 NotAnLValue, 6783 NoError 6784 } ErrorFound = NoError; 6785 SourceLocation ErrorLoc, NoteLoc; 6786 SourceRange ErrorRange, NoteRange; 6787 // If clause is write: 6788 // x = expr; 6789 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 6790 const auto *AtomicBinOp = 6791 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6792 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6793 X = AtomicBinOp->getLHS(); 6794 E = AtomicBinOp->getRHS(); 6795 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 6796 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 6797 if (!X->isLValue()) { 6798 ErrorFound = NotAnLValue; 6799 ErrorLoc = AtomicBinOp->getExprLoc(); 6800 ErrorRange = AtomicBinOp->getSourceRange(); 6801 NoteLoc = X->getExprLoc(); 6802 NoteRange = X->getSourceRange(); 6803 } 6804 } else if (!X->isInstantiationDependent() || 6805 !E->isInstantiationDependent()) { 6806 const Expr *NotScalarExpr = 6807 (X->isInstantiationDependent() || X->getType()->isScalarType()) 6808 ? E 6809 : X; 6810 ErrorFound = NotAScalarType; 6811 ErrorLoc = AtomicBinOp->getExprLoc(); 6812 ErrorRange = AtomicBinOp->getSourceRange(); 6813 NoteLoc = NotScalarExpr->getExprLoc(); 6814 NoteRange = NotScalarExpr->getSourceRange(); 6815 } 6816 } else if (!AtomicBody->isInstantiationDependent()) { 6817 ErrorFound = NotAnAssignmentOp; 6818 ErrorLoc = AtomicBody->getExprLoc(); 6819 ErrorRange = AtomicBody->getSourceRange(); 6820 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6821 : AtomicBody->getExprLoc(); 6822 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6823 : AtomicBody->getSourceRange(); 6824 } 6825 } else { 6826 ErrorFound = NotAnExpression; 6827 NoteLoc = ErrorLoc = Body->getBeginLoc(); 6828 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6829 } 6830 if (ErrorFound != NoError) { 6831 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 6832 << ErrorRange; 6833 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 6834 << NoteRange; 6835 return StmtError(); 6836 } 6837 if (CurContext->isDependentContext()) 6838 E = X = nullptr; 6839 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 6840 // If clause is update: 6841 // x++; 6842 // x--; 6843 // ++x; 6844 // --x; 6845 // x binop= expr; 6846 // x = x binop expr; 6847 // x = expr binop x; 6848 OpenMPAtomicUpdateChecker Checker(*this); 6849 if (Checker.checkStatement( 6850 Body, (AtomicKind == OMPC_update) 6851 ? diag::err_omp_atomic_update_not_expression_statement 6852 : diag::err_omp_atomic_not_expression_statement, 6853 diag::note_omp_atomic_update)) 6854 return StmtError(); 6855 if (!CurContext->isDependentContext()) { 6856 E = Checker.getExpr(); 6857 X = Checker.getX(); 6858 UE = Checker.getUpdateExpr(); 6859 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6860 } 6861 } else if (AtomicKind == OMPC_capture) { 6862 enum { 6863 NotAnAssignmentOp, 6864 NotACompoundStatement, 6865 NotTwoSubstatements, 6866 NotASpecificExpression, 6867 NoError 6868 } ErrorFound = NoError; 6869 SourceLocation ErrorLoc, NoteLoc; 6870 SourceRange ErrorRange, NoteRange; 6871 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) { 6872 // If clause is a capture: 6873 // v = x++; 6874 // v = x--; 6875 // v = ++x; 6876 // v = --x; 6877 // v = x binop= expr; 6878 // v = x = x binop expr; 6879 // v = x = expr binop x; 6880 const auto *AtomicBinOp = 6881 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6882 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6883 V = AtomicBinOp->getLHS(); 6884 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 6885 OpenMPAtomicUpdateChecker Checker(*this); 6886 if (Checker.checkStatement( 6887 Body, diag::err_omp_atomic_capture_not_expression_statement, 6888 diag::note_omp_atomic_update)) 6889 return StmtError(); 6890 E = Checker.getExpr(); 6891 X = Checker.getX(); 6892 UE = Checker.getUpdateExpr(); 6893 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6894 IsPostfixUpdate = Checker.isPostfixUpdate(); 6895 } else if (!AtomicBody->isInstantiationDependent()) { 6896 ErrorLoc = AtomicBody->getExprLoc(); 6897 ErrorRange = AtomicBody->getSourceRange(); 6898 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6899 : AtomicBody->getExprLoc(); 6900 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6901 : AtomicBody->getSourceRange(); 6902 ErrorFound = NotAnAssignmentOp; 6903 } 6904 if (ErrorFound != NoError) { 6905 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 6906 << ErrorRange; 6907 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 6908 return StmtError(); 6909 } 6910 if (CurContext->isDependentContext()) 6911 UE = V = E = X = nullptr; 6912 } else { 6913 // If clause is a capture: 6914 // { v = x; x = expr; } 6915 // { v = x; x++; } 6916 // { v = x; x--; } 6917 // { v = x; ++x; } 6918 // { v = x; --x; } 6919 // { v = x; x binop= expr; } 6920 // { v = x; x = x binop expr; } 6921 // { v = x; x = expr binop x; } 6922 // { x++; v = x; } 6923 // { x--; v = x; } 6924 // { ++x; v = x; } 6925 // { --x; v = x; } 6926 // { x binop= expr; v = x; } 6927 // { x = x binop expr; v = x; } 6928 // { x = expr binop x; v = x; } 6929 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 6930 // Check that this is { expr1; expr2; } 6931 if (CS->size() == 2) { 6932 Stmt *First = CS->body_front(); 6933 Stmt *Second = CS->body_back(); 6934 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 6935 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 6936 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 6937 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 6938 // Need to find what subexpression is 'v' and what is 'x'. 6939 OpenMPAtomicUpdateChecker Checker(*this); 6940 bool IsUpdateExprFound = !Checker.checkStatement(Second); 6941 BinaryOperator *BinOp = nullptr; 6942 if (IsUpdateExprFound) { 6943 BinOp = dyn_cast<BinaryOperator>(First); 6944 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 6945 } 6946 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 6947 // { v = x; x++; } 6948 // { v = x; x--; } 6949 // { v = x; ++x; } 6950 // { v = x; --x; } 6951 // { v = x; x binop= expr; } 6952 // { v = x; x = x binop expr; } 6953 // { v = x; x = expr binop x; } 6954 // Check that the first expression has form v = x. 6955 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 6956 llvm::FoldingSetNodeID XId, PossibleXId; 6957 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 6958 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 6959 IsUpdateExprFound = XId == PossibleXId; 6960 if (IsUpdateExprFound) { 6961 V = BinOp->getLHS(); 6962 X = Checker.getX(); 6963 E = Checker.getExpr(); 6964 UE = Checker.getUpdateExpr(); 6965 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6966 IsPostfixUpdate = true; 6967 } 6968 } 6969 if (!IsUpdateExprFound) { 6970 IsUpdateExprFound = !Checker.checkStatement(First); 6971 BinOp = nullptr; 6972 if (IsUpdateExprFound) { 6973 BinOp = dyn_cast<BinaryOperator>(Second); 6974 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 6975 } 6976 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 6977 // { x++; v = x; } 6978 // { x--; v = x; } 6979 // { ++x; v = x; } 6980 // { --x; v = x; } 6981 // { x binop= expr; v = x; } 6982 // { x = x binop expr; v = x; } 6983 // { x = expr binop x; v = x; } 6984 // Check that the second expression has form v = x. 6985 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 6986 llvm::FoldingSetNodeID XId, PossibleXId; 6987 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 6988 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 6989 IsUpdateExprFound = XId == PossibleXId; 6990 if (IsUpdateExprFound) { 6991 V = BinOp->getLHS(); 6992 X = Checker.getX(); 6993 E = Checker.getExpr(); 6994 UE = Checker.getUpdateExpr(); 6995 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6996 IsPostfixUpdate = false; 6997 } 6998 } 6999 } 7000 if (!IsUpdateExprFound) { 7001 // { v = x; x = expr; } 7002 auto *FirstExpr = dyn_cast<Expr>(First); 7003 auto *SecondExpr = dyn_cast<Expr>(Second); 7004 if (!FirstExpr || !SecondExpr || 7005 !(FirstExpr->isInstantiationDependent() || 7006 SecondExpr->isInstantiationDependent())) { 7007 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 7008 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 7009 ErrorFound = NotAnAssignmentOp; 7010 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 7011 : First->getBeginLoc(); 7012 NoteRange = ErrorRange = FirstBinOp 7013 ? FirstBinOp->getSourceRange() 7014 : SourceRange(ErrorLoc, ErrorLoc); 7015 } else { 7016 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 7017 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 7018 ErrorFound = NotAnAssignmentOp; 7019 NoteLoc = ErrorLoc = SecondBinOp 7020 ? SecondBinOp->getOperatorLoc() 7021 : Second->getBeginLoc(); 7022 NoteRange = ErrorRange = 7023 SecondBinOp ? SecondBinOp->getSourceRange() 7024 : SourceRange(ErrorLoc, ErrorLoc); 7025 } else { 7026 Expr *PossibleXRHSInFirst = 7027 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 7028 Expr *PossibleXLHSInSecond = 7029 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 7030 llvm::FoldingSetNodeID X1Id, X2Id; 7031 PossibleXRHSInFirst->Profile(X1Id, Context, 7032 /*Canonical=*/true); 7033 PossibleXLHSInSecond->Profile(X2Id, Context, 7034 /*Canonical=*/true); 7035 IsUpdateExprFound = X1Id == X2Id; 7036 if (IsUpdateExprFound) { 7037 V = FirstBinOp->getLHS(); 7038 X = SecondBinOp->getLHS(); 7039 E = SecondBinOp->getRHS(); 7040 UE = nullptr; 7041 IsXLHSInRHSPart = false; 7042 IsPostfixUpdate = true; 7043 } else { 7044 ErrorFound = NotASpecificExpression; 7045 ErrorLoc = FirstBinOp->getExprLoc(); 7046 ErrorRange = FirstBinOp->getSourceRange(); 7047 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 7048 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 7049 } 7050 } 7051 } 7052 } 7053 } 7054 } else { 7055 NoteLoc = ErrorLoc = Body->getBeginLoc(); 7056 NoteRange = ErrorRange = 7057 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 7058 ErrorFound = NotTwoSubstatements; 7059 } 7060 } else { 7061 NoteLoc = ErrorLoc = Body->getBeginLoc(); 7062 NoteRange = ErrorRange = 7063 SourceRange(Body->getBeginLoc(), Body->getBeginLoc()); 7064 ErrorFound = NotACompoundStatement; 7065 } 7066 if (ErrorFound != NoError) { 7067 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 7068 << ErrorRange; 7069 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 7070 return StmtError(); 7071 } 7072 if (CurContext->isDependentContext()) 7073 UE = V = E = X = nullptr; 7074 } 7075 } 7076 7077 setFunctionHasBranchProtectedScope(); 7078 7079 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 7080 X, V, E, UE, IsXLHSInRHSPart, 7081 IsPostfixUpdate); 7082 } 7083 7084 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 7085 Stmt *AStmt, 7086 SourceLocation StartLoc, 7087 SourceLocation EndLoc) { 7088 if (!AStmt) 7089 return StmtError(); 7090 7091 auto *CS = cast<CapturedStmt>(AStmt); 7092 // 1.2.2 OpenMP Language Terminology 7093 // Structured block - An executable statement with a single entry at the 7094 // top and a single exit at the bottom. 7095 // The point of exit cannot be a branch out of the structured block. 7096 // longjmp() and throw() must not violate the entry/exit criteria. 7097 CS->getCapturedDecl()->setNothrow(); 7098 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target); 7099 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7100 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7101 // 1.2.2 OpenMP Language Terminology 7102 // Structured block - An executable statement with a single entry at the 7103 // top and a single exit at the bottom. 7104 // The point of exit cannot be a branch out of the structured block. 7105 // longjmp() and throw() must not violate the entry/exit criteria. 7106 CS->getCapturedDecl()->setNothrow(); 7107 } 7108 7109 // OpenMP [2.16, Nesting of Regions] 7110 // If specified, a teams construct must be contained within a target 7111 // construct. That target construct must contain no statements or directives 7112 // outside of the teams construct. 7113 if (DSAStack->hasInnerTeamsRegion()) { 7114 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true); 7115 bool OMPTeamsFound = true; 7116 if (const auto *CS = dyn_cast<CompoundStmt>(S)) { 7117 auto I = CS->body_begin(); 7118 while (I != CS->body_end()) { 7119 const auto *OED = dyn_cast<OMPExecutableDirective>(*I); 7120 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) || 7121 OMPTeamsFound) { 7122 7123 OMPTeamsFound = false; 7124 break; 7125 } 7126 ++I; 7127 } 7128 assert(I != CS->body_end() && "Not found statement"); 7129 S = *I; 7130 } else { 7131 const auto *OED = dyn_cast<OMPExecutableDirective>(S); 7132 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 7133 } 7134 if (!OMPTeamsFound) { 7135 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 7136 Diag(DSAStack->getInnerTeamsRegionLoc(), 7137 diag::note_omp_nested_teams_construct_here); 7138 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here) 7139 << isa<OMPExecutableDirective>(S); 7140 return StmtError(); 7141 } 7142 } 7143 7144 setFunctionHasBranchProtectedScope(); 7145 7146 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 7147 } 7148 7149 StmtResult 7150 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 7151 Stmt *AStmt, SourceLocation StartLoc, 7152 SourceLocation EndLoc) { 7153 if (!AStmt) 7154 return StmtError(); 7155 7156 auto *CS = cast<CapturedStmt>(AStmt); 7157 // 1.2.2 OpenMP Language Terminology 7158 // Structured block - An executable statement with a single entry at the 7159 // top and a single exit at the bottom. 7160 // The point of exit cannot be a branch out of the structured block. 7161 // longjmp() and throw() must not violate the entry/exit criteria. 7162 CS->getCapturedDecl()->setNothrow(); 7163 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel); 7164 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7165 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7166 // 1.2.2 OpenMP Language Terminology 7167 // Structured block - An executable statement with a single entry at the 7168 // top and a single exit at the bottom. 7169 // The point of exit cannot be a branch out of the structured block. 7170 // longjmp() and throw() must not violate the entry/exit criteria. 7171 CS->getCapturedDecl()->setNothrow(); 7172 } 7173 7174 setFunctionHasBranchProtectedScope(); 7175 7176 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 7177 AStmt); 7178 } 7179 7180 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 7181 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7182 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7183 if (!AStmt) 7184 return StmtError(); 7185 7186 auto *CS = cast<CapturedStmt>(AStmt); 7187 // 1.2.2 OpenMP Language Terminology 7188 // Structured block - An executable statement with a single entry at the 7189 // top and a single exit at the bottom. 7190 // The point of exit cannot be a branch out of the structured block. 7191 // longjmp() and throw() must not violate the entry/exit criteria. 7192 CS->getCapturedDecl()->setNothrow(); 7193 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 7194 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7195 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7196 // 1.2.2 OpenMP Language Terminology 7197 // Structured block - An executable statement with a single entry at the 7198 // top and a single exit at the bottom. 7199 // The point of exit cannot be a branch out of the structured block. 7200 // longjmp() and throw() must not violate the entry/exit criteria. 7201 CS->getCapturedDecl()->setNothrow(); 7202 } 7203 7204 OMPLoopDirective::HelperExprs B; 7205 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7206 // define the nested loops number. 7207 unsigned NestedLoopCount = 7208 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 7209 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 7210 VarsWithImplicitDSA, B); 7211 if (NestedLoopCount == 0) 7212 return StmtError(); 7213 7214 assert((CurContext->isDependentContext() || B.builtAll()) && 7215 "omp target parallel for loop exprs were not built"); 7216 7217 if (!CurContext->isDependentContext()) { 7218 // Finalize the clauses that need pre-built expressions for CodeGen. 7219 for (OMPClause *C : Clauses) { 7220 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7221 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7222 B.NumIterations, *this, CurScope, 7223 DSAStack)) 7224 return StmtError(); 7225 } 7226 } 7227 7228 setFunctionHasBranchProtectedScope(); 7229 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc, 7230 NestedLoopCount, Clauses, AStmt, 7231 B, DSAStack->isCancelRegion()); 7232 } 7233 7234 /// Check for existence of a map clause in the list of clauses. 7235 static bool hasClauses(ArrayRef<OMPClause *> Clauses, 7236 const OpenMPClauseKind K) { 7237 return llvm::any_of( 7238 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); 7239 } 7240 7241 template <typename... Params> 7242 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, 7243 const Params... ClauseTypes) { 7244 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); 7245 } 7246 7247 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 7248 Stmt *AStmt, 7249 SourceLocation StartLoc, 7250 SourceLocation EndLoc) { 7251 if (!AStmt) 7252 return StmtError(); 7253 7254 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7255 7256 // OpenMP [2.10.1, Restrictions, p. 97] 7257 // At least one map clause must appear on the directive. 7258 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) { 7259 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 7260 << "'map' or 'use_device_ptr'" 7261 << getOpenMPDirectiveName(OMPD_target_data); 7262 return StmtError(); 7263 } 7264 7265 setFunctionHasBranchProtectedScope(); 7266 7267 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 7268 AStmt); 7269 } 7270 7271 StmtResult 7272 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 7273 SourceLocation StartLoc, 7274 SourceLocation EndLoc, Stmt *AStmt) { 7275 if (!AStmt) 7276 return StmtError(); 7277 7278 auto *CS = cast<CapturedStmt>(AStmt); 7279 // 1.2.2 OpenMP Language Terminology 7280 // Structured block - An executable statement with a single entry at the 7281 // top and a single exit at the bottom. 7282 // The point of exit cannot be a branch out of the structured block. 7283 // longjmp() and throw() must not violate the entry/exit criteria. 7284 CS->getCapturedDecl()->setNothrow(); 7285 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data); 7286 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7287 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7288 // 1.2.2 OpenMP Language Terminology 7289 // Structured block - An executable statement with a single entry at the 7290 // top and a single exit at the bottom. 7291 // The point of exit cannot be a branch out of the structured block. 7292 // longjmp() and throw() must not violate the entry/exit criteria. 7293 CS->getCapturedDecl()->setNothrow(); 7294 } 7295 7296 // OpenMP [2.10.2, Restrictions, p. 99] 7297 // At least one map clause must appear on the directive. 7298 if (!hasClauses(Clauses, OMPC_map)) { 7299 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 7300 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); 7301 return StmtError(); 7302 } 7303 7304 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 7305 AStmt); 7306 } 7307 7308 StmtResult 7309 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 7310 SourceLocation StartLoc, 7311 SourceLocation EndLoc, Stmt *AStmt) { 7312 if (!AStmt) 7313 return StmtError(); 7314 7315 auto *CS = cast<CapturedStmt>(AStmt); 7316 // 1.2.2 OpenMP Language Terminology 7317 // Structured block - An executable statement with a single entry at the 7318 // top and a single exit at the bottom. 7319 // The point of exit cannot be a branch out of the structured block. 7320 // longjmp() and throw() must not violate the entry/exit criteria. 7321 CS->getCapturedDecl()->setNothrow(); 7322 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data); 7323 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7324 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7325 // 1.2.2 OpenMP Language Terminology 7326 // Structured block - An executable statement with a single entry at the 7327 // top and a single exit at the bottom. 7328 // The point of exit cannot be a branch out of the structured block. 7329 // longjmp() and throw() must not violate the entry/exit criteria. 7330 CS->getCapturedDecl()->setNothrow(); 7331 } 7332 7333 // OpenMP [2.10.3, Restrictions, p. 102] 7334 // At least one map clause must appear on the directive. 7335 if (!hasClauses(Clauses, OMPC_map)) { 7336 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 7337 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data); 7338 return StmtError(); 7339 } 7340 7341 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 7342 AStmt); 7343 } 7344 7345 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 7346 SourceLocation StartLoc, 7347 SourceLocation EndLoc, 7348 Stmt *AStmt) { 7349 if (!AStmt) 7350 return StmtError(); 7351 7352 auto *CS = cast<CapturedStmt>(AStmt); 7353 // 1.2.2 OpenMP Language Terminology 7354 // Structured block - An executable statement with a single entry at the 7355 // top and a single exit at the bottom. 7356 // The point of exit cannot be a branch out of the structured block. 7357 // longjmp() and throw() must not violate the entry/exit criteria. 7358 CS->getCapturedDecl()->setNothrow(); 7359 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update); 7360 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7361 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7362 // 1.2.2 OpenMP Language Terminology 7363 // Structured block - An executable statement with a single entry at the 7364 // top and a single exit at the bottom. 7365 // The point of exit cannot be a branch out of the structured block. 7366 // longjmp() and throw() must not violate the entry/exit criteria. 7367 CS->getCapturedDecl()->setNothrow(); 7368 } 7369 7370 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { 7371 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 7372 return StmtError(); 7373 } 7374 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses, 7375 AStmt); 7376 } 7377 7378 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 7379 Stmt *AStmt, SourceLocation StartLoc, 7380 SourceLocation EndLoc) { 7381 if (!AStmt) 7382 return StmtError(); 7383 7384 auto *CS = cast<CapturedStmt>(AStmt); 7385 // 1.2.2 OpenMP Language Terminology 7386 // Structured block - An executable statement with a single entry at the 7387 // top and a single exit at the bottom. 7388 // The point of exit cannot be a branch out of the structured block. 7389 // longjmp() and throw() must not violate the entry/exit criteria. 7390 CS->getCapturedDecl()->setNothrow(); 7391 7392 setFunctionHasBranchProtectedScope(); 7393 7394 DSAStack->setParentTeamsRegionLoc(StartLoc); 7395 7396 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 7397 } 7398 7399 StmtResult 7400 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 7401 SourceLocation EndLoc, 7402 OpenMPDirectiveKind CancelRegion) { 7403 if (DSAStack->isParentNowaitRegion()) { 7404 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 7405 return StmtError(); 7406 } 7407 if (DSAStack->isParentOrderedRegion()) { 7408 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 7409 return StmtError(); 7410 } 7411 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 7412 CancelRegion); 7413 } 7414 7415 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 7416 SourceLocation StartLoc, 7417 SourceLocation EndLoc, 7418 OpenMPDirectiveKind CancelRegion) { 7419 if (DSAStack->isParentNowaitRegion()) { 7420 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 7421 return StmtError(); 7422 } 7423 if (DSAStack->isParentOrderedRegion()) { 7424 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 7425 return StmtError(); 7426 } 7427 DSAStack->setParentCancelRegion(/*Cancel=*/true); 7428 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 7429 CancelRegion); 7430 } 7431 7432 static bool checkGrainsizeNumTasksClauses(Sema &S, 7433 ArrayRef<OMPClause *> Clauses) { 7434 const OMPClause *PrevClause = nullptr; 7435 bool ErrorFound = false; 7436 for (const OMPClause *C : Clauses) { 7437 if (C->getClauseKind() == OMPC_grainsize || 7438 C->getClauseKind() == OMPC_num_tasks) { 7439 if (!PrevClause) 7440 PrevClause = C; 7441 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 7442 S.Diag(C->getBeginLoc(), 7443 diag::err_omp_grainsize_num_tasks_mutually_exclusive) 7444 << getOpenMPClauseName(C->getClauseKind()) 7445 << getOpenMPClauseName(PrevClause->getClauseKind()); 7446 S.Diag(PrevClause->getBeginLoc(), 7447 diag::note_omp_previous_grainsize_num_tasks) 7448 << getOpenMPClauseName(PrevClause->getClauseKind()); 7449 ErrorFound = true; 7450 } 7451 } 7452 } 7453 return ErrorFound; 7454 } 7455 7456 static bool checkReductionClauseWithNogroup(Sema &S, 7457 ArrayRef<OMPClause *> Clauses) { 7458 const OMPClause *ReductionClause = nullptr; 7459 const OMPClause *NogroupClause = nullptr; 7460 for (const OMPClause *C : Clauses) { 7461 if (C->getClauseKind() == OMPC_reduction) { 7462 ReductionClause = C; 7463 if (NogroupClause) 7464 break; 7465 continue; 7466 } 7467 if (C->getClauseKind() == OMPC_nogroup) { 7468 NogroupClause = C; 7469 if (ReductionClause) 7470 break; 7471 continue; 7472 } 7473 } 7474 if (ReductionClause && NogroupClause) { 7475 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup) 7476 << SourceRange(NogroupClause->getBeginLoc(), 7477 NogroupClause->getEndLoc()); 7478 return true; 7479 } 7480 return false; 7481 } 7482 7483 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 7484 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7485 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7486 if (!AStmt) 7487 return StmtError(); 7488 7489 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7490 OMPLoopDirective::HelperExprs B; 7491 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7492 // define the nested loops number. 7493 unsigned NestedLoopCount = 7494 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 7495 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 7496 VarsWithImplicitDSA, B); 7497 if (NestedLoopCount == 0) 7498 return StmtError(); 7499 7500 assert((CurContext->isDependentContext() || B.builtAll()) && 7501 "omp for loop exprs were not built"); 7502 7503 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 7504 // The grainsize clause and num_tasks clause are mutually exclusive and may 7505 // not appear on the same taskloop directive. 7506 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 7507 return StmtError(); 7508 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 7509 // If a reduction clause is present on the taskloop directive, the nogroup 7510 // clause must not be specified. 7511 if (checkReductionClauseWithNogroup(*this, Clauses)) 7512 return StmtError(); 7513 7514 setFunctionHasBranchProtectedScope(); 7515 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 7516 NestedLoopCount, Clauses, AStmt, B); 7517 } 7518 7519 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 7520 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7521 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7522 if (!AStmt) 7523 return StmtError(); 7524 7525 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7526 OMPLoopDirective::HelperExprs B; 7527 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7528 // define the nested loops number. 7529 unsigned NestedLoopCount = 7530 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 7531 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 7532 VarsWithImplicitDSA, B); 7533 if (NestedLoopCount == 0) 7534 return StmtError(); 7535 7536 assert((CurContext->isDependentContext() || B.builtAll()) && 7537 "omp for loop exprs were not built"); 7538 7539 if (!CurContext->isDependentContext()) { 7540 // Finalize the clauses that need pre-built expressions for CodeGen. 7541 for (OMPClause *C : Clauses) { 7542 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7543 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7544 B.NumIterations, *this, CurScope, 7545 DSAStack)) 7546 return StmtError(); 7547 } 7548 } 7549 7550 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 7551 // The grainsize clause and num_tasks clause are mutually exclusive and may 7552 // not appear on the same taskloop directive. 7553 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 7554 return StmtError(); 7555 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 7556 // If a reduction clause is present on the taskloop directive, the nogroup 7557 // clause must not be specified. 7558 if (checkReductionClauseWithNogroup(*this, Clauses)) 7559 return StmtError(); 7560 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7561 return StmtError(); 7562 7563 setFunctionHasBranchProtectedScope(); 7564 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 7565 NestedLoopCount, Clauses, AStmt, B); 7566 } 7567 7568 StmtResult Sema::ActOnOpenMPDistributeDirective( 7569 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7570 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7571 if (!AStmt) 7572 return StmtError(); 7573 7574 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 7575 OMPLoopDirective::HelperExprs B; 7576 // In presence of clause 'collapse' with number of loops, it will 7577 // define the nested loops number. 7578 unsigned NestedLoopCount = 7579 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 7580 nullptr /*ordered not a clause on distribute*/, AStmt, 7581 *this, *DSAStack, VarsWithImplicitDSA, B); 7582 if (NestedLoopCount == 0) 7583 return StmtError(); 7584 7585 assert((CurContext->isDependentContext() || B.builtAll()) && 7586 "omp for loop exprs were not built"); 7587 7588 setFunctionHasBranchProtectedScope(); 7589 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 7590 NestedLoopCount, Clauses, AStmt, B); 7591 } 7592 7593 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 7594 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7595 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7596 if (!AStmt) 7597 return StmtError(); 7598 7599 auto *CS = cast<CapturedStmt>(AStmt); 7600 // 1.2.2 OpenMP Language Terminology 7601 // Structured block - An executable statement with a single entry at the 7602 // top and a single exit at the bottom. 7603 // The point of exit cannot be a branch out of the structured block. 7604 // longjmp() and throw() must not violate the entry/exit criteria. 7605 CS->getCapturedDecl()->setNothrow(); 7606 for (int ThisCaptureLevel = 7607 getOpenMPCaptureLevels(OMPD_distribute_parallel_for); 7608 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7609 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7610 // 1.2.2 OpenMP Language Terminology 7611 // Structured block - An executable statement with a single entry at the 7612 // top and a single exit at the bottom. 7613 // The point of exit cannot be a branch out of the structured block. 7614 // longjmp() and throw() must not violate the entry/exit criteria. 7615 CS->getCapturedDecl()->setNothrow(); 7616 } 7617 7618 OMPLoopDirective::HelperExprs B; 7619 // In presence of clause 'collapse' with number of loops, it will 7620 // define the nested loops number. 7621 unsigned NestedLoopCount = checkOpenMPLoop( 7622 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 7623 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7624 VarsWithImplicitDSA, B); 7625 if (NestedLoopCount == 0) 7626 return StmtError(); 7627 7628 assert((CurContext->isDependentContext() || B.builtAll()) && 7629 "omp for loop exprs were not built"); 7630 7631 setFunctionHasBranchProtectedScope(); 7632 return OMPDistributeParallelForDirective::Create( 7633 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 7634 DSAStack->isCancelRegion()); 7635 } 7636 7637 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 7638 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7639 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7640 if (!AStmt) 7641 return StmtError(); 7642 7643 auto *CS = cast<CapturedStmt>(AStmt); 7644 // 1.2.2 OpenMP Language Terminology 7645 // Structured block - An executable statement with a single entry at the 7646 // top and a single exit at the bottom. 7647 // The point of exit cannot be a branch out of the structured block. 7648 // longjmp() and throw() must not violate the entry/exit criteria. 7649 CS->getCapturedDecl()->setNothrow(); 7650 for (int ThisCaptureLevel = 7651 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd); 7652 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7653 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7654 // 1.2.2 OpenMP Language Terminology 7655 // Structured block - An executable statement with a single entry at the 7656 // top and a single exit at the bottom. 7657 // The point of exit cannot be a branch out of the structured block. 7658 // longjmp() and throw() must not violate the entry/exit criteria. 7659 CS->getCapturedDecl()->setNothrow(); 7660 } 7661 7662 OMPLoopDirective::HelperExprs B; 7663 // In presence of clause 'collapse' with number of loops, it will 7664 // define the nested loops number. 7665 unsigned NestedLoopCount = checkOpenMPLoop( 7666 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 7667 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7668 VarsWithImplicitDSA, B); 7669 if (NestedLoopCount == 0) 7670 return StmtError(); 7671 7672 assert((CurContext->isDependentContext() || B.builtAll()) && 7673 "omp for loop exprs were not built"); 7674 7675 if (!CurContext->isDependentContext()) { 7676 // Finalize the clauses that need pre-built expressions for CodeGen. 7677 for (OMPClause *C : Clauses) { 7678 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7679 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7680 B.NumIterations, *this, CurScope, 7681 DSAStack)) 7682 return StmtError(); 7683 } 7684 } 7685 7686 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7687 return StmtError(); 7688 7689 setFunctionHasBranchProtectedScope(); 7690 return OMPDistributeParallelForSimdDirective::Create( 7691 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7692 } 7693 7694 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 7695 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7696 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7697 if (!AStmt) 7698 return StmtError(); 7699 7700 auto *CS = cast<CapturedStmt>(AStmt); 7701 // 1.2.2 OpenMP Language Terminology 7702 // Structured block - An executable statement with a single entry at the 7703 // top and a single exit at the bottom. 7704 // The point of exit cannot be a branch out of the structured block. 7705 // longjmp() and throw() must not violate the entry/exit criteria. 7706 CS->getCapturedDecl()->setNothrow(); 7707 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd); 7708 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7709 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7710 // 1.2.2 OpenMP Language Terminology 7711 // Structured block - An executable statement with a single entry at the 7712 // top and a single exit at the bottom. 7713 // The point of exit cannot be a branch out of the structured block. 7714 // longjmp() and throw() must not violate the entry/exit criteria. 7715 CS->getCapturedDecl()->setNothrow(); 7716 } 7717 7718 OMPLoopDirective::HelperExprs B; 7719 // In presence of clause 'collapse' with number of loops, it will 7720 // define the nested loops number. 7721 unsigned NestedLoopCount = 7722 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 7723 nullptr /*ordered not a clause on distribute*/, CS, *this, 7724 *DSAStack, VarsWithImplicitDSA, B); 7725 if (NestedLoopCount == 0) 7726 return StmtError(); 7727 7728 assert((CurContext->isDependentContext() || B.builtAll()) && 7729 "omp for loop exprs were not built"); 7730 7731 if (!CurContext->isDependentContext()) { 7732 // Finalize the clauses that need pre-built expressions for CodeGen. 7733 for (OMPClause *C : Clauses) { 7734 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7735 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7736 B.NumIterations, *this, CurScope, 7737 DSAStack)) 7738 return StmtError(); 7739 } 7740 } 7741 7742 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7743 return StmtError(); 7744 7745 setFunctionHasBranchProtectedScope(); 7746 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 7747 NestedLoopCount, Clauses, AStmt, B); 7748 } 7749 7750 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 7751 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7752 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7753 if (!AStmt) 7754 return StmtError(); 7755 7756 auto *CS = cast<CapturedStmt>(AStmt); 7757 // 1.2.2 OpenMP Language Terminology 7758 // Structured block - An executable statement with a single entry at the 7759 // top and a single exit at the bottom. 7760 // The point of exit cannot be a branch out of the structured block. 7761 // longjmp() and throw() must not violate the entry/exit criteria. 7762 CS->getCapturedDecl()->setNothrow(); 7763 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 7764 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7765 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7766 // 1.2.2 OpenMP Language Terminology 7767 // Structured block - An executable statement with a single entry at the 7768 // top and a single exit at the bottom. 7769 // The point of exit cannot be a branch out of the structured block. 7770 // longjmp() and throw() must not violate the entry/exit criteria. 7771 CS->getCapturedDecl()->setNothrow(); 7772 } 7773 7774 OMPLoopDirective::HelperExprs B; 7775 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7776 // define the nested loops number. 7777 unsigned NestedLoopCount = checkOpenMPLoop( 7778 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 7779 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 7780 VarsWithImplicitDSA, B); 7781 if (NestedLoopCount == 0) 7782 return StmtError(); 7783 7784 assert((CurContext->isDependentContext() || B.builtAll()) && 7785 "omp target parallel for simd loop exprs were not built"); 7786 7787 if (!CurContext->isDependentContext()) { 7788 // Finalize the clauses that need pre-built expressions for CodeGen. 7789 for (OMPClause *C : Clauses) { 7790 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7791 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7792 B.NumIterations, *this, CurScope, 7793 DSAStack)) 7794 return StmtError(); 7795 } 7796 } 7797 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7798 return StmtError(); 7799 7800 setFunctionHasBranchProtectedScope(); 7801 return OMPTargetParallelForSimdDirective::Create( 7802 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7803 } 7804 7805 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 7806 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7807 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7808 if (!AStmt) 7809 return StmtError(); 7810 7811 auto *CS = cast<CapturedStmt>(AStmt); 7812 // 1.2.2 OpenMP Language Terminology 7813 // Structured block - An executable statement with a single entry at the 7814 // top and a single exit at the bottom. 7815 // The point of exit cannot be a branch out of the structured block. 7816 // longjmp() and throw() must not violate the entry/exit criteria. 7817 CS->getCapturedDecl()->setNothrow(); 7818 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd); 7819 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7820 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7821 // 1.2.2 OpenMP Language Terminology 7822 // Structured block - An executable statement with a single entry at the 7823 // top and a single exit at the bottom. 7824 // The point of exit cannot be a branch out of the structured block. 7825 // longjmp() and throw() must not violate the entry/exit criteria. 7826 CS->getCapturedDecl()->setNothrow(); 7827 } 7828 7829 OMPLoopDirective::HelperExprs B; 7830 // In presence of clause 'collapse' with number of loops, it will define the 7831 // nested loops number. 7832 unsigned NestedLoopCount = 7833 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 7834 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 7835 VarsWithImplicitDSA, B); 7836 if (NestedLoopCount == 0) 7837 return StmtError(); 7838 7839 assert((CurContext->isDependentContext() || B.builtAll()) && 7840 "omp target simd loop exprs were not built"); 7841 7842 if (!CurContext->isDependentContext()) { 7843 // Finalize the clauses that need pre-built expressions for CodeGen. 7844 for (OMPClause *C : Clauses) { 7845 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7846 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7847 B.NumIterations, *this, CurScope, 7848 DSAStack)) 7849 return StmtError(); 7850 } 7851 } 7852 7853 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7854 return StmtError(); 7855 7856 setFunctionHasBranchProtectedScope(); 7857 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 7858 NestedLoopCount, Clauses, AStmt, B); 7859 } 7860 7861 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 7862 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7863 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7864 if (!AStmt) 7865 return StmtError(); 7866 7867 auto *CS = cast<CapturedStmt>(AStmt); 7868 // 1.2.2 OpenMP Language Terminology 7869 // Structured block - An executable statement with a single entry at the 7870 // top and a single exit at the bottom. 7871 // The point of exit cannot be a branch out of the structured block. 7872 // longjmp() and throw() must not violate the entry/exit criteria. 7873 CS->getCapturedDecl()->setNothrow(); 7874 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute); 7875 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7876 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7877 // 1.2.2 OpenMP Language Terminology 7878 // Structured block - An executable statement with a single entry at the 7879 // top and a single exit at the bottom. 7880 // The point of exit cannot be a branch out of the structured block. 7881 // longjmp() and throw() must not violate the entry/exit criteria. 7882 CS->getCapturedDecl()->setNothrow(); 7883 } 7884 7885 OMPLoopDirective::HelperExprs B; 7886 // In presence of clause 'collapse' with number of loops, it will 7887 // define the nested loops number. 7888 unsigned NestedLoopCount = 7889 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 7890 nullptr /*ordered not a clause on distribute*/, CS, *this, 7891 *DSAStack, VarsWithImplicitDSA, B); 7892 if (NestedLoopCount == 0) 7893 return StmtError(); 7894 7895 assert((CurContext->isDependentContext() || B.builtAll()) && 7896 "omp teams distribute loop exprs were not built"); 7897 7898 setFunctionHasBranchProtectedScope(); 7899 7900 DSAStack->setParentTeamsRegionLoc(StartLoc); 7901 7902 return OMPTeamsDistributeDirective::Create( 7903 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7904 } 7905 7906 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 7907 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7908 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7909 if (!AStmt) 7910 return StmtError(); 7911 7912 auto *CS = cast<CapturedStmt>(AStmt); 7913 // 1.2.2 OpenMP Language Terminology 7914 // Structured block - An executable statement with a single entry at the 7915 // top and a single exit at the bottom. 7916 // The point of exit cannot be a branch out of the structured block. 7917 // longjmp() and throw() must not violate the entry/exit criteria. 7918 CS->getCapturedDecl()->setNothrow(); 7919 for (int ThisCaptureLevel = 7920 getOpenMPCaptureLevels(OMPD_teams_distribute_simd); 7921 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7922 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7923 // 1.2.2 OpenMP Language Terminology 7924 // Structured block - An executable statement with a single entry at the 7925 // top and a single exit at the bottom. 7926 // The point of exit cannot be a branch out of the structured block. 7927 // longjmp() and throw() must not violate the entry/exit criteria. 7928 CS->getCapturedDecl()->setNothrow(); 7929 } 7930 7931 7932 OMPLoopDirective::HelperExprs B; 7933 // In presence of clause 'collapse' with number of loops, it will 7934 // define the nested loops number. 7935 unsigned NestedLoopCount = checkOpenMPLoop( 7936 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 7937 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7938 VarsWithImplicitDSA, B); 7939 7940 if (NestedLoopCount == 0) 7941 return StmtError(); 7942 7943 assert((CurContext->isDependentContext() || B.builtAll()) && 7944 "omp teams distribute simd loop exprs were not built"); 7945 7946 if (!CurContext->isDependentContext()) { 7947 // Finalize the clauses that need pre-built expressions for CodeGen. 7948 for (OMPClause *C : Clauses) { 7949 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7950 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7951 B.NumIterations, *this, CurScope, 7952 DSAStack)) 7953 return StmtError(); 7954 } 7955 } 7956 7957 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7958 return StmtError(); 7959 7960 setFunctionHasBranchProtectedScope(); 7961 7962 DSAStack->setParentTeamsRegionLoc(StartLoc); 7963 7964 return OMPTeamsDistributeSimdDirective::Create( 7965 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7966 } 7967 7968 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 7969 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7970 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 7971 if (!AStmt) 7972 return StmtError(); 7973 7974 auto *CS = cast<CapturedStmt>(AStmt); 7975 // 1.2.2 OpenMP Language Terminology 7976 // Structured block - An executable statement with a single entry at the 7977 // top and a single exit at the bottom. 7978 // The point of exit cannot be a branch out of the structured block. 7979 // longjmp() and throw() must not violate the entry/exit criteria. 7980 CS->getCapturedDecl()->setNothrow(); 7981 7982 for (int ThisCaptureLevel = 7983 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd); 7984 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7985 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7986 // 1.2.2 OpenMP Language Terminology 7987 // Structured block - An executable statement with a single entry at the 7988 // top and a single exit at the bottom. 7989 // The point of exit cannot be a branch out of the structured block. 7990 // longjmp() and throw() must not violate the entry/exit criteria. 7991 CS->getCapturedDecl()->setNothrow(); 7992 } 7993 7994 OMPLoopDirective::HelperExprs B; 7995 // In presence of clause 'collapse' with number of loops, it will 7996 // define the nested loops number. 7997 unsigned NestedLoopCount = checkOpenMPLoop( 7998 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 7999 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8000 VarsWithImplicitDSA, B); 8001 8002 if (NestedLoopCount == 0) 8003 return StmtError(); 8004 8005 assert((CurContext->isDependentContext() || B.builtAll()) && 8006 "omp for loop exprs were not built"); 8007 8008 if (!CurContext->isDependentContext()) { 8009 // Finalize the clauses that need pre-built expressions for CodeGen. 8010 for (OMPClause *C : Clauses) { 8011 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8012 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8013 B.NumIterations, *this, CurScope, 8014 DSAStack)) 8015 return StmtError(); 8016 } 8017 } 8018 8019 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8020 return StmtError(); 8021 8022 setFunctionHasBranchProtectedScope(); 8023 8024 DSAStack->setParentTeamsRegionLoc(StartLoc); 8025 8026 return OMPTeamsDistributeParallelForSimdDirective::Create( 8027 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 8028 } 8029 8030 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 8031 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8032 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8033 if (!AStmt) 8034 return StmtError(); 8035 8036 auto *CS = cast<CapturedStmt>(AStmt); 8037 // 1.2.2 OpenMP Language Terminology 8038 // Structured block - An executable statement with a single entry at the 8039 // top and a single exit at the bottom. 8040 // The point of exit cannot be a branch out of the structured block. 8041 // longjmp() and throw() must not violate the entry/exit criteria. 8042 CS->getCapturedDecl()->setNothrow(); 8043 8044 for (int ThisCaptureLevel = 8045 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for); 8046 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8047 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8048 // 1.2.2 OpenMP Language Terminology 8049 // Structured block - An executable statement with a single entry at the 8050 // top and a single exit at the bottom. 8051 // The point of exit cannot be a branch out of the structured block. 8052 // longjmp() and throw() must not violate the entry/exit criteria. 8053 CS->getCapturedDecl()->setNothrow(); 8054 } 8055 8056 OMPLoopDirective::HelperExprs B; 8057 // In presence of clause 'collapse' with number of loops, it will 8058 // define the nested loops number. 8059 unsigned NestedLoopCount = checkOpenMPLoop( 8060 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 8061 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8062 VarsWithImplicitDSA, B); 8063 8064 if (NestedLoopCount == 0) 8065 return StmtError(); 8066 8067 assert((CurContext->isDependentContext() || B.builtAll()) && 8068 "omp for loop exprs were not built"); 8069 8070 setFunctionHasBranchProtectedScope(); 8071 8072 DSAStack->setParentTeamsRegionLoc(StartLoc); 8073 8074 return OMPTeamsDistributeParallelForDirective::Create( 8075 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 8076 DSAStack->isCancelRegion()); 8077 } 8078 8079 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 8080 Stmt *AStmt, 8081 SourceLocation StartLoc, 8082 SourceLocation EndLoc) { 8083 if (!AStmt) 8084 return StmtError(); 8085 8086 auto *CS = cast<CapturedStmt>(AStmt); 8087 // 1.2.2 OpenMP Language Terminology 8088 // Structured block - An executable statement with a single entry at the 8089 // top and a single exit at the bottom. 8090 // The point of exit cannot be a branch out of the structured block. 8091 // longjmp() and throw() must not violate the entry/exit criteria. 8092 CS->getCapturedDecl()->setNothrow(); 8093 8094 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams); 8095 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8096 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8097 // 1.2.2 OpenMP Language Terminology 8098 // Structured block - An executable statement with a single entry at the 8099 // top and a single exit at the bottom. 8100 // The point of exit cannot be a branch out of the structured block. 8101 // longjmp() and throw() must not violate the entry/exit criteria. 8102 CS->getCapturedDecl()->setNothrow(); 8103 } 8104 setFunctionHasBranchProtectedScope(); 8105 8106 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 8107 AStmt); 8108 } 8109 8110 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 8111 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8112 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8113 if (!AStmt) 8114 return StmtError(); 8115 8116 auto *CS = cast<CapturedStmt>(AStmt); 8117 // 1.2.2 OpenMP Language Terminology 8118 // Structured block - An executable statement with a single entry at the 8119 // top and a single exit at the bottom. 8120 // The point of exit cannot be a branch out of the structured block. 8121 // longjmp() and throw() must not violate the entry/exit criteria. 8122 CS->getCapturedDecl()->setNothrow(); 8123 for (int ThisCaptureLevel = 8124 getOpenMPCaptureLevels(OMPD_target_teams_distribute); 8125 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8126 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8127 // 1.2.2 OpenMP Language Terminology 8128 // Structured block - An executable statement with a single entry at the 8129 // top and a single exit at the bottom. 8130 // The point of exit cannot be a branch out of the structured block. 8131 // longjmp() and throw() must not violate the entry/exit criteria. 8132 CS->getCapturedDecl()->setNothrow(); 8133 } 8134 8135 OMPLoopDirective::HelperExprs B; 8136 // In presence of clause 'collapse' with number of loops, it will 8137 // define the nested loops number. 8138 unsigned NestedLoopCount = checkOpenMPLoop( 8139 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses), 8140 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8141 VarsWithImplicitDSA, B); 8142 if (NestedLoopCount == 0) 8143 return StmtError(); 8144 8145 assert((CurContext->isDependentContext() || B.builtAll()) && 8146 "omp target teams distribute loop exprs were not built"); 8147 8148 setFunctionHasBranchProtectedScope(); 8149 return OMPTargetTeamsDistributeDirective::Create( 8150 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 8151 } 8152 8153 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 8154 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8155 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8156 if (!AStmt) 8157 return StmtError(); 8158 8159 auto *CS = cast<CapturedStmt>(AStmt); 8160 // 1.2.2 OpenMP Language Terminology 8161 // Structured block - An executable statement with a single entry at the 8162 // top and a single exit at the bottom. 8163 // The point of exit cannot be a branch out of the structured block. 8164 // longjmp() and throw() must not violate the entry/exit criteria. 8165 CS->getCapturedDecl()->setNothrow(); 8166 for (int ThisCaptureLevel = 8167 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for); 8168 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8169 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8170 // 1.2.2 OpenMP Language Terminology 8171 // Structured block - An executable statement with a single entry at the 8172 // top and a single exit at the bottom. 8173 // The point of exit cannot be a branch out of the structured block. 8174 // longjmp() and throw() must not violate the entry/exit criteria. 8175 CS->getCapturedDecl()->setNothrow(); 8176 } 8177 8178 OMPLoopDirective::HelperExprs B; 8179 // In presence of clause 'collapse' with number of loops, it will 8180 // define the nested loops number. 8181 unsigned NestedLoopCount = checkOpenMPLoop( 8182 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 8183 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8184 VarsWithImplicitDSA, B); 8185 if (NestedLoopCount == 0) 8186 return StmtError(); 8187 8188 assert((CurContext->isDependentContext() || B.builtAll()) && 8189 "omp target teams distribute parallel for loop exprs were not built"); 8190 8191 if (!CurContext->isDependentContext()) { 8192 // Finalize the clauses that need pre-built expressions for CodeGen. 8193 for (OMPClause *C : Clauses) { 8194 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8195 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8196 B.NumIterations, *this, CurScope, 8197 DSAStack)) 8198 return StmtError(); 8199 } 8200 } 8201 8202 setFunctionHasBranchProtectedScope(); 8203 return OMPTargetTeamsDistributeParallelForDirective::Create( 8204 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 8205 DSAStack->isCancelRegion()); 8206 } 8207 8208 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 8209 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8210 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8211 if (!AStmt) 8212 return StmtError(); 8213 8214 auto *CS = cast<CapturedStmt>(AStmt); 8215 // 1.2.2 OpenMP Language Terminology 8216 // Structured block - An executable statement with a single entry at the 8217 // top and a single exit at the bottom. 8218 // The point of exit cannot be a branch out of the structured block. 8219 // longjmp() and throw() must not violate the entry/exit criteria. 8220 CS->getCapturedDecl()->setNothrow(); 8221 for (int ThisCaptureLevel = getOpenMPCaptureLevels( 8222 OMPD_target_teams_distribute_parallel_for_simd); 8223 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8224 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8225 // 1.2.2 OpenMP Language Terminology 8226 // Structured block - An executable statement with a single entry at the 8227 // top and a single exit at the bottom. 8228 // The point of exit cannot be a branch out of the structured block. 8229 // longjmp() and throw() must not violate the entry/exit criteria. 8230 CS->getCapturedDecl()->setNothrow(); 8231 } 8232 8233 OMPLoopDirective::HelperExprs B; 8234 // In presence of clause 'collapse' with number of loops, it will 8235 // define the nested loops number. 8236 unsigned NestedLoopCount = 8237 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd, 8238 getCollapseNumberExpr(Clauses), 8239 nullptr /*ordered not a clause on distribute*/, CS, *this, 8240 *DSAStack, VarsWithImplicitDSA, B); 8241 if (NestedLoopCount == 0) 8242 return StmtError(); 8243 8244 assert((CurContext->isDependentContext() || B.builtAll()) && 8245 "omp target teams distribute parallel for simd loop exprs were not " 8246 "built"); 8247 8248 if (!CurContext->isDependentContext()) { 8249 // Finalize the clauses that need pre-built expressions for CodeGen. 8250 for (OMPClause *C : Clauses) { 8251 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8252 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8253 B.NumIterations, *this, CurScope, 8254 DSAStack)) 8255 return StmtError(); 8256 } 8257 } 8258 8259 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8260 return StmtError(); 8261 8262 setFunctionHasBranchProtectedScope(); 8263 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 8264 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 8265 } 8266 8267 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 8268 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 8269 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) { 8270 if (!AStmt) 8271 return StmtError(); 8272 8273 auto *CS = cast<CapturedStmt>(AStmt); 8274 // 1.2.2 OpenMP Language Terminology 8275 // Structured block - An executable statement with a single entry at the 8276 // top and a single exit at the bottom. 8277 // The point of exit cannot be a branch out of the structured block. 8278 // longjmp() and throw() must not violate the entry/exit criteria. 8279 CS->getCapturedDecl()->setNothrow(); 8280 for (int ThisCaptureLevel = 8281 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd); 8282 ThisCaptureLevel > 1; --ThisCaptureLevel) { 8283 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 8284 // 1.2.2 OpenMP Language Terminology 8285 // Structured block - An executable statement with a single entry at the 8286 // top and a single exit at the bottom. 8287 // The point of exit cannot be a branch out of the structured block. 8288 // longjmp() and throw() must not violate the entry/exit criteria. 8289 CS->getCapturedDecl()->setNothrow(); 8290 } 8291 8292 OMPLoopDirective::HelperExprs B; 8293 // In presence of clause 'collapse' with number of loops, it will 8294 // define the nested loops number. 8295 unsigned NestedLoopCount = checkOpenMPLoop( 8296 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 8297 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 8298 VarsWithImplicitDSA, B); 8299 if (NestedLoopCount == 0) 8300 return StmtError(); 8301 8302 assert((CurContext->isDependentContext() || B.builtAll()) && 8303 "omp target teams distribute simd loop exprs were not built"); 8304 8305 if (!CurContext->isDependentContext()) { 8306 // Finalize the clauses that need pre-built expressions for CodeGen. 8307 for (OMPClause *C : Clauses) { 8308 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 8309 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 8310 B.NumIterations, *this, CurScope, 8311 DSAStack)) 8312 return StmtError(); 8313 } 8314 } 8315 8316 if (checkSimdlenSafelenSpecified(*this, Clauses)) 8317 return StmtError(); 8318 8319 setFunctionHasBranchProtectedScope(); 8320 return OMPTargetTeamsDistributeSimdDirective::Create( 8321 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 8322 } 8323 8324 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 8325 SourceLocation StartLoc, 8326 SourceLocation LParenLoc, 8327 SourceLocation EndLoc) { 8328 OMPClause *Res = nullptr; 8329 switch (Kind) { 8330 case OMPC_final: 8331 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 8332 break; 8333 case OMPC_num_threads: 8334 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 8335 break; 8336 case OMPC_safelen: 8337 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 8338 break; 8339 case OMPC_simdlen: 8340 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 8341 break; 8342 case OMPC_collapse: 8343 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 8344 break; 8345 case OMPC_ordered: 8346 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 8347 break; 8348 case OMPC_device: 8349 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc); 8350 break; 8351 case OMPC_num_teams: 8352 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 8353 break; 8354 case OMPC_thread_limit: 8355 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 8356 break; 8357 case OMPC_priority: 8358 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 8359 break; 8360 case OMPC_grainsize: 8361 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 8362 break; 8363 case OMPC_num_tasks: 8364 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 8365 break; 8366 case OMPC_hint: 8367 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 8368 break; 8369 case OMPC_if: 8370 case OMPC_default: 8371 case OMPC_proc_bind: 8372 case OMPC_schedule: 8373 case OMPC_private: 8374 case OMPC_firstprivate: 8375 case OMPC_lastprivate: 8376 case OMPC_shared: 8377 case OMPC_reduction: 8378 case OMPC_task_reduction: 8379 case OMPC_in_reduction: 8380 case OMPC_linear: 8381 case OMPC_aligned: 8382 case OMPC_copyin: 8383 case OMPC_copyprivate: 8384 case OMPC_nowait: 8385 case OMPC_untied: 8386 case OMPC_mergeable: 8387 case OMPC_threadprivate: 8388 case OMPC_flush: 8389 case OMPC_read: 8390 case OMPC_write: 8391 case OMPC_update: 8392 case OMPC_capture: 8393 case OMPC_seq_cst: 8394 case OMPC_depend: 8395 case OMPC_threads: 8396 case OMPC_simd: 8397 case OMPC_map: 8398 case OMPC_nogroup: 8399 case OMPC_dist_schedule: 8400 case OMPC_defaultmap: 8401 case OMPC_unknown: 8402 case OMPC_uniform: 8403 case OMPC_to: 8404 case OMPC_from: 8405 case OMPC_use_device_ptr: 8406 case OMPC_is_device_ptr: 8407 case OMPC_unified_address: 8408 case OMPC_unified_shared_memory: 8409 case OMPC_reverse_offload: 8410 case OMPC_dynamic_allocators: 8411 case OMPC_atomic_default_mem_order: 8412 llvm_unreachable("Clause is not allowed."); 8413 } 8414 return Res; 8415 } 8416 8417 // An OpenMP directive such as 'target parallel' has two captured regions: 8418 // for the 'target' and 'parallel' respectively. This function returns 8419 // the region in which to capture expressions associated with a clause. 8420 // A return value of OMPD_unknown signifies that the expression should not 8421 // be captured. 8422 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 8423 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 8424 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 8425 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 8426 switch (CKind) { 8427 case OMPC_if: 8428 switch (DKind) { 8429 case OMPD_target_parallel: 8430 case OMPD_target_parallel_for: 8431 case OMPD_target_parallel_for_simd: 8432 // If this clause applies to the nested 'parallel' region, capture within 8433 // the 'target' region, otherwise do not capture. 8434 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 8435 CaptureRegion = OMPD_target; 8436 break; 8437 case OMPD_target_teams_distribute_parallel_for: 8438 case OMPD_target_teams_distribute_parallel_for_simd: 8439 // If this clause applies to the nested 'parallel' region, capture within 8440 // the 'teams' region, otherwise do not capture. 8441 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 8442 CaptureRegion = OMPD_teams; 8443 break; 8444 case OMPD_teams_distribute_parallel_for: 8445 case OMPD_teams_distribute_parallel_for_simd: 8446 CaptureRegion = OMPD_teams; 8447 break; 8448 case OMPD_target_update: 8449 case OMPD_target_enter_data: 8450 case OMPD_target_exit_data: 8451 CaptureRegion = OMPD_task; 8452 break; 8453 case OMPD_cancel: 8454 case OMPD_parallel: 8455 case OMPD_parallel_sections: 8456 case OMPD_parallel_for: 8457 case OMPD_parallel_for_simd: 8458 case OMPD_target: 8459 case OMPD_target_simd: 8460 case OMPD_target_teams: 8461 case OMPD_target_teams_distribute: 8462 case OMPD_target_teams_distribute_simd: 8463 case OMPD_distribute_parallel_for: 8464 case OMPD_distribute_parallel_for_simd: 8465 case OMPD_task: 8466 case OMPD_taskloop: 8467 case OMPD_taskloop_simd: 8468 case OMPD_target_data: 8469 // Do not capture if-clause expressions. 8470 break; 8471 case OMPD_threadprivate: 8472 case OMPD_taskyield: 8473 case OMPD_barrier: 8474 case OMPD_taskwait: 8475 case OMPD_cancellation_point: 8476 case OMPD_flush: 8477 case OMPD_declare_reduction: 8478 case OMPD_declare_mapper: 8479 case OMPD_declare_simd: 8480 case OMPD_declare_target: 8481 case OMPD_end_declare_target: 8482 case OMPD_teams: 8483 case OMPD_simd: 8484 case OMPD_for: 8485 case OMPD_for_simd: 8486 case OMPD_sections: 8487 case OMPD_section: 8488 case OMPD_single: 8489 case OMPD_master: 8490 case OMPD_critical: 8491 case OMPD_taskgroup: 8492 case OMPD_distribute: 8493 case OMPD_ordered: 8494 case OMPD_atomic: 8495 case OMPD_distribute_simd: 8496 case OMPD_teams_distribute: 8497 case OMPD_teams_distribute_simd: 8498 case OMPD_requires: 8499 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 8500 case OMPD_unknown: 8501 llvm_unreachable("Unknown OpenMP directive"); 8502 } 8503 break; 8504 case OMPC_num_threads: 8505 switch (DKind) { 8506 case OMPD_target_parallel: 8507 case OMPD_target_parallel_for: 8508 case OMPD_target_parallel_for_simd: 8509 CaptureRegion = OMPD_target; 8510 break; 8511 case OMPD_teams_distribute_parallel_for: 8512 case OMPD_teams_distribute_parallel_for_simd: 8513 case OMPD_target_teams_distribute_parallel_for: 8514 case OMPD_target_teams_distribute_parallel_for_simd: 8515 CaptureRegion = OMPD_teams; 8516 break; 8517 case OMPD_parallel: 8518 case OMPD_parallel_sections: 8519 case OMPD_parallel_for: 8520 case OMPD_parallel_for_simd: 8521 case OMPD_distribute_parallel_for: 8522 case OMPD_distribute_parallel_for_simd: 8523 // Do not capture num_threads-clause expressions. 8524 break; 8525 case OMPD_target_data: 8526 case OMPD_target_enter_data: 8527 case OMPD_target_exit_data: 8528 case OMPD_target_update: 8529 case OMPD_target: 8530 case OMPD_target_simd: 8531 case OMPD_target_teams: 8532 case OMPD_target_teams_distribute: 8533 case OMPD_target_teams_distribute_simd: 8534 case OMPD_cancel: 8535 case OMPD_task: 8536 case OMPD_taskloop: 8537 case OMPD_taskloop_simd: 8538 case OMPD_threadprivate: 8539 case OMPD_taskyield: 8540 case OMPD_barrier: 8541 case OMPD_taskwait: 8542 case OMPD_cancellation_point: 8543 case OMPD_flush: 8544 case OMPD_declare_reduction: 8545 case OMPD_declare_mapper: 8546 case OMPD_declare_simd: 8547 case OMPD_declare_target: 8548 case OMPD_end_declare_target: 8549 case OMPD_teams: 8550 case OMPD_simd: 8551 case OMPD_for: 8552 case OMPD_for_simd: 8553 case OMPD_sections: 8554 case OMPD_section: 8555 case OMPD_single: 8556 case OMPD_master: 8557 case OMPD_critical: 8558 case OMPD_taskgroup: 8559 case OMPD_distribute: 8560 case OMPD_ordered: 8561 case OMPD_atomic: 8562 case OMPD_distribute_simd: 8563 case OMPD_teams_distribute: 8564 case OMPD_teams_distribute_simd: 8565 case OMPD_requires: 8566 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 8567 case OMPD_unknown: 8568 llvm_unreachable("Unknown OpenMP directive"); 8569 } 8570 break; 8571 case OMPC_num_teams: 8572 switch (DKind) { 8573 case OMPD_target_teams: 8574 case OMPD_target_teams_distribute: 8575 case OMPD_target_teams_distribute_simd: 8576 case OMPD_target_teams_distribute_parallel_for: 8577 case OMPD_target_teams_distribute_parallel_for_simd: 8578 CaptureRegion = OMPD_target; 8579 break; 8580 case OMPD_teams_distribute_parallel_for: 8581 case OMPD_teams_distribute_parallel_for_simd: 8582 case OMPD_teams: 8583 case OMPD_teams_distribute: 8584 case OMPD_teams_distribute_simd: 8585 // Do not capture num_teams-clause expressions. 8586 break; 8587 case OMPD_distribute_parallel_for: 8588 case OMPD_distribute_parallel_for_simd: 8589 case OMPD_task: 8590 case OMPD_taskloop: 8591 case OMPD_taskloop_simd: 8592 case OMPD_target_data: 8593 case OMPD_target_enter_data: 8594 case OMPD_target_exit_data: 8595 case OMPD_target_update: 8596 case OMPD_cancel: 8597 case OMPD_parallel: 8598 case OMPD_parallel_sections: 8599 case OMPD_parallel_for: 8600 case OMPD_parallel_for_simd: 8601 case OMPD_target: 8602 case OMPD_target_simd: 8603 case OMPD_target_parallel: 8604 case OMPD_target_parallel_for: 8605 case OMPD_target_parallel_for_simd: 8606 case OMPD_threadprivate: 8607 case OMPD_taskyield: 8608 case OMPD_barrier: 8609 case OMPD_taskwait: 8610 case OMPD_cancellation_point: 8611 case OMPD_flush: 8612 case OMPD_declare_reduction: 8613 case OMPD_declare_mapper: 8614 case OMPD_declare_simd: 8615 case OMPD_declare_target: 8616 case OMPD_end_declare_target: 8617 case OMPD_simd: 8618 case OMPD_for: 8619 case OMPD_for_simd: 8620 case OMPD_sections: 8621 case OMPD_section: 8622 case OMPD_single: 8623 case OMPD_master: 8624 case OMPD_critical: 8625 case OMPD_taskgroup: 8626 case OMPD_distribute: 8627 case OMPD_ordered: 8628 case OMPD_atomic: 8629 case OMPD_distribute_simd: 8630 case OMPD_requires: 8631 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 8632 case OMPD_unknown: 8633 llvm_unreachable("Unknown OpenMP directive"); 8634 } 8635 break; 8636 case OMPC_thread_limit: 8637 switch (DKind) { 8638 case OMPD_target_teams: 8639 case OMPD_target_teams_distribute: 8640 case OMPD_target_teams_distribute_simd: 8641 case OMPD_target_teams_distribute_parallel_for: 8642 case OMPD_target_teams_distribute_parallel_for_simd: 8643 CaptureRegion = OMPD_target; 8644 break; 8645 case OMPD_teams_distribute_parallel_for: 8646 case OMPD_teams_distribute_parallel_for_simd: 8647 case OMPD_teams: 8648 case OMPD_teams_distribute: 8649 case OMPD_teams_distribute_simd: 8650 // Do not capture thread_limit-clause expressions. 8651 break; 8652 case OMPD_distribute_parallel_for: 8653 case OMPD_distribute_parallel_for_simd: 8654 case OMPD_task: 8655 case OMPD_taskloop: 8656 case OMPD_taskloop_simd: 8657 case OMPD_target_data: 8658 case OMPD_target_enter_data: 8659 case OMPD_target_exit_data: 8660 case OMPD_target_update: 8661 case OMPD_cancel: 8662 case OMPD_parallel: 8663 case OMPD_parallel_sections: 8664 case OMPD_parallel_for: 8665 case OMPD_parallel_for_simd: 8666 case OMPD_target: 8667 case OMPD_target_simd: 8668 case OMPD_target_parallel: 8669 case OMPD_target_parallel_for: 8670 case OMPD_target_parallel_for_simd: 8671 case OMPD_threadprivate: 8672 case OMPD_taskyield: 8673 case OMPD_barrier: 8674 case OMPD_taskwait: 8675 case OMPD_cancellation_point: 8676 case OMPD_flush: 8677 case OMPD_declare_reduction: 8678 case OMPD_declare_mapper: 8679 case OMPD_declare_simd: 8680 case OMPD_declare_target: 8681 case OMPD_end_declare_target: 8682 case OMPD_simd: 8683 case OMPD_for: 8684 case OMPD_for_simd: 8685 case OMPD_sections: 8686 case OMPD_section: 8687 case OMPD_single: 8688 case OMPD_master: 8689 case OMPD_critical: 8690 case OMPD_taskgroup: 8691 case OMPD_distribute: 8692 case OMPD_ordered: 8693 case OMPD_atomic: 8694 case OMPD_distribute_simd: 8695 case OMPD_requires: 8696 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 8697 case OMPD_unknown: 8698 llvm_unreachable("Unknown OpenMP directive"); 8699 } 8700 break; 8701 case OMPC_schedule: 8702 switch (DKind) { 8703 case OMPD_parallel_for: 8704 case OMPD_parallel_for_simd: 8705 case OMPD_distribute_parallel_for: 8706 case OMPD_distribute_parallel_for_simd: 8707 case OMPD_teams_distribute_parallel_for: 8708 case OMPD_teams_distribute_parallel_for_simd: 8709 case OMPD_target_parallel_for: 8710 case OMPD_target_parallel_for_simd: 8711 case OMPD_target_teams_distribute_parallel_for: 8712 case OMPD_target_teams_distribute_parallel_for_simd: 8713 CaptureRegion = OMPD_parallel; 8714 break; 8715 case OMPD_for: 8716 case OMPD_for_simd: 8717 // Do not capture schedule-clause expressions. 8718 break; 8719 case OMPD_task: 8720 case OMPD_taskloop: 8721 case OMPD_taskloop_simd: 8722 case OMPD_target_data: 8723 case OMPD_target_enter_data: 8724 case OMPD_target_exit_data: 8725 case OMPD_target_update: 8726 case OMPD_teams: 8727 case OMPD_teams_distribute: 8728 case OMPD_teams_distribute_simd: 8729 case OMPD_target_teams_distribute: 8730 case OMPD_target_teams_distribute_simd: 8731 case OMPD_target: 8732 case OMPD_target_simd: 8733 case OMPD_target_parallel: 8734 case OMPD_cancel: 8735 case OMPD_parallel: 8736 case OMPD_parallel_sections: 8737 case OMPD_threadprivate: 8738 case OMPD_taskyield: 8739 case OMPD_barrier: 8740 case OMPD_taskwait: 8741 case OMPD_cancellation_point: 8742 case OMPD_flush: 8743 case OMPD_declare_reduction: 8744 case OMPD_declare_mapper: 8745 case OMPD_declare_simd: 8746 case OMPD_declare_target: 8747 case OMPD_end_declare_target: 8748 case OMPD_simd: 8749 case OMPD_sections: 8750 case OMPD_section: 8751 case OMPD_single: 8752 case OMPD_master: 8753 case OMPD_critical: 8754 case OMPD_taskgroup: 8755 case OMPD_distribute: 8756 case OMPD_ordered: 8757 case OMPD_atomic: 8758 case OMPD_distribute_simd: 8759 case OMPD_target_teams: 8760 case OMPD_requires: 8761 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 8762 case OMPD_unknown: 8763 llvm_unreachable("Unknown OpenMP directive"); 8764 } 8765 break; 8766 case OMPC_dist_schedule: 8767 switch (DKind) { 8768 case OMPD_teams_distribute_parallel_for: 8769 case OMPD_teams_distribute_parallel_for_simd: 8770 case OMPD_teams_distribute: 8771 case OMPD_teams_distribute_simd: 8772 case OMPD_target_teams_distribute_parallel_for: 8773 case OMPD_target_teams_distribute_parallel_for_simd: 8774 case OMPD_target_teams_distribute: 8775 case OMPD_target_teams_distribute_simd: 8776 CaptureRegion = OMPD_teams; 8777 break; 8778 case OMPD_distribute_parallel_for: 8779 case OMPD_distribute_parallel_for_simd: 8780 case OMPD_distribute: 8781 case OMPD_distribute_simd: 8782 // Do not capture thread_limit-clause expressions. 8783 break; 8784 case OMPD_parallel_for: 8785 case OMPD_parallel_for_simd: 8786 case OMPD_target_parallel_for_simd: 8787 case OMPD_target_parallel_for: 8788 case OMPD_task: 8789 case OMPD_taskloop: 8790 case OMPD_taskloop_simd: 8791 case OMPD_target_data: 8792 case OMPD_target_enter_data: 8793 case OMPD_target_exit_data: 8794 case OMPD_target_update: 8795 case OMPD_teams: 8796 case OMPD_target: 8797 case OMPD_target_simd: 8798 case OMPD_target_parallel: 8799 case OMPD_cancel: 8800 case OMPD_parallel: 8801 case OMPD_parallel_sections: 8802 case OMPD_threadprivate: 8803 case OMPD_taskyield: 8804 case OMPD_barrier: 8805 case OMPD_taskwait: 8806 case OMPD_cancellation_point: 8807 case OMPD_flush: 8808 case OMPD_declare_reduction: 8809 case OMPD_declare_mapper: 8810 case OMPD_declare_simd: 8811 case OMPD_declare_target: 8812 case OMPD_end_declare_target: 8813 case OMPD_simd: 8814 case OMPD_for: 8815 case OMPD_for_simd: 8816 case OMPD_sections: 8817 case OMPD_section: 8818 case OMPD_single: 8819 case OMPD_master: 8820 case OMPD_critical: 8821 case OMPD_taskgroup: 8822 case OMPD_ordered: 8823 case OMPD_atomic: 8824 case OMPD_target_teams: 8825 case OMPD_requires: 8826 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 8827 case OMPD_unknown: 8828 llvm_unreachable("Unknown OpenMP directive"); 8829 } 8830 break; 8831 case OMPC_device: 8832 switch (DKind) { 8833 case OMPD_target_update: 8834 case OMPD_target_enter_data: 8835 case OMPD_target_exit_data: 8836 case OMPD_target: 8837 case OMPD_target_simd: 8838 case OMPD_target_teams: 8839 case OMPD_target_parallel: 8840 case OMPD_target_teams_distribute: 8841 case OMPD_target_teams_distribute_simd: 8842 case OMPD_target_parallel_for: 8843 case OMPD_target_parallel_for_simd: 8844 case OMPD_target_teams_distribute_parallel_for: 8845 case OMPD_target_teams_distribute_parallel_for_simd: 8846 CaptureRegion = OMPD_task; 8847 break; 8848 case OMPD_target_data: 8849 // Do not capture device-clause expressions. 8850 break; 8851 case OMPD_teams_distribute_parallel_for: 8852 case OMPD_teams_distribute_parallel_for_simd: 8853 case OMPD_teams: 8854 case OMPD_teams_distribute: 8855 case OMPD_teams_distribute_simd: 8856 case OMPD_distribute_parallel_for: 8857 case OMPD_distribute_parallel_for_simd: 8858 case OMPD_task: 8859 case OMPD_taskloop: 8860 case OMPD_taskloop_simd: 8861 case OMPD_cancel: 8862 case OMPD_parallel: 8863 case OMPD_parallel_sections: 8864 case OMPD_parallel_for: 8865 case OMPD_parallel_for_simd: 8866 case OMPD_threadprivate: 8867 case OMPD_taskyield: 8868 case OMPD_barrier: 8869 case OMPD_taskwait: 8870 case OMPD_cancellation_point: 8871 case OMPD_flush: 8872 case OMPD_declare_reduction: 8873 case OMPD_declare_mapper: 8874 case OMPD_declare_simd: 8875 case OMPD_declare_target: 8876 case OMPD_end_declare_target: 8877 case OMPD_simd: 8878 case OMPD_for: 8879 case OMPD_for_simd: 8880 case OMPD_sections: 8881 case OMPD_section: 8882 case OMPD_single: 8883 case OMPD_master: 8884 case OMPD_critical: 8885 case OMPD_taskgroup: 8886 case OMPD_distribute: 8887 case OMPD_ordered: 8888 case OMPD_atomic: 8889 case OMPD_distribute_simd: 8890 case OMPD_requires: 8891 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 8892 case OMPD_unknown: 8893 llvm_unreachable("Unknown OpenMP directive"); 8894 } 8895 break; 8896 case OMPC_firstprivate: 8897 case OMPC_lastprivate: 8898 case OMPC_reduction: 8899 case OMPC_task_reduction: 8900 case OMPC_in_reduction: 8901 case OMPC_linear: 8902 case OMPC_default: 8903 case OMPC_proc_bind: 8904 case OMPC_final: 8905 case OMPC_safelen: 8906 case OMPC_simdlen: 8907 case OMPC_collapse: 8908 case OMPC_private: 8909 case OMPC_shared: 8910 case OMPC_aligned: 8911 case OMPC_copyin: 8912 case OMPC_copyprivate: 8913 case OMPC_ordered: 8914 case OMPC_nowait: 8915 case OMPC_untied: 8916 case OMPC_mergeable: 8917 case OMPC_threadprivate: 8918 case OMPC_flush: 8919 case OMPC_read: 8920 case OMPC_write: 8921 case OMPC_update: 8922 case OMPC_capture: 8923 case OMPC_seq_cst: 8924 case OMPC_depend: 8925 case OMPC_threads: 8926 case OMPC_simd: 8927 case OMPC_map: 8928 case OMPC_priority: 8929 case OMPC_grainsize: 8930 case OMPC_nogroup: 8931 case OMPC_num_tasks: 8932 case OMPC_hint: 8933 case OMPC_defaultmap: 8934 case OMPC_unknown: 8935 case OMPC_uniform: 8936 case OMPC_to: 8937 case OMPC_from: 8938 case OMPC_use_device_ptr: 8939 case OMPC_is_device_ptr: 8940 case OMPC_unified_address: 8941 case OMPC_unified_shared_memory: 8942 case OMPC_reverse_offload: 8943 case OMPC_dynamic_allocators: 8944 case OMPC_atomic_default_mem_order: 8945 llvm_unreachable("Unexpected OpenMP clause."); 8946 } 8947 return CaptureRegion; 8948 } 8949 8950 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 8951 Expr *Condition, SourceLocation StartLoc, 8952 SourceLocation LParenLoc, 8953 SourceLocation NameModifierLoc, 8954 SourceLocation ColonLoc, 8955 SourceLocation EndLoc) { 8956 Expr *ValExpr = Condition; 8957 Stmt *HelperValStmt = nullptr; 8958 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 8959 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 8960 !Condition->isInstantiationDependent() && 8961 !Condition->containsUnexpandedParameterPack()) { 8962 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 8963 if (Val.isInvalid()) 8964 return nullptr; 8965 8966 ValExpr = Val.get(); 8967 8968 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 8969 CaptureRegion = 8970 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier); 8971 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 8972 ValExpr = MakeFullExpr(ValExpr).get(); 8973 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 8974 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 8975 HelperValStmt = buildPreInits(Context, Captures); 8976 } 8977 } 8978 8979 return new (Context) 8980 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 8981 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 8982 } 8983 8984 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 8985 SourceLocation StartLoc, 8986 SourceLocation LParenLoc, 8987 SourceLocation EndLoc) { 8988 Expr *ValExpr = Condition; 8989 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 8990 !Condition->isInstantiationDependent() && 8991 !Condition->containsUnexpandedParameterPack()) { 8992 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 8993 if (Val.isInvalid()) 8994 return nullptr; 8995 8996 ValExpr = MakeFullExpr(Val.get()).get(); 8997 } 8998 8999 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 9000 } 9001 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 9002 Expr *Op) { 9003 if (!Op) 9004 return ExprError(); 9005 9006 class IntConvertDiagnoser : public ICEConvertDiagnoser { 9007 public: 9008 IntConvertDiagnoser() 9009 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 9010 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 9011 QualType T) override { 9012 return S.Diag(Loc, diag::err_omp_not_integral) << T; 9013 } 9014 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 9015 QualType T) override { 9016 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 9017 } 9018 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 9019 QualType T, 9020 QualType ConvTy) override { 9021 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 9022 } 9023 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 9024 QualType ConvTy) override { 9025 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 9026 << ConvTy->isEnumeralType() << ConvTy; 9027 } 9028 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 9029 QualType T) override { 9030 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 9031 } 9032 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 9033 QualType ConvTy) override { 9034 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 9035 << ConvTy->isEnumeralType() << ConvTy; 9036 } 9037 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 9038 QualType) override { 9039 llvm_unreachable("conversion functions are permitted"); 9040 } 9041 } ConvertDiagnoser; 9042 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 9043 } 9044 9045 static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, 9046 OpenMPClauseKind CKind, 9047 bool StrictlyPositive) { 9048 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 9049 !ValExpr->isInstantiationDependent()) { 9050 SourceLocation Loc = ValExpr->getExprLoc(); 9051 ExprResult Value = 9052 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 9053 if (Value.isInvalid()) 9054 return false; 9055 9056 ValExpr = Value.get(); 9057 // The expression must evaluate to a non-negative integer value. 9058 llvm::APSInt Result; 9059 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && 9060 Result.isSigned() && 9061 !((!StrictlyPositive && Result.isNonNegative()) || 9062 (StrictlyPositive && Result.isStrictlyPositive()))) { 9063 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 9064 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 9065 << ValExpr->getSourceRange(); 9066 return false; 9067 } 9068 } 9069 return true; 9070 } 9071 9072 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 9073 SourceLocation StartLoc, 9074 SourceLocation LParenLoc, 9075 SourceLocation EndLoc) { 9076 Expr *ValExpr = NumThreads; 9077 Stmt *HelperValStmt = nullptr; 9078 9079 // OpenMP [2.5, Restrictions] 9080 // The num_threads expression must evaluate to a positive integer value. 9081 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 9082 /*StrictlyPositive=*/true)) 9083 return nullptr; 9084 9085 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 9086 OpenMPDirectiveKind CaptureRegion = 9087 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads); 9088 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 9089 ValExpr = MakeFullExpr(ValExpr).get(); 9090 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 9091 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 9092 HelperValStmt = buildPreInits(Context, Captures); 9093 } 9094 9095 return new (Context) OMPNumThreadsClause( 9096 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 9097 } 9098 9099 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 9100 OpenMPClauseKind CKind, 9101 bool StrictlyPositive) { 9102 if (!E) 9103 return ExprError(); 9104 if (E->isValueDependent() || E->isTypeDependent() || 9105 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 9106 return E; 9107 llvm::APSInt Result; 9108 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 9109 if (ICE.isInvalid()) 9110 return ExprError(); 9111 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 9112 (!StrictlyPositive && !Result.isNonNegative())) { 9113 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 9114 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 9115 << E->getSourceRange(); 9116 return ExprError(); 9117 } 9118 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 9119 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 9120 << E->getSourceRange(); 9121 return ExprError(); 9122 } 9123 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 9124 DSAStack->setAssociatedLoops(Result.getExtValue()); 9125 else if (CKind == OMPC_ordered) 9126 DSAStack->setAssociatedLoops(Result.getExtValue()); 9127 return ICE; 9128 } 9129 9130 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 9131 SourceLocation LParenLoc, 9132 SourceLocation EndLoc) { 9133 // OpenMP [2.8.1, simd construct, Description] 9134 // The parameter of the safelen clause must be a constant 9135 // positive integer expression. 9136 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 9137 if (Safelen.isInvalid()) 9138 return nullptr; 9139 return new (Context) 9140 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 9141 } 9142 9143 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 9144 SourceLocation LParenLoc, 9145 SourceLocation EndLoc) { 9146 // OpenMP [2.8.1, simd construct, Description] 9147 // The parameter of the simdlen clause must be a constant 9148 // positive integer expression. 9149 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 9150 if (Simdlen.isInvalid()) 9151 return nullptr; 9152 return new (Context) 9153 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 9154 } 9155 9156 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 9157 SourceLocation StartLoc, 9158 SourceLocation LParenLoc, 9159 SourceLocation EndLoc) { 9160 // OpenMP [2.7.1, loop construct, Description] 9161 // OpenMP [2.8.1, simd construct, Description] 9162 // OpenMP [2.9.6, distribute construct, Description] 9163 // The parameter of the collapse clause must be a constant 9164 // positive integer expression. 9165 ExprResult NumForLoopsResult = 9166 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 9167 if (NumForLoopsResult.isInvalid()) 9168 return nullptr; 9169 return new (Context) 9170 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 9171 } 9172 9173 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 9174 SourceLocation EndLoc, 9175 SourceLocation LParenLoc, 9176 Expr *NumForLoops) { 9177 // OpenMP [2.7.1, loop construct, Description] 9178 // OpenMP [2.8.1, simd construct, Description] 9179 // OpenMP [2.9.6, distribute construct, Description] 9180 // The parameter of the ordered clause must be a constant 9181 // positive integer expression if any. 9182 if (NumForLoops && LParenLoc.isValid()) { 9183 ExprResult NumForLoopsResult = 9184 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 9185 if (NumForLoopsResult.isInvalid()) 9186 return nullptr; 9187 NumForLoops = NumForLoopsResult.get(); 9188 } else { 9189 NumForLoops = nullptr; 9190 } 9191 auto *Clause = OMPOrderedClause::Create( 9192 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0, 9193 StartLoc, LParenLoc, EndLoc); 9194 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause); 9195 return Clause; 9196 } 9197 9198 OMPClause *Sema::ActOnOpenMPSimpleClause( 9199 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 9200 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 9201 OMPClause *Res = nullptr; 9202 switch (Kind) { 9203 case OMPC_default: 9204 Res = 9205 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 9206 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 9207 break; 9208 case OMPC_proc_bind: 9209 Res = ActOnOpenMPProcBindClause( 9210 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 9211 LParenLoc, EndLoc); 9212 break; 9213 case OMPC_atomic_default_mem_order: 9214 Res = ActOnOpenMPAtomicDefaultMemOrderClause( 9215 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument), 9216 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 9217 break; 9218 case OMPC_if: 9219 case OMPC_final: 9220 case OMPC_num_threads: 9221 case OMPC_safelen: 9222 case OMPC_simdlen: 9223 case OMPC_collapse: 9224 case OMPC_schedule: 9225 case OMPC_private: 9226 case OMPC_firstprivate: 9227 case OMPC_lastprivate: 9228 case OMPC_shared: 9229 case OMPC_reduction: 9230 case OMPC_task_reduction: 9231 case OMPC_in_reduction: 9232 case OMPC_linear: 9233 case OMPC_aligned: 9234 case OMPC_copyin: 9235 case OMPC_copyprivate: 9236 case OMPC_ordered: 9237 case OMPC_nowait: 9238 case OMPC_untied: 9239 case OMPC_mergeable: 9240 case OMPC_threadprivate: 9241 case OMPC_flush: 9242 case OMPC_read: 9243 case OMPC_write: 9244 case OMPC_update: 9245 case OMPC_capture: 9246 case OMPC_seq_cst: 9247 case OMPC_depend: 9248 case OMPC_device: 9249 case OMPC_threads: 9250 case OMPC_simd: 9251 case OMPC_map: 9252 case OMPC_num_teams: 9253 case OMPC_thread_limit: 9254 case OMPC_priority: 9255 case OMPC_grainsize: 9256 case OMPC_nogroup: 9257 case OMPC_num_tasks: 9258 case OMPC_hint: 9259 case OMPC_dist_schedule: 9260 case OMPC_defaultmap: 9261 case OMPC_unknown: 9262 case OMPC_uniform: 9263 case OMPC_to: 9264 case OMPC_from: 9265 case OMPC_use_device_ptr: 9266 case OMPC_is_device_ptr: 9267 case OMPC_unified_address: 9268 case OMPC_unified_shared_memory: 9269 case OMPC_reverse_offload: 9270 case OMPC_dynamic_allocators: 9271 llvm_unreachable("Clause is not allowed."); 9272 } 9273 return Res; 9274 } 9275 9276 static std::string 9277 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 9278 ArrayRef<unsigned> Exclude = llvm::None) { 9279 SmallString<256> Buffer; 9280 llvm::raw_svector_ostream Out(Buffer); 9281 unsigned Bound = Last >= 2 ? Last - 2 : 0; 9282 unsigned Skipped = Exclude.size(); 9283 auto S = Exclude.begin(), E = Exclude.end(); 9284 for (unsigned I = First; I < Last; ++I) { 9285 if (std::find(S, E, I) != E) { 9286 --Skipped; 9287 continue; 9288 } 9289 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'"; 9290 if (I == Bound - Skipped) 9291 Out << " or "; 9292 else if (I != Bound + 1 - Skipped) 9293 Out << ", "; 9294 } 9295 return Out.str(); 9296 } 9297 9298 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 9299 SourceLocation KindKwLoc, 9300 SourceLocation StartLoc, 9301 SourceLocation LParenLoc, 9302 SourceLocation EndLoc) { 9303 if (Kind == OMPC_DEFAULT_unknown) { 9304 static_assert(OMPC_DEFAULT_unknown > 0, 9305 "OMPC_DEFAULT_unknown not greater than 0"); 9306 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 9307 << getListOfPossibleValues(OMPC_default, /*First=*/0, 9308 /*Last=*/OMPC_DEFAULT_unknown) 9309 << getOpenMPClauseName(OMPC_default); 9310 return nullptr; 9311 } 9312 switch (Kind) { 9313 case OMPC_DEFAULT_none: 9314 DSAStack->setDefaultDSANone(KindKwLoc); 9315 break; 9316 case OMPC_DEFAULT_shared: 9317 DSAStack->setDefaultDSAShared(KindKwLoc); 9318 break; 9319 case OMPC_DEFAULT_unknown: 9320 llvm_unreachable("Clause kind is not allowed."); 9321 break; 9322 } 9323 return new (Context) 9324 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 9325 } 9326 9327 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 9328 SourceLocation KindKwLoc, 9329 SourceLocation StartLoc, 9330 SourceLocation LParenLoc, 9331 SourceLocation EndLoc) { 9332 if (Kind == OMPC_PROC_BIND_unknown) { 9333 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 9334 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0, 9335 /*Last=*/OMPC_PROC_BIND_unknown) 9336 << getOpenMPClauseName(OMPC_proc_bind); 9337 return nullptr; 9338 } 9339 return new (Context) 9340 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 9341 } 9342 9343 OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause( 9344 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc, 9345 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 9346 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) { 9347 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 9348 << getListOfPossibleValues( 9349 OMPC_atomic_default_mem_order, /*First=*/0, 9350 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) 9351 << getOpenMPClauseName(OMPC_atomic_default_mem_order); 9352 return nullptr; 9353 } 9354 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc, 9355 LParenLoc, EndLoc); 9356 } 9357 9358 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 9359 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 9360 SourceLocation StartLoc, SourceLocation LParenLoc, 9361 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 9362 SourceLocation EndLoc) { 9363 OMPClause *Res = nullptr; 9364 switch (Kind) { 9365 case OMPC_schedule: 9366 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 9367 assert(Argument.size() == NumberOfElements && 9368 ArgumentLoc.size() == NumberOfElements); 9369 Res = ActOnOpenMPScheduleClause( 9370 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 9371 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 9372 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 9373 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 9374 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 9375 break; 9376 case OMPC_if: 9377 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 9378 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 9379 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 9380 DelimLoc, EndLoc); 9381 break; 9382 case OMPC_dist_schedule: 9383 Res = ActOnOpenMPDistScheduleClause( 9384 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 9385 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 9386 break; 9387 case OMPC_defaultmap: 9388 enum { Modifier, DefaultmapKind }; 9389 Res = ActOnOpenMPDefaultmapClause( 9390 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 9391 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 9392 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 9393 EndLoc); 9394 break; 9395 case OMPC_final: 9396 case OMPC_num_threads: 9397 case OMPC_safelen: 9398 case OMPC_simdlen: 9399 case OMPC_collapse: 9400 case OMPC_default: 9401 case OMPC_proc_bind: 9402 case OMPC_private: 9403 case OMPC_firstprivate: 9404 case OMPC_lastprivate: 9405 case OMPC_shared: 9406 case OMPC_reduction: 9407 case OMPC_task_reduction: 9408 case OMPC_in_reduction: 9409 case OMPC_linear: 9410 case OMPC_aligned: 9411 case OMPC_copyin: 9412 case OMPC_copyprivate: 9413 case OMPC_ordered: 9414 case OMPC_nowait: 9415 case OMPC_untied: 9416 case OMPC_mergeable: 9417 case OMPC_threadprivate: 9418 case OMPC_flush: 9419 case OMPC_read: 9420 case OMPC_write: 9421 case OMPC_update: 9422 case OMPC_capture: 9423 case OMPC_seq_cst: 9424 case OMPC_depend: 9425 case OMPC_device: 9426 case OMPC_threads: 9427 case OMPC_simd: 9428 case OMPC_map: 9429 case OMPC_num_teams: 9430 case OMPC_thread_limit: 9431 case OMPC_priority: 9432 case OMPC_grainsize: 9433 case OMPC_nogroup: 9434 case OMPC_num_tasks: 9435 case OMPC_hint: 9436 case OMPC_unknown: 9437 case OMPC_uniform: 9438 case OMPC_to: 9439 case OMPC_from: 9440 case OMPC_use_device_ptr: 9441 case OMPC_is_device_ptr: 9442 case OMPC_unified_address: 9443 case OMPC_unified_shared_memory: 9444 case OMPC_reverse_offload: 9445 case OMPC_dynamic_allocators: 9446 case OMPC_atomic_default_mem_order: 9447 llvm_unreachable("Clause is not allowed."); 9448 } 9449 return Res; 9450 } 9451 9452 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 9453 OpenMPScheduleClauseModifier M2, 9454 SourceLocation M1Loc, SourceLocation M2Loc) { 9455 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 9456 SmallVector<unsigned, 2> Excluded; 9457 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 9458 Excluded.push_back(M2); 9459 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 9460 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 9461 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 9462 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 9463 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 9464 << getListOfPossibleValues(OMPC_schedule, 9465 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 9466 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 9467 Excluded) 9468 << getOpenMPClauseName(OMPC_schedule); 9469 return true; 9470 } 9471 return false; 9472 } 9473 9474 OMPClause *Sema::ActOnOpenMPScheduleClause( 9475 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 9476 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 9477 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 9478 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 9479 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 9480 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 9481 return nullptr; 9482 // OpenMP, 2.7.1, Loop Construct, Restrictions 9483 // Either the monotonic modifier or the nonmonotonic modifier can be specified 9484 // but not both. 9485 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 9486 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 9487 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 9488 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 9489 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 9490 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 9491 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 9492 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 9493 return nullptr; 9494 } 9495 if (Kind == OMPC_SCHEDULE_unknown) { 9496 std::string Values; 9497 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 9498 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 9499 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 9500 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 9501 Exclude); 9502 } else { 9503 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 9504 /*Last=*/OMPC_SCHEDULE_unknown); 9505 } 9506 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 9507 << Values << getOpenMPClauseName(OMPC_schedule); 9508 return nullptr; 9509 } 9510 // OpenMP, 2.7.1, Loop Construct, Restrictions 9511 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 9512 // schedule(guided). 9513 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 9514 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 9515 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 9516 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 9517 diag::err_omp_schedule_nonmonotonic_static); 9518 return nullptr; 9519 } 9520 Expr *ValExpr = ChunkSize; 9521 Stmt *HelperValStmt = nullptr; 9522 if (ChunkSize) { 9523 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 9524 !ChunkSize->isInstantiationDependent() && 9525 !ChunkSize->containsUnexpandedParameterPack()) { 9526 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 9527 ExprResult Val = 9528 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 9529 if (Val.isInvalid()) 9530 return nullptr; 9531 9532 ValExpr = Val.get(); 9533 9534 // OpenMP [2.7.1, Restrictions] 9535 // chunk_size must be a loop invariant integer expression with a positive 9536 // value. 9537 llvm::APSInt Result; 9538 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 9539 if (Result.isSigned() && !Result.isStrictlyPositive()) { 9540 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 9541 << "schedule" << 1 << ChunkSize->getSourceRange(); 9542 return nullptr; 9543 } 9544 } else if (getOpenMPCaptureRegionForClause( 9545 DSAStack->getCurrentDirective(), OMPC_schedule) != 9546 OMPD_unknown && 9547 !CurContext->isDependentContext()) { 9548 ValExpr = MakeFullExpr(ValExpr).get(); 9549 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 9550 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 9551 HelperValStmt = buildPreInits(Context, Captures); 9552 } 9553 } 9554 } 9555 9556 return new (Context) 9557 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 9558 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 9559 } 9560 9561 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 9562 SourceLocation StartLoc, 9563 SourceLocation EndLoc) { 9564 OMPClause *Res = nullptr; 9565 switch (Kind) { 9566 case OMPC_ordered: 9567 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 9568 break; 9569 case OMPC_nowait: 9570 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 9571 break; 9572 case OMPC_untied: 9573 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 9574 break; 9575 case OMPC_mergeable: 9576 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 9577 break; 9578 case OMPC_read: 9579 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 9580 break; 9581 case OMPC_write: 9582 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 9583 break; 9584 case OMPC_update: 9585 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 9586 break; 9587 case OMPC_capture: 9588 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 9589 break; 9590 case OMPC_seq_cst: 9591 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 9592 break; 9593 case OMPC_threads: 9594 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 9595 break; 9596 case OMPC_simd: 9597 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 9598 break; 9599 case OMPC_nogroup: 9600 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 9601 break; 9602 case OMPC_unified_address: 9603 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc); 9604 break; 9605 case OMPC_unified_shared_memory: 9606 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 9607 break; 9608 case OMPC_reverse_offload: 9609 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc); 9610 break; 9611 case OMPC_dynamic_allocators: 9612 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc); 9613 break; 9614 case OMPC_if: 9615 case OMPC_final: 9616 case OMPC_num_threads: 9617 case OMPC_safelen: 9618 case OMPC_simdlen: 9619 case OMPC_collapse: 9620 case OMPC_schedule: 9621 case OMPC_private: 9622 case OMPC_firstprivate: 9623 case OMPC_lastprivate: 9624 case OMPC_shared: 9625 case OMPC_reduction: 9626 case OMPC_task_reduction: 9627 case OMPC_in_reduction: 9628 case OMPC_linear: 9629 case OMPC_aligned: 9630 case OMPC_copyin: 9631 case OMPC_copyprivate: 9632 case OMPC_default: 9633 case OMPC_proc_bind: 9634 case OMPC_threadprivate: 9635 case OMPC_flush: 9636 case OMPC_depend: 9637 case OMPC_device: 9638 case OMPC_map: 9639 case OMPC_num_teams: 9640 case OMPC_thread_limit: 9641 case OMPC_priority: 9642 case OMPC_grainsize: 9643 case OMPC_num_tasks: 9644 case OMPC_hint: 9645 case OMPC_dist_schedule: 9646 case OMPC_defaultmap: 9647 case OMPC_unknown: 9648 case OMPC_uniform: 9649 case OMPC_to: 9650 case OMPC_from: 9651 case OMPC_use_device_ptr: 9652 case OMPC_is_device_ptr: 9653 case OMPC_atomic_default_mem_order: 9654 llvm_unreachable("Clause is not allowed."); 9655 } 9656 return Res; 9657 } 9658 9659 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 9660 SourceLocation EndLoc) { 9661 DSAStack->setNowaitRegion(); 9662 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 9663 } 9664 9665 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 9666 SourceLocation EndLoc) { 9667 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 9668 } 9669 9670 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 9671 SourceLocation EndLoc) { 9672 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 9673 } 9674 9675 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 9676 SourceLocation EndLoc) { 9677 return new (Context) OMPReadClause(StartLoc, EndLoc); 9678 } 9679 9680 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 9681 SourceLocation EndLoc) { 9682 return new (Context) OMPWriteClause(StartLoc, EndLoc); 9683 } 9684 9685 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 9686 SourceLocation EndLoc) { 9687 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 9688 } 9689 9690 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 9691 SourceLocation EndLoc) { 9692 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 9693 } 9694 9695 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 9696 SourceLocation EndLoc) { 9697 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 9698 } 9699 9700 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 9701 SourceLocation EndLoc) { 9702 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 9703 } 9704 9705 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 9706 SourceLocation EndLoc) { 9707 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 9708 } 9709 9710 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 9711 SourceLocation EndLoc) { 9712 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 9713 } 9714 9715 OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc, 9716 SourceLocation EndLoc) { 9717 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc); 9718 } 9719 9720 OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc, 9721 SourceLocation EndLoc) { 9722 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc); 9723 } 9724 9725 OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc, 9726 SourceLocation EndLoc) { 9727 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc); 9728 } 9729 9730 OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc, 9731 SourceLocation EndLoc) { 9732 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc); 9733 } 9734 9735 OMPClause *Sema::ActOnOpenMPVarListClause( 9736 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 9737 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 9738 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 9739 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind, 9740 OpenMPLinearClauseKind LinKind, 9741 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 9742 ArrayRef<SourceLocation> MapTypeModifiersLoc, 9743 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 9744 SourceLocation DepLinMapLoc) { 9745 OMPClause *Res = nullptr; 9746 switch (Kind) { 9747 case OMPC_private: 9748 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 9749 break; 9750 case OMPC_firstprivate: 9751 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 9752 break; 9753 case OMPC_lastprivate: 9754 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 9755 break; 9756 case OMPC_shared: 9757 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 9758 break; 9759 case OMPC_reduction: 9760 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 9761 EndLoc, ReductionIdScopeSpec, ReductionId); 9762 break; 9763 case OMPC_task_reduction: 9764 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 9765 EndLoc, ReductionIdScopeSpec, 9766 ReductionId); 9767 break; 9768 case OMPC_in_reduction: 9769 Res = 9770 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 9771 EndLoc, ReductionIdScopeSpec, ReductionId); 9772 break; 9773 case OMPC_linear: 9774 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 9775 LinKind, DepLinMapLoc, ColonLoc, EndLoc); 9776 break; 9777 case OMPC_aligned: 9778 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 9779 ColonLoc, EndLoc); 9780 break; 9781 case OMPC_copyin: 9782 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 9783 break; 9784 case OMPC_copyprivate: 9785 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 9786 break; 9787 case OMPC_flush: 9788 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 9789 break; 9790 case OMPC_depend: 9791 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, 9792 StartLoc, LParenLoc, EndLoc); 9793 break; 9794 case OMPC_map: 9795 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc, MapType, 9796 IsMapTypeImplicit, DepLinMapLoc, ColonLoc, 9797 VarList, StartLoc, LParenLoc, EndLoc); 9798 break; 9799 case OMPC_to: 9800 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc); 9801 break; 9802 case OMPC_from: 9803 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc); 9804 break; 9805 case OMPC_use_device_ptr: 9806 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 9807 break; 9808 case OMPC_is_device_ptr: 9809 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 9810 break; 9811 case OMPC_if: 9812 case OMPC_final: 9813 case OMPC_num_threads: 9814 case OMPC_safelen: 9815 case OMPC_simdlen: 9816 case OMPC_collapse: 9817 case OMPC_default: 9818 case OMPC_proc_bind: 9819 case OMPC_schedule: 9820 case OMPC_ordered: 9821 case OMPC_nowait: 9822 case OMPC_untied: 9823 case OMPC_mergeable: 9824 case OMPC_threadprivate: 9825 case OMPC_read: 9826 case OMPC_write: 9827 case OMPC_update: 9828 case OMPC_capture: 9829 case OMPC_seq_cst: 9830 case OMPC_device: 9831 case OMPC_threads: 9832 case OMPC_simd: 9833 case OMPC_num_teams: 9834 case OMPC_thread_limit: 9835 case OMPC_priority: 9836 case OMPC_grainsize: 9837 case OMPC_nogroup: 9838 case OMPC_num_tasks: 9839 case OMPC_hint: 9840 case OMPC_dist_schedule: 9841 case OMPC_defaultmap: 9842 case OMPC_unknown: 9843 case OMPC_uniform: 9844 case OMPC_unified_address: 9845 case OMPC_unified_shared_memory: 9846 case OMPC_reverse_offload: 9847 case OMPC_dynamic_allocators: 9848 case OMPC_atomic_default_mem_order: 9849 llvm_unreachable("Clause is not allowed."); 9850 } 9851 return Res; 9852 } 9853 9854 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 9855 ExprObjectKind OK, SourceLocation Loc) { 9856 ExprResult Res = BuildDeclRefExpr( 9857 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 9858 if (!Res.isUsable()) 9859 return ExprError(); 9860 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 9861 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 9862 if (!Res.isUsable()) 9863 return ExprError(); 9864 } 9865 if (VK != VK_LValue && Res.get()->isGLValue()) { 9866 Res = DefaultLvalueConversion(Res.get()); 9867 if (!Res.isUsable()) 9868 return ExprError(); 9869 } 9870 return Res; 9871 } 9872 9873 static std::pair<ValueDecl *, bool> 9874 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 9875 SourceRange &ERange, bool AllowArraySection = false) { 9876 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 9877 RefExpr->containsUnexpandedParameterPack()) 9878 return std::make_pair(nullptr, true); 9879 9880 // OpenMP [3.1, C/C++] 9881 // A list item is a variable name. 9882 // OpenMP [2.9.3.3, Restrictions, p.1] 9883 // A variable that is part of another variable (as an array or 9884 // structure element) cannot appear in a private clause. 9885 RefExpr = RefExpr->IgnoreParens(); 9886 enum { 9887 NoArrayExpr = -1, 9888 ArraySubscript = 0, 9889 OMPArraySection = 1 9890 } IsArrayExpr = NoArrayExpr; 9891 if (AllowArraySection) { 9892 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 9893 Expr *Base = ASE->getBase()->IgnoreParenImpCasts(); 9894 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 9895 Base = TempASE->getBase()->IgnoreParenImpCasts(); 9896 RefExpr = Base; 9897 IsArrayExpr = ArraySubscript; 9898 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 9899 Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 9900 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 9901 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 9902 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 9903 Base = TempASE->getBase()->IgnoreParenImpCasts(); 9904 RefExpr = Base; 9905 IsArrayExpr = OMPArraySection; 9906 } 9907 } 9908 ELoc = RefExpr->getExprLoc(); 9909 ERange = RefExpr->getSourceRange(); 9910 RefExpr = RefExpr->IgnoreParenImpCasts(); 9911 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 9912 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 9913 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 9914 (S.getCurrentThisType().isNull() || !ME || 9915 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 9916 !isa<FieldDecl>(ME->getMemberDecl()))) { 9917 if (IsArrayExpr != NoArrayExpr) { 9918 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 9919 << ERange; 9920 } else { 9921 S.Diag(ELoc, 9922 AllowArraySection 9923 ? diag::err_omp_expected_var_name_member_expr_or_array_item 9924 : diag::err_omp_expected_var_name_member_expr) 9925 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 9926 } 9927 return std::make_pair(nullptr, false); 9928 } 9929 return std::make_pair( 9930 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false); 9931 } 9932 9933 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 9934 SourceLocation StartLoc, 9935 SourceLocation LParenLoc, 9936 SourceLocation EndLoc) { 9937 SmallVector<Expr *, 8> Vars; 9938 SmallVector<Expr *, 8> PrivateCopies; 9939 for (Expr *RefExpr : VarList) { 9940 assert(RefExpr && "NULL expr in OpenMP private clause."); 9941 SourceLocation ELoc; 9942 SourceRange ERange; 9943 Expr *SimpleRefExpr = RefExpr; 9944 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 9945 if (Res.second) { 9946 // It will be analyzed later. 9947 Vars.push_back(RefExpr); 9948 PrivateCopies.push_back(nullptr); 9949 } 9950 ValueDecl *D = Res.first; 9951 if (!D) 9952 continue; 9953 9954 QualType Type = D->getType(); 9955 auto *VD = dyn_cast<VarDecl>(D); 9956 9957 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 9958 // A variable that appears in a private clause must not have an incomplete 9959 // type or a reference type. 9960 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 9961 continue; 9962 Type = Type.getNonReferenceType(); 9963 9964 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 9965 // A variable that is privatized must not have a const-qualified type 9966 // unless it is of class type with a mutable member. This restriction does 9967 // not apply to the firstprivate clause. 9968 // 9969 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions] 9970 // A variable that appears in a private clause must not have a 9971 // const-qualified type unless it is of class type with a mutable member. 9972 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc)) 9973 continue; 9974 9975 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 9976 // in a Construct] 9977 // Variables with the predetermined data-sharing attributes may not be 9978 // listed in data-sharing attributes clauses, except for the cases 9979 // listed below. For these exceptions only, listing a predetermined 9980 // variable in a data-sharing attribute clause is allowed and overrides 9981 // the variable's predetermined data-sharing attributes. 9982 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 9983 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 9984 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 9985 << getOpenMPClauseName(OMPC_private); 9986 reportOriginalDsa(*this, DSAStack, D, DVar); 9987 continue; 9988 } 9989 9990 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 9991 // Variably modified types are not supported for tasks. 9992 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 9993 isOpenMPTaskingDirective(CurrDir)) { 9994 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 9995 << getOpenMPClauseName(OMPC_private) << Type 9996 << getOpenMPDirectiveName(CurrDir); 9997 bool IsDecl = 9998 !VD || 9999 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10000 Diag(D->getLocation(), 10001 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10002 << D; 10003 continue; 10004 } 10005 10006 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 10007 // A list item cannot appear in both a map clause and a data-sharing 10008 // attribute clause on the same construct 10009 if (isOpenMPTargetExecutionDirective(CurrDir)) { 10010 OpenMPClauseKind ConflictKind; 10011 if (DSAStack->checkMappableExprComponentListsForDecl( 10012 VD, /*CurrentRegionOnly=*/true, 10013 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 10014 OpenMPClauseKind WhereFoundClauseKind) -> bool { 10015 ConflictKind = WhereFoundClauseKind; 10016 return true; 10017 })) { 10018 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 10019 << getOpenMPClauseName(OMPC_private) 10020 << getOpenMPClauseName(ConflictKind) 10021 << getOpenMPDirectiveName(CurrDir); 10022 reportOriginalDsa(*this, DSAStack, D, DVar); 10023 continue; 10024 } 10025 } 10026 10027 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 10028 // A variable of class type (or array thereof) that appears in a private 10029 // clause requires an accessible, unambiguous default constructor for the 10030 // class type. 10031 // Generate helper private variable and initialize it with the default 10032 // value. The address of the original variable is replaced by the address of 10033 // the new private variable in CodeGen. This new variable is not added to 10034 // IdResolver, so the code in the OpenMP region uses original variable for 10035 // proper diagnostics. 10036 Type = Type.getUnqualifiedType(); 10037 VarDecl *VDPrivate = 10038 buildVarDecl(*this, ELoc, Type, D->getName(), 10039 D->hasAttrs() ? &D->getAttrs() : nullptr, 10040 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 10041 ActOnUninitializedDecl(VDPrivate); 10042 if (VDPrivate->isInvalidDecl()) 10043 continue; 10044 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 10045 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 10046 10047 DeclRefExpr *Ref = nullptr; 10048 if (!VD && !CurContext->isDependentContext()) 10049 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 10050 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 10051 Vars.push_back((VD || CurContext->isDependentContext()) 10052 ? RefExpr->IgnoreParens() 10053 : Ref); 10054 PrivateCopies.push_back(VDPrivateRefExpr); 10055 } 10056 10057 if (Vars.empty()) 10058 return nullptr; 10059 10060 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 10061 PrivateCopies); 10062 } 10063 10064 namespace { 10065 class DiagsUninitializedSeveretyRAII { 10066 private: 10067 DiagnosticsEngine &Diags; 10068 SourceLocation SavedLoc; 10069 bool IsIgnored = false; 10070 10071 public: 10072 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 10073 bool IsIgnored) 10074 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 10075 if (!IsIgnored) { 10076 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 10077 /*Map*/ diag::Severity::Ignored, Loc); 10078 } 10079 } 10080 ~DiagsUninitializedSeveretyRAII() { 10081 if (!IsIgnored) 10082 Diags.popMappings(SavedLoc); 10083 } 10084 }; 10085 } 10086 10087 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 10088 SourceLocation StartLoc, 10089 SourceLocation LParenLoc, 10090 SourceLocation EndLoc) { 10091 SmallVector<Expr *, 8> Vars; 10092 SmallVector<Expr *, 8> PrivateCopies; 10093 SmallVector<Expr *, 8> Inits; 10094 SmallVector<Decl *, 4> ExprCaptures; 10095 bool IsImplicitClause = 10096 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 10097 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc(); 10098 10099 for (Expr *RefExpr : VarList) { 10100 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 10101 SourceLocation ELoc; 10102 SourceRange ERange; 10103 Expr *SimpleRefExpr = RefExpr; 10104 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 10105 if (Res.second) { 10106 // It will be analyzed later. 10107 Vars.push_back(RefExpr); 10108 PrivateCopies.push_back(nullptr); 10109 Inits.push_back(nullptr); 10110 } 10111 ValueDecl *D = Res.first; 10112 if (!D) 10113 continue; 10114 10115 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 10116 QualType Type = D->getType(); 10117 auto *VD = dyn_cast<VarDecl>(D); 10118 10119 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 10120 // A variable that appears in a private clause must not have an incomplete 10121 // type or a reference type. 10122 if (RequireCompleteType(ELoc, Type, 10123 diag::err_omp_firstprivate_incomplete_type)) 10124 continue; 10125 Type = Type.getNonReferenceType(); 10126 10127 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 10128 // A variable of class type (or array thereof) that appears in a private 10129 // clause requires an accessible, unambiguous copy constructor for the 10130 // class type. 10131 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 10132 10133 // If an implicit firstprivate variable found it was checked already. 10134 DSAStackTy::DSAVarData TopDVar; 10135 if (!IsImplicitClause) { 10136 DSAStackTy::DSAVarData DVar = 10137 DSAStack->getTopDSA(D, /*FromParent=*/false); 10138 TopDVar = DVar; 10139 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 10140 bool IsConstant = ElemType.isConstant(Context); 10141 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 10142 // A list item that specifies a given variable may not appear in more 10143 // than one clause on the same directive, except that a variable may be 10144 // specified in both firstprivate and lastprivate clauses. 10145 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 10146 // A list item may appear in a firstprivate or lastprivate clause but not 10147 // both. 10148 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 10149 (isOpenMPDistributeDirective(CurrDir) || 10150 DVar.CKind != OMPC_lastprivate) && 10151 DVar.RefExpr) { 10152 Diag(ELoc, diag::err_omp_wrong_dsa) 10153 << getOpenMPClauseName(DVar.CKind) 10154 << getOpenMPClauseName(OMPC_firstprivate); 10155 reportOriginalDsa(*this, DSAStack, D, DVar); 10156 continue; 10157 } 10158 10159 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 10160 // in a Construct] 10161 // Variables with the predetermined data-sharing attributes may not be 10162 // listed in data-sharing attributes clauses, except for the cases 10163 // listed below. For these exceptions only, listing a predetermined 10164 // variable in a data-sharing attribute clause is allowed and overrides 10165 // the variable's predetermined data-sharing attributes. 10166 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 10167 // in a Construct, C/C++, p.2] 10168 // Variables with const-qualified type having no mutable member may be 10169 // listed in a firstprivate clause, even if they are static data members. 10170 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 10171 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 10172 Diag(ELoc, diag::err_omp_wrong_dsa) 10173 << getOpenMPClauseName(DVar.CKind) 10174 << getOpenMPClauseName(OMPC_firstprivate); 10175 reportOriginalDsa(*this, DSAStack, D, DVar); 10176 continue; 10177 } 10178 10179 // OpenMP [2.9.3.4, Restrictions, p.2] 10180 // A list item that is private within a parallel region must not appear 10181 // in a firstprivate clause on a worksharing construct if any of the 10182 // worksharing regions arising from the worksharing construct ever bind 10183 // to any of the parallel regions arising from the parallel construct. 10184 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 10185 // A list item that is private within a teams region must not appear in a 10186 // firstprivate clause on a distribute construct if any of the distribute 10187 // regions arising from the distribute construct ever bind to any of the 10188 // teams regions arising from the teams construct. 10189 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 10190 // A list item that appears in a reduction clause of a teams construct 10191 // must not appear in a firstprivate clause on a distribute construct if 10192 // any of the distribute regions arising from the distribute construct 10193 // ever bind to any of the teams regions arising from the teams construct. 10194 if ((isOpenMPWorksharingDirective(CurrDir) || 10195 isOpenMPDistributeDirective(CurrDir)) && 10196 !isOpenMPParallelDirective(CurrDir) && 10197 !isOpenMPTeamsDirective(CurrDir)) { 10198 DVar = DSAStack->getImplicitDSA(D, true); 10199 if (DVar.CKind != OMPC_shared && 10200 (isOpenMPParallelDirective(DVar.DKind) || 10201 isOpenMPTeamsDirective(DVar.DKind) || 10202 DVar.DKind == OMPD_unknown)) { 10203 Diag(ELoc, diag::err_omp_required_access) 10204 << getOpenMPClauseName(OMPC_firstprivate) 10205 << getOpenMPClauseName(OMPC_shared); 10206 reportOriginalDsa(*this, DSAStack, D, DVar); 10207 continue; 10208 } 10209 } 10210 // OpenMP [2.9.3.4, Restrictions, p.3] 10211 // A list item that appears in a reduction clause of a parallel construct 10212 // must not appear in a firstprivate clause on a worksharing or task 10213 // construct if any of the worksharing or task regions arising from the 10214 // worksharing or task construct ever bind to any of the parallel regions 10215 // arising from the parallel construct. 10216 // OpenMP [2.9.3.4, Restrictions, p.4] 10217 // A list item that appears in a reduction clause in worksharing 10218 // construct must not appear in a firstprivate clause in a task construct 10219 // encountered during execution of any of the worksharing regions arising 10220 // from the worksharing construct. 10221 if (isOpenMPTaskingDirective(CurrDir)) { 10222 DVar = DSAStack->hasInnermostDSA( 10223 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; }, 10224 [](OpenMPDirectiveKind K) { 10225 return isOpenMPParallelDirective(K) || 10226 isOpenMPWorksharingDirective(K) || 10227 isOpenMPTeamsDirective(K); 10228 }, 10229 /*FromParent=*/true); 10230 if (DVar.CKind == OMPC_reduction && 10231 (isOpenMPParallelDirective(DVar.DKind) || 10232 isOpenMPWorksharingDirective(DVar.DKind) || 10233 isOpenMPTeamsDirective(DVar.DKind))) { 10234 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 10235 << getOpenMPDirectiveName(DVar.DKind); 10236 reportOriginalDsa(*this, DSAStack, D, DVar); 10237 continue; 10238 } 10239 } 10240 10241 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 10242 // A list item cannot appear in both a map clause and a data-sharing 10243 // attribute clause on the same construct 10244 if (isOpenMPTargetExecutionDirective(CurrDir)) { 10245 OpenMPClauseKind ConflictKind; 10246 if (DSAStack->checkMappableExprComponentListsForDecl( 10247 VD, /*CurrentRegionOnly=*/true, 10248 [&ConflictKind]( 10249 OMPClauseMappableExprCommon::MappableExprComponentListRef, 10250 OpenMPClauseKind WhereFoundClauseKind) { 10251 ConflictKind = WhereFoundClauseKind; 10252 return true; 10253 })) { 10254 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 10255 << getOpenMPClauseName(OMPC_firstprivate) 10256 << getOpenMPClauseName(ConflictKind) 10257 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 10258 reportOriginalDsa(*this, DSAStack, D, DVar); 10259 continue; 10260 } 10261 } 10262 } 10263 10264 // Variably modified types are not supported for tasks. 10265 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 10266 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 10267 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 10268 << getOpenMPClauseName(OMPC_firstprivate) << Type 10269 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 10270 bool IsDecl = 10271 !VD || 10272 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10273 Diag(D->getLocation(), 10274 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10275 << D; 10276 continue; 10277 } 10278 10279 Type = Type.getUnqualifiedType(); 10280 VarDecl *VDPrivate = 10281 buildVarDecl(*this, ELoc, Type, D->getName(), 10282 D->hasAttrs() ? &D->getAttrs() : nullptr, 10283 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 10284 // Generate helper private variable and initialize it with the value of the 10285 // original variable. The address of the original variable is replaced by 10286 // the address of the new private variable in the CodeGen. This new variable 10287 // is not added to IdResolver, so the code in the OpenMP region uses 10288 // original variable for proper diagnostics and variable capturing. 10289 Expr *VDInitRefExpr = nullptr; 10290 // For arrays generate initializer for single element and replace it by the 10291 // original array element in CodeGen. 10292 if (Type->isArrayType()) { 10293 VarDecl *VDInit = 10294 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 10295 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 10296 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get(); 10297 ElemType = ElemType.getUnqualifiedType(); 10298 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 10299 ".firstprivate.temp"); 10300 InitializedEntity Entity = 10301 InitializedEntity::InitializeVariable(VDInitTemp); 10302 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 10303 10304 InitializationSequence InitSeq(*this, Entity, Kind, Init); 10305 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 10306 if (Result.isInvalid()) 10307 VDPrivate->setInvalidDecl(); 10308 else 10309 VDPrivate->setInit(Result.getAs<Expr>()); 10310 // Remove temp variable declaration. 10311 Context.Deallocate(VDInitTemp); 10312 } else { 10313 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 10314 ".firstprivate.temp"); 10315 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 10316 RefExpr->getExprLoc()); 10317 AddInitializerToDecl(VDPrivate, 10318 DefaultLvalueConversion(VDInitRefExpr).get(), 10319 /*DirectInit=*/false); 10320 } 10321 if (VDPrivate->isInvalidDecl()) { 10322 if (IsImplicitClause) { 10323 Diag(RefExpr->getExprLoc(), 10324 diag::note_omp_task_predetermined_firstprivate_here); 10325 } 10326 continue; 10327 } 10328 CurContext->addDecl(VDPrivate); 10329 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 10330 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 10331 RefExpr->getExprLoc()); 10332 DeclRefExpr *Ref = nullptr; 10333 if (!VD && !CurContext->isDependentContext()) { 10334 if (TopDVar.CKind == OMPC_lastprivate) { 10335 Ref = TopDVar.PrivateCopy; 10336 } else { 10337 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 10338 if (!isOpenMPCapturedDecl(D)) 10339 ExprCaptures.push_back(Ref->getDecl()); 10340 } 10341 } 10342 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 10343 Vars.push_back((VD || CurContext->isDependentContext()) 10344 ? RefExpr->IgnoreParens() 10345 : Ref); 10346 PrivateCopies.push_back(VDPrivateRefExpr); 10347 Inits.push_back(VDInitRefExpr); 10348 } 10349 10350 if (Vars.empty()) 10351 return nullptr; 10352 10353 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10354 Vars, PrivateCopies, Inits, 10355 buildPreInits(Context, ExprCaptures)); 10356 } 10357 10358 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 10359 SourceLocation StartLoc, 10360 SourceLocation LParenLoc, 10361 SourceLocation EndLoc) { 10362 SmallVector<Expr *, 8> Vars; 10363 SmallVector<Expr *, 8> SrcExprs; 10364 SmallVector<Expr *, 8> DstExprs; 10365 SmallVector<Expr *, 8> AssignmentOps; 10366 SmallVector<Decl *, 4> ExprCaptures; 10367 SmallVector<Expr *, 4> ExprPostUpdates; 10368 for (Expr *RefExpr : VarList) { 10369 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 10370 SourceLocation ELoc; 10371 SourceRange ERange; 10372 Expr *SimpleRefExpr = RefExpr; 10373 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 10374 if (Res.second) { 10375 // It will be analyzed later. 10376 Vars.push_back(RefExpr); 10377 SrcExprs.push_back(nullptr); 10378 DstExprs.push_back(nullptr); 10379 AssignmentOps.push_back(nullptr); 10380 } 10381 ValueDecl *D = Res.first; 10382 if (!D) 10383 continue; 10384 10385 QualType Type = D->getType(); 10386 auto *VD = dyn_cast<VarDecl>(D); 10387 10388 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 10389 // A variable that appears in a lastprivate clause must not have an 10390 // incomplete type or a reference type. 10391 if (RequireCompleteType(ELoc, Type, 10392 diag::err_omp_lastprivate_incomplete_type)) 10393 continue; 10394 Type = Type.getNonReferenceType(); 10395 10396 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 10397 // A variable that is privatized must not have a const-qualified type 10398 // unless it is of class type with a mutable member. This restriction does 10399 // not apply to the firstprivate clause. 10400 // 10401 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions] 10402 // A variable that appears in a lastprivate clause must not have a 10403 // const-qualified type unless it is of class type with a mutable member. 10404 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc)) 10405 continue; 10406 10407 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 10408 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 10409 // in a Construct] 10410 // Variables with the predetermined data-sharing attributes may not be 10411 // listed in data-sharing attributes clauses, except for the cases 10412 // listed below. 10413 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 10414 // A list item may appear in a firstprivate or lastprivate clause but not 10415 // both. 10416 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 10417 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 10418 (isOpenMPDistributeDirective(CurrDir) || 10419 DVar.CKind != OMPC_firstprivate) && 10420 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 10421 Diag(ELoc, diag::err_omp_wrong_dsa) 10422 << getOpenMPClauseName(DVar.CKind) 10423 << getOpenMPClauseName(OMPC_lastprivate); 10424 reportOriginalDsa(*this, DSAStack, D, DVar); 10425 continue; 10426 } 10427 10428 // OpenMP [2.14.3.5, Restrictions, p.2] 10429 // A list item that is private within a parallel region, or that appears in 10430 // the reduction clause of a parallel construct, must not appear in a 10431 // lastprivate clause on a worksharing construct if any of the corresponding 10432 // worksharing regions ever binds to any of the corresponding parallel 10433 // regions. 10434 DSAStackTy::DSAVarData TopDVar = DVar; 10435 if (isOpenMPWorksharingDirective(CurrDir) && 10436 !isOpenMPParallelDirective(CurrDir) && 10437 !isOpenMPTeamsDirective(CurrDir)) { 10438 DVar = DSAStack->getImplicitDSA(D, true); 10439 if (DVar.CKind != OMPC_shared) { 10440 Diag(ELoc, diag::err_omp_required_access) 10441 << getOpenMPClauseName(OMPC_lastprivate) 10442 << getOpenMPClauseName(OMPC_shared); 10443 reportOriginalDsa(*this, DSAStack, D, DVar); 10444 continue; 10445 } 10446 } 10447 10448 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 10449 // A variable of class type (or array thereof) that appears in a 10450 // lastprivate clause requires an accessible, unambiguous default 10451 // constructor for the class type, unless the list item is also specified 10452 // in a firstprivate clause. 10453 // A variable of class type (or array thereof) that appears in a 10454 // lastprivate clause requires an accessible, unambiguous copy assignment 10455 // operator for the class type. 10456 Type = Context.getBaseElementType(Type).getNonReferenceType(); 10457 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(), 10458 Type.getUnqualifiedType(), ".lastprivate.src", 10459 D->hasAttrs() ? &D->getAttrs() : nullptr); 10460 DeclRefExpr *PseudoSrcExpr = 10461 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 10462 VarDecl *DstVD = 10463 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 10464 D->hasAttrs() ? &D->getAttrs() : nullptr); 10465 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 10466 // For arrays generate assignment operation for single element and replace 10467 // it by the original array element in CodeGen. 10468 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 10469 PseudoDstExpr, PseudoSrcExpr); 10470 if (AssignmentOp.isInvalid()) 10471 continue; 10472 AssignmentOp = 10473 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 10474 if (AssignmentOp.isInvalid()) 10475 continue; 10476 10477 DeclRefExpr *Ref = nullptr; 10478 if (!VD && !CurContext->isDependentContext()) { 10479 if (TopDVar.CKind == OMPC_firstprivate) { 10480 Ref = TopDVar.PrivateCopy; 10481 } else { 10482 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 10483 if (!isOpenMPCapturedDecl(D)) 10484 ExprCaptures.push_back(Ref->getDecl()); 10485 } 10486 if (TopDVar.CKind == OMPC_firstprivate || 10487 (!isOpenMPCapturedDecl(D) && 10488 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 10489 ExprResult RefRes = DefaultLvalueConversion(Ref); 10490 if (!RefRes.isUsable()) 10491 continue; 10492 ExprResult PostUpdateRes = 10493 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 10494 RefRes.get()); 10495 if (!PostUpdateRes.isUsable()) 10496 continue; 10497 ExprPostUpdates.push_back( 10498 IgnoredValueConversions(PostUpdateRes.get()).get()); 10499 } 10500 } 10501 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 10502 Vars.push_back((VD || CurContext->isDependentContext()) 10503 ? RefExpr->IgnoreParens() 10504 : Ref); 10505 SrcExprs.push_back(PseudoSrcExpr); 10506 DstExprs.push_back(PseudoDstExpr); 10507 AssignmentOps.push_back(AssignmentOp.get()); 10508 } 10509 10510 if (Vars.empty()) 10511 return nullptr; 10512 10513 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10514 Vars, SrcExprs, DstExprs, AssignmentOps, 10515 buildPreInits(Context, ExprCaptures), 10516 buildPostUpdate(*this, ExprPostUpdates)); 10517 } 10518 10519 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 10520 SourceLocation StartLoc, 10521 SourceLocation LParenLoc, 10522 SourceLocation EndLoc) { 10523 SmallVector<Expr *, 8> Vars; 10524 for (Expr *RefExpr : VarList) { 10525 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 10526 SourceLocation ELoc; 10527 SourceRange ERange; 10528 Expr *SimpleRefExpr = RefExpr; 10529 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 10530 if (Res.second) { 10531 // It will be analyzed later. 10532 Vars.push_back(RefExpr); 10533 } 10534 ValueDecl *D = Res.first; 10535 if (!D) 10536 continue; 10537 10538 auto *VD = dyn_cast<VarDecl>(D); 10539 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 10540 // in a Construct] 10541 // Variables with the predetermined data-sharing attributes may not be 10542 // listed in data-sharing attributes clauses, except for the cases 10543 // listed below. For these exceptions only, listing a predetermined 10544 // variable in a data-sharing attribute clause is allowed and overrides 10545 // the variable's predetermined data-sharing attributes. 10546 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 10547 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 10548 DVar.RefExpr) { 10549 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 10550 << getOpenMPClauseName(OMPC_shared); 10551 reportOriginalDsa(*this, DSAStack, D, DVar); 10552 continue; 10553 } 10554 10555 DeclRefExpr *Ref = nullptr; 10556 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 10557 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 10558 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 10559 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 10560 ? RefExpr->IgnoreParens() 10561 : Ref); 10562 } 10563 10564 if (Vars.empty()) 10565 return nullptr; 10566 10567 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 10568 } 10569 10570 namespace { 10571 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 10572 DSAStackTy *Stack; 10573 10574 public: 10575 bool VisitDeclRefExpr(DeclRefExpr *E) { 10576 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 10577 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false); 10578 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 10579 return false; 10580 if (DVar.CKind != OMPC_unknown) 10581 return true; 10582 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 10583 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; }, 10584 /*FromParent=*/true); 10585 return DVarPrivate.CKind != OMPC_unknown; 10586 } 10587 return false; 10588 } 10589 bool VisitStmt(Stmt *S) { 10590 for (Stmt *Child : S->children()) { 10591 if (Child && Visit(Child)) 10592 return true; 10593 } 10594 return false; 10595 } 10596 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 10597 }; 10598 } // namespace 10599 10600 namespace { 10601 // Transform MemberExpression for specified FieldDecl of current class to 10602 // DeclRefExpr to specified OMPCapturedExprDecl. 10603 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 10604 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 10605 ValueDecl *Field = nullptr; 10606 DeclRefExpr *CapturedExpr = nullptr; 10607 10608 public: 10609 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 10610 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 10611 10612 ExprResult TransformMemberExpr(MemberExpr *E) { 10613 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 10614 E->getMemberDecl() == Field) { 10615 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 10616 return CapturedExpr; 10617 } 10618 return BaseTransform::TransformMemberExpr(E); 10619 } 10620 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 10621 }; 10622 } // namespace 10623 10624 template <typename T, typename U> 10625 static T filterLookupForUDR(SmallVectorImpl<U> &Lookups, 10626 const llvm::function_ref<T(ValueDecl *)> Gen) { 10627 for (U &Set : Lookups) { 10628 for (auto *D : Set) { 10629 if (T Res = Gen(cast<ValueDecl>(D))) 10630 return Res; 10631 } 10632 } 10633 return T(); 10634 } 10635 10636 static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) { 10637 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case"); 10638 10639 for (auto RD : D->redecls()) { 10640 // Don't bother with extra checks if we already know this one isn't visible. 10641 if (RD == D) 10642 continue; 10643 10644 auto ND = cast<NamedDecl>(RD); 10645 if (LookupResult::isVisible(SemaRef, ND)) 10646 return ND; 10647 } 10648 10649 return nullptr; 10650 } 10651 10652 static void 10653 argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &ReductionId, 10654 SourceLocation Loc, QualType Ty, 10655 SmallVectorImpl<UnresolvedSet<8>> &Lookups) { 10656 // Find all of the associated namespaces and classes based on the 10657 // arguments we have. 10658 Sema::AssociatedNamespaceSet AssociatedNamespaces; 10659 Sema::AssociatedClassSet AssociatedClasses; 10660 OpaqueValueExpr OVE(Loc, Ty, VK_LValue); 10661 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces, 10662 AssociatedClasses); 10663 10664 // C++ [basic.lookup.argdep]p3: 10665 // Let X be the lookup set produced by unqualified lookup (3.4.1) 10666 // and let Y be the lookup set produced by argument dependent 10667 // lookup (defined as follows). If X contains [...] then Y is 10668 // empty. Otherwise Y is the set of declarations found in the 10669 // namespaces associated with the argument types as described 10670 // below. The set of declarations found by the lookup of the name 10671 // is the union of X and Y. 10672 // 10673 // Here, we compute Y and add its members to the overloaded 10674 // candidate set. 10675 for (auto *NS : AssociatedNamespaces) { 10676 // When considering an associated namespace, the lookup is the 10677 // same as the lookup performed when the associated namespace is 10678 // used as a qualifier (3.4.3.2) except that: 10679 // 10680 // -- Any using-directives in the associated namespace are 10681 // ignored. 10682 // 10683 // -- Any namespace-scope friend functions declared in 10684 // associated classes are visible within their respective 10685 // namespaces even if they are not visible during an ordinary 10686 // lookup (11.4). 10687 DeclContext::lookup_result R = NS->lookup(ReductionId.getName()); 10688 for (auto *D : R) { 10689 auto *Underlying = D; 10690 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 10691 Underlying = USD->getTargetDecl(); 10692 10693 if (!isa<OMPDeclareReductionDecl>(Underlying)) 10694 continue; 10695 10696 if (!SemaRef.isVisible(D)) { 10697 D = findAcceptableDecl(SemaRef, D); 10698 if (!D) 10699 continue; 10700 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) 10701 Underlying = USD->getTargetDecl(); 10702 } 10703 Lookups.emplace_back(); 10704 Lookups.back().addDecl(Underlying); 10705 } 10706 } 10707 } 10708 10709 static ExprResult 10710 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 10711 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 10712 const DeclarationNameInfo &ReductionId, QualType Ty, 10713 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 10714 if (ReductionIdScopeSpec.isInvalid()) 10715 return ExprError(); 10716 SmallVector<UnresolvedSet<8>, 4> Lookups; 10717 if (S) { 10718 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 10719 Lookup.suppressDiagnostics(); 10720 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 10721 NamedDecl *D = Lookup.getRepresentativeDecl(); 10722 do { 10723 S = S->getParent(); 10724 } while (S && !S->isDeclScope(D)); 10725 if (S) 10726 S = S->getParent(); 10727 Lookups.emplace_back(); 10728 Lookups.back().append(Lookup.begin(), Lookup.end()); 10729 Lookup.clear(); 10730 } 10731 } else if (auto *ULE = 10732 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 10733 Lookups.push_back(UnresolvedSet<8>()); 10734 Decl *PrevD = nullptr; 10735 for (NamedDecl *D : ULE->decls()) { 10736 if (D == PrevD) 10737 Lookups.push_back(UnresolvedSet<8>()); 10738 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D)) 10739 Lookups.back().addDecl(DRD); 10740 PrevD = D; 10741 } 10742 } 10743 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || 10744 Ty->isInstantiationDependentType() || 10745 Ty->containsUnexpandedParameterPack() || 10746 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) { 10747 return !D->isInvalidDecl() && 10748 (D->getType()->isDependentType() || 10749 D->getType()->isInstantiationDependentType() || 10750 D->getType()->containsUnexpandedParameterPack()); 10751 })) { 10752 UnresolvedSet<8> ResSet; 10753 for (const UnresolvedSet<8> &Set : Lookups) { 10754 if (Set.empty()) 10755 continue; 10756 ResSet.append(Set.begin(), Set.end()); 10757 // The last item marks the end of all declarations at the specified scope. 10758 ResSet.addDecl(Set[Set.size() - 1]); 10759 } 10760 return UnresolvedLookupExpr::Create( 10761 SemaRef.Context, /*NamingClass=*/nullptr, 10762 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 10763 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 10764 } 10765 // Lookup inside the classes. 10766 // C++ [over.match.oper]p3: 10767 // For a unary operator @ with an operand of a type whose 10768 // cv-unqualified version is T1, and for a binary operator @ with 10769 // a left operand of a type whose cv-unqualified version is T1 and 10770 // a right operand of a type whose cv-unqualified version is T2, 10771 // three sets of candidate functions, designated member 10772 // candidates, non-member candidates and built-in candidates, are 10773 // constructed as follows: 10774 // -- If T1 is a complete class type or a class currently being 10775 // defined, the set of member candidates is the result of the 10776 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise, 10777 // the set of member candidates is empty. 10778 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 10779 Lookup.suppressDiagnostics(); 10780 if (const auto *TyRec = Ty->getAs<RecordType>()) { 10781 // Complete the type if it can be completed. 10782 // If the type is neither complete nor being defined, bail out now. 10783 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() || 10784 TyRec->getDecl()->getDefinition()) { 10785 Lookup.clear(); 10786 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl()); 10787 if (Lookup.empty()) { 10788 Lookups.emplace_back(); 10789 Lookups.back().append(Lookup.begin(), Lookup.end()); 10790 } 10791 } 10792 } 10793 // Perform ADL. 10794 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups); 10795 if (auto *VD = filterLookupForUDR<ValueDecl *>( 10796 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 10797 if (!D->isInvalidDecl() && 10798 SemaRef.Context.hasSameType(D->getType(), Ty)) 10799 return D; 10800 return nullptr; 10801 })) 10802 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(), 10803 VK_LValue, Loc); 10804 if (auto *VD = filterLookupForUDR<ValueDecl *>( 10805 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 10806 if (!D->isInvalidDecl() && 10807 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 10808 !Ty.isMoreQualifiedThan(D->getType())) 10809 return D; 10810 return nullptr; 10811 })) { 10812 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 10813 /*DetectVirtual=*/false); 10814 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 10815 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 10816 VD->getType().getUnqualifiedType()))) { 10817 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(), 10818 /*DiagID=*/0) != 10819 Sema::AR_inaccessible) { 10820 SemaRef.BuildBasePathArray(Paths, BasePath); 10821 return SemaRef.BuildDeclRefExpr( 10822 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc); 10823 } 10824 } 10825 } 10826 } 10827 if (ReductionIdScopeSpec.isSet()) { 10828 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range; 10829 return ExprError(); 10830 } 10831 return ExprEmpty(); 10832 } 10833 10834 namespace { 10835 /// Data for the reduction-based clauses. 10836 struct ReductionData { 10837 /// List of original reduction items. 10838 SmallVector<Expr *, 8> Vars; 10839 /// List of private copies of the reduction items. 10840 SmallVector<Expr *, 8> Privates; 10841 /// LHS expressions for the reduction_op expressions. 10842 SmallVector<Expr *, 8> LHSs; 10843 /// RHS expressions for the reduction_op expressions. 10844 SmallVector<Expr *, 8> RHSs; 10845 /// Reduction operation expression. 10846 SmallVector<Expr *, 8> ReductionOps; 10847 /// Taskgroup descriptors for the corresponding reduction items in 10848 /// in_reduction clauses. 10849 SmallVector<Expr *, 8> TaskgroupDescriptors; 10850 /// List of captures for clause. 10851 SmallVector<Decl *, 4> ExprCaptures; 10852 /// List of postupdate expressions. 10853 SmallVector<Expr *, 4> ExprPostUpdates; 10854 ReductionData() = delete; 10855 /// Reserves required memory for the reduction data. 10856 ReductionData(unsigned Size) { 10857 Vars.reserve(Size); 10858 Privates.reserve(Size); 10859 LHSs.reserve(Size); 10860 RHSs.reserve(Size); 10861 ReductionOps.reserve(Size); 10862 TaskgroupDescriptors.reserve(Size); 10863 ExprCaptures.reserve(Size); 10864 ExprPostUpdates.reserve(Size); 10865 } 10866 /// Stores reduction item and reduction operation only (required for dependent 10867 /// reduction item). 10868 void push(Expr *Item, Expr *ReductionOp) { 10869 Vars.emplace_back(Item); 10870 Privates.emplace_back(nullptr); 10871 LHSs.emplace_back(nullptr); 10872 RHSs.emplace_back(nullptr); 10873 ReductionOps.emplace_back(ReductionOp); 10874 TaskgroupDescriptors.emplace_back(nullptr); 10875 } 10876 /// Stores reduction data. 10877 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp, 10878 Expr *TaskgroupDescriptor) { 10879 Vars.emplace_back(Item); 10880 Privates.emplace_back(Private); 10881 LHSs.emplace_back(LHS); 10882 RHSs.emplace_back(RHS); 10883 ReductionOps.emplace_back(ReductionOp); 10884 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor); 10885 } 10886 }; 10887 } // namespace 10888 10889 static bool checkOMPArraySectionConstantForReduction( 10890 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement, 10891 SmallVectorImpl<llvm::APSInt> &ArraySizes) { 10892 const Expr *Length = OASE->getLength(); 10893 if (Length == nullptr) { 10894 // For array sections of the form [1:] or [:], we would need to analyze 10895 // the lower bound... 10896 if (OASE->getColonLoc().isValid()) 10897 return false; 10898 10899 // This is an array subscript which has implicit length 1! 10900 SingleElement = true; 10901 ArraySizes.push_back(llvm::APSInt::get(1)); 10902 } else { 10903 Expr::EvalResult Result; 10904 if (!Length->EvaluateAsInt(Result, Context)) 10905 return false; 10906 10907 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 10908 SingleElement = (ConstantLengthValue.getSExtValue() == 1); 10909 ArraySizes.push_back(ConstantLengthValue); 10910 } 10911 10912 // Get the base of this array section and walk up from there. 10913 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 10914 10915 // We require length = 1 for all array sections except the right-most to 10916 // guarantee that the memory region is contiguous and has no holes in it. 10917 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) { 10918 Length = TempOASE->getLength(); 10919 if (Length == nullptr) { 10920 // For array sections of the form [1:] or [:], we would need to analyze 10921 // the lower bound... 10922 if (OASE->getColonLoc().isValid()) 10923 return false; 10924 10925 // This is an array subscript which has implicit length 1! 10926 ArraySizes.push_back(llvm::APSInt::get(1)); 10927 } else { 10928 Expr::EvalResult Result; 10929 if (!Length->EvaluateAsInt(Result, Context)) 10930 return false; 10931 10932 llvm::APSInt ConstantLengthValue = Result.Val.getInt(); 10933 if (ConstantLengthValue.getSExtValue() != 1) 10934 return false; 10935 10936 ArraySizes.push_back(ConstantLengthValue); 10937 } 10938 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 10939 } 10940 10941 // If we have a single element, we don't need to add the implicit lengths. 10942 if (!SingleElement) { 10943 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) { 10944 // Has implicit length 1! 10945 ArraySizes.push_back(llvm::APSInt::get(1)); 10946 Base = TempASE->getBase()->IgnoreParenImpCasts(); 10947 } 10948 } 10949 10950 // This array section can be privatized as a single value or as a constant 10951 // sized array. 10952 return true; 10953 } 10954 10955 static bool actOnOMPReductionKindClause( 10956 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, 10957 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 10958 SourceLocation ColonLoc, SourceLocation EndLoc, 10959 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 10960 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { 10961 DeclarationName DN = ReductionId.getName(); 10962 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator(); 10963 BinaryOperatorKind BOK = BO_Comma; 10964 10965 ASTContext &Context = S.Context; 10966 // OpenMP [2.14.3.6, reduction clause] 10967 // C 10968 // reduction-identifier is either an identifier or one of the following 10969 // operators: +, -, *, &, |, ^, && and || 10970 // C++ 10971 // reduction-identifier is either an id-expression or one of the following 10972 // operators: +, -, *, &, |, ^, && and || 10973 switch (OOK) { 10974 case OO_Plus: 10975 case OO_Minus: 10976 BOK = BO_Add; 10977 break; 10978 case OO_Star: 10979 BOK = BO_Mul; 10980 break; 10981 case OO_Amp: 10982 BOK = BO_And; 10983 break; 10984 case OO_Pipe: 10985 BOK = BO_Or; 10986 break; 10987 case OO_Caret: 10988 BOK = BO_Xor; 10989 break; 10990 case OO_AmpAmp: 10991 BOK = BO_LAnd; 10992 break; 10993 case OO_PipePipe: 10994 BOK = BO_LOr; 10995 break; 10996 case OO_New: 10997 case OO_Delete: 10998 case OO_Array_New: 10999 case OO_Array_Delete: 11000 case OO_Slash: 11001 case OO_Percent: 11002 case OO_Tilde: 11003 case OO_Exclaim: 11004 case OO_Equal: 11005 case OO_Less: 11006 case OO_Greater: 11007 case OO_LessEqual: 11008 case OO_GreaterEqual: 11009 case OO_PlusEqual: 11010 case OO_MinusEqual: 11011 case OO_StarEqual: 11012 case OO_SlashEqual: 11013 case OO_PercentEqual: 11014 case OO_CaretEqual: 11015 case OO_AmpEqual: 11016 case OO_PipeEqual: 11017 case OO_LessLess: 11018 case OO_GreaterGreater: 11019 case OO_LessLessEqual: 11020 case OO_GreaterGreaterEqual: 11021 case OO_EqualEqual: 11022 case OO_ExclaimEqual: 11023 case OO_Spaceship: 11024 case OO_PlusPlus: 11025 case OO_MinusMinus: 11026 case OO_Comma: 11027 case OO_ArrowStar: 11028 case OO_Arrow: 11029 case OO_Call: 11030 case OO_Subscript: 11031 case OO_Conditional: 11032 case OO_Coawait: 11033 case NUM_OVERLOADED_OPERATORS: 11034 llvm_unreachable("Unexpected reduction identifier"); 11035 case OO_None: 11036 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) { 11037 if (II->isStr("max")) 11038 BOK = BO_GT; 11039 else if (II->isStr("min")) 11040 BOK = BO_LT; 11041 } 11042 break; 11043 } 11044 SourceRange ReductionIdRange; 11045 if (ReductionIdScopeSpec.isValid()) 11046 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 11047 else 11048 ReductionIdRange.setBegin(ReductionId.getBeginLoc()); 11049 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 11050 11051 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 11052 bool FirstIter = true; 11053 for (Expr *RefExpr : VarList) { 11054 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 11055 // OpenMP [2.1, C/C++] 11056 // A list item is a variable or array section, subject to the restrictions 11057 // specified in Section 2.4 on page 42 and in each of the sections 11058 // describing clauses and directives for which a list appears. 11059 // OpenMP [2.14.3.3, Restrictions, p.1] 11060 // A variable that is part of another variable (as an array or 11061 // structure element) cannot appear in a private clause. 11062 if (!FirstIter && IR != ER) 11063 ++IR; 11064 FirstIter = false; 11065 SourceLocation ELoc; 11066 SourceRange ERange; 11067 Expr *SimpleRefExpr = RefExpr; 11068 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 11069 /*AllowArraySection=*/true); 11070 if (Res.second) { 11071 // Try to find 'declare reduction' corresponding construct before using 11072 // builtin/overloaded operators. 11073 QualType Type = Context.DependentTy; 11074 CXXCastPath BasePath; 11075 ExprResult DeclareReductionRef = buildDeclareReductionRef( 11076 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 11077 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 11078 Expr *ReductionOp = nullptr; 11079 if (S.CurContext->isDependentContext() && 11080 (DeclareReductionRef.isUnset() || 11081 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 11082 ReductionOp = DeclareReductionRef.get(); 11083 // It will be analyzed later. 11084 RD.push(RefExpr, ReductionOp); 11085 } 11086 ValueDecl *D = Res.first; 11087 if (!D) 11088 continue; 11089 11090 Expr *TaskgroupDescriptor = nullptr; 11091 QualType Type; 11092 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 11093 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 11094 if (ASE) { 11095 Type = ASE->getType().getNonReferenceType(); 11096 } else if (OASE) { 11097 QualType BaseType = 11098 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 11099 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe()) 11100 Type = ATy->getElementType(); 11101 else 11102 Type = BaseType->getPointeeType(); 11103 Type = Type.getNonReferenceType(); 11104 } else { 11105 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 11106 } 11107 auto *VD = dyn_cast<VarDecl>(D); 11108 11109 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 11110 // A variable that appears in a private clause must not have an incomplete 11111 // type or a reference type. 11112 if (S.RequireCompleteType(ELoc, D->getType(), 11113 diag::err_omp_reduction_incomplete_type)) 11114 continue; 11115 // OpenMP [2.14.3.6, reduction clause, Restrictions] 11116 // A list item that appears in a reduction clause must not be 11117 // const-qualified. 11118 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc, 11119 /*AcceptIfMutable*/ false, ASE || OASE)) 11120 continue; 11121 11122 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); 11123 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 11124 // If a list-item is a reference type then it must bind to the same object 11125 // for all threads of the team. 11126 if (!ASE && !OASE) { 11127 if (VD) { 11128 VarDecl *VDDef = VD->getDefinition(); 11129 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 11130 DSARefChecker Check(Stack); 11131 if (Check.Visit(VDDef->getInit())) { 11132 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) 11133 << getOpenMPClauseName(ClauseKind) << ERange; 11134 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 11135 continue; 11136 } 11137 } 11138 } 11139 11140 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 11141 // in a Construct] 11142 // Variables with the predetermined data-sharing attributes may not be 11143 // listed in data-sharing attributes clauses, except for the cases 11144 // listed below. For these exceptions only, listing a predetermined 11145 // variable in a data-sharing attribute clause is allowed and overrides 11146 // the variable's predetermined data-sharing attributes. 11147 // OpenMP [2.14.3.6, Restrictions, p.3] 11148 // Any number of reduction clauses can be specified on the directive, 11149 // but a list item can appear only once in the reduction clauses for that 11150 // directive. 11151 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false); 11152 if (DVar.CKind == OMPC_reduction) { 11153 S.Diag(ELoc, diag::err_omp_once_referenced) 11154 << getOpenMPClauseName(ClauseKind); 11155 if (DVar.RefExpr) 11156 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 11157 continue; 11158 } 11159 if (DVar.CKind != OMPC_unknown) { 11160 S.Diag(ELoc, diag::err_omp_wrong_dsa) 11161 << getOpenMPClauseName(DVar.CKind) 11162 << getOpenMPClauseName(OMPC_reduction); 11163 reportOriginalDsa(S, Stack, D, DVar); 11164 continue; 11165 } 11166 11167 // OpenMP [2.14.3.6, Restrictions, p.1] 11168 // A list item that appears in a reduction clause of a worksharing 11169 // construct must be shared in the parallel regions to which any of the 11170 // worksharing regions arising from the worksharing construct bind. 11171 if (isOpenMPWorksharingDirective(CurrDir) && 11172 !isOpenMPParallelDirective(CurrDir) && 11173 !isOpenMPTeamsDirective(CurrDir)) { 11174 DVar = Stack->getImplicitDSA(D, true); 11175 if (DVar.CKind != OMPC_shared) { 11176 S.Diag(ELoc, diag::err_omp_required_access) 11177 << getOpenMPClauseName(OMPC_reduction) 11178 << getOpenMPClauseName(OMPC_shared); 11179 reportOriginalDsa(S, Stack, D, DVar); 11180 continue; 11181 } 11182 } 11183 } 11184 11185 // Try to find 'declare reduction' corresponding construct before using 11186 // builtin/overloaded operators. 11187 CXXCastPath BasePath; 11188 ExprResult DeclareReductionRef = buildDeclareReductionRef( 11189 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 11190 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 11191 if (DeclareReductionRef.isInvalid()) 11192 continue; 11193 if (S.CurContext->isDependentContext() && 11194 (DeclareReductionRef.isUnset() || 11195 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 11196 RD.push(RefExpr, DeclareReductionRef.get()); 11197 continue; 11198 } 11199 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 11200 // Not allowed reduction identifier is found. 11201 S.Diag(ReductionId.getBeginLoc(), 11202 diag::err_omp_unknown_reduction_identifier) 11203 << Type << ReductionIdRange; 11204 continue; 11205 } 11206 11207 // OpenMP [2.14.3.6, reduction clause, Restrictions] 11208 // The type of a list item that appears in a reduction clause must be valid 11209 // for the reduction-identifier. For a max or min reduction in C, the type 11210 // of the list item must be an allowed arithmetic data type: char, int, 11211 // float, double, or _Bool, possibly modified with long, short, signed, or 11212 // unsigned. For a max or min reduction in C++, the type of the list item 11213 // must be an allowed arithmetic data type: char, wchar_t, int, float, 11214 // double, or bool, possibly modified with long, short, signed, or unsigned. 11215 if (DeclareReductionRef.isUnset()) { 11216 if ((BOK == BO_GT || BOK == BO_LT) && 11217 !(Type->isScalarType() || 11218 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 11219 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 11220 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; 11221 if (!ASE && !OASE) { 11222 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 11223 VarDecl::DeclarationOnly; 11224 S.Diag(D->getLocation(), 11225 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11226 << D; 11227 } 11228 continue; 11229 } 11230 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 11231 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { 11232 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) 11233 << getOpenMPClauseName(ClauseKind); 11234 if (!ASE && !OASE) { 11235 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 11236 VarDecl::DeclarationOnly; 11237 S.Diag(D->getLocation(), 11238 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11239 << D; 11240 } 11241 continue; 11242 } 11243 } 11244 11245 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 11246 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", 11247 D->hasAttrs() ? &D->getAttrs() : nullptr); 11248 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), 11249 D->hasAttrs() ? &D->getAttrs() : nullptr); 11250 QualType PrivateTy = Type; 11251 11252 // Try if we can determine constant lengths for all array sections and avoid 11253 // the VLA. 11254 bool ConstantLengthOASE = false; 11255 if (OASE) { 11256 bool SingleElement; 11257 llvm::SmallVector<llvm::APSInt, 4> ArraySizes; 11258 ConstantLengthOASE = checkOMPArraySectionConstantForReduction( 11259 Context, OASE, SingleElement, ArraySizes); 11260 11261 // If we don't have a single element, we must emit a constant array type. 11262 if (ConstantLengthOASE && !SingleElement) { 11263 for (llvm::APSInt &Size : ArraySizes) 11264 PrivateTy = Context.getConstantArrayType( 11265 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0); 11266 } 11267 } 11268 11269 if ((OASE && !ConstantLengthOASE) || 11270 (!OASE && !ASE && 11271 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 11272 if (!Context.getTargetInfo().isVLASupported() && 11273 S.shouldDiagnoseTargetSupportFromOpenMP()) { 11274 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 11275 S.Diag(ELoc, diag::note_vla_unsupported); 11276 continue; 11277 } 11278 // For arrays/array sections only: 11279 // Create pseudo array type for private copy. The size for this array will 11280 // be generated during codegen. 11281 // For array subscripts or single variables Private Ty is the same as Type 11282 // (type of the variable or single array element). 11283 PrivateTy = Context.getVariableArrayType( 11284 Type, 11285 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue), 11286 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 11287 } else if (!ASE && !OASE && 11288 Context.getAsArrayType(D->getType().getNonReferenceType())) { 11289 PrivateTy = D->getType().getNonReferenceType(); 11290 } 11291 // Private copy. 11292 VarDecl *PrivateVD = 11293 buildVarDecl(S, ELoc, PrivateTy, D->getName(), 11294 D->hasAttrs() ? &D->getAttrs() : nullptr, 11295 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 11296 // Add initializer for private variable. 11297 Expr *Init = nullptr; 11298 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); 11299 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); 11300 if (DeclareReductionRef.isUsable()) { 11301 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 11302 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 11303 if (DRD->getInitializer()) { 11304 Init = DRDRef; 11305 RHSVD->setInit(DRDRef); 11306 RHSVD->setInitStyle(VarDecl::CallInit); 11307 } 11308 } else { 11309 switch (BOK) { 11310 case BO_Add: 11311 case BO_Xor: 11312 case BO_Or: 11313 case BO_LOr: 11314 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 11315 if (Type->isScalarType() || Type->isAnyComplexType()) 11316 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 11317 break; 11318 case BO_Mul: 11319 case BO_LAnd: 11320 if (Type->isScalarType() || Type->isAnyComplexType()) { 11321 // '*' and '&&' reduction ops - initializer is '1'. 11322 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 11323 } 11324 break; 11325 case BO_And: { 11326 // '&' reduction op - initializer is '~0'. 11327 QualType OrigType = Type; 11328 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 11329 Type = ComplexTy->getElementType(); 11330 if (Type->isRealFloatingType()) { 11331 llvm::APFloat InitValue = 11332 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), 11333 /*isIEEE=*/true); 11334 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 11335 Type, ELoc); 11336 } else if (Type->isScalarType()) { 11337 uint64_t Size = Context.getTypeSize(Type); 11338 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 11339 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 11340 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 11341 } 11342 if (Init && OrigType->isAnyComplexType()) { 11343 // Init = 0xFFFF + 0xFFFFi; 11344 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 11345 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 11346 } 11347 Type = OrigType; 11348 break; 11349 } 11350 case BO_LT: 11351 case BO_GT: { 11352 // 'min' reduction op - initializer is 'Largest representable number in 11353 // the reduction list item type'. 11354 // 'max' reduction op - initializer is 'Least representable number in 11355 // the reduction list item type'. 11356 if (Type->isIntegerType() || Type->isPointerType()) { 11357 bool IsSigned = Type->hasSignedIntegerRepresentation(); 11358 uint64_t Size = Context.getTypeSize(Type); 11359 QualType IntTy = 11360 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 11361 llvm::APInt InitValue = 11362 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 11363 : llvm::APInt::getMinValue(Size) 11364 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 11365 : llvm::APInt::getMaxValue(Size); 11366 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 11367 if (Type->isPointerType()) { 11368 // Cast to pointer type. 11369 ExprResult CastExpr = S.BuildCStyleCastExpr( 11370 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init); 11371 if (CastExpr.isInvalid()) 11372 continue; 11373 Init = CastExpr.get(); 11374 } 11375 } else if (Type->isRealFloatingType()) { 11376 llvm::APFloat InitValue = llvm::APFloat::getLargest( 11377 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 11378 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 11379 Type, ELoc); 11380 } 11381 break; 11382 } 11383 case BO_PtrMemD: 11384 case BO_PtrMemI: 11385 case BO_MulAssign: 11386 case BO_Div: 11387 case BO_Rem: 11388 case BO_Sub: 11389 case BO_Shl: 11390 case BO_Shr: 11391 case BO_LE: 11392 case BO_GE: 11393 case BO_EQ: 11394 case BO_NE: 11395 case BO_Cmp: 11396 case BO_AndAssign: 11397 case BO_XorAssign: 11398 case BO_OrAssign: 11399 case BO_Assign: 11400 case BO_AddAssign: 11401 case BO_SubAssign: 11402 case BO_DivAssign: 11403 case BO_RemAssign: 11404 case BO_ShlAssign: 11405 case BO_ShrAssign: 11406 case BO_Comma: 11407 llvm_unreachable("Unexpected reduction operation"); 11408 } 11409 } 11410 if (Init && DeclareReductionRef.isUnset()) 11411 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 11412 else if (!Init) 11413 S.ActOnUninitializedDecl(RHSVD); 11414 if (RHSVD->isInvalidDecl()) 11415 continue; 11416 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 11417 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) 11418 << Type << ReductionIdRange; 11419 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 11420 VarDecl::DeclarationOnly; 11421 S.Diag(D->getLocation(), 11422 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11423 << D; 11424 continue; 11425 } 11426 // Store initializer for single element in private copy. Will be used during 11427 // codegen. 11428 PrivateVD->setInit(RHSVD->getInit()); 11429 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 11430 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); 11431 ExprResult ReductionOp; 11432 if (DeclareReductionRef.isUsable()) { 11433 QualType RedTy = DeclareReductionRef.get()->getType(); 11434 QualType PtrRedTy = Context.getPointerType(RedTy); 11435 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 11436 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 11437 if (!BasePath.empty()) { 11438 LHS = S.DefaultLvalueConversion(LHS.get()); 11439 RHS = S.DefaultLvalueConversion(RHS.get()); 11440 LHS = ImplicitCastExpr::Create(Context, PtrRedTy, 11441 CK_UncheckedDerivedToBase, LHS.get(), 11442 &BasePath, LHS.get()->getValueKind()); 11443 RHS = ImplicitCastExpr::Create(Context, PtrRedTy, 11444 CK_UncheckedDerivedToBase, RHS.get(), 11445 &BasePath, RHS.get()->getValueKind()); 11446 } 11447 FunctionProtoType::ExtProtoInfo EPI; 11448 QualType Params[] = {PtrRedTy, PtrRedTy}; 11449 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 11450 auto *OVE = new (Context) OpaqueValueExpr( 11451 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 11452 S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); 11453 Expr *Args[] = {LHS.get(), RHS.get()}; 11454 ReductionOp = 11455 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); 11456 } else { 11457 ReductionOp = S.BuildBinOp( 11458 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE); 11459 if (ReductionOp.isUsable()) { 11460 if (BOK != BO_LT && BOK != BO_GT) { 11461 ReductionOp = 11462 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 11463 BO_Assign, LHSDRE, ReductionOp.get()); 11464 } else { 11465 auto *ConditionalOp = new (Context) 11466 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE, 11467 Type, VK_LValue, OK_Ordinary); 11468 ReductionOp = 11469 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(), 11470 BO_Assign, LHSDRE, ConditionalOp); 11471 } 11472 if (ReductionOp.isUsable()) 11473 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(), 11474 /*DiscardedValue*/ false); 11475 } 11476 if (!ReductionOp.isUsable()) 11477 continue; 11478 } 11479 11480 // OpenMP [2.15.4.6, Restrictions, p.2] 11481 // A list item that appears in an in_reduction clause of a task construct 11482 // must appear in a task_reduction clause of a construct associated with a 11483 // taskgroup region that includes the participating task in its taskgroup 11484 // set. The construct associated with the innermost region that meets this 11485 // condition must specify the same reduction-identifier as the in_reduction 11486 // clause. 11487 if (ClauseKind == OMPC_in_reduction) { 11488 SourceRange ParentSR; 11489 BinaryOperatorKind ParentBOK; 11490 const Expr *ParentReductionOp; 11491 Expr *ParentBOKTD, *ParentReductionOpTD; 11492 DSAStackTy::DSAVarData ParentBOKDSA = 11493 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK, 11494 ParentBOKTD); 11495 DSAStackTy::DSAVarData ParentReductionOpDSA = 11496 Stack->getTopMostTaskgroupReductionData( 11497 D, ParentSR, ParentReductionOp, ParentReductionOpTD); 11498 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown; 11499 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown; 11500 if (!IsParentBOK && !IsParentReductionOp) { 11501 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction); 11502 continue; 11503 } 11504 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) || 11505 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK || 11506 IsParentReductionOp) { 11507 bool EmitError = true; 11508 if (IsParentReductionOp && DeclareReductionRef.isUsable()) { 11509 llvm::FoldingSetNodeID RedId, ParentRedId; 11510 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true); 11511 DeclareReductionRef.get()->Profile(RedId, Context, 11512 /*Canonical=*/true); 11513 EmitError = RedId != ParentRedId; 11514 } 11515 if (EmitError) { 11516 S.Diag(ReductionId.getBeginLoc(), 11517 diag::err_omp_reduction_identifier_mismatch) 11518 << ReductionIdRange << RefExpr->getSourceRange(); 11519 S.Diag(ParentSR.getBegin(), 11520 diag::note_omp_previous_reduction_identifier) 11521 << ParentSR 11522 << (IsParentBOK ? ParentBOKDSA.RefExpr 11523 : ParentReductionOpDSA.RefExpr) 11524 ->getSourceRange(); 11525 continue; 11526 } 11527 } 11528 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD; 11529 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined."); 11530 } 11531 11532 DeclRefExpr *Ref = nullptr; 11533 Expr *VarsExpr = RefExpr->IgnoreParens(); 11534 if (!VD && !S.CurContext->isDependentContext()) { 11535 if (ASE || OASE) { 11536 TransformExprToCaptures RebuildToCapture(S, D); 11537 VarsExpr = 11538 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 11539 Ref = RebuildToCapture.getCapturedExpr(); 11540 } else { 11541 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); 11542 } 11543 if (!S.isOpenMPCapturedDecl(D)) { 11544 RD.ExprCaptures.emplace_back(Ref->getDecl()); 11545 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 11546 ExprResult RefRes = S.DefaultLvalueConversion(Ref); 11547 if (!RefRes.isUsable()) 11548 continue; 11549 ExprResult PostUpdateRes = 11550 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 11551 RefRes.get()); 11552 if (!PostUpdateRes.isUsable()) 11553 continue; 11554 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 11555 Stack->getCurrentDirective() == OMPD_taskgroup) { 11556 S.Diag(RefExpr->getExprLoc(), 11557 diag::err_omp_reduction_non_addressable_expression) 11558 << RefExpr->getSourceRange(); 11559 continue; 11560 } 11561 RD.ExprPostUpdates.emplace_back( 11562 S.IgnoredValueConversions(PostUpdateRes.get()).get()); 11563 } 11564 } 11565 } 11566 // All reduction items are still marked as reduction (to do not increase 11567 // code base size). 11568 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref); 11569 if (CurrDir == OMPD_taskgroup) { 11570 if (DeclareReductionRef.isUsable()) 11571 Stack->addTaskgroupReductionData(D, ReductionIdRange, 11572 DeclareReductionRef.get()); 11573 else 11574 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK); 11575 } 11576 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(), 11577 TaskgroupDescriptor); 11578 } 11579 return RD.Vars.empty(); 11580 } 11581 11582 OMPClause *Sema::ActOnOpenMPReductionClause( 11583 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 11584 SourceLocation ColonLoc, SourceLocation EndLoc, 11585 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 11586 ArrayRef<Expr *> UnresolvedReductions) { 11587 ReductionData RD(VarList.size()); 11588 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, 11589 StartLoc, LParenLoc, ColonLoc, EndLoc, 11590 ReductionIdScopeSpec, ReductionId, 11591 UnresolvedReductions, RD)) 11592 return nullptr; 11593 11594 return OMPReductionClause::Create( 11595 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 11596 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 11597 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 11598 buildPreInits(Context, RD.ExprCaptures), 11599 buildPostUpdate(*this, RD.ExprPostUpdates)); 11600 } 11601 11602 OMPClause *Sema::ActOnOpenMPTaskReductionClause( 11603 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 11604 SourceLocation ColonLoc, SourceLocation EndLoc, 11605 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 11606 ArrayRef<Expr *> UnresolvedReductions) { 11607 ReductionData RD(VarList.size()); 11608 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList, 11609 StartLoc, LParenLoc, ColonLoc, EndLoc, 11610 ReductionIdScopeSpec, ReductionId, 11611 UnresolvedReductions, RD)) 11612 return nullptr; 11613 11614 return OMPTaskReductionClause::Create( 11615 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 11616 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 11617 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 11618 buildPreInits(Context, RD.ExprCaptures), 11619 buildPostUpdate(*this, RD.ExprPostUpdates)); 11620 } 11621 11622 OMPClause *Sema::ActOnOpenMPInReductionClause( 11623 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 11624 SourceLocation ColonLoc, SourceLocation EndLoc, 11625 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 11626 ArrayRef<Expr *> UnresolvedReductions) { 11627 ReductionData RD(VarList.size()); 11628 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList, 11629 StartLoc, LParenLoc, ColonLoc, EndLoc, 11630 ReductionIdScopeSpec, ReductionId, 11631 UnresolvedReductions, RD)) 11632 return nullptr; 11633 11634 return OMPInReductionClause::Create( 11635 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 11636 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 11637 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors, 11638 buildPreInits(Context, RD.ExprCaptures), 11639 buildPostUpdate(*this, RD.ExprPostUpdates)); 11640 } 11641 11642 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 11643 SourceLocation LinLoc) { 11644 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 11645 LinKind == OMPC_LINEAR_unknown) { 11646 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 11647 return true; 11648 } 11649 return false; 11650 } 11651 11652 bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc, 11653 OpenMPLinearClauseKind LinKind, 11654 QualType Type) { 11655 const auto *VD = dyn_cast_or_null<VarDecl>(D); 11656 // A variable must not have an incomplete type or a reference type. 11657 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 11658 return true; 11659 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 11660 !Type->isReferenceType()) { 11661 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 11662 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 11663 return true; 11664 } 11665 Type = Type.getNonReferenceType(); 11666 11667 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions] 11668 // A variable that is privatized must not have a const-qualified type 11669 // unless it is of class type with a mutable member. This restriction does 11670 // not apply to the firstprivate clause. 11671 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc)) 11672 return true; 11673 11674 // A list item must be of integral or pointer type. 11675 Type = Type.getUnqualifiedType().getCanonicalType(); 11676 const auto *Ty = Type.getTypePtrOrNull(); 11677 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 11678 !Ty->isPointerType())) { 11679 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 11680 if (D) { 11681 bool IsDecl = 11682 !VD || 11683 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 11684 Diag(D->getLocation(), 11685 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11686 << D; 11687 } 11688 return true; 11689 } 11690 return false; 11691 } 11692 11693 OMPClause *Sema::ActOnOpenMPLinearClause( 11694 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 11695 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 11696 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 11697 SmallVector<Expr *, 8> Vars; 11698 SmallVector<Expr *, 8> Privates; 11699 SmallVector<Expr *, 8> Inits; 11700 SmallVector<Decl *, 4> ExprCaptures; 11701 SmallVector<Expr *, 4> ExprPostUpdates; 11702 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 11703 LinKind = OMPC_LINEAR_val; 11704 for (Expr *RefExpr : VarList) { 11705 assert(RefExpr && "NULL expr in OpenMP linear clause."); 11706 SourceLocation ELoc; 11707 SourceRange ERange; 11708 Expr *SimpleRefExpr = RefExpr; 11709 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11710 if (Res.second) { 11711 // It will be analyzed later. 11712 Vars.push_back(RefExpr); 11713 Privates.push_back(nullptr); 11714 Inits.push_back(nullptr); 11715 } 11716 ValueDecl *D = Res.first; 11717 if (!D) 11718 continue; 11719 11720 QualType Type = D->getType(); 11721 auto *VD = dyn_cast<VarDecl>(D); 11722 11723 // OpenMP [2.14.3.7, linear clause] 11724 // A list-item cannot appear in more than one linear clause. 11725 // A list-item that appears in a linear clause cannot appear in any 11726 // other data-sharing attribute clause. 11727 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 11728 if (DVar.RefExpr) { 11729 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 11730 << getOpenMPClauseName(OMPC_linear); 11731 reportOriginalDsa(*this, DSAStack, D, DVar); 11732 continue; 11733 } 11734 11735 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 11736 continue; 11737 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 11738 11739 // Build private copy of original var. 11740 VarDecl *Private = 11741 buildVarDecl(*this, ELoc, Type, D->getName(), 11742 D->hasAttrs() ? &D->getAttrs() : nullptr, 11743 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 11744 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 11745 // Build var to save initial value. 11746 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 11747 Expr *InitExpr; 11748 DeclRefExpr *Ref = nullptr; 11749 if (!VD && !CurContext->isDependentContext()) { 11750 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 11751 if (!isOpenMPCapturedDecl(D)) { 11752 ExprCaptures.push_back(Ref->getDecl()); 11753 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 11754 ExprResult RefRes = DefaultLvalueConversion(Ref); 11755 if (!RefRes.isUsable()) 11756 continue; 11757 ExprResult PostUpdateRes = 11758 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 11759 SimpleRefExpr, RefRes.get()); 11760 if (!PostUpdateRes.isUsable()) 11761 continue; 11762 ExprPostUpdates.push_back( 11763 IgnoredValueConversions(PostUpdateRes.get()).get()); 11764 } 11765 } 11766 } 11767 if (LinKind == OMPC_LINEAR_uval) 11768 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 11769 else 11770 InitExpr = VD ? SimpleRefExpr : Ref; 11771 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 11772 /*DirectInit=*/false); 11773 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 11774 11775 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 11776 Vars.push_back((VD || CurContext->isDependentContext()) 11777 ? RefExpr->IgnoreParens() 11778 : Ref); 11779 Privates.push_back(PrivateRef); 11780 Inits.push_back(InitRef); 11781 } 11782 11783 if (Vars.empty()) 11784 return nullptr; 11785 11786 Expr *StepExpr = Step; 11787 Expr *CalcStepExpr = nullptr; 11788 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 11789 !Step->isInstantiationDependent() && 11790 !Step->containsUnexpandedParameterPack()) { 11791 SourceLocation StepLoc = Step->getBeginLoc(); 11792 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 11793 if (Val.isInvalid()) 11794 return nullptr; 11795 StepExpr = Val.get(); 11796 11797 // Build var to save the step value. 11798 VarDecl *SaveVar = 11799 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 11800 ExprResult SaveRef = 11801 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 11802 ExprResult CalcStep = 11803 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 11804 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false); 11805 11806 // Warn about zero linear step (it would be probably better specified as 11807 // making corresponding variables 'const'). 11808 llvm::APSInt Result; 11809 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); 11810 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) 11811 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 11812 << (Vars.size() > 1); 11813 if (!IsConstant && CalcStep.isUsable()) { 11814 // Calculate the step beforehand instead of doing this on each iteration. 11815 // (This is not used if the number of iterations may be kfold-ed). 11816 CalcStepExpr = CalcStep.get(); 11817 } 11818 } 11819 11820 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 11821 ColonLoc, EndLoc, Vars, Privates, Inits, 11822 StepExpr, CalcStepExpr, 11823 buildPreInits(Context, ExprCaptures), 11824 buildPostUpdate(*this, ExprPostUpdates)); 11825 } 11826 11827 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 11828 Expr *NumIterations, Sema &SemaRef, 11829 Scope *S, DSAStackTy *Stack) { 11830 // Walk the vars and build update/final expressions for the CodeGen. 11831 SmallVector<Expr *, 8> Updates; 11832 SmallVector<Expr *, 8> Finals; 11833 Expr *Step = Clause.getStep(); 11834 Expr *CalcStep = Clause.getCalcStep(); 11835 // OpenMP [2.14.3.7, linear clause] 11836 // If linear-step is not specified it is assumed to be 1. 11837 if (!Step) 11838 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 11839 else if (CalcStep) 11840 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 11841 bool HasErrors = false; 11842 auto CurInit = Clause.inits().begin(); 11843 auto CurPrivate = Clause.privates().begin(); 11844 OpenMPLinearClauseKind LinKind = Clause.getModifier(); 11845 for (Expr *RefExpr : Clause.varlists()) { 11846 SourceLocation ELoc; 11847 SourceRange ERange; 11848 Expr *SimpleRefExpr = RefExpr; 11849 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange); 11850 ValueDecl *D = Res.first; 11851 if (Res.second || !D) { 11852 Updates.push_back(nullptr); 11853 Finals.push_back(nullptr); 11854 HasErrors = true; 11855 continue; 11856 } 11857 auto &&Info = Stack->isLoopControlVariable(D); 11858 // OpenMP [2.15.11, distribute simd Construct] 11859 // A list item may not appear in a linear clause, unless it is the loop 11860 // iteration variable. 11861 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) && 11862 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) { 11863 SemaRef.Diag(ELoc, 11864 diag::err_omp_linear_distribute_var_non_loop_iteration); 11865 Updates.push_back(nullptr); 11866 Finals.push_back(nullptr); 11867 HasErrors = true; 11868 continue; 11869 } 11870 Expr *InitExpr = *CurInit; 11871 11872 // Build privatized reference to the current linear var. 11873 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 11874 Expr *CapturedRef; 11875 if (LinKind == OMPC_LINEAR_uval) 11876 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 11877 else 11878 CapturedRef = 11879 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 11880 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 11881 /*RefersToCapture=*/true); 11882 11883 // Build update: Var = InitExpr + IV * Step 11884 ExprResult Update; 11885 if (!Info.first) 11886 Update = 11887 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, 11888 InitExpr, IV, Step, /* Subtract */ false); 11889 else 11890 Update = *CurPrivate; 11891 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(), 11892 /*DiscardedValue*/ false); 11893 11894 // Build final: Var = InitExpr + NumIterations * Step 11895 ExprResult Final; 11896 if (!Info.first) 11897 Final = 11898 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 11899 InitExpr, NumIterations, Step, /*Subtract=*/false); 11900 else 11901 Final = *CurPrivate; 11902 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(), 11903 /*DiscardedValue*/ false); 11904 11905 if (!Update.isUsable() || !Final.isUsable()) { 11906 Updates.push_back(nullptr); 11907 Finals.push_back(nullptr); 11908 HasErrors = true; 11909 } else { 11910 Updates.push_back(Update.get()); 11911 Finals.push_back(Final.get()); 11912 } 11913 ++CurInit; 11914 ++CurPrivate; 11915 } 11916 Clause.setUpdates(Updates); 11917 Clause.setFinals(Finals); 11918 return HasErrors; 11919 } 11920 11921 OMPClause *Sema::ActOnOpenMPAlignedClause( 11922 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 11923 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 11924 SmallVector<Expr *, 8> Vars; 11925 for (Expr *RefExpr : VarList) { 11926 assert(RefExpr && "NULL expr in OpenMP linear clause."); 11927 SourceLocation ELoc; 11928 SourceRange ERange; 11929 Expr *SimpleRefExpr = RefExpr; 11930 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11931 if (Res.second) { 11932 // It will be analyzed later. 11933 Vars.push_back(RefExpr); 11934 } 11935 ValueDecl *D = Res.first; 11936 if (!D) 11937 continue; 11938 11939 QualType QType = D->getType(); 11940 auto *VD = dyn_cast<VarDecl>(D); 11941 11942 // OpenMP [2.8.1, simd construct, Restrictions] 11943 // The type of list items appearing in the aligned clause must be 11944 // array, pointer, reference to array, or reference to pointer. 11945 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 11946 const Type *Ty = QType.getTypePtrOrNull(); 11947 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 11948 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 11949 << QType << getLangOpts().CPlusPlus << ERange; 11950 bool IsDecl = 11951 !VD || 11952 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 11953 Diag(D->getLocation(), 11954 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11955 << D; 11956 continue; 11957 } 11958 11959 // OpenMP [2.8.1, simd construct, Restrictions] 11960 // A list-item cannot appear in more than one aligned clause. 11961 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 11962 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange; 11963 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 11964 << getOpenMPClauseName(OMPC_aligned); 11965 continue; 11966 } 11967 11968 DeclRefExpr *Ref = nullptr; 11969 if (!VD && isOpenMPCapturedDecl(D)) 11970 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 11971 Vars.push_back(DefaultFunctionArrayConversion( 11972 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 11973 .get()); 11974 } 11975 11976 // OpenMP [2.8.1, simd construct, Description] 11977 // The parameter of the aligned clause, alignment, must be a constant 11978 // positive integer expression. 11979 // If no optional parameter is specified, implementation-defined default 11980 // alignments for SIMD instructions on the target platforms are assumed. 11981 if (Alignment != nullptr) { 11982 ExprResult AlignResult = 11983 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 11984 if (AlignResult.isInvalid()) 11985 return nullptr; 11986 Alignment = AlignResult.get(); 11987 } 11988 if (Vars.empty()) 11989 return nullptr; 11990 11991 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 11992 EndLoc, Vars, Alignment); 11993 } 11994 11995 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 11996 SourceLocation StartLoc, 11997 SourceLocation LParenLoc, 11998 SourceLocation EndLoc) { 11999 SmallVector<Expr *, 8> Vars; 12000 SmallVector<Expr *, 8> SrcExprs; 12001 SmallVector<Expr *, 8> DstExprs; 12002 SmallVector<Expr *, 8> AssignmentOps; 12003 for (Expr *RefExpr : VarList) { 12004 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 12005 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 12006 // It will be analyzed later. 12007 Vars.push_back(RefExpr); 12008 SrcExprs.push_back(nullptr); 12009 DstExprs.push_back(nullptr); 12010 AssignmentOps.push_back(nullptr); 12011 continue; 12012 } 12013 12014 SourceLocation ELoc = RefExpr->getExprLoc(); 12015 // OpenMP [2.1, C/C++] 12016 // A list item is a variable name. 12017 // OpenMP [2.14.4.1, Restrictions, p.1] 12018 // A list item that appears in a copyin clause must be threadprivate. 12019 auto *DE = dyn_cast<DeclRefExpr>(RefExpr); 12020 if (!DE || !isa<VarDecl>(DE->getDecl())) { 12021 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 12022 << 0 << RefExpr->getSourceRange(); 12023 continue; 12024 } 12025 12026 Decl *D = DE->getDecl(); 12027 auto *VD = cast<VarDecl>(D); 12028 12029 QualType Type = VD->getType(); 12030 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 12031 // It will be analyzed later. 12032 Vars.push_back(DE); 12033 SrcExprs.push_back(nullptr); 12034 DstExprs.push_back(nullptr); 12035 AssignmentOps.push_back(nullptr); 12036 continue; 12037 } 12038 12039 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 12040 // A list item that appears in a copyin clause must be threadprivate. 12041 if (!DSAStack->isThreadPrivate(VD)) { 12042 Diag(ELoc, diag::err_omp_required_access) 12043 << getOpenMPClauseName(OMPC_copyin) 12044 << getOpenMPDirectiveName(OMPD_threadprivate); 12045 continue; 12046 } 12047 12048 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 12049 // A variable of class type (or array thereof) that appears in a 12050 // copyin clause requires an accessible, unambiguous copy assignment 12051 // operator for the class type. 12052 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 12053 VarDecl *SrcVD = 12054 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(), 12055 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 12056 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr( 12057 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 12058 VarDecl *DstVD = 12059 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst", 12060 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 12061 DeclRefExpr *PseudoDstExpr = 12062 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 12063 // For arrays generate assignment operation for single element and replace 12064 // it by the original array element in CodeGen. 12065 ExprResult AssignmentOp = 12066 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr, 12067 PseudoSrcExpr); 12068 if (AssignmentOp.isInvalid()) 12069 continue; 12070 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 12071 /*DiscardedValue*/ false); 12072 if (AssignmentOp.isInvalid()) 12073 continue; 12074 12075 DSAStack->addDSA(VD, DE, OMPC_copyin); 12076 Vars.push_back(DE); 12077 SrcExprs.push_back(PseudoSrcExpr); 12078 DstExprs.push_back(PseudoDstExpr); 12079 AssignmentOps.push_back(AssignmentOp.get()); 12080 } 12081 12082 if (Vars.empty()) 12083 return nullptr; 12084 12085 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 12086 SrcExprs, DstExprs, AssignmentOps); 12087 } 12088 12089 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 12090 SourceLocation StartLoc, 12091 SourceLocation LParenLoc, 12092 SourceLocation EndLoc) { 12093 SmallVector<Expr *, 8> Vars; 12094 SmallVector<Expr *, 8> SrcExprs; 12095 SmallVector<Expr *, 8> DstExprs; 12096 SmallVector<Expr *, 8> AssignmentOps; 12097 for (Expr *RefExpr : VarList) { 12098 assert(RefExpr && "NULL expr in OpenMP linear clause."); 12099 SourceLocation ELoc; 12100 SourceRange ERange; 12101 Expr *SimpleRefExpr = RefExpr; 12102 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 12103 if (Res.second) { 12104 // It will be analyzed later. 12105 Vars.push_back(RefExpr); 12106 SrcExprs.push_back(nullptr); 12107 DstExprs.push_back(nullptr); 12108 AssignmentOps.push_back(nullptr); 12109 } 12110 ValueDecl *D = Res.first; 12111 if (!D) 12112 continue; 12113 12114 QualType Type = D->getType(); 12115 auto *VD = dyn_cast<VarDecl>(D); 12116 12117 // OpenMP [2.14.4.2, Restrictions, p.2] 12118 // A list item that appears in a copyprivate clause may not appear in a 12119 // private or firstprivate clause on the single construct. 12120 if (!VD || !DSAStack->isThreadPrivate(VD)) { 12121 DSAStackTy::DSAVarData DVar = 12122 DSAStack->getTopDSA(D, /*FromParent=*/false); 12123 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 12124 DVar.RefExpr) { 12125 Diag(ELoc, diag::err_omp_wrong_dsa) 12126 << getOpenMPClauseName(DVar.CKind) 12127 << getOpenMPClauseName(OMPC_copyprivate); 12128 reportOriginalDsa(*this, DSAStack, D, DVar); 12129 continue; 12130 } 12131 12132 // OpenMP [2.11.4.2, Restrictions, p.1] 12133 // All list items that appear in a copyprivate clause must be either 12134 // threadprivate or private in the enclosing context. 12135 if (DVar.CKind == OMPC_unknown) { 12136 DVar = DSAStack->getImplicitDSA(D, false); 12137 if (DVar.CKind == OMPC_shared) { 12138 Diag(ELoc, diag::err_omp_required_access) 12139 << getOpenMPClauseName(OMPC_copyprivate) 12140 << "threadprivate or private in the enclosing context"; 12141 reportOriginalDsa(*this, DSAStack, D, DVar); 12142 continue; 12143 } 12144 } 12145 } 12146 12147 // Variably modified types are not supported. 12148 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 12149 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 12150 << getOpenMPClauseName(OMPC_copyprivate) << Type 12151 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 12152 bool IsDecl = 12153 !VD || 12154 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 12155 Diag(D->getLocation(), 12156 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 12157 << D; 12158 continue; 12159 } 12160 12161 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 12162 // A variable of class type (or array thereof) that appears in a 12163 // copyin clause requires an accessible, unambiguous copy assignment 12164 // operator for the class type. 12165 Type = Context.getBaseElementType(Type.getNonReferenceType()) 12166 .getUnqualifiedType(); 12167 VarDecl *SrcVD = 12168 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src", 12169 D->hasAttrs() ? &D->getAttrs() : nullptr); 12170 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 12171 VarDecl *DstVD = 12172 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst", 12173 D->hasAttrs() ? &D->getAttrs() : nullptr); 12174 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 12175 ExprResult AssignmentOp = BuildBinOp( 12176 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr); 12177 if (AssignmentOp.isInvalid()) 12178 continue; 12179 AssignmentOp = 12180 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false); 12181 if (AssignmentOp.isInvalid()) 12182 continue; 12183 12184 // No need to mark vars as copyprivate, they are already threadprivate or 12185 // implicitly private. 12186 assert(VD || isOpenMPCapturedDecl(D)); 12187 Vars.push_back( 12188 VD ? RefExpr->IgnoreParens() 12189 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 12190 SrcExprs.push_back(PseudoSrcExpr); 12191 DstExprs.push_back(PseudoDstExpr); 12192 AssignmentOps.push_back(AssignmentOp.get()); 12193 } 12194 12195 if (Vars.empty()) 12196 return nullptr; 12197 12198 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 12199 Vars, SrcExprs, DstExprs, AssignmentOps); 12200 } 12201 12202 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 12203 SourceLocation StartLoc, 12204 SourceLocation LParenLoc, 12205 SourceLocation EndLoc) { 12206 if (VarList.empty()) 12207 return nullptr; 12208 12209 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 12210 } 12211 12212 OMPClause * 12213 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, 12214 SourceLocation DepLoc, SourceLocation ColonLoc, 12215 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 12216 SourceLocation LParenLoc, SourceLocation EndLoc) { 12217 if (DSAStack->getCurrentDirective() == OMPD_ordered && 12218 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 12219 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 12220 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 12221 return nullptr; 12222 } 12223 if (DSAStack->getCurrentDirective() != OMPD_ordered && 12224 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 12225 DepKind == OMPC_DEPEND_sink)) { 12226 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink}; 12227 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 12228 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 12229 /*Last=*/OMPC_DEPEND_unknown, Except) 12230 << getOpenMPClauseName(OMPC_depend); 12231 return nullptr; 12232 } 12233 SmallVector<Expr *, 8> Vars; 12234 DSAStackTy::OperatorOffsetTy OpsOffs; 12235 llvm::APSInt DepCounter(/*BitWidth=*/32); 12236 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 12237 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) { 12238 if (const Expr *OrderedCountExpr = 12239 DSAStack->getParentOrderedRegionParam().first) { 12240 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 12241 TotalDepCount.setIsUnsigned(/*Val=*/true); 12242 } 12243 } 12244 for (Expr *RefExpr : VarList) { 12245 assert(RefExpr && "NULL expr in OpenMP shared clause."); 12246 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 12247 // It will be analyzed later. 12248 Vars.push_back(RefExpr); 12249 continue; 12250 } 12251 12252 SourceLocation ELoc = RefExpr->getExprLoc(); 12253 Expr *SimpleExpr = RefExpr->IgnoreParenCasts(); 12254 if (DepKind == OMPC_DEPEND_sink) { 12255 if (DSAStack->getParentOrderedRegionParam().first && 12256 DepCounter >= TotalDepCount) { 12257 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 12258 continue; 12259 } 12260 ++DepCounter; 12261 // OpenMP [2.13.9, Summary] 12262 // depend(dependence-type : vec), where dependence-type is: 12263 // 'sink' and where vec is the iteration vector, which has the form: 12264 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 12265 // where n is the value specified by the ordered clause in the loop 12266 // directive, xi denotes the loop iteration variable of the i-th nested 12267 // loop associated with the loop directive, and di is a constant 12268 // non-negative integer. 12269 if (CurContext->isDependentContext()) { 12270 // It will be analyzed later. 12271 Vars.push_back(RefExpr); 12272 continue; 12273 } 12274 SimpleExpr = SimpleExpr->IgnoreImplicit(); 12275 OverloadedOperatorKind OOK = OO_None; 12276 SourceLocation OOLoc; 12277 Expr *LHS = SimpleExpr; 12278 Expr *RHS = nullptr; 12279 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 12280 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 12281 OOLoc = BO->getOperatorLoc(); 12282 LHS = BO->getLHS()->IgnoreParenImpCasts(); 12283 RHS = BO->getRHS()->IgnoreParenImpCasts(); 12284 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 12285 OOK = OCE->getOperator(); 12286 OOLoc = OCE->getOperatorLoc(); 12287 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 12288 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 12289 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 12290 OOK = MCE->getMethodDecl() 12291 ->getNameInfo() 12292 .getName() 12293 .getCXXOverloadedOperator(); 12294 OOLoc = MCE->getCallee()->getExprLoc(); 12295 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 12296 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 12297 } 12298 SourceLocation ELoc; 12299 SourceRange ERange; 12300 auto Res = getPrivateItem(*this, LHS, ELoc, ERange); 12301 if (Res.second) { 12302 // It will be analyzed later. 12303 Vars.push_back(RefExpr); 12304 } 12305 ValueDecl *D = Res.first; 12306 if (!D) 12307 continue; 12308 12309 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 12310 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 12311 continue; 12312 } 12313 if (RHS) { 12314 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 12315 RHS, OMPC_depend, /*StrictlyPositive=*/false); 12316 if (RHSRes.isInvalid()) 12317 continue; 12318 } 12319 if (!CurContext->isDependentContext() && 12320 DSAStack->getParentOrderedRegionParam().first && 12321 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 12322 const ValueDecl *VD = 12323 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue()); 12324 if (VD) 12325 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 12326 << 1 << VD; 12327 else 12328 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; 12329 continue; 12330 } 12331 OpsOffs.emplace_back(RHS, OOK); 12332 } else { 12333 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 12334 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 12335 (ASE && 12336 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() && 12337 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 12338 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 12339 << RefExpr->getSourceRange(); 12340 continue; 12341 } 12342 bool Suppress = getDiagnostics().getSuppressAllDiagnostics(); 12343 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 12344 ExprResult Res = 12345 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts()); 12346 getDiagnostics().setSuppressAllDiagnostics(Suppress); 12347 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) { 12348 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 12349 << RefExpr->getSourceRange(); 12350 continue; 12351 } 12352 } 12353 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 12354 } 12355 12356 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 12357 TotalDepCount > VarList.size() && 12358 DSAStack->getParentOrderedRegionParam().first && 12359 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { 12360 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 12361 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 12362 } 12363 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 12364 Vars.empty()) 12365 return nullptr; 12366 12367 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 12368 DepKind, DepLoc, ColonLoc, Vars, 12369 TotalDepCount.getZExtValue()); 12370 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) && 12371 DSAStack->isParentOrderedRegion()) 12372 DSAStack->addDoacrossDependClause(C, OpsOffs); 12373 return C; 12374 } 12375 12376 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, 12377 SourceLocation LParenLoc, 12378 SourceLocation EndLoc) { 12379 Expr *ValExpr = Device; 12380 Stmt *HelperValStmt = nullptr; 12381 12382 // OpenMP [2.9.1, Restrictions] 12383 // The device expression must evaluate to a non-negative integer value. 12384 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 12385 /*StrictlyPositive=*/false)) 12386 return nullptr; 12387 12388 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 12389 OpenMPDirectiveKind CaptureRegion = 12390 getOpenMPCaptureRegionForClause(DKind, OMPC_device); 12391 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 12392 ValExpr = MakeFullExpr(ValExpr).get(); 12393 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 12394 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 12395 HelperValStmt = buildPreInits(Context, Captures); 12396 } 12397 12398 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion, 12399 StartLoc, LParenLoc, EndLoc); 12400 } 12401 12402 static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 12403 DSAStackTy *Stack, QualType QTy, 12404 bool FullCheck = true) { 12405 NamedDecl *ND; 12406 if (QTy->isIncompleteType(&ND)) { 12407 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 12408 return false; 12409 } 12410 if (FullCheck && !SemaRef.CurContext->isDependentContext() && 12411 !QTy.isTrivialType(SemaRef.Context)) 12412 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR; 12413 return true; 12414 } 12415 12416 /// Return true if it can be proven that the provided array expression 12417 /// (array section or array subscript) does NOT specify the whole size of the 12418 /// array whose base type is \a BaseQTy. 12419 static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 12420 const Expr *E, 12421 QualType BaseQTy) { 12422 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 12423 12424 // If this is an array subscript, it refers to the whole size if the size of 12425 // the dimension is constant and equals 1. Also, an array section assumes the 12426 // format of an array subscript if no colon is used. 12427 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) { 12428 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 12429 return ATy->getSize().getSExtValue() != 1; 12430 // Size can't be evaluated statically. 12431 return false; 12432 } 12433 12434 assert(OASE && "Expecting array section if not an array subscript."); 12435 const Expr *LowerBound = OASE->getLowerBound(); 12436 const Expr *Length = OASE->getLength(); 12437 12438 // If there is a lower bound that does not evaluates to zero, we are not 12439 // covering the whole dimension. 12440 if (LowerBound) { 12441 Expr::EvalResult Result; 12442 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext())) 12443 return false; // Can't get the integer value as a constant. 12444 12445 llvm::APSInt ConstLowerBound = Result.Val.getInt(); 12446 if (ConstLowerBound.getSExtValue()) 12447 return true; 12448 } 12449 12450 // If we don't have a length we covering the whole dimension. 12451 if (!Length) 12452 return false; 12453 12454 // If the base is a pointer, we don't have a way to get the size of the 12455 // pointee. 12456 if (BaseQTy->isPointerType()) 12457 return false; 12458 12459 // We can only check if the length is the same as the size of the dimension 12460 // if we have a constant array. 12461 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 12462 if (!CATy) 12463 return false; 12464 12465 Expr::EvalResult Result; 12466 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 12467 return false; // Can't get the integer value as a constant. 12468 12469 llvm::APSInt ConstLength = Result.Val.getInt(); 12470 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 12471 } 12472 12473 // Return true if it can be proven that the provided array expression (array 12474 // section or array subscript) does NOT specify a single element of the array 12475 // whose base type is \a BaseQTy. 12476 static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 12477 const Expr *E, 12478 QualType BaseQTy) { 12479 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 12480 12481 // An array subscript always refer to a single element. Also, an array section 12482 // assumes the format of an array subscript if no colon is used. 12483 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) 12484 return false; 12485 12486 assert(OASE && "Expecting array section if not an array subscript."); 12487 const Expr *Length = OASE->getLength(); 12488 12489 // If we don't have a length we have to check if the array has unitary size 12490 // for this dimension. Also, we should always expect a length if the base type 12491 // is pointer. 12492 if (!Length) { 12493 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 12494 return ATy->getSize().getSExtValue() != 1; 12495 // We cannot assume anything. 12496 return false; 12497 } 12498 12499 // Check if the length evaluates to 1. 12500 Expr::EvalResult Result; 12501 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext())) 12502 return false; // Can't get the integer value as a constant. 12503 12504 llvm::APSInt ConstLength = Result.Val.getInt(); 12505 return ConstLength.getSExtValue() != 1; 12506 } 12507 12508 // Return the expression of the base of the mappable expression or null if it 12509 // cannot be determined and do all the necessary checks to see if the expression 12510 // is valid as a standalone mappable expression. In the process, record all the 12511 // components of the expression. 12512 static const Expr *checkMapClauseExpressionBase( 12513 Sema &SemaRef, Expr *E, 12514 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 12515 OpenMPClauseKind CKind, bool NoDiagnose) { 12516 SourceLocation ELoc = E->getExprLoc(); 12517 SourceRange ERange = E->getSourceRange(); 12518 12519 // The base of elements of list in a map clause have to be either: 12520 // - a reference to variable or field. 12521 // - a member expression. 12522 // - an array expression. 12523 // 12524 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 12525 // reference to 'r'. 12526 // 12527 // If we have: 12528 // 12529 // struct SS { 12530 // Bla S; 12531 // foo() { 12532 // #pragma omp target map (S.Arr[:12]); 12533 // } 12534 // } 12535 // 12536 // We want to retrieve the member expression 'this->S'; 12537 12538 const Expr *RelevantExpr = nullptr; 12539 12540 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2] 12541 // If a list item is an array section, it must specify contiguous storage. 12542 // 12543 // For this restriction it is sufficient that we make sure only references 12544 // to variables or fields and array expressions, and that no array sections 12545 // exist except in the rightmost expression (unless they cover the whole 12546 // dimension of the array). E.g. these would be invalid: 12547 // 12548 // r.ArrS[3:5].Arr[6:7] 12549 // 12550 // r.ArrS[3:5].x 12551 // 12552 // but these would be valid: 12553 // r.ArrS[3].Arr[6:7] 12554 // 12555 // r.ArrS[3].x 12556 12557 bool AllowUnitySizeArraySection = true; 12558 bool AllowWholeSizeArraySection = true; 12559 12560 while (!RelevantExpr) { 12561 E = E->IgnoreParenImpCasts(); 12562 12563 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) { 12564 if (!isa<VarDecl>(CurE->getDecl())) 12565 return nullptr; 12566 12567 RelevantExpr = CurE; 12568 12569 // If we got a reference to a declaration, we should not expect any array 12570 // section before that. 12571 AllowUnitySizeArraySection = false; 12572 AllowWholeSizeArraySection = false; 12573 12574 // Record the component. 12575 CurComponents.emplace_back(CurE, CurE->getDecl()); 12576 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) { 12577 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts(); 12578 12579 if (isa<CXXThisExpr>(BaseE)) 12580 // We found a base expression: this->Val. 12581 RelevantExpr = CurE; 12582 else 12583 E = BaseE; 12584 12585 if (!isa<FieldDecl>(CurE->getMemberDecl())) { 12586 if (!NoDiagnose) { 12587 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 12588 << CurE->getSourceRange(); 12589 return nullptr; 12590 } 12591 if (RelevantExpr) 12592 return nullptr; 12593 continue; 12594 } 12595 12596 auto *FD = cast<FieldDecl>(CurE->getMemberDecl()); 12597 12598 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 12599 // A bit-field cannot appear in a map clause. 12600 // 12601 if (FD->isBitField()) { 12602 if (!NoDiagnose) { 12603 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 12604 << CurE->getSourceRange() << getOpenMPClauseName(CKind); 12605 return nullptr; 12606 } 12607 if (RelevantExpr) 12608 return nullptr; 12609 continue; 12610 } 12611 12612 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 12613 // If the type of a list item is a reference to a type T then the type 12614 // will be considered to be T for all purposes of this clause. 12615 QualType CurType = BaseE->getType().getNonReferenceType(); 12616 12617 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 12618 // A list item cannot be a variable that is a member of a structure with 12619 // a union type. 12620 // 12621 if (CurType->isUnionType()) { 12622 if (!NoDiagnose) { 12623 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 12624 << CurE->getSourceRange(); 12625 return nullptr; 12626 } 12627 continue; 12628 } 12629 12630 // If we got a member expression, we should not expect any array section 12631 // before that: 12632 // 12633 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 12634 // If a list item is an element of a structure, only the rightmost symbol 12635 // of the variable reference can be an array section. 12636 // 12637 AllowUnitySizeArraySection = false; 12638 AllowWholeSizeArraySection = false; 12639 12640 // Record the component. 12641 CurComponents.emplace_back(CurE, FD); 12642 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) { 12643 E = CurE->getBase()->IgnoreParenImpCasts(); 12644 12645 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 12646 if (!NoDiagnose) { 12647 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 12648 << 0 << CurE->getSourceRange(); 12649 return nullptr; 12650 } 12651 continue; 12652 } 12653 12654 // If we got an array subscript that express the whole dimension we 12655 // can have any array expressions before. If it only expressing part of 12656 // the dimension, we can only have unitary-size array expressions. 12657 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, 12658 E->getType())) 12659 AllowWholeSizeArraySection = false; 12660 12661 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) { 12662 Expr::EvalResult Result; 12663 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) { 12664 if (!Result.Val.getInt().isNullValue()) { 12665 SemaRef.Diag(CurE->getIdx()->getExprLoc(), 12666 diag::err_omp_invalid_map_this_expr); 12667 SemaRef.Diag(CurE->getIdx()->getExprLoc(), 12668 diag::note_omp_invalid_subscript_on_this_ptr_map); 12669 } 12670 } 12671 RelevantExpr = TE; 12672 } 12673 12674 // Record the component - we don't have any declaration associated. 12675 CurComponents.emplace_back(CurE, nullptr); 12676 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) { 12677 assert(!NoDiagnose && "Array sections cannot be implicitly mapped."); 12678 E = CurE->getBase()->IgnoreParenImpCasts(); 12679 12680 QualType CurType = 12681 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 12682 12683 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 12684 // If the type of a list item is a reference to a type T then the type 12685 // will be considered to be T for all purposes of this clause. 12686 if (CurType->isReferenceType()) 12687 CurType = CurType->getPointeeType(); 12688 12689 bool IsPointer = CurType->isAnyPointerType(); 12690 12691 if (!IsPointer && !CurType->isArrayType()) { 12692 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 12693 << 0 << CurE->getSourceRange(); 12694 return nullptr; 12695 } 12696 12697 bool NotWhole = 12698 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType); 12699 bool NotUnity = 12700 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType); 12701 12702 if (AllowWholeSizeArraySection) { 12703 // Any array section is currently allowed. Allowing a whole size array 12704 // section implies allowing a unity array section as well. 12705 // 12706 // If this array section refers to the whole dimension we can still 12707 // accept other array sections before this one, except if the base is a 12708 // pointer. Otherwise, only unitary sections are accepted. 12709 if (NotWhole || IsPointer) 12710 AllowWholeSizeArraySection = false; 12711 } else if (AllowUnitySizeArraySection && NotUnity) { 12712 // A unity or whole array section is not allowed and that is not 12713 // compatible with the properties of the current array section. 12714 SemaRef.Diag( 12715 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 12716 << CurE->getSourceRange(); 12717 return nullptr; 12718 } 12719 12720 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) { 12721 Expr::EvalResult ResultR; 12722 Expr::EvalResult ResultL; 12723 if (CurE->getLength()->EvaluateAsInt(ResultR, 12724 SemaRef.getASTContext())) { 12725 if (!ResultR.Val.getInt().isOneValue()) { 12726 SemaRef.Diag(CurE->getLength()->getExprLoc(), 12727 diag::err_omp_invalid_map_this_expr); 12728 SemaRef.Diag(CurE->getLength()->getExprLoc(), 12729 diag::note_omp_invalid_length_on_this_ptr_mapping); 12730 } 12731 } 12732 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt( 12733 ResultL, SemaRef.getASTContext())) { 12734 if (!ResultL.Val.getInt().isNullValue()) { 12735 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(), 12736 diag::err_omp_invalid_map_this_expr); 12737 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(), 12738 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping); 12739 } 12740 } 12741 RelevantExpr = TE; 12742 } 12743 12744 // Record the component - we don't have any declaration associated. 12745 CurComponents.emplace_back(CurE, nullptr); 12746 } else { 12747 if (!NoDiagnose) { 12748 // If nothing else worked, this is not a valid map clause expression. 12749 SemaRef.Diag( 12750 ELoc, diag::err_omp_expected_named_var_member_or_array_expression) 12751 << ERange; 12752 } 12753 return nullptr; 12754 } 12755 } 12756 12757 return RelevantExpr; 12758 } 12759 12760 // Return true if expression E associated with value VD has conflicts with other 12761 // map information. 12762 static bool checkMapConflicts( 12763 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E, 12764 bool CurrentRegionOnly, 12765 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 12766 OpenMPClauseKind CKind) { 12767 assert(VD && E); 12768 SourceLocation ELoc = E->getExprLoc(); 12769 SourceRange ERange = E->getSourceRange(); 12770 12771 // In order to easily check the conflicts we need to match each component of 12772 // the expression under test with the components of the expressions that are 12773 // already in the stack. 12774 12775 assert(!CurComponents.empty() && "Map clause expression with no components!"); 12776 assert(CurComponents.back().getAssociatedDeclaration() == VD && 12777 "Map clause expression with unexpected base!"); 12778 12779 // Variables to help detecting enclosing problems in data environment nests. 12780 bool IsEnclosedByDataEnvironmentExpr = false; 12781 const Expr *EnclosingExpr = nullptr; 12782 12783 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 12784 VD, CurrentRegionOnly, 12785 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc, 12786 ERange, CKind, &EnclosingExpr, 12787 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef 12788 StackComponents, 12789 OpenMPClauseKind) { 12790 assert(!StackComponents.empty() && 12791 "Map clause expression with no components!"); 12792 assert(StackComponents.back().getAssociatedDeclaration() == VD && 12793 "Map clause expression with unexpected base!"); 12794 (void)VD; 12795 12796 // The whole expression in the stack. 12797 const Expr *RE = StackComponents.front().getAssociatedExpression(); 12798 12799 // Expressions must start from the same base. Here we detect at which 12800 // point both expressions diverge from each other and see if we can 12801 // detect if the memory referred to both expressions is contiguous and 12802 // do not overlap. 12803 auto CI = CurComponents.rbegin(); 12804 auto CE = CurComponents.rend(); 12805 auto SI = StackComponents.rbegin(); 12806 auto SE = StackComponents.rend(); 12807 for (; CI != CE && SI != SE; ++CI, ++SI) { 12808 12809 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 12810 // At most one list item can be an array item derived from a given 12811 // variable in map clauses of the same construct. 12812 if (CurrentRegionOnly && 12813 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 12814 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) && 12815 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 12816 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) { 12817 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 12818 diag::err_omp_multiple_array_items_in_map_clause) 12819 << CI->getAssociatedExpression()->getSourceRange(); 12820 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 12821 diag::note_used_here) 12822 << SI->getAssociatedExpression()->getSourceRange(); 12823 return true; 12824 } 12825 12826 // Do both expressions have the same kind? 12827 if (CI->getAssociatedExpression()->getStmtClass() != 12828 SI->getAssociatedExpression()->getStmtClass()) 12829 break; 12830 12831 // Are we dealing with different variables/fields? 12832 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 12833 break; 12834 } 12835 // Check if the extra components of the expressions in the enclosing 12836 // data environment are redundant for the current base declaration. 12837 // If they are, the maps completely overlap, which is legal. 12838 for (; SI != SE; ++SI) { 12839 QualType Type; 12840 if (const auto *ASE = 12841 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 12842 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 12843 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>( 12844 SI->getAssociatedExpression())) { 12845 const Expr *E = OASE->getBase()->IgnoreParenImpCasts(); 12846 Type = 12847 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 12848 } 12849 if (Type.isNull() || Type->isAnyPointerType() || 12850 checkArrayExpressionDoesNotReferToWholeSize( 12851 SemaRef, SI->getAssociatedExpression(), Type)) 12852 break; 12853 } 12854 12855 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 12856 // List items of map clauses in the same construct must not share 12857 // original storage. 12858 // 12859 // If the expressions are exactly the same or one is a subset of the 12860 // other, it means they are sharing storage. 12861 if (CI == CE && SI == SE) { 12862 if (CurrentRegionOnly) { 12863 if (CKind == OMPC_map) { 12864 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 12865 } else { 12866 assert(CKind == OMPC_to || CKind == OMPC_from); 12867 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 12868 << ERange; 12869 } 12870 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 12871 << RE->getSourceRange(); 12872 return true; 12873 } 12874 // If we find the same expression in the enclosing data environment, 12875 // that is legal. 12876 IsEnclosedByDataEnvironmentExpr = true; 12877 return false; 12878 } 12879 12880 QualType DerivedType = 12881 std::prev(CI)->getAssociatedDeclaration()->getType(); 12882 SourceLocation DerivedLoc = 12883 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 12884 12885 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 12886 // If the type of a list item is a reference to a type T then the type 12887 // will be considered to be T for all purposes of this clause. 12888 DerivedType = DerivedType.getNonReferenceType(); 12889 12890 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 12891 // A variable for which the type is pointer and an array section 12892 // derived from that variable must not appear as list items of map 12893 // clauses of the same construct. 12894 // 12895 // Also, cover one of the cases in: 12896 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 12897 // If any part of the original storage of a list item has corresponding 12898 // storage in the device data environment, all of the original storage 12899 // must have corresponding storage in the device data environment. 12900 // 12901 if (DerivedType->isAnyPointerType()) { 12902 if (CI == CE || SI == SE) { 12903 SemaRef.Diag( 12904 DerivedLoc, 12905 diag::err_omp_pointer_mapped_along_with_derived_section) 12906 << DerivedLoc; 12907 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 12908 << RE->getSourceRange(); 12909 return true; 12910 } 12911 if (CI->getAssociatedExpression()->getStmtClass() != 12912 SI->getAssociatedExpression()->getStmtClass() || 12913 CI->getAssociatedDeclaration()->getCanonicalDecl() == 12914 SI->getAssociatedDeclaration()->getCanonicalDecl()) { 12915 assert(CI != CE && SI != SE); 12916 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced) 12917 << DerivedLoc; 12918 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 12919 << RE->getSourceRange(); 12920 return true; 12921 } 12922 } 12923 12924 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 12925 // List items of map clauses in the same construct must not share 12926 // original storage. 12927 // 12928 // An expression is a subset of the other. 12929 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 12930 if (CKind == OMPC_map) { 12931 if (CI != CE || SI != SE) { 12932 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is 12933 // a pointer. 12934 auto Begin = 12935 CI != CE ? CurComponents.begin() : StackComponents.begin(); 12936 auto End = CI != CE ? CurComponents.end() : StackComponents.end(); 12937 auto It = Begin; 12938 while (It != End && !It->getAssociatedDeclaration()) 12939 std::advance(It, 1); 12940 assert(It != End && 12941 "Expected at least one component with the declaration."); 12942 if (It != Begin && It->getAssociatedDeclaration() 12943 ->getType() 12944 .getCanonicalType() 12945 ->isAnyPointerType()) { 12946 IsEnclosedByDataEnvironmentExpr = false; 12947 EnclosingExpr = nullptr; 12948 return false; 12949 } 12950 } 12951 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 12952 } else { 12953 assert(CKind == OMPC_to || CKind == OMPC_from); 12954 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 12955 << ERange; 12956 } 12957 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 12958 << RE->getSourceRange(); 12959 return true; 12960 } 12961 12962 // The current expression uses the same base as other expression in the 12963 // data environment but does not contain it completely. 12964 if (!CurrentRegionOnly && SI != SE) 12965 EnclosingExpr = RE; 12966 12967 // The current expression is a subset of the expression in the data 12968 // environment. 12969 IsEnclosedByDataEnvironmentExpr |= 12970 (!CurrentRegionOnly && CI != CE && SI == SE); 12971 12972 return false; 12973 }); 12974 12975 if (CurrentRegionOnly) 12976 return FoundError; 12977 12978 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 12979 // If any part of the original storage of a list item has corresponding 12980 // storage in the device data environment, all of the original storage must 12981 // have corresponding storage in the device data environment. 12982 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 12983 // If a list item is an element of a structure, and a different element of 12984 // the structure has a corresponding list item in the device data environment 12985 // prior to a task encountering the construct associated with the map clause, 12986 // then the list item must also have a corresponding list item in the device 12987 // data environment prior to the task encountering the construct. 12988 // 12989 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 12990 SemaRef.Diag(ELoc, 12991 diag::err_omp_original_storage_is_shared_and_does_not_contain) 12992 << ERange; 12993 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 12994 << EnclosingExpr->getSourceRange(); 12995 return true; 12996 } 12997 12998 return FoundError; 12999 } 13000 13001 namespace { 13002 // Utility struct that gathers all the related lists associated with a mappable 13003 // expression. 13004 struct MappableVarListInfo { 13005 // The list of expressions. 13006 ArrayRef<Expr *> VarList; 13007 // The list of processed expressions. 13008 SmallVector<Expr *, 16> ProcessedVarList; 13009 // The mappble components for each expression. 13010 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 13011 // The base declaration of the variable. 13012 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 13013 13014 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 13015 // We have a list of components and base declarations for each entry in the 13016 // variable list. 13017 VarComponents.reserve(VarList.size()); 13018 VarBaseDeclarations.reserve(VarList.size()); 13019 } 13020 }; 13021 } 13022 13023 // Check the validity of the provided variable list for the provided clause kind 13024 // \a CKind. In the check process the valid expressions, and mappable expression 13025 // components and variables are extracted and used to fill \a Vars, 13026 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and 13027 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'. 13028 static void 13029 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS, 13030 OpenMPClauseKind CKind, MappableVarListInfo &MVLI, 13031 SourceLocation StartLoc, 13032 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 13033 bool IsMapTypeImplicit = false) { 13034 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 13035 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 13036 "Unexpected clause kind with mappable expressions!"); 13037 13038 // Keep track of the mappable components and base declarations in this clause. 13039 // Each entry in the list is going to have a list of components associated. We 13040 // record each set of the components so that we can build the clause later on. 13041 // In the end we should have the same amount of declarations and component 13042 // lists. 13043 13044 for (Expr *RE : MVLI.VarList) { 13045 assert(RE && "Null expr in omp to/from/map clause"); 13046 SourceLocation ELoc = RE->getExprLoc(); 13047 13048 const Expr *VE = RE->IgnoreParenLValueCasts(); 13049 13050 if (VE->isValueDependent() || VE->isTypeDependent() || 13051 VE->isInstantiationDependent() || 13052 VE->containsUnexpandedParameterPack()) { 13053 // We can only analyze this information once the missing information is 13054 // resolved. 13055 MVLI.ProcessedVarList.push_back(RE); 13056 continue; 13057 } 13058 13059 Expr *SimpleExpr = RE->IgnoreParenCasts(); 13060 13061 if (!RE->IgnoreParenImpCasts()->isLValue()) { 13062 SemaRef.Diag(ELoc, 13063 diag::err_omp_expected_named_var_member_or_array_expression) 13064 << RE->getSourceRange(); 13065 continue; 13066 } 13067 13068 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 13069 ValueDecl *CurDeclaration = nullptr; 13070 13071 // Obtain the array or member expression bases if required. Also, fill the 13072 // components array with all the components identified in the process. 13073 const Expr *BE = checkMapClauseExpressionBase( 13074 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false); 13075 if (!BE) 13076 continue; 13077 13078 assert(!CurComponents.empty() && 13079 "Invalid mappable expression information."); 13080 13081 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) { 13082 // Add store "this" pointer to class in DSAStackTy for future checking 13083 DSAS->addMappedClassesQualTypes(TE->getType()); 13084 // Skip restriction checking for variable or field declarations 13085 MVLI.ProcessedVarList.push_back(RE); 13086 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 13087 MVLI.VarComponents.back().append(CurComponents.begin(), 13088 CurComponents.end()); 13089 MVLI.VarBaseDeclarations.push_back(nullptr); 13090 continue; 13091 } 13092 13093 // For the following checks, we rely on the base declaration which is 13094 // expected to be associated with the last component. The declaration is 13095 // expected to be a variable or a field (if 'this' is being mapped). 13096 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 13097 assert(CurDeclaration && "Null decl on map clause."); 13098 assert( 13099 CurDeclaration->isCanonicalDecl() && 13100 "Expecting components to have associated only canonical declarations."); 13101 13102 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 13103 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 13104 13105 assert((VD || FD) && "Only variables or fields are expected here!"); 13106 (void)FD; 13107 13108 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 13109 // threadprivate variables cannot appear in a map clause. 13110 // OpenMP 4.5 [2.10.5, target update Construct] 13111 // threadprivate variables cannot appear in a from clause. 13112 if (VD && DSAS->isThreadPrivate(VD)) { 13113 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 13114 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 13115 << getOpenMPClauseName(CKind); 13116 reportOriginalDsa(SemaRef, DSAS, VD, DVar); 13117 continue; 13118 } 13119 13120 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 13121 // A list item cannot appear in both a map clause and a data-sharing 13122 // attribute clause on the same construct. 13123 13124 // Check conflicts with other map clause expressions. We check the conflicts 13125 // with the current construct separately from the enclosing data 13126 // environment, because the restrictions are different. We only have to 13127 // check conflicts across regions for the map clauses. 13128 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 13129 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 13130 break; 13131 if (CKind == OMPC_map && 13132 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 13133 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 13134 break; 13135 13136 // OpenMP 4.5 [2.10.5, target update Construct] 13137 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 13138 // If the type of a list item is a reference to a type T then the type will 13139 // be considered to be T for all purposes of this clause. 13140 auto I = llvm::find_if( 13141 CurComponents, 13142 [](const OMPClauseMappableExprCommon::MappableComponent &MC) { 13143 return MC.getAssociatedDeclaration(); 13144 }); 13145 assert(I != CurComponents.end() && "Null decl on map clause."); 13146 QualType Type = 13147 I->getAssociatedDeclaration()->getType().getNonReferenceType(); 13148 13149 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 13150 // A list item in a to or from clause must have a mappable type. 13151 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 13152 // A list item must have a mappable type. 13153 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 13154 DSAS, Type)) 13155 continue; 13156 13157 if (CKind == OMPC_map) { 13158 // target enter data 13159 // OpenMP [2.10.2, Restrictions, p. 99] 13160 // A map-type must be specified in all map clauses and must be either 13161 // to or alloc. 13162 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 13163 if (DKind == OMPD_target_enter_data && 13164 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 13165 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 13166 << (IsMapTypeImplicit ? 1 : 0) 13167 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 13168 << getOpenMPDirectiveName(DKind); 13169 continue; 13170 } 13171 13172 // target exit_data 13173 // OpenMP [2.10.3, Restrictions, p. 102] 13174 // A map-type must be specified in all map clauses and must be either 13175 // from, release, or delete. 13176 if (DKind == OMPD_target_exit_data && 13177 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 13178 MapType == OMPC_MAP_delete)) { 13179 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 13180 << (IsMapTypeImplicit ? 1 : 0) 13181 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 13182 << getOpenMPDirectiveName(DKind); 13183 continue; 13184 } 13185 13186 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 13187 // A list item cannot appear in both a map clause and a data-sharing 13188 // attribute clause on the same construct 13189 if (VD && isOpenMPTargetExecutionDirective(DKind)) { 13190 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false); 13191 if (isOpenMPPrivate(DVar.CKind)) { 13192 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 13193 << getOpenMPClauseName(DVar.CKind) 13194 << getOpenMPClauseName(OMPC_map) 13195 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 13196 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar); 13197 continue; 13198 } 13199 } 13200 } 13201 13202 // Save the current expression. 13203 MVLI.ProcessedVarList.push_back(RE); 13204 13205 // Store the components in the stack so that they can be used to check 13206 // against other clauses later on. 13207 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 13208 /*WhereFoundClauseKind=*/OMPC_map); 13209 13210 // Save the components and declaration to create the clause. For purposes of 13211 // the clause creation, any component list that has has base 'this' uses 13212 // null as base declaration. 13213 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 13214 MVLI.VarComponents.back().append(CurComponents.begin(), 13215 CurComponents.end()); 13216 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 13217 : CurDeclaration); 13218 } 13219 } 13220 13221 OMPClause * 13222 Sema::ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers, 13223 ArrayRef<SourceLocation> MapTypeModifiersLoc, 13224 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 13225 SourceLocation MapLoc, SourceLocation ColonLoc, 13226 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 13227 SourceLocation LParenLoc, SourceLocation EndLoc) { 13228 MappableVarListInfo MVLI(VarList); 13229 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc, 13230 MapType, IsMapTypeImplicit); 13231 13232 OpenMPMapModifierKind Modifiers[] = { OMPC_MAP_MODIFIER_unknown, 13233 OMPC_MAP_MODIFIER_unknown }; 13234 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers]; 13235 13236 // Process map-type-modifiers, flag errors for duplicate modifiers. 13237 unsigned Count = 0; 13238 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) { 13239 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown && 13240 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) { 13241 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier); 13242 continue; 13243 } 13244 assert(Count < OMPMapClause::NumberOfModifiers && 13245 "Modifiers exceed the allowed number of map type modifiers"); 13246 Modifiers[Count] = MapTypeModifiers[I]; 13247 ModifiersLoc[Count] = MapTypeModifiersLoc[I]; 13248 ++Count; 13249 } 13250 13251 // We need to produce a map clause even if we don't have variables so that 13252 // other diagnostics related with non-existing map clauses are accurate. 13253 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, 13254 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 13255 MVLI.VarComponents, Modifiers, ModifiersLoc, 13256 MapType, IsMapTypeImplicit, MapLoc); 13257 } 13258 13259 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 13260 TypeResult ParsedType) { 13261 assert(ParsedType.isUsable()); 13262 13263 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 13264 if (ReductionType.isNull()) 13265 return QualType(); 13266 13267 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 13268 // A type name in a declare reduction directive cannot be a function type, an 13269 // array type, a reference type, or a type qualified with const, volatile or 13270 // restrict. 13271 if (ReductionType.hasQualifiers()) { 13272 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 13273 return QualType(); 13274 } 13275 13276 if (ReductionType->isFunctionType()) { 13277 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 13278 return QualType(); 13279 } 13280 if (ReductionType->isReferenceType()) { 13281 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 13282 return QualType(); 13283 } 13284 if (ReductionType->isArrayType()) { 13285 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 13286 return QualType(); 13287 } 13288 return ReductionType; 13289 } 13290 13291 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 13292 Scope *S, DeclContext *DC, DeclarationName Name, 13293 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 13294 AccessSpecifier AS, Decl *PrevDeclInScope) { 13295 SmallVector<Decl *, 8> Decls; 13296 Decls.reserve(ReductionTypes.size()); 13297 13298 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 13299 forRedeclarationInCurContext()); 13300 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 13301 // A reduction-identifier may not be re-declared in the current scope for the 13302 // same type or for a type that is compatible according to the base language 13303 // rules. 13304 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 13305 OMPDeclareReductionDecl *PrevDRD = nullptr; 13306 bool InCompoundScope = true; 13307 if (S != nullptr) { 13308 // Find previous declaration with the same name not referenced in other 13309 // declarations. 13310 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 13311 InCompoundScope = 13312 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 13313 LookupName(Lookup, S); 13314 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 13315 /*AllowInlineNamespace=*/false); 13316 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 13317 LookupResult::Filter Filter = Lookup.makeFilter(); 13318 while (Filter.hasNext()) { 13319 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 13320 if (InCompoundScope) { 13321 auto I = UsedAsPrevious.find(PrevDecl); 13322 if (I == UsedAsPrevious.end()) 13323 UsedAsPrevious[PrevDecl] = false; 13324 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope()) 13325 UsedAsPrevious[D] = true; 13326 } 13327 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 13328 PrevDecl->getLocation(); 13329 } 13330 Filter.done(); 13331 if (InCompoundScope) { 13332 for (const auto &PrevData : UsedAsPrevious) { 13333 if (!PrevData.second) { 13334 PrevDRD = PrevData.first; 13335 break; 13336 } 13337 } 13338 } 13339 } else if (PrevDeclInScope != nullptr) { 13340 auto *PrevDRDInScope = PrevDRD = 13341 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 13342 do { 13343 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 13344 PrevDRDInScope->getLocation(); 13345 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 13346 } while (PrevDRDInScope != nullptr); 13347 } 13348 for (const auto &TyData : ReductionTypes) { 13349 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 13350 bool Invalid = false; 13351 if (I != PreviousRedeclTypes.end()) { 13352 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 13353 << TyData.first; 13354 Diag(I->second, diag::note_previous_definition); 13355 Invalid = true; 13356 } 13357 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 13358 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 13359 Name, TyData.first, PrevDRD); 13360 DC->addDecl(DRD); 13361 DRD->setAccess(AS); 13362 Decls.push_back(DRD); 13363 if (Invalid) 13364 DRD->setInvalidDecl(); 13365 else 13366 PrevDRD = DRD; 13367 } 13368 13369 return DeclGroupPtrTy::make( 13370 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 13371 } 13372 13373 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 13374 auto *DRD = cast<OMPDeclareReductionDecl>(D); 13375 13376 // Enter new function scope. 13377 PushFunctionScope(); 13378 setFunctionHasBranchProtectedScope(); 13379 getCurFunction()->setHasOMPDeclareReductionCombiner(); 13380 13381 if (S != nullptr) 13382 PushDeclContext(S, DRD); 13383 else 13384 CurContext = DRD; 13385 13386 PushExpressionEvaluationContext( 13387 ExpressionEvaluationContext::PotentiallyEvaluated); 13388 13389 QualType ReductionType = DRD->getType(); 13390 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 13391 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 13392 // uses semantics of argument handles by value, but it should be passed by 13393 // reference. C lang does not support references, so pass all parameters as 13394 // pointers. 13395 // Create 'T omp_in;' variable. 13396 VarDecl *OmpInParm = 13397 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 13398 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 13399 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 13400 // uses semantics of argument handles by value, but it should be passed by 13401 // reference. C lang does not support references, so pass all parameters as 13402 // pointers. 13403 // Create 'T omp_out;' variable. 13404 VarDecl *OmpOutParm = 13405 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 13406 if (S != nullptr) { 13407 PushOnScopeChains(OmpInParm, S); 13408 PushOnScopeChains(OmpOutParm, S); 13409 } else { 13410 DRD->addDecl(OmpInParm); 13411 DRD->addDecl(OmpOutParm); 13412 } 13413 Expr *InE = 13414 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation()); 13415 Expr *OutE = 13416 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation()); 13417 DRD->setCombinerData(InE, OutE); 13418 } 13419 13420 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 13421 auto *DRD = cast<OMPDeclareReductionDecl>(D); 13422 DiscardCleanupsInEvaluationContext(); 13423 PopExpressionEvaluationContext(); 13424 13425 PopDeclContext(); 13426 PopFunctionScopeInfo(); 13427 13428 if (Combiner != nullptr) 13429 DRD->setCombiner(Combiner); 13430 else 13431 DRD->setInvalidDecl(); 13432 } 13433 13434 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 13435 auto *DRD = cast<OMPDeclareReductionDecl>(D); 13436 13437 // Enter new function scope. 13438 PushFunctionScope(); 13439 setFunctionHasBranchProtectedScope(); 13440 13441 if (S != nullptr) 13442 PushDeclContext(S, DRD); 13443 else 13444 CurContext = DRD; 13445 13446 PushExpressionEvaluationContext( 13447 ExpressionEvaluationContext::PotentiallyEvaluated); 13448 13449 QualType ReductionType = DRD->getType(); 13450 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 13451 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 13452 // uses semantics of argument handles by value, but it should be passed by 13453 // reference. C lang does not support references, so pass all parameters as 13454 // pointers. 13455 // Create 'T omp_priv;' variable. 13456 VarDecl *OmpPrivParm = 13457 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 13458 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 13459 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 13460 // uses semantics of argument handles by value, but it should be passed by 13461 // reference. C lang does not support references, so pass all parameters as 13462 // pointers. 13463 // Create 'T omp_orig;' variable. 13464 VarDecl *OmpOrigParm = 13465 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 13466 if (S != nullptr) { 13467 PushOnScopeChains(OmpPrivParm, S); 13468 PushOnScopeChains(OmpOrigParm, S); 13469 } else { 13470 DRD->addDecl(OmpPrivParm); 13471 DRD->addDecl(OmpOrigParm); 13472 } 13473 Expr *OrigE = 13474 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation()); 13475 Expr *PrivE = 13476 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation()); 13477 DRD->setInitializerData(OrigE, PrivE); 13478 return OmpPrivParm; 13479 } 13480 13481 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 13482 VarDecl *OmpPrivParm) { 13483 auto *DRD = cast<OMPDeclareReductionDecl>(D); 13484 DiscardCleanupsInEvaluationContext(); 13485 PopExpressionEvaluationContext(); 13486 13487 PopDeclContext(); 13488 PopFunctionScopeInfo(); 13489 13490 if (Initializer != nullptr) { 13491 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit); 13492 } else if (OmpPrivParm->hasInit()) { 13493 DRD->setInitializer(OmpPrivParm->getInit(), 13494 OmpPrivParm->isDirectInit() 13495 ? OMPDeclareReductionDecl::DirectInit 13496 : OMPDeclareReductionDecl::CopyInit); 13497 } else { 13498 DRD->setInvalidDecl(); 13499 } 13500 } 13501 13502 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 13503 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 13504 for (Decl *D : DeclReductions.get()) { 13505 if (IsValid) { 13506 if (S) 13507 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S, 13508 /*AddToContext=*/false); 13509 } else { 13510 D->setInvalidDecl(); 13511 } 13512 } 13513 return DeclReductions; 13514 } 13515 13516 TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) { 13517 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S); 13518 QualType T = TInfo->getType(); 13519 if (D.isInvalidType()) 13520 return true; 13521 13522 if (getLangOpts().CPlusPlus) { 13523 // Check that there are no default arguments (C++ only). 13524 CheckExtraCXXDefaultArguments(D); 13525 } 13526 13527 return CreateParsedType(T, TInfo); 13528 } 13529 13530 QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc, 13531 TypeResult ParsedType) { 13532 assert(ParsedType.isUsable() && "Expect usable parsed mapper type"); 13533 13534 QualType MapperType = GetTypeFromParser(ParsedType.get()); 13535 assert(!MapperType.isNull() && "Expect valid mapper type"); 13536 13537 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 13538 // The type must be of struct, union or class type in C and C++ 13539 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) { 13540 Diag(TyLoc, diag::err_omp_mapper_wrong_type); 13541 return QualType(); 13542 } 13543 return MapperType; 13544 } 13545 13546 OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart( 13547 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType, 13548 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS, 13549 Decl *PrevDeclInScope) { 13550 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName, 13551 forRedeclarationInCurContext()); 13552 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions 13553 // A mapper-identifier may not be redeclared in the current scope for the 13554 // same type or for a type that is compatible according to the base language 13555 // rules. 13556 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 13557 OMPDeclareMapperDecl *PrevDMD = nullptr; 13558 bool InCompoundScope = true; 13559 if (S != nullptr) { 13560 // Find previous declaration with the same name not referenced in other 13561 // declarations. 13562 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 13563 InCompoundScope = 13564 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 13565 LookupName(Lookup, S); 13566 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 13567 /*AllowInlineNamespace=*/false); 13568 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious; 13569 LookupResult::Filter Filter = Lookup.makeFilter(); 13570 while (Filter.hasNext()) { 13571 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next()); 13572 if (InCompoundScope) { 13573 auto I = UsedAsPrevious.find(PrevDecl); 13574 if (I == UsedAsPrevious.end()) 13575 UsedAsPrevious[PrevDecl] = false; 13576 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope()) 13577 UsedAsPrevious[D] = true; 13578 } 13579 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 13580 PrevDecl->getLocation(); 13581 } 13582 Filter.done(); 13583 if (InCompoundScope) { 13584 for (const auto &PrevData : UsedAsPrevious) { 13585 if (!PrevData.second) { 13586 PrevDMD = PrevData.first; 13587 break; 13588 } 13589 } 13590 } 13591 } else if (PrevDeclInScope) { 13592 auto *PrevDMDInScope = PrevDMD = 13593 cast<OMPDeclareMapperDecl>(PrevDeclInScope); 13594 do { 13595 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] = 13596 PrevDMDInScope->getLocation(); 13597 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope(); 13598 } while (PrevDMDInScope != nullptr); 13599 } 13600 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType()); 13601 bool Invalid = false; 13602 if (I != PreviousRedeclTypes.end()) { 13603 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition) 13604 << MapperType << Name; 13605 Diag(I->second, diag::note_previous_definition); 13606 Invalid = true; 13607 } 13608 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name, 13609 MapperType, VN, PrevDMD); 13610 DC->addDecl(DMD); 13611 DMD->setAccess(AS); 13612 if (Invalid) 13613 DMD->setInvalidDecl(); 13614 13615 // Enter new function scope. 13616 PushFunctionScope(); 13617 setFunctionHasBranchProtectedScope(); 13618 13619 CurContext = DMD; 13620 13621 return DMD; 13622 } 13623 13624 void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD, 13625 Scope *S, 13626 QualType MapperType, 13627 SourceLocation StartLoc, 13628 DeclarationName VN) { 13629 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString()); 13630 if (S) 13631 PushOnScopeChains(VD, S); 13632 else 13633 DMD->addDecl(VD); 13634 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc); 13635 DMD->setMapperVarRef(MapperVarRefExpr); 13636 } 13637 13638 Sema::DeclGroupPtrTy 13639 Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S, 13640 ArrayRef<OMPClause *> ClauseList) { 13641 PopDeclContext(); 13642 PopFunctionScopeInfo(); 13643 13644 if (D) { 13645 if (S) 13646 PushOnScopeChains(D, S, /*AddToContext=*/false); 13647 D->CreateClauses(Context, ClauseList); 13648 } 13649 13650 return DeclGroupPtrTy::make(DeclGroupRef(D)); 13651 } 13652 13653 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 13654 SourceLocation StartLoc, 13655 SourceLocation LParenLoc, 13656 SourceLocation EndLoc) { 13657 Expr *ValExpr = NumTeams; 13658 Stmt *HelperValStmt = nullptr; 13659 13660 // OpenMP [teams Constrcut, Restrictions] 13661 // The num_teams expression must evaluate to a positive integer value. 13662 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 13663 /*StrictlyPositive=*/true)) 13664 return nullptr; 13665 13666 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 13667 OpenMPDirectiveKind CaptureRegion = 13668 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams); 13669 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 13670 ValExpr = MakeFullExpr(ValExpr).get(); 13671 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 13672 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 13673 HelperValStmt = buildPreInits(Context, Captures); 13674 } 13675 13676 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 13677 StartLoc, LParenLoc, EndLoc); 13678 } 13679 13680 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 13681 SourceLocation StartLoc, 13682 SourceLocation LParenLoc, 13683 SourceLocation EndLoc) { 13684 Expr *ValExpr = ThreadLimit; 13685 Stmt *HelperValStmt = nullptr; 13686 13687 // OpenMP [teams Constrcut, Restrictions] 13688 // The thread_limit expression must evaluate to a positive integer value. 13689 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 13690 /*StrictlyPositive=*/true)) 13691 return nullptr; 13692 13693 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 13694 OpenMPDirectiveKind CaptureRegion = 13695 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit); 13696 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 13697 ValExpr = MakeFullExpr(ValExpr).get(); 13698 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 13699 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 13700 HelperValStmt = buildPreInits(Context, Captures); 13701 } 13702 13703 return new (Context) OMPThreadLimitClause( 13704 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 13705 } 13706 13707 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 13708 SourceLocation StartLoc, 13709 SourceLocation LParenLoc, 13710 SourceLocation EndLoc) { 13711 Expr *ValExpr = Priority; 13712 13713 // OpenMP [2.9.1, task Constrcut] 13714 // The priority-value is a non-negative numerical scalar expression. 13715 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority, 13716 /*StrictlyPositive=*/false)) 13717 return nullptr; 13718 13719 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc); 13720 } 13721 13722 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 13723 SourceLocation StartLoc, 13724 SourceLocation LParenLoc, 13725 SourceLocation EndLoc) { 13726 Expr *ValExpr = Grainsize; 13727 13728 // OpenMP [2.9.2, taskloop Constrcut] 13729 // The parameter of the grainsize clause must be a positive integer 13730 // expression. 13731 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize, 13732 /*StrictlyPositive=*/true)) 13733 return nullptr; 13734 13735 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc); 13736 } 13737 13738 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 13739 SourceLocation StartLoc, 13740 SourceLocation LParenLoc, 13741 SourceLocation EndLoc) { 13742 Expr *ValExpr = NumTasks; 13743 13744 // OpenMP [2.9.2, taskloop Constrcut] 13745 // The parameter of the num_tasks clause must be a positive integer 13746 // expression. 13747 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks, 13748 /*StrictlyPositive=*/true)) 13749 return nullptr; 13750 13751 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc); 13752 } 13753 13754 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 13755 SourceLocation LParenLoc, 13756 SourceLocation EndLoc) { 13757 // OpenMP [2.13.2, critical construct, Description] 13758 // ... where hint-expression is an integer constant expression that evaluates 13759 // to a valid lock hint. 13760 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 13761 if (HintExpr.isInvalid()) 13762 return nullptr; 13763 return new (Context) 13764 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 13765 } 13766 13767 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 13768 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 13769 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 13770 SourceLocation EndLoc) { 13771 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 13772 std::string Values; 13773 Values += "'"; 13774 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 13775 Values += "'"; 13776 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 13777 << Values << getOpenMPClauseName(OMPC_dist_schedule); 13778 return nullptr; 13779 } 13780 Expr *ValExpr = ChunkSize; 13781 Stmt *HelperValStmt = nullptr; 13782 if (ChunkSize) { 13783 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 13784 !ChunkSize->isInstantiationDependent() && 13785 !ChunkSize->containsUnexpandedParameterPack()) { 13786 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc(); 13787 ExprResult Val = 13788 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 13789 if (Val.isInvalid()) 13790 return nullptr; 13791 13792 ValExpr = Val.get(); 13793 13794 // OpenMP [2.7.1, Restrictions] 13795 // chunk_size must be a loop invariant integer expression with a positive 13796 // value. 13797 llvm::APSInt Result; 13798 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 13799 if (Result.isSigned() && !Result.isStrictlyPositive()) { 13800 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 13801 << "dist_schedule" << ChunkSize->getSourceRange(); 13802 return nullptr; 13803 } 13804 } else if (getOpenMPCaptureRegionForClause( 13805 DSAStack->getCurrentDirective(), OMPC_dist_schedule) != 13806 OMPD_unknown && 13807 !CurContext->isDependentContext()) { 13808 ValExpr = MakeFullExpr(ValExpr).get(); 13809 llvm::MapVector<const Expr *, DeclRefExpr *> Captures; 13810 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 13811 HelperValStmt = buildPreInits(Context, Captures); 13812 } 13813 } 13814 } 13815 13816 return new (Context) 13817 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 13818 Kind, ValExpr, HelperValStmt); 13819 } 13820 13821 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 13822 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 13823 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 13824 SourceLocation KindLoc, SourceLocation EndLoc) { 13825 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)' 13826 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) { 13827 std::string Value; 13828 SourceLocation Loc; 13829 Value += "'"; 13830 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 13831 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 13832 OMPC_DEFAULTMAP_MODIFIER_tofrom); 13833 Loc = MLoc; 13834 } else { 13835 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 13836 OMPC_DEFAULTMAP_scalar); 13837 Loc = KindLoc; 13838 } 13839 Value += "'"; 13840 Diag(Loc, diag::err_omp_unexpected_clause_value) 13841 << Value << getOpenMPClauseName(OMPC_defaultmap); 13842 return nullptr; 13843 } 13844 DSAStack->setDefaultDMAToFromScalar(StartLoc); 13845 13846 return new (Context) 13847 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 13848 } 13849 13850 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 13851 DeclContext *CurLexicalContext = getCurLexicalContext(); 13852 if (!CurLexicalContext->isFileContext() && 13853 !CurLexicalContext->isExternCContext() && 13854 !CurLexicalContext->isExternCXXContext() && 13855 !isa<CXXRecordDecl>(CurLexicalContext) && 13856 !isa<ClassTemplateDecl>(CurLexicalContext) && 13857 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) && 13858 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) { 13859 Diag(Loc, diag::err_omp_region_not_file_context); 13860 return false; 13861 } 13862 ++DeclareTargetNestingLevel; 13863 return true; 13864 } 13865 13866 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 13867 assert(DeclareTargetNestingLevel > 0 && 13868 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 13869 --DeclareTargetNestingLevel; 13870 } 13871 13872 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, 13873 CXXScopeSpec &ScopeSpec, 13874 const DeclarationNameInfo &Id, 13875 OMPDeclareTargetDeclAttr::MapTypeTy MT, 13876 NamedDeclSetType &SameDirectiveDecls) { 13877 LookupResult Lookup(*this, Id, LookupOrdinaryName); 13878 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 13879 13880 if (Lookup.isAmbiguous()) 13881 return; 13882 Lookup.suppressDiagnostics(); 13883 13884 if (!Lookup.isSingleResult()) { 13885 if (TypoCorrection Corrected = 13886 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, 13887 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this), 13888 CTK_ErrorRecovery)) { 13889 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 13890 << Id.getName()); 13891 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 13892 return; 13893 } 13894 13895 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 13896 return; 13897 } 13898 13899 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 13900 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) || 13901 isa<FunctionTemplateDecl>(ND)) { 13902 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 13903 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 13904 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 13905 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration( 13906 cast<ValueDecl>(ND)); 13907 if (!Res) { 13908 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT); 13909 ND->addAttr(A); 13910 if (ASTMutationListener *ML = Context.getASTMutationListener()) 13911 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 13912 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc()); 13913 } else if (*Res != MT) { 13914 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link) 13915 << Id.getName(); 13916 } 13917 } else { 13918 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 13919 } 13920 } 13921 13922 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 13923 Sema &SemaRef, Decl *D) { 13924 if (!D || !isa<VarDecl>(D)) 13925 return; 13926 auto *VD = cast<VarDecl>(D); 13927 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) 13928 return; 13929 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context); 13930 SemaRef.Diag(SL, diag::note_used_here) << SR; 13931 } 13932 13933 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 13934 Sema &SemaRef, DSAStackTy *Stack, 13935 ValueDecl *VD) { 13936 return VD->hasAttr<OMPDeclareTargetDeclAttr>() || 13937 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(), 13938 /*FullCheck=*/false); 13939 } 13940 13941 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 13942 SourceLocation IdLoc) { 13943 if (!D || D->isInvalidDecl()) 13944 return; 13945 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 13946 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation(); 13947 if (auto *VD = dyn_cast<VarDecl>(D)) { 13948 // Only global variables can be marked as declare target. 13949 if (!VD->isFileVarDecl() && !VD->isStaticLocal() && 13950 !VD->isStaticDataMember()) 13951 return; 13952 // 2.10.6: threadprivate variable cannot appear in a declare target 13953 // directive. 13954 if (DSAStack->isThreadPrivate(VD)) { 13955 Diag(SL, diag::err_omp_threadprivate_in_target); 13956 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 13957 return; 13958 } 13959 } 13960 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) 13961 D = FTD->getTemplatedDecl(); 13962 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 13963 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 13964 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD); 13965 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) { 13966 assert(IdLoc.isValid() && "Source location is expected"); 13967 Diag(IdLoc, diag::err_omp_function_in_link_clause); 13968 Diag(FD->getLocation(), diag::note_defined_here) << FD; 13969 return; 13970 } 13971 } 13972 if (auto *VD = dyn_cast<ValueDecl>(D)) { 13973 // Problem if any with var declared with incomplete type will be reported 13974 // as normal, so no need to check it here. 13975 if ((E || !VD->getType()->isIncompleteType()) && 13976 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) 13977 return; 13978 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 13979 // Checking declaration inside declare target region. 13980 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) || 13981 isa<FunctionTemplateDecl>(D)) { 13982 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit( 13983 Context, OMPDeclareTargetDeclAttr::MT_To); 13984 D->addAttr(A); 13985 if (ASTMutationListener *ML = Context.getASTMutationListener()) 13986 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 13987 } 13988 return; 13989 } 13990 } 13991 if (!E) 13992 return; 13993 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 13994 } 13995 13996 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, 13997 SourceLocation StartLoc, 13998 SourceLocation LParenLoc, 13999 SourceLocation EndLoc) { 14000 MappableVarListInfo MVLI(VarList); 14001 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc); 14002 if (MVLI.ProcessedVarList.empty()) 14003 return nullptr; 14004 14005 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc, 14006 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 14007 MVLI.VarComponents); 14008 } 14009 14010 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, 14011 SourceLocation StartLoc, 14012 SourceLocation LParenLoc, 14013 SourceLocation EndLoc) { 14014 MappableVarListInfo MVLI(VarList); 14015 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc); 14016 if (MVLI.ProcessedVarList.empty()) 14017 return nullptr; 14018 14019 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc, 14020 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 14021 MVLI.VarComponents); 14022 } 14023 14024 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 14025 SourceLocation StartLoc, 14026 SourceLocation LParenLoc, 14027 SourceLocation EndLoc) { 14028 MappableVarListInfo MVLI(VarList); 14029 SmallVector<Expr *, 8> PrivateCopies; 14030 SmallVector<Expr *, 8> Inits; 14031 14032 for (Expr *RefExpr : VarList) { 14033 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 14034 SourceLocation ELoc; 14035 SourceRange ERange; 14036 Expr *SimpleRefExpr = RefExpr; 14037 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 14038 if (Res.second) { 14039 // It will be analyzed later. 14040 MVLI.ProcessedVarList.push_back(RefExpr); 14041 PrivateCopies.push_back(nullptr); 14042 Inits.push_back(nullptr); 14043 } 14044 ValueDecl *D = Res.first; 14045 if (!D) 14046 continue; 14047 14048 QualType Type = D->getType(); 14049 Type = Type.getNonReferenceType().getUnqualifiedType(); 14050 14051 auto *VD = dyn_cast<VarDecl>(D); 14052 14053 // Item should be a pointer or reference to pointer. 14054 if (!Type->isPointerType()) { 14055 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 14056 << 0 << RefExpr->getSourceRange(); 14057 continue; 14058 } 14059 14060 // Build the private variable and the expression that refers to it. 14061 auto VDPrivate = 14062 buildVarDecl(*this, ELoc, Type, D->getName(), 14063 D->hasAttrs() ? &D->getAttrs() : nullptr, 14064 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr); 14065 if (VDPrivate->isInvalidDecl()) 14066 continue; 14067 14068 CurContext->addDecl(VDPrivate); 14069 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr( 14070 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 14071 14072 // Add temporary variable to initialize the private copy of the pointer. 14073 VarDecl *VDInit = 14074 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 14075 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr( 14076 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc()); 14077 AddInitializerToDecl(VDPrivate, 14078 DefaultLvalueConversion(VDInitRefExpr).get(), 14079 /*DirectInit=*/false); 14080 14081 // If required, build a capture to implement the privatization initialized 14082 // with the current list item value. 14083 DeclRefExpr *Ref = nullptr; 14084 if (!VD) 14085 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 14086 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 14087 PrivateCopies.push_back(VDPrivateRefExpr); 14088 Inits.push_back(VDInitRefExpr); 14089 14090 // We need to add a data sharing attribute for this variable to make sure it 14091 // is correctly captured. A variable that shows up in a use_device_ptr has 14092 // similar properties of a first private variable. 14093 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 14094 14095 // Create a mappable component for the list item. List items in this clause 14096 // only need a component. 14097 MVLI.VarBaseDeclarations.push_back(D); 14098 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 14099 MVLI.VarComponents.back().push_back( 14100 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D)); 14101 } 14102 14103 if (MVLI.ProcessedVarList.empty()) 14104 return nullptr; 14105 14106 return OMPUseDevicePtrClause::Create( 14107 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 14108 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents); 14109 } 14110 14111 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 14112 SourceLocation StartLoc, 14113 SourceLocation LParenLoc, 14114 SourceLocation EndLoc) { 14115 MappableVarListInfo MVLI(VarList); 14116 for (Expr *RefExpr : VarList) { 14117 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 14118 SourceLocation ELoc; 14119 SourceRange ERange; 14120 Expr *SimpleRefExpr = RefExpr; 14121 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 14122 if (Res.second) { 14123 // It will be analyzed later. 14124 MVLI.ProcessedVarList.push_back(RefExpr); 14125 } 14126 ValueDecl *D = Res.first; 14127 if (!D) 14128 continue; 14129 14130 QualType Type = D->getType(); 14131 // item should be a pointer or array or reference to pointer or array 14132 if (!Type.getNonReferenceType()->isPointerType() && 14133 !Type.getNonReferenceType()->isArrayType()) { 14134 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 14135 << 0 << RefExpr->getSourceRange(); 14136 continue; 14137 } 14138 14139 // Check if the declaration in the clause does not show up in any data 14140 // sharing attribute. 14141 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false); 14142 if (isOpenMPPrivate(DVar.CKind)) { 14143 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 14144 << getOpenMPClauseName(DVar.CKind) 14145 << getOpenMPClauseName(OMPC_is_device_ptr) 14146 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 14147 reportOriginalDsa(*this, DSAStack, D, DVar); 14148 continue; 14149 } 14150 14151 const Expr *ConflictExpr; 14152 if (DSAStack->checkMappableExprComponentListsForDecl( 14153 D, /*CurrentRegionOnly=*/true, 14154 [&ConflictExpr]( 14155 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 14156 OpenMPClauseKind) -> bool { 14157 ConflictExpr = R.front().getAssociatedExpression(); 14158 return true; 14159 })) { 14160 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 14161 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 14162 << ConflictExpr->getSourceRange(); 14163 continue; 14164 } 14165 14166 // Store the components in the stack so that they can be used to check 14167 // against other clauses later on. 14168 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D); 14169 DSAStack->addMappableExpressionComponents( 14170 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 14171 14172 // Record the expression we've just processed. 14173 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 14174 14175 // Create a mappable component for the list item. List items in this clause 14176 // only need a component. We use a null declaration to signal fields in 14177 // 'this'. 14178 assert((isa<DeclRefExpr>(SimpleRefExpr) || 14179 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 14180 "Unexpected device pointer expression!"); 14181 MVLI.VarBaseDeclarations.push_back( 14182 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 14183 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 14184 MVLI.VarComponents.back().push_back(MC); 14185 } 14186 14187 if (MVLI.ProcessedVarList.empty()) 14188 return nullptr; 14189 14190 return OMPIsDevicePtrClause::Create( 14191 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 14192 MVLI.VarBaseDeclarations, MVLI.VarComponents); 14193 } 14194