1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// \file 10 /// \brief This file implements semantic analysis for OpenMP directives and 11 /// clauses. 12 /// 13 //===----------------------------------------------------------------------===// 14 15 #include "TreeTransform.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclOpenMP.h" 22 #include "clang/AST/StmtCXX.h" 23 #include "clang/AST/StmtOpenMP.h" 24 #include "clang/AST/StmtVisitor.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 Expr *CheckMapClauseExpressionBase( 39 Sema &SemaRef, Expr *E, 40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 41 OpenMPClauseKind CKind, bool NoDiagnose); 42 43 namespace { 44 /// \brief Default data sharing attributes, which can be applied to directive. 45 enum DefaultDataSharingAttributes { 46 DSA_unspecified = 0, /// \brief Data sharing attribute not specified. 47 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'. 48 DSA_shared = 1 << 1, /// \brief 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 /// \brief Stack for tracking declarations used in OpenMP directives and 58 /// clauses and their data-sharing attributes. 59 class DSAStackTy final { 60 public: 61 struct DSAVarData final { 62 OpenMPDirectiveKind DKind = OMPD_unknown; 63 OpenMPClauseKind CKind = OMPC_unknown; 64 Expr *RefExpr = nullptr; 65 DeclRefExpr *PrivateCopy = nullptr; 66 SourceLocation ImplicitDSALoc; 67 DSAVarData() = default; 68 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, Expr *RefExpr, 69 DeclRefExpr *PrivateCopy, SourceLocation ImplicitDSALoc) 70 : DKind(DKind), CKind(CKind), RefExpr(RefExpr), 71 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {} 72 }; 73 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4> 74 OperatorOffsetTy; 75 76 private: 77 struct DSAInfo final { 78 OpenMPClauseKind Attributes = OMPC_unknown; 79 /// Pointer to a reference expression and a flag which shows that the 80 /// variable is marked as lastprivate(true) or not (false). 81 llvm::PointerIntPair<Expr *, 1, bool> RefExpr; 82 DeclRefExpr *PrivateCopy = nullptr; 83 }; 84 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy; 85 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy; 86 typedef std::pair<unsigned, VarDecl *> LCDeclInfo; 87 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy; 88 /// Struct that associates a component with the clause kind where they are 89 /// found. 90 struct MappedExprComponentTy { 91 OMPClauseMappableExprCommon::MappableExprComponentLists Components; 92 OpenMPClauseKind Kind = OMPC_unknown; 93 }; 94 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy> 95 MappedExprComponentsTy; 96 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>> 97 CriticalsWithHintsTy; 98 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy> 99 DoacrossDependMapTy; 100 struct ReductionData { 101 typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType; 102 SourceRange ReductionRange; 103 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp; 104 ReductionData() = default; 105 void set(BinaryOperatorKind BO, SourceRange RR) { 106 ReductionRange = RR; 107 ReductionOp = BO; 108 } 109 void set(const Expr *RefExpr, SourceRange RR) { 110 ReductionRange = RR; 111 ReductionOp = RefExpr; 112 } 113 }; 114 typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy; 115 116 struct SharingMapTy final { 117 DeclSAMapTy SharingMap; 118 DeclReductionMapTy ReductionMap; 119 AlignedMapTy AlignedMap; 120 MappedExprComponentsTy MappedExprComponents; 121 LoopControlVariablesMapTy LCVMap; 122 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 123 SourceLocation DefaultAttrLoc; 124 DefaultMapAttributes DefaultMapAttr = DMA_unspecified; 125 SourceLocation DefaultMapAttrLoc; 126 OpenMPDirectiveKind Directive = OMPD_unknown; 127 DeclarationNameInfo DirectiveName; 128 Scope *CurScope = nullptr; 129 SourceLocation ConstructLoc; 130 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 131 /// get the data (loop counters etc.) about enclosing loop-based construct. 132 /// This data is required during codegen. 133 DoacrossDependMapTy DoacrossDepends; 134 /// \brief first argument (Expr *) contains optional argument of the 135 /// 'ordered' clause, the second one is true if the regions has 'ordered' 136 /// clause, false otherwise. 137 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion; 138 bool NowaitRegion = false; 139 bool CancelRegion = false; 140 unsigned AssociatedLoops = 1; 141 SourceLocation InnerTeamsRegionLoc; 142 /// Reference to the taskgroup task_reduction reference expression. 143 Expr *TaskgroupReductionRef = nullptr; 144 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 145 Scope *CurScope, SourceLocation Loc) 146 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 147 ConstructLoc(Loc) {} 148 SharingMapTy() = default; 149 }; 150 151 typedef SmallVector<SharingMapTy, 4> StackTy; 152 153 /// \brief Stack of used declaration and their data-sharing attributes. 154 DeclSAMapTy Threadprivates; 155 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr; 156 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack; 157 /// \brief true, if check for DSA must be from parent directive, false, if 158 /// from current directive. 159 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 160 Sema &SemaRef; 161 bool ForceCapturing = false; 162 CriticalsWithHintsTy Criticals; 163 164 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator; 165 166 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D); 167 168 /// \brief Checks if the variable is a local for OpenMP region. 169 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter); 170 171 bool isStackEmpty() const { 172 return Stack.empty() || 173 Stack.back().second != CurrentNonCapturingFunctionScope || 174 Stack.back().first.empty(); 175 } 176 177 public: 178 explicit DSAStackTy(Sema &S) : SemaRef(S) {} 179 180 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 181 OpenMPClauseKind getClauseParsingMode() const { 182 assert(isClauseParsingMode() && "Must be in clause parsing mode."); 183 return ClauseKindMode; 184 } 185 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 186 187 bool isForceVarCapturing() const { return ForceCapturing; } 188 void setForceVarCapturing(bool V) { ForceCapturing = V; } 189 190 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 191 Scope *CurScope, SourceLocation Loc) { 192 if (Stack.empty() || 193 Stack.back().second != CurrentNonCapturingFunctionScope) 194 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope); 195 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc); 196 Stack.back().first.back().DefaultAttrLoc = Loc; 197 } 198 199 void pop() { 200 assert(!Stack.back().first.empty() && 201 "Data-sharing attributes stack is empty!"); 202 Stack.back().first.pop_back(); 203 } 204 205 /// Start new OpenMP region stack in new non-capturing function. 206 void pushFunction() { 207 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction(); 208 assert(!isa<CapturingScopeInfo>(CurFnScope)); 209 CurrentNonCapturingFunctionScope = CurFnScope; 210 } 211 /// Pop region stack for non-capturing function. 212 void popFunction(const FunctionScopeInfo *OldFSI) { 213 if (!Stack.empty() && Stack.back().second == OldFSI) { 214 assert(Stack.back().first.empty()); 215 Stack.pop_back(); 216 } 217 CurrentNonCapturingFunctionScope = nullptr; 218 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) { 219 if (!isa<CapturingScopeInfo>(FSI)) { 220 CurrentNonCapturingFunctionScope = FSI; 221 break; 222 } 223 } 224 } 225 226 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) { 227 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint); 228 } 229 const std::pair<OMPCriticalDirective *, llvm::APSInt> 230 getCriticalWithHint(const DeclarationNameInfo &Name) const { 231 auto I = Criticals.find(Name.getAsString()); 232 if (I != Criticals.end()) 233 return I->second; 234 return std::make_pair(nullptr, llvm::APSInt()); 235 } 236 /// \brief If 'aligned' declaration for given variable \a D was not seen yet, 237 /// add it and return NULL; otherwise return previous occurrence's expression 238 /// for diagnostics. 239 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE); 240 241 /// \brief Register specified variable as loop control variable. 242 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture); 243 /// \brief Check if the specified variable is a loop control variable for 244 /// current region. 245 /// \return The index of the loop control variable in the list of associated 246 /// for-loops (from outer to inner). 247 LCDeclInfo isLoopControlVariable(ValueDecl *D); 248 /// \brief Check if the specified variable is a loop control variable for 249 /// parent region. 250 /// \return The index of the loop control variable in the list of associated 251 /// for-loops (from outer to inner). 252 LCDeclInfo isParentLoopControlVariable(ValueDecl *D); 253 /// \brief Get the loop control variable for the I-th loop (or nullptr) in 254 /// parent directive. 255 ValueDecl *getParentLoopControlVariable(unsigned I); 256 257 /// \brief Adds explicit data sharing attribute to the specified declaration. 258 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, 259 DeclRefExpr *PrivateCopy = nullptr); 260 261 /// Adds additional information for the reduction items with the reduction id 262 /// represented as an operator. 263 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR, 264 BinaryOperatorKind BOK); 265 /// Adds additional information for the reduction items with the reduction id 266 /// represented as reduction identifier. 267 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR, 268 const Expr *ReductionRef); 269 /// Returns the location and reduction operation from the innermost parent 270 /// region for the given \p D. 271 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR, 272 BinaryOperatorKind &BOK, 273 Expr *&TaskgroupDescriptor); 274 /// Returns the location and reduction operation from the innermost parent 275 /// region for the given \p D. 276 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR, 277 const Expr *&ReductionRef, 278 Expr *&TaskgroupDescriptor); 279 /// Return reduction reference expression for the current taskgroup. 280 Expr *getTaskgroupReductionRef() const { 281 assert(Stack.back().first.back().Directive == OMPD_taskgroup && 282 "taskgroup reference expression requested for non taskgroup " 283 "directive."); 284 return Stack.back().first.back().TaskgroupReductionRef; 285 } 286 /// Checks if the given \p VD declaration is actually a taskgroup reduction 287 /// descriptor variable at the \p Level of OpenMP regions. 288 bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const { 289 return Stack.back().first[Level].TaskgroupReductionRef && 290 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef) 291 ->getDecl() == VD; 292 } 293 294 /// \brief Returns data sharing attributes from top of the stack for the 295 /// specified declaration. 296 DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 297 /// \brief Returns data-sharing attributes for the specified declaration. 298 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent); 299 /// \brief Checks if the specified variables has data-sharing attributes which 300 /// match specified \a CPred predicate in any directive which matches \a DPred 301 /// predicate. 302 DSAVarData hasDSA(ValueDecl *D, 303 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 304 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 305 bool FromParent); 306 /// \brief Checks if the specified variables has data-sharing attributes which 307 /// match specified \a CPred predicate in any innermost directive which 308 /// matches \a DPred predicate. 309 DSAVarData 310 hasInnermostDSA(ValueDecl *D, 311 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 312 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 313 bool FromParent); 314 /// \brief Checks if the specified variables has explicit data-sharing 315 /// attributes which match specified \a CPred predicate at the specified 316 /// OpenMP region. 317 bool hasExplicitDSA(ValueDecl *D, 318 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 319 unsigned Level, bool NotLastprivate = false); 320 321 /// \brief Returns true if the directive at level \Level matches in the 322 /// specified \a DPred predicate. 323 bool hasExplicitDirective( 324 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 325 unsigned Level); 326 327 /// \brief Finds a directive which matches specified \a DPred predicate. 328 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind, 329 const DeclarationNameInfo &, 330 SourceLocation)> &DPred, 331 bool FromParent); 332 333 /// \brief Returns currently analyzed directive. 334 OpenMPDirectiveKind getCurrentDirective() const { 335 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive; 336 } 337 /// \brief Returns directive kind at specified level. 338 OpenMPDirectiveKind getDirective(unsigned Level) const { 339 assert(!isStackEmpty() && "No directive at specified level."); 340 return Stack.back().first[Level].Directive; 341 } 342 /// \brief Returns parent directive. 343 OpenMPDirectiveKind getParentDirective() const { 344 if (isStackEmpty() || Stack.back().first.size() == 1) 345 return OMPD_unknown; 346 return std::next(Stack.back().first.rbegin())->Directive; 347 } 348 349 /// \brief Set default data sharing attribute to none. 350 void setDefaultDSANone(SourceLocation Loc) { 351 assert(!isStackEmpty()); 352 Stack.back().first.back().DefaultAttr = DSA_none; 353 Stack.back().first.back().DefaultAttrLoc = Loc; 354 } 355 /// \brief Set default data sharing attribute to shared. 356 void setDefaultDSAShared(SourceLocation Loc) { 357 assert(!isStackEmpty()); 358 Stack.back().first.back().DefaultAttr = DSA_shared; 359 Stack.back().first.back().DefaultAttrLoc = Loc; 360 } 361 /// Set default data mapping attribute to 'tofrom:scalar'. 362 void setDefaultDMAToFromScalar(SourceLocation Loc) { 363 assert(!isStackEmpty()); 364 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar; 365 Stack.back().first.back().DefaultMapAttrLoc = Loc; 366 } 367 368 DefaultDataSharingAttributes getDefaultDSA() const { 369 return isStackEmpty() ? DSA_unspecified 370 : Stack.back().first.back().DefaultAttr; 371 } 372 SourceLocation getDefaultDSALocation() const { 373 return isStackEmpty() ? SourceLocation() 374 : Stack.back().first.back().DefaultAttrLoc; 375 } 376 DefaultMapAttributes getDefaultDMA() const { 377 return isStackEmpty() ? DMA_unspecified 378 : Stack.back().first.back().DefaultMapAttr; 379 } 380 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const { 381 return Stack.back().first[Level].DefaultMapAttr; 382 } 383 SourceLocation getDefaultDMALocation() const { 384 return isStackEmpty() ? SourceLocation() 385 : Stack.back().first.back().DefaultMapAttrLoc; 386 } 387 388 /// \brief Checks if the specified variable is a threadprivate. 389 bool isThreadPrivate(VarDecl *D) { 390 DSAVarData DVar = getTopDSA(D, false); 391 return isOpenMPThreadPrivate(DVar.CKind); 392 } 393 394 /// \brief Marks current region as ordered (it has an 'ordered' clause). 395 void setOrderedRegion(bool IsOrdered, Expr *Param) { 396 assert(!isStackEmpty()); 397 Stack.back().first.back().OrderedRegion.setInt(IsOrdered); 398 Stack.back().first.back().OrderedRegion.setPointer(Param); 399 } 400 /// \brief Returns true, if parent region is ordered (has associated 401 /// 'ordered' clause), false - otherwise. 402 bool isParentOrderedRegion() const { 403 if (isStackEmpty() || Stack.back().first.size() == 1) 404 return false; 405 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt(); 406 } 407 /// \brief Returns optional parameter for the ordered region. 408 Expr *getParentOrderedRegionParam() const { 409 if (isStackEmpty() || Stack.back().first.size() == 1) 410 return nullptr; 411 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer(); 412 } 413 /// \brief Marks current region as nowait (it has a 'nowait' clause). 414 void setNowaitRegion(bool IsNowait = true) { 415 assert(!isStackEmpty()); 416 Stack.back().first.back().NowaitRegion = IsNowait; 417 } 418 /// \brief Returns true, if parent region is nowait (has associated 419 /// 'nowait' clause), false - otherwise. 420 bool isParentNowaitRegion() const { 421 if (isStackEmpty() || Stack.back().first.size() == 1) 422 return false; 423 return std::next(Stack.back().first.rbegin())->NowaitRegion; 424 } 425 /// \brief Marks parent region as cancel region. 426 void setParentCancelRegion(bool Cancel = true) { 427 if (!isStackEmpty() && Stack.back().first.size() > 1) { 428 auto &StackElemRef = *std::next(Stack.back().first.rbegin()); 429 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel; 430 } 431 } 432 /// \brief Return true if current region has inner cancel construct. 433 bool isCancelRegion() const { 434 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion; 435 } 436 437 /// \brief Set collapse value for the region. 438 void setAssociatedLoops(unsigned Val) { 439 assert(!isStackEmpty()); 440 Stack.back().first.back().AssociatedLoops = Val; 441 } 442 /// \brief Return collapse value for region. 443 unsigned getAssociatedLoops() const { 444 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops; 445 } 446 447 /// \brief Marks current target region as one with closely nested teams 448 /// region. 449 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 450 if (!isStackEmpty() && Stack.back().first.size() > 1) { 451 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc = 452 TeamsRegionLoc; 453 } 454 } 455 /// \brief Returns true, if current region has closely nested teams region. 456 bool hasInnerTeamsRegion() const { 457 return getInnerTeamsRegionLoc().isValid(); 458 } 459 /// \brief Returns location of the nested teams region (if any). 460 SourceLocation getInnerTeamsRegionLoc() const { 461 return isStackEmpty() ? SourceLocation() 462 : Stack.back().first.back().InnerTeamsRegionLoc; 463 } 464 465 Scope *getCurScope() const { 466 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope; 467 } 468 Scope *getCurScope() { 469 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope; 470 } 471 SourceLocation getConstructLoc() { 472 return isStackEmpty() ? SourceLocation() 473 : Stack.back().first.back().ConstructLoc; 474 } 475 476 /// Do the check specified in \a Check to all component lists and return true 477 /// if any issue is found. 478 bool checkMappableExprComponentListsForDecl( 479 ValueDecl *VD, bool CurrentRegionOnly, 480 const llvm::function_ref< 481 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 482 OpenMPClauseKind)> &Check) { 483 if (isStackEmpty()) 484 return false; 485 auto SI = Stack.back().first.rbegin(); 486 auto SE = Stack.back().first.rend(); 487 488 if (SI == SE) 489 return false; 490 491 if (CurrentRegionOnly) { 492 SE = std::next(SI); 493 } else { 494 ++SI; 495 } 496 497 for (; SI != SE; ++SI) { 498 auto MI = SI->MappedExprComponents.find(VD); 499 if (MI != SI->MappedExprComponents.end()) 500 for (auto &L : MI->second.Components) 501 if (Check(L, MI->second.Kind)) 502 return true; 503 } 504 return false; 505 } 506 507 /// Do the check specified in \a Check to all component lists at a given level 508 /// and return true if any issue is found. 509 bool checkMappableExprComponentListsForDeclAtLevel( 510 ValueDecl *VD, unsigned Level, 511 const llvm::function_ref< 512 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 513 OpenMPClauseKind)> &Check) { 514 if (isStackEmpty()) 515 return false; 516 517 auto StartI = Stack.back().first.begin(); 518 auto EndI = Stack.back().first.end(); 519 if (std::distance(StartI, EndI) <= (int)Level) 520 return false; 521 std::advance(StartI, Level); 522 523 auto MI = StartI->MappedExprComponents.find(VD); 524 if (MI != StartI->MappedExprComponents.end()) 525 for (auto &L : MI->second.Components) 526 if (Check(L, MI->second.Kind)) 527 return true; 528 return false; 529 } 530 531 /// Create a new mappable expression component list associated with a given 532 /// declaration and initialize it with the provided list of components. 533 void addMappableExpressionComponents( 534 ValueDecl *VD, 535 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 536 OpenMPClauseKind WhereFoundClauseKind) { 537 assert(!isStackEmpty() && 538 "Not expecting to retrieve components from a empty stack!"); 539 auto &MEC = Stack.back().first.back().MappedExprComponents[VD]; 540 // Create new entry and append the new components there. 541 MEC.Components.resize(MEC.Components.size() + 1); 542 MEC.Components.back().append(Components.begin(), Components.end()); 543 MEC.Kind = WhereFoundClauseKind; 544 } 545 546 unsigned getNestingLevel() const { 547 assert(!isStackEmpty()); 548 return Stack.back().first.size() - 1; 549 } 550 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) { 551 assert(!isStackEmpty() && Stack.back().first.size() > 1); 552 auto &StackElem = *std::next(Stack.back().first.rbegin()); 553 assert(isOpenMPWorksharingDirective(StackElem.Directive)); 554 StackElem.DoacrossDepends.insert({C, OpsOffs}); 555 } 556 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 557 getDoacrossDependClauses() const { 558 assert(!isStackEmpty()); 559 auto &StackElem = Stack.back().first.back(); 560 if (isOpenMPWorksharingDirective(StackElem.Directive)) { 561 auto &Ref = StackElem.DoacrossDepends; 562 return llvm::make_range(Ref.begin(), Ref.end()); 563 } 564 return llvm::make_range(StackElem.DoacrossDepends.end(), 565 StackElem.DoacrossDepends.end()); 566 } 567 }; 568 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) { 569 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) || 570 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown; 571 } 572 } // namespace 573 574 static Expr *getExprAsWritten(Expr *E) { 575 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E)) 576 E = ExprTemp->getSubExpr(); 577 578 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 579 E = MTE->GetTemporaryExpr(); 580 581 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 582 E = Binder->getSubExpr(); 583 584 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 585 E = ICE->getSubExprAsWritten(); 586 return E->IgnoreParens(); 587 } 588 589 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 590 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) 591 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 592 D = ME->getMemberDecl(); 593 auto *VD = dyn_cast<VarDecl>(D); 594 auto *FD = dyn_cast<FieldDecl>(D); 595 if (VD != nullptr) { 596 VD = VD->getCanonicalDecl(); 597 D = VD; 598 } else { 599 assert(FD); 600 FD = FD->getCanonicalDecl(); 601 D = FD; 602 } 603 return D; 604 } 605 606 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter, 607 ValueDecl *D) { 608 D = getCanonicalDecl(D); 609 auto *VD = dyn_cast<VarDecl>(D); 610 auto *FD = dyn_cast<FieldDecl>(D); 611 DSAVarData DVar; 612 if (isStackEmpty() || Iter == Stack.back().first.rend()) { 613 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 614 // in a region but not in construct] 615 // File-scope or namespace-scope variables referenced in called routines 616 // in the region are shared unless they appear in a threadprivate 617 // directive. 618 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D)) 619 DVar.CKind = OMPC_shared; 620 621 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 622 // in a region but not in construct] 623 // Variables with static storage duration that are declared in called 624 // routines in the region are shared. 625 if (VD && VD->hasGlobalStorage()) 626 DVar.CKind = OMPC_shared; 627 628 // Non-static data members are shared by default. 629 if (FD) 630 DVar.CKind = OMPC_shared; 631 632 return DVar; 633 } 634 635 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 636 // in a Construct, C/C++, predetermined, p.1] 637 // Variables with automatic storage duration that are declared in a scope 638 // inside the construct are private. 639 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 640 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 641 DVar.CKind = OMPC_private; 642 return DVar; 643 } 644 645 DVar.DKind = Iter->Directive; 646 // Explicitly specified attributes and local variables with predetermined 647 // attributes. 648 if (Iter->SharingMap.count(D)) { 649 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer(); 650 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy; 651 DVar.CKind = Iter->SharingMap[D].Attributes; 652 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 653 return DVar; 654 } 655 656 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 657 // in a Construct, C/C++, implicitly determined, p.1] 658 // In a parallel or task construct, the data-sharing attributes of these 659 // variables are determined by the default clause, if present. 660 switch (Iter->DefaultAttr) { 661 case DSA_shared: 662 DVar.CKind = OMPC_shared; 663 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 664 return DVar; 665 case DSA_none: 666 return DVar; 667 case DSA_unspecified: 668 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 669 // in a Construct, implicitly determined, p.2] 670 // In a parallel construct, if no default clause is present, these 671 // variables are shared. 672 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 673 if (isOpenMPParallelDirective(DVar.DKind) || 674 isOpenMPTeamsDirective(DVar.DKind)) { 675 DVar.CKind = OMPC_shared; 676 return DVar; 677 } 678 679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 680 // in a Construct, implicitly determined, p.4] 681 // In a task construct, if no default clause is present, a variable that in 682 // the enclosing context is determined to be shared by all implicit tasks 683 // bound to the current team is shared. 684 if (isOpenMPTaskingDirective(DVar.DKind)) { 685 DSAVarData DVarTemp; 686 auto I = Iter, E = Stack.back().first.rend(); 687 do { 688 ++I; 689 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 690 // Referenced in a Construct, implicitly determined, p.6] 691 // In a task construct, if no default clause is present, a variable 692 // whose data-sharing attribute is not determined by the rules above is 693 // firstprivate. 694 DVarTemp = getDSA(I, D); 695 if (DVarTemp.CKind != OMPC_shared) { 696 DVar.RefExpr = nullptr; 697 DVar.CKind = OMPC_firstprivate; 698 return DVar; 699 } 700 } while (I != E && !isParallelOrTaskRegion(I->Directive)); 701 DVar.CKind = 702 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 703 return DVar; 704 } 705 } 706 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 707 // in a Construct, implicitly determined, p.3] 708 // For constructs other than task, if no default clause is present, these 709 // variables inherit their data-sharing attributes from the enclosing 710 // context. 711 return getDSA(++Iter, D); 712 } 713 714 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) { 715 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 716 D = getCanonicalDecl(D); 717 auto &StackElem = Stack.back().first.back(); 718 auto It = StackElem.AlignedMap.find(D); 719 if (It == StackElem.AlignedMap.end()) { 720 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 721 StackElem.AlignedMap[D] = NewDE; 722 return nullptr; 723 } else { 724 assert(It->second && "Unexpected nullptr expr in the aligned map"); 725 return It->second; 726 } 727 return nullptr; 728 } 729 730 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) { 731 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 732 D = getCanonicalDecl(D); 733 auto &StackElem = Stack.back().first.back(); 734 StackElem.LCVMap.insert( 735 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)}); 736 } 737 738 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) { 739 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 740 D = getCanonicalDecl(D); 741 auto &StackElem = Stack.back().first.back(); 742 auto It = StackElem.LCVMap.find(D); 743 if (It != StackElem.LCVMap.end()) 744 return It->second; 745 return {0, nullptr}; 746 } 747 748 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) { 749 assert(!isStackEmpty() && Stack.back().first.size() > 1 && 750 "Data-sharing attributes stack is empty"); 751 D = getCanonicalDecl(D); 752 auto &StackElem = *std::next(Stack.back().first.rbegin()); 753 auto It = StackElem.LCVMap.find(D); 754 if (It != StackElem.LCVMap.end()) 755 return It->second; 756 return {0, nullptr}; 757 } 758 759 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) { 760 assert(!isStackEmpty() && Stack.back().first.size() > 1 && 761 "Data-sharing attributes stack is empty"); 762 auto &StackElem = *std::next(Stack.back().first.rbegin()); 763 if (StackElem.LCVMap.size() < I) 764 return nullptr; 765 for (auto &Pair : StackElem.LCVMap) 766 if (Pair.second.first == I) 767 return Pair.first; 768 return nullptr; 769 } 770 771 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, 772 DeclRefExpr *PrivateCopy) { 773 D = getCanonicalDecl(D); 774 if (A == OMPC_threadprivate) { 775 auto &Data = Threadprivates[D]; 776 Data.Attributes = A; 777 Data.RefExpr.setPointer(E); 778 Data.PrivateCopy = nullptr; 779 } else { 780 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 781 auto &Data = Stack.back().first.back().SharingMap[D]; 782 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 783 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 784 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 785 (isLoopControlVariable(D).first && A == OMPC_private)); 786 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 787 Data.RefExpr.setInt(/*IntVal=*/true); 788 return; 789 } 790 const bool IsLastprivate = 791 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 792 Data.Attributes = A; 793 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 794 Data.PrivateCopy = PrivateCopy; 795 if (PrivateCopy) { 796 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()]; 797 Data.Attributes = A; 798 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 799 Data.PrivateCopy = nullptr; 800 } 801 } 802 } 803 804 /// \brief Build a variable declaration for OpenMP loop iteration variable. 805 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 806 StringRef Name, const AttrVec *Attrs = nullptr) { 807 DeclContext *DC = SemaRef.CurContext; 808 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 809 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 810 VarDecl *Decl = 811 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 812 if (Attrs) { 813 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 814 I != E; ++I) 815 Decl->addAttr(*I); 816 } 817 Decl->setImplicit(); 818 return Decl; 819 } 820 821 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 822 SourceLocation Loc, 823 bool RefersToCapture = false) { 824 D->setReferenced(); 825 D->markUsed(S.Context); 826 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 827 SourceLocation(), D, RefersToCapture, Loc, Ty, 828 VK_LValue); 829 } 830 831 void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR, 832 BinaryOperatorKind BOK) { 833 D = getCanonicalDecl(D); 834 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 835 assert( 836 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && 837 "Additional reduction info may be specified only for reduction items."); 838 auto &ReductionData = Stack.back().first.back().ReductionMap[D]; 839 assert(ReductionData.ReductionRange.isInvalid() && 840 Stack.back().first.back().Directive == OMPD_taskgroup && 841 "Additional reduction info may be specified only once for reduction " 842 "items."); 843 ReductionData.set(BOK, SR); 844 Expr *&TaskgroupReductionRef = 845 Stack.back().first.back().TaskgroupReductionRef; 846 if (!TaskgroupReductionRef) { 847 auto *VD = buildVarDecl(SemaRef, SR.getBegin(), 848 SemaRef.Context.VoidPtrTy, ".task_red."); 849 TaskgroupReductionRef = 850 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 851 } 852 } 853 854 void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR, 855 const Expr *ReductionRef) { 856 D = getCanonicalDecl(D); 857 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 858 assert( 859 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && 860 "Additional reduction info may be specified only for reduction items."); 861 auto &ReductionData = Stack.back().first.back().ReductionMap[D]; 862 assert(ReductionData.ReductionRange.isInvalid() && 863 Stack.back().first.back().Directive == OMPD_taskgroup && 864 "Additional reduction info may be specified only once for reduction " 865 "items."); 866 ReductionData.set(ReductionRef, SR); 867 Expr *&TaskgroupReductionRef = 868 Stack.back().first.back().TaskgroupReductionRef; 869 if (!TaskgroupReductionRef) { 870 auto *VD = buildVarDecl(SemaRef, SR.getBegin(), SemaRef.Context.VoidPtrTy, 871 ".task_red."); 872 TaskgroupReductionRef = 873 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin()); 874 } 875 } 876 877 DSAStackTy::DSAVarData 878 DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR, 879 BinaryOperatorKind &BOK, 880 Expr *&TaskgroupDescriptor) { 881 D = getCanonicalDecl(D); 882 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 883 if (Stack.back().first.empty()) 884 return DSAVarData(); 885 for (auto I = std::next(Stack.back().first.rbegin(), 1), 886 E = Stack.back().first.rend(); 887 I != E; std::advance(I, 1)) { 888 auto &Data = I->SharingMap[D]; 889 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) 890 continue; 891 auto &ReductionData = I->ReductionMap[D]; 892 if (!ReductionData.ReductionOp || 893 ReductionData.ReductionOp.is<const Expr *>()) 894 return DSAVarData(); 895 SR = ReductionData.ReductionRange; 896 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>(); 897 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 898 "expression for the descriptor is not " 899 "set."); 900 TaskgroupDescriptor = I->TaskgroupReductionRef; 901 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), 902 Data.PrivateCopy, I->DefaultAttrLoc); 903 } 904 return DSAVarData(); 905 } 906 907 DSAStackTy::DSAVarData 908 DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR, 909 const Expr *&ReductionRef, 910 Expr *&TaskgroupDescriptor) { 911 D = getCanonicalDecl(D); 912 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 913 if (Stack.back().first.empty()) 914 return DSAVarData(); 915 for (auto I = std::next(Stack.back().first.rbegin(), 1), 916 E = Stack.back().first.rend(); 917 I != E; std::advance(I, 1)) { 918 auto &Data = I->SharingMap[D]; 919 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) 920 continue; 921 auto &ReductionData = I->ReductionMap[D]; 922 if (!ReductionData.ReductionOp || 923 !ReductionData.ReductionOp.is<const Expr *>()) 924 return DSAVarData(); 925 SR = ReductionData.ReductionRange; 926 ReductionRef = ReductionData.ReductionOp.get<const Expr *>(); 927 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 928 "expression for the descriptor is not " 929 "set."); 930 TaskgroupDescriptor = I->TaskgroupReductionRef; 931 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), 932 Data.PrivateCopy, I->DefaultAttrLoc); 933 } 934 return DSAVarData(); 935 } 936 937 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) { 938 D = D->getCanonicalDecl(); 939 if (!isStackEmpty()) { 940 reverse_iterator I = Iter, E = Stack.back().first.rend(); 941 Scope *TopScope = nullptr; 942 while (I != E && !isParallelOrTaskRegion(I->Directive) && 943 !isOpenMPTargetExecutionDirective(I->Directive)) 944 ++I; 945 if (I == E) 946 return false; 947 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; 948 Scope *CurScope = getCurScope(); 949 while (CurScope != TopScope && !CurScope->isDeclScope(D)) 950 CurScope = CurScope->getParent(); 951 return CurScope != TopScope; 952 } 953 return false; 954 } 955 956 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) { 957 D = getCanonicalDecl(D); 958 DSAVarData DVar; 959 960 auto *VD = dyn_cast<VarDecl>(D); 961 auto TI = Threadprivates.find(D); 962 if (TI != Threadprivates.end()) { 963 DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); 964 DVar.CKind = OMPC_threadprivate; 965 return DVar; 966 } else if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) { 967 DVar.RefExpr = buildDeclRefExpr( 968 SemaRef, VD, D->getType().getNonReferenceType(), 969 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation()); 970 DVar.CKind = OMPC_threadprivate; 971 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 972 return DVar; 973 } 974 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 975 // in a Construct, C/C++, predetermined, p.1] 976 // Variables appearing in threadprivate directives are threadprivate. 977 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 978 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 979 SemaRef.getLangOpts().OpenMPUseTLS && 980 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 981 (VD && VD->getStorageClass() == SC_Register && 982 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 983 DVar.RefExpr = buildDeclRefExpr( 984 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation()); 985 DVar.CKind = OMPC_threadprivate; 986 addDSA(D, DVar.RefExpr, OMPC_threadprivate); 987 return DVar; 988 } 989 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD && 990 VD->isLocalVarDeclOrParm() && !isStackEmpty() && 991 !isLoopControlVariable(D).first) { 992 auto IterTarget = 993 std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(), 994 [](const SharingMapTy &Data) { 995 return isOpenMPTargetExecutionDirective(Data.Directive); 996 }); 997 if (IterTarget != Stack.back().first.rend()) { 998 auto ParentIterTarget = std::next(IterTarget, 1); 999 auto Iter = Stack.back().first.rbegin(); 1000 while (Iter != ParentIterTarget) { 1001 if (isOpenMPLocal(VD, Iter)) { 1002 DVar.RefExpr = 1003 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1004 D->getLocation()); 1005 DVar.CKind = OMPC_threadprivate; 1006 return DVar; 1007 } 1008 std::advance(Iter, 1); 1009 } 1010 if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) { 1011 auto DSAIter = IterTarget->SharingMap.find(D); 1012 if (DSAIter != IterTarget->SharingMap.end() && 1013 isOpenMPPrivate(DSAIter->getSecond().Attributes)) { 1014 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer(); 1015 DVar.CKind = OMPC_threadprivate; 1016 return DVar; 1017 } else if (!SemaRef.IsOpenMPCapturedByRef( 1018 D, std::distance(ParentIterTarget, 1019 Stack.back().first.rend()))) { 1020 DVar.RefExpr = 1021 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 1022 IterTarget->ConstructLoc); 1023 DVar.CKind = OMPC_threadprivate; 1024 return DVar; 1025 } 1026 } 1027 } 1028 } 1029 1030 if (isStackEmpty()) 1031 // Not in OpenMP execution region and top scope was already checked. 1032 return DVar; 1033 1034 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1035 // in a Construct, C/C++, predetermined, p.4] 1036 // Static data members are shared. 1037 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1038 // in a Construct, C/C++, predetermined, p.7] 1039 // Variables with static storage duration that are declared in a scope 1040 // inside the construct are shared. 1041 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; }; 1042 if (VD && VD->isStaticDataMember()) { 1043 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent); 1044 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 1045 return DVar; 1046 1047 DVar.CKind = OMPC_shared; 1048 return DVar; 1049 } 1050 1051 QualType Type = D->getType().getNonReferenceType().getCanonicalType(); 1052 bool IsConstant = Type.isConstant(SemaRef.getASTContext()); 1053 Type = SemaRef.getASTContext().getBaseElementType(Type); 1054 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 1055 // in a Construct, C/C++, predetermined, p.6] 1056 // Variables with const qualified type having no mutable member are 1057 // shared. 1058 CXXRecordDecl *RD = 1059 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 1060 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 1061 if (auto *CTD = CTSD->getSpecializedTemplate()) 1062 RD = CTD->getTemplatedDecl(); 1063 if (IsConstant && 1064 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() && 1065 RD->hasMutableFields())) { 1066 // Variables with const-qualified type having no mutable member may be 1067 // listed in a firstprivate clause, even if they are static data members. 1068 DSAVarData DVarTemp = hasDSA( 1069 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; }, 1070 MatchesAlways, FromParent); 1071 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr) 1072 return DVarTemp; 1073 1074 DVar.CKind = OMPC_shared; 1075 return DVar; 1076 } 1077 1078 // Explicitly specified attributes and local variables with predetermined 1079 // attributes. 1080 auto I = Stack.back().first.rbegin(); 1081 auto EndI = Stack.back().first.rend(); 1082 if (FromParent && I != EndI) 1083 std::advance(I, 1); 1084 if (I->SharingMap.count(D)) { 1085 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer(); 1086 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy; 1087 DVar.CKind = I->SharingMap[D].Attributes; 1088 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1089 DVar.DKind = I->Directive; 1090 } 1091 1092 return DVar; 1093 } 1094 1095 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1096 bool FromParent) { 1097 if (isStackEmpty()) { 1098 StackTy::reverse_iterator I; 1099 return getDSA(I, D); 1100 } 1101 D = getCanonicalDecl(D); 1102 auto StartI = Stack.back().first.rbegin(); 1103 auto EndI = Stack.back().first.rend(); 1104 if (FromParent && StartI != EndI) 1105 std::advance(StartI, 1); 1106 return getDSA(StartI, D); 1107 } 1108 1109 DSAStackTy::DSAVarData 1110 DSAStackTy::hasDSA(ValueDecl *D, 1111 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 1112 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 1113 bool FromParent) { 1114 if (isStackEmpty()) 1115 return {}; 1116 D = getCanonicalDecl(D); 1117 auto I = Stack.back().first.rbegin(); 1118 auto EndI = Stack.back().first.rend(); 1119 if (FromParent && I != EndI) 1120 std::advance(I, 1); 1121 for (; I != EndI; std::advance(I, 1)) { 1122 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive)) 1123 continue; 1124 auto NewI = I; 1125 DSAVarData DVar = getDSA(NewI, D); 1126 if (I == NewI && CPred(DVar.CKind)) 1127 return DVar; 1128 } 1129 return {}; 1130 } 1131 1132 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 1133 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 1134 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 1135 bool FromParent) { 1136 if (isStackEmpty()) 1137 return {}; 1138 D = getCanonicalDecl(D); 1139 auto StartI = Stack.back().first.rbegin(); 1140 auto EndI = Stack.back().first.rend(); 1141 if (FromParent && StartI != EndI) 1142 std::advance(StartI, 1); 1143 if (StartI == EndI || !DPred(StartI->Directive)) 1144 return {}; 1145 auto NewI = StartI; 1146 DSAVarData DVar = getDSA(NewI, D); 1147 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData(); 1148 } 1149 1150 bool DSAStackTy::hasExplicitDSA( 1151 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 1152 unsigned Level, bool NotLastprivate) { 1153 if (isStackEmpty()) 1154 return false; 1155 D = getCanonicalDecl(D); 1156 auto StartI = Stack.back().first.begin(); 1157 auto EndI = Stack.back().first.end(); 1158 if (std::distance(StartI, EndI) <= (int)Level) 1159 return false; 1160 std::advance(StartI, Level); 1161 return (StartI->SharingMap.count(D) > 0) && 1162 StartI->SharingMap[D].RefExpr.getPointer() && 1163 CPred(StartI->SharingMap[D].Attributes) && 1164 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt()); 1165 } 1166 1167 bool DSAStackTy::hasExplicitDirective( 1168 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 1169 unsigned Level) { 1170 if (isStackEmpty()) 1171 return false; 1172 auto StartI = Stack.back().first.begin(); 1173 auto EndI = Stack.back().first.end(); 1174 if (std::distance(StartI, EndI) <= (int)Level) 1175 return false; 1176 std::advance(StartI, Level); 1177 return DPred(StartI->Directive); 1178 } 1179 1180 bool DSAStackTy::hasDirective( 1181 const llvm::function_ref<bool(OpenMPDirectiveKind, 1182 const DeclarationNameInfo &, SourceLocation)> 1183 &DPred, 1184 bool FromParent) { 1185 // We look only in the enclosing region. 1186 if (isStackEmpty()) 1187 return false; 1188 auto StartI = std::next(Stack.back().first.rbegin()); 1189 auto EndI = Stack.back().first.rend(); 1190 if (FromParent && StartI != EndI) 1191 StartI = std::next(StartI); 1192 for (auto I = StartI, EE = EndI; I != EE; ++I) { 1193 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 1194 return true; 1195 } 1196 return false; 1197 } 1198 1199 void Sema::InitDataSharingAttributesStack() { 1200 VarDataSharingAttributesStack = new DSAStackTy(*this); 1201 } 1202 1203 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 1204 1205 void Sema::pushOpenMPFunctionRegion() { 1206 DSAStack->pushFunction(); 1207 } 1208 1209 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 1210 DSAStack->popFunction(OldFSI); 1211 } 1212 1213 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) { 1214 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1215 1216 auto &Ctx = getASTContext(); 1217 bool IsByRef = true; 1218 1219 // Find the directive that is associated with the provided scope. 1220 D = cast<ValueDecl>(D->getCanonicalDecl()); 1221 auto Ty = D->getType(); 1222 1223 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 1224 // This table summarizes how a given variable should be passed to the device 1225 // given its type and the clauses where it appears. This table is based on 1226 // the description in OpenMP 4.5 [2.10.4, target Construct] and 1227 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 1228 // 1229 // ========================================================================= 1230 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 1231 // | |(tofrom:scalar)| | pvt | | | | 1232 // ========================================================================= 1233 // | scl | | | | - | | bycopy| 1234 // | scl | | - | x | - | - | bycopy| 1235 // | scl | | x | - | - | - | null | 1236 // | scl | x | | | - | | byref | 1237 // | scl | x | - | x | - | - | bycopy| 1238 // | scl | x | x | - | - | - | null | 1239 // | scl | | - | - | - | x | byref | 1240 // | scl | x | - | - | - | x | byref | 1241 // 1242 // | agg | n.a. | | | - | | byref | 1243 // | agg | n.a. | - | x | - | - | byref | 1244 // | agg | n.a. | x | - | - | - | null | 1245 // | agg | n.a. | - | - | - | x | byref | 1246 // | agg | n.a. | - | - | - | x[] | byref | 1247 // 1248 // | ptr | n.a. | | | - | | bycopy| 1249 // | ptr | n.a. | - | x | - | - | bycopy| 1250 // | ptr | n.a. | x | - | - | - | null | 1251 // | ptr | n.a. | - | - | - | x | byref | 1252 // | ptr | n.a. | - | - | - | x[] | bycopy| 1253 // | ptr | n.a. | - | - | x | | bycopy| 1254 // | ptr | n.a. | - | - | x | x | bycopy| 1255 // | ptr | n.a. | - | - | x | x[] | bycopy| 1256 // ========================================================================= 1257 // Legend: 1258 // scl - scalar 1259 // ptr - pointer 1260 // agg - aggregate 1261 // x - applies 1262 // - - invalid in this combination 1263 // [] - mapped with an array section 1264 // byref - should be mapped by reference 1265 // byval - should be mapped by value 1266 // null - initialize a local variable to null on the device 1267 // 1268 // Observations: 1269 // - All scalar declarations that show up in a map clause have to be passed 1270 // by reference, because they may have been mapped in the enclosing data 1271 // environment. 1272 // - If the scalar value does not fit the size of uintptr, it has to be 1273 // passed by reference, regardless the result in the table above. 1274 // - For pointers mapped by value that have either an implicit map or an 1275 // array section, the runtime library may pass the NULL value to the 1276 // device instead of the value passed to it by the compiler. 1277 1278 if (Ty->isReferenceType()) 1279 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 1280 1281 // Locate map clauses and see if the variable being captured is referred to 1282 // in any of those clauses. Here we only care about variables, not fields, 1283 // because fields are part of aggregates. 1284 bool IsVariableUsedInMapClause = false; 1285 bool IsVariableAssociatedWithSection = false; 1286 1287 DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1288 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 1289 MapExprComponents, 1290 OpenMPClauseKind WhereFoundClauseKind) { 1291 // Only the map clause information influences how a variable is 1292 // captured. E.g. is_device_ptr does not require changing the default 1293 // behavior. 1294 if (WhereFoundClauseKind != OMPC_map) 1295 return false; 1296 1297 auto EI = MapExprComponents.rbegin(); 1298 auto EE = MapExprComponents.rend(); 1299 1300 assert(EI != EE && "Invalid map expression!"); 1301 1302 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 1303 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 1304 1305 ++EI; 1306 if (EI == EE) 1307 return false; 1308 1309 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 1310 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 1311 isa<MemberExpr>(EI->getAssociatedExpression())) { 1312 IsVariableAssociatedWithSection = true; 1313 // There is nothing more we need to know about this variable. 1314 return true; 1315 } 1316 1317 // Keep looking for more map info. 1318 return false; 1319 }); 1320 1321 if (IsVariableUsedInMapClause) { 1322 // If variable is identified in a map clause it is always captured by 1323 // reference except if it is a pointer that is dereferenced somehow. 1324 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 1325 } else { 1326 // By default, all the data that has a scalar type is mapped by copy 1327 // (except for reduction variables). 1328 IsByRef = 1329 !Ty->isScalarType() || 1330 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar || 1331 DSAStack->hasExplicitDSA( 1332 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level); 1333 } 1334 } 1335 1336 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 1337 IsByRef = 1338 !DSAStack->hasExplicitDSA( 1339 D, 1340 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; }, 1341 Level, /*NotLastprivate=*/true) && 1342 // If the variable is artificial and must be captured by value - try to 1343 // capture by value. 1344 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() && 1345 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue()); 1346 } 1347 1348 // When passing data by copy, we need to make sure it fits the uintptr size 1349 // and alignment, because the runtime library only deals with uintptr types. 1350 // If it does not fit the uintptr size, we need to pass the data by reference 1351 // instead. 1352 if (!IsByRef && 1353 (Ctx.getTypeSizeInChars(Ty) > 1354 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 1355 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 1356 IsByRef = true; 1357 } 1358 1359 return IsByRef; 1360 } 1361 1362 unsigned Sema::getOpenMPNestingLevel() const { 1363 assert(getLangOpts().OpenMP); 1364 return DSAStack->getNestingLevel(); 1365 } 1366 1367 bool Sema::isInOpenMPTargetExecutionDirective() const { 1368 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) && 1369 !DSAStack->isClauseParsingMode()) || 1370 DSAStack->hasDirective( 1371 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 1372 SourceLocation) -> bool { 1373 return isOpenMPTargetExecutionDirective(K); 1374 }, 1375 false); 1376 } 1377 1378 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) { 1379 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1380 D = getCanonicalDecl(D); 1381 1382 // If we are attempting to capture a global variable in a directive with 1383 // 'target' we return true so that this global is also mapped to the device. 1384 // 1385 // FIXME: If the declaration is enclosed in a 'declare target' directive, 1386 // then it should not be captured. Therefore, an extra check has to be 1387 // inserted here once support for 'declare target' is added. 1388 // 1389 auto *VD = dyn_cast<VarDecl>(D); 1390 if (VD && !VD->hasLocalStorage() && isInOpenMPTargetExecutionDirective()) 1391 return VD; 1392 1393 if (DSAStack->getCurrentDirective() != OMPD_unknown && 1394 (!DSAStack->isClauseParsingMode() || 1395 DSAStack->getParentDirective() != OMPD_unknown)) { 1396 auto &&Info = DSAStack->isLoopControlVariable(D); 1397 if (Info.first || 1398 (VD && VD->hasLocalStorage() && 1399 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) || 1400 (VD && DSAStack->isForceVarCapturing())) 1401 return VD ? VD : Info.second; 1402 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 1403 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind)) 1404 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1405 DVarPrivate = DSAStack->hasDSA( 1406 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 1407 DSAStack->isClauseParsingMode()); 1408 if (DVarPrivate.CKind != OMPC_unknown) 1409 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1410 } 1411 return nullptr; 1412 } 1413 1414 void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex, 1415 unsigned Level) const { 1416 SmallVector<OpenMPDirectiveKind, 4> Regions; 1417 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level)); 1418 FunctionScopesIndex -= Regions.size(); 1419 } 1420 1421 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) { 1422 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1423 return DSAStack->hasExplicitDSA( 1424 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, 1425 Level) || 1426 (DSAStack->isClauseParsingMode() && 1427 DSAStack->getClauseParsingMode() == OMPC_private) || 1428 // Consider taskgroup reduction descriptor variable a private to avoid 1429 // possible capture in the region. 1430 (DSAStack->hasExplicitDirective( 1431 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; }, 1432 Level) && 1433 DSAStack->isTaskgroupReductionRef(D, Level)); 1434 } 1435 1436 void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) { 1437 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1438 D = getCanonicalDecl(D); 1439 OpenMPClauseKind OMPC = OMPC_unknown; 1440 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) { 1441 const unsigned NewLevel = I - 1; 1442 if (DSAStack->hasExplicitDSA(D, 1443 [&OMPC](const OpenMPClauseKind K) { 1444 if (isOpenMPPrivate(K)) { 1445 OMPC = K; 1446 return true; 1447 } 1448 return false; 1449 }, 1450 NewLevel)) 1451 break; 1452 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1453 D, NewLevel, 1454 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 1455 OpenMPClauseKind) { return true; })) { 1456 OMPC = OMPC_map; 1457 break; 1458 } 1459 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1460 NewLevel)) { 1461 OMPC = OMPC_firstprivate; 1462 break; 1463 } 1464 } 1465 if (OMPC != OMPC_unknown) 1466 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC)); 1467 } 1468 1469 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) { 1470 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1471 // Return true if the current level is no longer enclosed in a target region. 1472 1473 auto *VD = dyn_cast<VarDecl>(D); 1474 return VD && !VD->hasLocalStorage() && 1475 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1476 Level); 1477 } 1478 1479 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 1480 1481 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 1482 const DeclarationNameInfo &DirName, 1483 Scope *CurScope, SourceLocation Loc) { 1484 DSAStack->push(DKind, DirName, CurScope, Loc); 1485 PushExpressionEvaluationContext( 1486 ExpressionEvaluationContext::PotentiallyEvaluated); 1487 } 1488 1489 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 1490 DSAStack->setClauseParsingMode(K); 1491 } 1492 1493 void Sema::EndOpenMPClause() { 1494 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 1495 } 1496 1497 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 1498 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 1499 // A variable of class type (or array thereof) that appears in a lastprivate 1500 // clause requires an accessible, unambiguous default constructor for the 1501 // class type, unless the list item is also specified in a firstprivate 1502 // clause. 1503 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 1504 for (auto *C : D->clauses()) { 1505 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 1506 SmallVector<Expr *, 8> PrivateCopies; 1507 for (auto *DE : Clause->varlists()) { 1508 if (DE->isValueDependent() || DE->isTypeDependent()) { 1509 PrivateCopies.push_back(nullptr); 1510 continue; 1511 } 1512 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 1513 VarDecl *VD = cast<VarDecl>(DRE->getDecl()); 1514 QualType Type = VD->getType().getNonReferenceType(); 1515 auto DVar = DSAStack->getTopDSA(VD, false); 1516 if (DVar.CKind == OMPC_lastprivate) { 1517 // Generate helper private variable and initialize it with the 1518 // default value. The address of the original variable is replaced 1519 // by the address of the new private variable in CodeGen. This new 1520 // variable is not added to IdResolver, so the code in the OpenMP 1521 // region uses original variable for proper diagnostics. 1522 auto *VDPrivate = buildVarDecl( 1523 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 1524 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr); 1525 ActOnUninitializedDecl(VDPrivate); 1526 if (VDPrivate->isInvalidDecl()) 1527 continue; 1528 PrivateCopies.push_back(buildDeclRefExpr( 1529 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 1530 } else { 1531 // The variable is also a firstprivate, so initialization sequence 1532 // for private copy is generated already. 1533 PrivateCopies.push_back(nullptr); 1534 } 1535 } 1536 // Set initializers to private copies if no errors were found. 1537 if (PrivateCopies.size() == Clause->varlist_size()) 1538 Clause->setPrivateCopies(PrivateCopies); 1539 } 1540 } 1541 } 1542 1543 DSAStack->pop(); 1544 DiscardCleanupsInEvaluationContext(); 1545 PopExpressionEvaluationContext(); 1546 } 1547 1548 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 1549 Expr *NumIterations, Sema &SemaRef, 1550 Scope *S, DSAStackTy *Stack); 1551 1552 namespace { 1553 1554 class VarDeclFilterCCC : public CorrectionCandidateCallback { 1555 private: 1556 Sema &SemaRef; 1557 1558 public: 1559 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 1560 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1561 NamedDecl *ND = Candidate.getCorrectionDecl(); 1562 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 1563 return VD->hasGlobalStorage() && 1564 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1565 SemaRef.getCurScope()); 1566 } 1567 return false; 1568 } 1569 }; 1570 1571 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback { 1572 private: 1573 Sema &SemaRef; 1574 1575 public: 1576 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 1577 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1578 NamedDecl *ND = Candidate.getCorrectionDecl(); 1579 if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) { 1580 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1581 SemaRef.getCurScope()); 1582 } 1583 return false; 1584 } 1585 }; 1586 1587 } // namespace 1588 1589 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 1590 CXXScopeSpec &ScopeSpec, 1591 const DeclarationNameInfo &Id) { 1592 LookupResult Lookup(*this, Id, LookupOrdinaryName); 1593 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 1594 1595 if (Lookup.isAmbiguous()) 1596 return ExprError(); 1597 1598 VarDecl *VD; 1599 if (!Lookup.isSingleResult()) { 1600 if (TypoCorrection Corrected = CorrectTypo( 1601 Id, LookupOrdinaryName, CurScope, nullptr, 1602 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) { 1603 diagnoseTypo(Corrected, 1604 PDiag(Lookup.empty() 1605 ? diag::err_undeclared_var_use_suggest 1606 : diag::err_omp_expected_var_arg_suggest) 1607 << Id.getName()); 1608 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 1609 } else { 1610 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 1611 : diag::err_omp_expected_var_arg) 1612 << Id.getName(); 1613 return ExprError(); 1614 } 1615 } else { 1616 if (!(VD = Lookup.getAsSingle<VarDecl>())) { 1617 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 1618 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 1619 return ExprError(); 1620 } 1621 } 1622 Lookup.suppressDiagnostics(); 1623 1624 // OpenMP [2.9.2, Syntax, C/C++] 1625 // Variables must be file-scope, namespace-scope, or static block-scope. 1626 if (!VD->hasGlobalStorage()) { 1627 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 1628 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal(); 1629 bool IsDecl = 1630 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1631 Diag(VD->getLocation(), 1632 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1633 << VD; 1634 return ExprError(); 1635 } 1636 1637 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 1638 NamedDecl *ND = CanonicalVD; 1639 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 1640 // A threadprivate directive for file-scope variables must appear outside 1641 // any definition or declaration. 1642 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 1643 !getCurLexicalContext()->isTranslationUnit()) { 1644 Diag(Id.getLoc(), diag::err_omp_var_scope) 1645 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1646 bool IsDecl = 1647 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1648 Diag(VD->getLocation(), 1649 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1650 << VD; 1651 return ExprError(); 1652 } 1653 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 1654 // A threadprivate directive for static class member variables must appear 1655 // in the class definition, in the same scope in which the member 1656 // variables are declared. 1657 if (CanonicalVD->isStaticDataMember() && 1658 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 1659 Diag(Id.getLoc(), diag::err_omp_var_scope) 1660 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1661 bool IsDecl = 1662 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1663 Diag(VD->getLocation(), 1664 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1665 << VD; 1666 return ExprError(); 1667 } 1668 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 1669 // A threadprivate directive for namespace-scope variables must appear 1670 // outside any definition or declaration other than the namespace 1671 // definition itself. 1672 if (CanonicalVD->getDeclContext()->isNamespace() && 1673 (!getCurLexicalContext()->isFileContext() || 1674 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 1675 Diag(Id.getLoc(), diag::err_omp_var_scope) 1676 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1677 bool IsDecl = 1678 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1679 Diag(VD->getLocation(), 1680 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1681 << VD; 1682 return ExprError(); 1683 } 1684 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 1685 // A threadprivate directive for static block-scope variables must appear 1686 // in the scope of the variable and not in a nested scope. 1687 if (CanonicalVD->isStaticLocal() && CurScope && 1688 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 1689 Diag(Id.getLoc(), diag::err_omp_var_scope) 1690 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1691 bool IsDecl = 1692 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1693 Diag(VD->getLocation(), 1694 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1695 << VD; 1696 return ExprError(); 1697 } 1698 1699 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 1700 // A threadprivate directive must lexically precede all references to any 1701 // of the variables in its list. 1702 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) { 1703 Diag(Id.getLoc(), diag::err_omp_var_used) 1704 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1705 return ExprError(); 1706 } 1707 1708 QualType ExprType = VD->getType().getNonReferenceType(); 1709 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 1710 SourceLocation(), VD, 1711 /*RefersToEnclosingVariableOrCapture=*/false, 1712 Id.getLoc(), ExprType, VK_LValue); 1713 } 1714 1715 Sema::DeclGroupPtrTy 1716 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 1717 ArrayRef<Expr *> VarList) { 1718 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 1719 CurContext->addDecl(D); 1720 return DeclGroupPtrTy::make(DeclGroupRef(D)); 1721 } 1722 return nullptr; 1723 } 1724 1725 namespace { 1726 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> { 1727 Sema &SemaRef; 1728 1729 public: 1730 bool VisitDeclRefExpr(const DeclRefExpr *E) { 1731 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1732 if (VD->hasLocalStorage()) { 1733 SemaRef.Diag(E->getLocStart(), 1734 diag::err_omp_local_var_in_threadprivate_init) 1735 << E->getSourceRange(); 1736 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 1737 << VD << VD->getSourceRange(); 1738 return true; 1739 } 1740 } 1741 return false; 1742 } 1743 bool VisitStmt(const Stmt *S) { 1744 for (auto Child : S->children()) { 1745 if (Child && Visit(Child)) 1746 return true; 1747 } 1748 return false; 1749 } 1750 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 1751 }; 1752 } // namespace 1753 1754 OMPThreadPrivateDecl * 1755 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 1756 SmallVector<Expr *, 8> Vars; 1757 for (auto &RefExpr : VarList) { 1758 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr); 1759 VarDecl *VD = cast<VarDecl>(DE->getDecl()); 1760 SourceLocation ILoc = DE->getExprLoc(); 1761 1762 // Mark variable as used. 1763 VD->setReferenced(); 1764 VD->markUsed(Context); 1765 1766 QualType QType = VD->getType(); 1767 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 1768 // It will be analyzed later. 1769 Vars.push_back(DE); 1770 continue; 1771 } 1772 1773 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1774 // A threadprivate variable must not have an incomplete type. 1775 if (RequireCompleteType(ILoc, VD->getType(), 1776 diag::err_omp_threadprivate_incomplete_type)) { 1777 continue; 1778 } 1779 1780 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1781 // A threadprivate variable must not have a reference type. 1782 if (VD->getType()->isReferenceType()) { 1783 Diag(ILoc, diag::err_omp_ref_type_arg) 1784 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 1785 bool IsDecl = 1786 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1787 Diag(VD->getLocation(), 1788 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1789 << VD; 1790 continue; 1791 } 1792 1793 // Check if this is a TLS variable. If TLS is not being supported, produce 1794 // the corresponding diagnostic. 1795 if ((VD->getTLSKind() != VarDecl::TLS_None && 1796 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1797 getLangOpts().OpenMPUseTLS && 1798 getASTContext().getTargetInfo().isTLSSupported())) || 1799 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 1800 !VD->isLocalVarDecl())) { 1801 Diag(ILoc, diag::err_omp_var_thread_local) 1802 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 1803 bool IsDecl = 1804 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1805 Diag(VD->getLocation(), 1806 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1807 << VD; 1808 continue; 1809 } 1810 1811 // Check if initial value of threadprivate variable reference variable with 1812 // local storage (it is not supported by runtime). 1813 if (auto Init = VD->getAnyInitializer()) { 1814 LocalVarRefChecker Checker(*this); 1815 if (Checker.Visit(Init)) 1816 continue; 1817 } 1818 1819 Vars.push_back(RefExpr); 1820 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 1821 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 1822 Context, SourceRange(Loc, Loc))); 1823 if (auto *ML = Context.getASTMutationListener()) 1824 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 1825 } 1826 OMPThreadPrivateDecl *D = nullptr; 1827 if (!Vars.empty()) { 1828 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 1829 Vars); 1830 D->setAccess(AS_public); 1831 } 1832 return D; 1833 } 1834 1835 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack, 1836 const ValueDecl *D, DSAStackTy::DSAVarData DVar, 1837 bool IsLoopIterVar = false) { 1838 if (DVar.RefExpr) { 1839 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 1840 << getOpenMPClauseName(DVar.CKind); 1841 return; 1842 } 1843 enum { 1844 PDSA_StaticMemberShared, 1845 PDSA_StaticLocalVarShared, 1846 PDSA_LoopIterVarPrivate, 1847 PDSA_LoopIterVarLinear, 1848 PDSA_LoopIterVarLastprivate, 1849 PDSA_ConstVarShared, 1850 PDSA_GlobalVarShared, 1851 PDSA_TaskVarFirstprivate, 1852 PDSA_LocalVarPrivate, 1853 PDSA_Implicit 1854 } Reason = PDSA_Implicit; 1855 bool ReportHint = false; 1856 auto ReportLoc = D->getLocation(); 1857 auto *VD = dyn_cast<VarDecl>(D); 1858 if (IsLoopIterVar) { 1859 if (DVar.CKind == OMPC_private) 1860 Reason = PDSA_LoopIterVarPrivate; 1861 else if (DVar.CKind == OMPC_lastprivate) 1862 Reason = PDSA_LoopIterVarLastprivate; 1863 else 1864 Reason = PDSA_LoopIterVarLinear; 1865 } else if (isOpenMPTaskingDirective(DVar.DKind) && 1866 DVar.CKind == OMPC_firstprivate) { 1867 Reason = PDSA_TaskVarFirstprivate; 1868 ReportLoc = DVar.ImplicitDSALoc; 1869 } else if (VD && VD->isStaticLocal()) 1870 Reason = PDSA_StaticLocalVarShared; 1871 else if (VD && VD->isStaticDataMember()) 1872 Reason = PDSA_StaticMemberShared; 1873 else if (VD && VD->isFileVarDecl()) 1874 Reason = PDSA_GlobalVarShared; 1875 else if (D->getType().isConstant(SemaRef.getASTContext())) 1876 Reason = PDSA_ConstVarShared; 1877 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 1878 ReportHint = true; 1879 Reason = PDSA_LocalVarPrivate; 1880 } 1881 if (Reason != PDSA_Implicit) { 1882 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 1883 << Reason << ReportHint 1884 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 1885 } else if (DVar.ImplicitDSALoc.isValid()) { 1886 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 1887 << getOpenMPClauseName(DVar.CKind); 1888 } 1889 } 1890 1891 namespace { 1892 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> { 1893 DSAStackTy *Stack; 1894 Sema &SemaRef; 1895 bool ErrorFound; 1896 CapturedStmt *CS; 1897 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate; 1898 llvm::SmallVector<Expr *, 8> ImplicitMap; 1899 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 1900 llvm::DenseSet<ValueDecl *> ImplicitDeclarations; 1901 1902 public: 1903 void VisitDeclRefExpr(DeclRefExpr *E) { 1904 if (E->isTypeDependent() || E->isValueDependent() || 1905 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1906 return; 1907 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1908 VD = VD->getCanonicalDecl(); 1909 // Skip internally declared variables. 1910 if (VD->hasLocalStorage() && !CS->capturesVariable(VD)) 1911 return; 1912 1913 auto DVar = Stack->getTopDSA(VD, false); 1914 // Check if the variable has explicit DSA set and stop analysis if it so. 1915 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second) 1916 return; 1917 1918 // Skip internally declared static variables. 1919 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD)) 1920 return; 1921 1922 auto ELoc = E->getExprLoc(); 1923 auto DKind = Stack->getCurrentDirective(); 1924 // The default(none) clause requires that each variable that is referenced 1925 // in the construct, and does not have a predetermined data-sharing 1926 // attribute, must have its data-sharing attribute explicitly determined 1927 // by being listed in a data-sharing attribute clause. 1928 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && 1929 isParallelOrTaskRegion(DKind) && 1930 VarsWithInheritedDSA.count(VD) == 0) { 1931 VarsWithInheritedDSA[VD] = E; 1932 return; 1933 } 1934 1935 if (isOpenMPTargetExecutionDirective(DKind) && 1936 !Stack->isLoopControlVariable(VD).first) { 1937 if (!Stack->checkMappableExprComponentListsForDecl( 1938 VD, /*CurrentRegionOnly=*/true, 1939 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 1940 StackComponents, 1941 OpenMPClauseKind) { 1942 // Variable is used if it has been marked as an array, array 1943 // section or the variable iself. 1944 return StackComponents.size() == 1 || 1945 std::all_of( 1946 std::next(StackComponents.rbegin()), 1947 StackComponents.rend(), 1948 [](const OMPClauseMappableExprCommon:: 1949 MappableComponent &MC) { 1950 return MC.getAssociatedDeclaration() == 1951 nullptr && 1952 (isa<OMPArraySectionExpr>( 1953 MC.getAssociatedExpression()) || 1954 isa<ArraySubscriptExpr>( 1955 MC.getAssociatedExpression())); 1956 }); 1957 })) { 1958 bool IsFirstprivate = false; 1959 // By default lambdas are captured as firstprivates. 1960 if (const auto *RD = 1961 VD->getType().getNonReferenceType()->getAsCXXRecordDecl()) 1962 IsFirstprivate = RD->isLambda(); 1963 IsFirstprivate = 1964 IsFirstprivate || 1965 (VD->getType().getNonReferenceType()->isScalarType() && 1966 Stack->getDefaultDMA() != DMA_tofrom_scalar); 1967 if (IsFirstprivate) 1968 ImplicitFirstprivate.emplace_back(E); 1969 else 1970 ImplicitMap.emplace_back(E); 1971 return; 1972 } 1973 } 1974 1975 // OpenMP [2.9.3.6, Restrictions, p.2] 1976 // A list item that appears in a reduction clause of the innermost 1977 // enclosing worksharing or parallel construct may not be accessed in an 1978 // explicit task. 1979 DVar = Stack->hasInnermostDSA( 1980 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 1981 [](OpenMPDirectiveKind K) -> bool { 1982 return isOpenMPParallelDirective(K) || 1983 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 1984 }, 1985 /*FromParent=*/true); 1986 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 1987 ErrorFound = true; 1988 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1989 ReportOriginalDSA(SemaRef, Stack, VD, DVar); 1990 return; 1991 } 1992 1993 // Define implicit data-sharing attributes for task. 1994 DVar = Stack->getImplicitDSA(VD, false); 1995 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 1996 !Stack->isLoopControlVariable(VD).first) 1997 ImplicitFirstprivate.push_back(E); 1998 } 1999 } 2000 void VisitMemberExpr(MemberExpr *E) { 2001 if (E->isTypeDependent() || E->isValueDependent() || 2002 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 2003 return; 2004 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl()); 2005 OpenMPDirectiveKind DKind = Stack->getCurrentDirective(); 2006 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 2007 if (!FD) 2008 return; 2009 auto DVar = Stack->getTopDSA(FD, false); 2010 // Check if the variable has explicit DSA set and stop analysis if it 2011 // so. 2012 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second) 2013 return; 2014 2015 if (isOpenMPTargetExecutionDirective(DKind) && 2016 !Stack->isLoopControlVariable(FD).first && 2017 !Stack->checkMappableExprComponentListsForDecl( 2018 FD, /*CurrentRegionOnly=*/true, 2019 [](OMPClauseMappableExprCommon::MappableExprComponentListRef 2020 StackComponents, 2021 OpenMPClauseKind) { 2022 return isa<CXXThisExpr>( 2023 cast<MemberExpr>( 2024 StackComponents.back().getAssociatedExpression()) 2025 ->getBase() 2026 ->IgnoreParens()); 2027 })) { 2028 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 2029 // A bit-field cannot appear in a map clause. 2030 // 2031 if (FD->isBitField()) 2032 return; 2033 ImplicitMap.emplace_back(E); 2034 return; 2035 } 2036 2037 auto ELoc = E->getExprLoc(); 2038 // OpenMP [2.9.3.6, Restrictions, p.2] 2039 // A list item that appears in a reduction clause of the innermost 2040 // enclosing worksharing or parallel construct may not be accessed in 2041 // an explicit task. 2042 DVar = Stack->hasInnermostDSA( 2043 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 2044 [](OpenMPDirectiveKind K) -> bool { 2045 return isOpenMPParallelDirective(K) || 2046 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 2047 }, 2048 /*FromParent=*/true); 2049 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 2050 ErrorFound = true; 2051 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 2052 ReportOriginalDSA(SemaRef, Stack, FD, DVar); 2053 return; 2054 } 2055 2056 // Define implicit data-sharing attributes for task. 2057 DVar = Stack->getImplicitDSA(FD, false); 2058 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 2059 !Stack->isLoopControlVariable(FD).first) 2060 ImplicitFirstprivate.push_back(E); 2061 return; 2062 } 2063 if (isOpenMPTargetExecutionDirective(DKind)) { 2064 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 2065 if (!CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map, 2066 /*NoDiagnose=*/true)) 2067 return; 2068 auto *VD = cast<ValueDecl>( 2069 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl()); 2070 if (!Stack->checkMappableExprComponentListsForDecl( 2071 VD, /*CurrentRegionOnly=*/true, 2072 [&CurComponents]( 2073 OMPClauseMappableExprCommon::MappableExprComponentListRef 2074 StackComponents, 2075 OpenMPClauseKind) { 2076 auto CCI = CurComponents.rbegin(); 2077 auto CCE = CurComponents.rend(); 2078 for (const auto &SC : llvm::reverse(StackComponents)) { 2079 // Do both expressions have the same kind? 2080 if (CCI->getAssociatedExpression()->getStmtClass() != 2081 SC.getAssociatedExpression()->getStmtClass()) 2082 if (!(isa<OMPArraySectionExpr>( 2083 SC.getAssociatedExpression()) && 2084 isa<ArraySubscriptExpr>( 2085 CCI->getAssociatedExpression()))) 2086 return false; 2087 2088 Decl *CCD = CCI->getAssociatedDeclaration(); 2089 Decl *SCD = SC.getAssociatedDeclaration(); 2090 CCD = CCD ? CCD->getCanonicalDecl() : nullptr; 2091 SCD = SCD ? SCD->getCanonicalDecl() : nullptr; 2092 if (SCD != CCD) 2093 return false; 2094 std::advance(CCI, 1); 2095 if (CCI == CCE) 2096 break; 2097 } 2098 return true; 2099 })) { 2100 Visit(E->getBase()); 2101 } 2102 } else 2103 Visit(E->getBase()); 2104 } 2105 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 2106 for (auto *C : S->clauses()) { 2107 // Skip analysis of arguments of implicitly defined firstprivate clause 2108 // for task|target directives. 2109 // Skip analysis of arguments of implicitly defined map clause for target 2110 // directives. 2111 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) && 2112 C->isImplicit())) { 2113 for (auto *CC : C->children()) { 2114 if (CC) 2115 Visit(CC); 2116 } 2117 } 2118 } 2119 } 2120 void VisitStmt(Stmt *S) { 2121 for (auto *C : S->children()) { 2122 if (C && !isa<OMPExecutableDirective>(C)) 2123 Visit(C); 2124 } 2125 } 2126 2127 bool isErrorFound() { return ErrorFound; } 2128 ArrayRef<Expr *> getImplicitFirstprivate() const { 2129 return ImplicitFirstprivate; 2130 } 2131 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; } 2132 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() { 2133 return VarsWithInheritedDSA; 2134 } 2135 2136 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 2137 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {} 2138 }; 2139 } // namespace 2140 2141 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 2142 switch (DKind) { 2143 case OMPD_parallel: 2144 case OMPD_parallel_for: 2145 case OMPD_parallel_for_simd: 2146 case OMPD_parallel_sections: 2147 case OMPD_teams: 2148 case OMPD_teams_distribute: 2149 case OMPD_teams_distribute_simd: { 2150 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2151 QualType KmpInt32PtrTy = 2152 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2153 Sema::CapturedParamNameType Params[] = { 2154 std::make_pair(".global_tid.", KmpInt32PtrTy), 2155 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2156 std::make_pair(StringRef(), QualType()) // __context with shared vars 2157 }; 2158 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2159 Params); 2160 break; 2161 } 2162 case OMPD_target_teams: 2163 case OMPD_target_parallel: 2164 case OMPD_target_parallel_for: 2165 case OMPD_target_parallel_for_simd: 2166 case OMPD_target_teams_distribute: 2167 case OMPD_target_teams_distribute_simd: { 2168 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2169 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 2170 FunctionProtoType::ExtProtoInfo EPI; 2171 EPI.Variadic = true; 2172 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2173 Sema::CapturedParamNameType Params[] = { 2174 std::make_pair(".global_tid.", KmpInt32Ty), 2175 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 2176 std::make_pair(".privates.", Context.VoidPtrTy.withConst()), 2177 std::make_pair(".copy_fn.", 2178 Context.getPointerType(CopyFnType).withConst()), 2179 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2180 std::make_pair(StringRef(), QualType()) // __context with shared vars 2181 }; 2182 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2183 Params); 2184 // Mark this captured region as inlined, because we don't use outlined 2185 // function directly. 2186 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2187 AlwaysInlineAttr::CreateImplicit( 2188 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 2189 Sema::CapturedParamNameType ParamsTarget[] = { 2190 std::make_pair(StringRef(), QualType()) // __context with shared vars 2191 }; 2192 // Start a captured region for 'target' with no implicit parameters. 2193 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2194 ParamsTarget); 2195 QualType KmpInt32PtrTy = 2196 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2197 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 2198 std::make_pair(".global_tid.", KmpInt32PtrTy), 2199 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2200 std::make_pair(StringRef(), QualType()) // __context with shared vars 2201 }; 2202 // Start a captured region for 'teams' or 'parallel'. Both regions have 2203 // the same implicit parameters. 2204 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2205 ParamsTeamsOrParallel); 2206 break; 2207 } 2208 case OMPD_target: 2209 case OMPD_target_simd: { 2210 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2211 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 2212 FunctionProtoType::ExtProtoInfo EPI; 2213 EPI.Variadic = true; 2214 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2215 Sema::CapturedParamNameType Params[] = { 2216 std::make_pair(".global_tid.", KmpInt32Ty), 2217 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 2218 std::make_pair(".privates.", Context.VoidPtrTy.withConst()), 2219 std::make_pair(".copy_fn.", 2220 Context.getPointerType(CopyFnType).withConst()), 2221 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2222 std::make_pair(StringRef(), QualType()) // __context with shared vars 2223 }; 2224 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2225 Params); 2226 // Mark this captured region as inlined, because we don't use outlined 2227 // function directly. 2228 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2229 AlwaysInlineAttr::CreateImplicit( 2230 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 2231 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2232 std::make_pair(StringRef(), QualType())); 2233 break; 2234 } 2235 case OMPD_simd: 2236 case OMPD_for: 2237 case OMPD_for_simd: 2238 case OMPD_sections: 2239 case OMPD_section: 2240 case OMPD_single: 2241 case OMPD_master: 2242 case OMPD_critical: 2243 case OMPD_taskgroup: 2244 case OMPD_distribute: 2245 case OMPD_distribute_simd: 2246 case OMPD_ordered: 2247 case OMPD_atomic: 2248 case OMPD_target_data: { 2249 Sema::CapturedParamNameType Params[] = { 2250 std::make_pair(StringRef(), QualType()) // __context with shared vars 2251 }; 2252 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2253 Params); 2254 break; 2255 } 2256 case OMPD_task: { 2257 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2258 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 2259 FunctionProtoType::ExtProtoInfo EPI; 2260 EPI.Variadic = true; 2261 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2262 Sema::CapturedParamNameType Params[] = { 2263 std::make_pair(".global_tid.", KmpInt32Ty), 2264 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 2265 std::make_pair(".privates.", Context.VoidPtrTy.withConst()), 2266 std::make_pair(".copy_fn.", 2267 Context.getPointerType(CopyFnType).withConst()), 2268 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2269 std::make_pair(StringRef(), QualType()) // __context with shared vars 2270 }; 2271 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2272 Params); 2273 // Mark this captured region as inlined, because we don't use outlined 2274 // function directly. 2275 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2276 AlwaysInlineAttr::CreateImplicit( 2277 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 2278 break; 2279 } 2280 case OMPD_taskloop: 2281 case OMPD_taskloop_simd: { 2282 QualType KmpInt32Ty = 2283 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 2284 QualType KmpUInt64Ty = 2285 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 2286 QualType KmpInt64Ty = 2287 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 2288 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 2289 FunctionProtoType::ExtProtoInfo EPI; 2290 EPI.Variadic = true; 2291 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2292 Sema::CapturedParamNameType Params[] = { 2293 std::make_pair(".global_tid.", KmpInt32Ty), 2294 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 2295 std::make_pair(".privates.", 2296 Context.VoidPtrTy.withConst().withRestrict()), 2297 std::make_pair( 2298 ".copy_fn.", 2299 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2300 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2301 std::make_pair(".lb.", KmpUInt64Ty), 2302 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty), 2303 std::make_pair(".liter.", KmpInt32Ty), 2304 std::make_pair(".reductions.", 2305 Context.VoidPtrTy.withConst().withRestrict()), 2306 std::make_pair(StringRef(), QualType()) // __context with shared vars 2307 }; 2308 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2309 Params); 2310 // Mark this captured region as inlined, because we don't use outlined 2311 // function directly. 2312 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2313 AlwaysInlineAttr::CreateImplicit( 2314 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 2315 break; 2316 } 2317 case OMPD_distribute_parallel_for_simd: 2318 case OMPD_distribute_parallel_for: { 2319 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2320 QualType KmpInt32PtrTy = 2321 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2322 Sema::CapturedParamNameType Params[] = { 2323 std::make_pair(".global_tid.", KmpInt32PtrTy), 2324 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2325 std::make_pair(".previous.lb.", Context.getSizeType()), 2326 std::make_pair(".previous.ub.", Context.getSizeType()), 2327 std::make_pair(StringRef(), QualType()) // __context with shared vars 2328 }; 2329 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2330 Params); 2331 break; 2332 } 2333 case OMPD_target_teams_distribute_parallel_for: 2334 case OMPD_target_teams_distribute_parallel_for_simd: { 2335 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2336 QualType KmpInt32PtrTy = 2337 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2338 2339 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 2340 FunctionProtoType::ExtProtoInfo EPI; 2341 EPI.Variadic = true; 2342 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2343 Sema::CapturedParamNameType Params[] = { 2344 std::make_pair(".global_tid.", KmpInt32Ty), 2345 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 2346 std::make_pair(".privates.", Context.VoidPtrTy.withConst()), 2347 std::make_pair(".copy_fn.", 2348 Context.getPointerType(CopyFnType).withConst()), 2349 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2350 std::make_pair(StringRef(), QualType()) // __context with shared vars 2351 }; 2352 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2353 Params); 2354 // Mark this captured region as inlined, because we don't use outlined 2355 // function directly. 2356 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2357 AlwaysInlineAttr::CreateImplicit( 2358 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 2359 Sema::CapturedParamNameType ParamsTarget[] = { 2360 std::make_pair(StringRef(), QualType()) // __context with shared vars 2361 }; 2362 // Start a captured region for 'target' with no implicit parameters. 2363 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2364 ParamsTarget); 2365 2366 Sema::CapturedParamNameType ParamsTeams[] = { 2367 std::make_pair(".global_tid.", KmpInt32PtrTy), 2368 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2369 std::make_pair(StringRef(), QualType()) // __context with shared vars 2370 }; 2371 // Start a captured region for 'target' with no implicit parameters. 2372 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2373 ParamsTeams); 2374 2375 Sema::CapturedParamNameType ParamsParallel[] = { 2376 std::make_pair(".global_tid.", KmpInt32PtrTy), 2377 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2378 std::make_pair(".previous.lb.", Context.getSizeType()), 2379 std::make_pair(".previous.ub.", Context.getSizeType()), 2380 std::make_pair(StringRef(), QualType()) // __context with shared vars 2381 }; 2382 // Start a captured region for 'teams' or 'parallel'. Both regions have 2383 // the same implicit parameters. 2384 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2385 ParamsParallel); 2386 break; 2387 } 2388 2389 case OMPD_teams_distribute_parallel_for: 2390 case OMPD_teams_distribute_parallel_for_simd: { 2391 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2392 QualType KmpInt32PtrTy = 2393 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2394 2395 Sema::CapturedParamNameType ParamsTeams[] = { 2396 std::make_pair(".global_tid.", KmpInt32PtrTy), 2397 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2398 std::make_pair(StringRef(), QualType()) // __context with shared vars 2399 }; 2400 // Start a captured region for 'target' with no implicit parameters. 2401 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2402 ParamsTeams); 2403 2404 Sema::CapturedParamNameType ParamsParallel[] = { 2405 std::make_pair(".global_tid.", KmpInt32PtrTy), 2406 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2407 std::make_pair(".previous.lb.", Context.getSizeType()), 2408 std::make_pair(".previous.ub.", Context.getSizeType()), 2409 std::make_pair(StringRef(), QualType()) // __context with shared vars 2410 }; 2411 // Start a captured region for 'teams' or 'parallel'. Both regions have 2412 // the same implicit parameters. 2413 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2414 ParamsParallel); 2415 break; 2416 } 2417 case OMPD_target_update: 2418 case OMPD_target_enter_data: 2419 case OMPD_target_exit_data: { 2420 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2421 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 2422 FunctionProtoType::ExtProtoInfo EPI; 2423 EPI.Variadic = true; 2424 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2425 Sema::CapturedParamNameType Params[] = { 2426 std::make_pair(".global_tid.", KmpInt32Ty), 2427 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 2428 std::make_pair(".privates.", Context.VoidPtrTy.withConst()), 2429 std::make_pair(".copy_fn.", 2430 Context.getPointerType(CopyFnType).withConst()), 2431 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2432 std::make_pair(StringRef(), QualType()) // __context with shared vars 2433 }; 2434 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2435 Params); 2436 // Mark this captured region as inlined, because we don't use outlined 2437 // function directly. 2438 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2439 AlwaysInlineAttr::CreateImplicit( 2440 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 2441 break; 2442 } 2443 case OMPD_threadprivate: 2444 case OMPD_taskyield: 2445 case OMPD_barrier: 2446 case OMPD_taskwait: 2447 case OMPD_cancellation_point: 2448 case OMPD_cancel: 2449 case OMPD_flush: 2450 case OMPD_declare_reduction: 2451 case OMPD_declare_simd: 2452 case OMPD_declare_target: 2453 case OMPD_end_declare_target: 2454 llvm_unreachable("OpenMP Directive is not allowed"); 2455 case OMPD_unknown: 2456 llvm_unreachable("Unknown OpenMP directive"); 2457 } 2458 } 2459 2460 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 2461 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2462 getOpenMPCaptureRegions(CaptureRegions, DKind); 2463 return CaptureRegions.size(); 2464 } 2465 2466 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 2467 Expr *CaptureExpr, bool WithInit, 2468 bool AsExpression) { 2469 assert(CaptureExpr); 2470 ASTContext &C = S.getASTContext(); 2471 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 2472 QualType Ty = Init->getType(); 2473 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 2474 if (S.getLangOpts().CPlusPlus) { 2475 Ty = C.getLValueReferenceType(Ty); 2476 } else { 2477 Ty = C.getPointerType(Ty); 2478 ExprResult Res = 2479 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 2480 if (!Res.isUsable()) 2481 return nullptr; 2482 Init = Res.get(); 2483 } 2484 WithInit = true; 2485 } 2486 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 2487 CaptureExpr->getLocStart()); 2488 if (!WithInit) 2489 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange())); 2490 S.CurContext->addHiddenDecl(CED); 2491 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 2492 return CED; 2493 } 2494 2495 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 2496 bool WithInit) { 2497 OMPCapturedExprDecl *CD; 2498 if (auto *VD = S.IsOpenMPCapturedDecl(D)) { 2499 CD = cast<OMPCapturedExprDecl>(VD); 2500 } else { 2501 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 2502 /*AsExpression=*/false); 2503 } 2504 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 2505 CaptureExpr->getExprLoc()); 2506 } 2507 2508 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 2509 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get(); 2510 if (!Ref) { 2511 OMPCapturedExprDecl *CD = buildCaptureDecl( 2512 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr, 2513 /*WithInit=*/true, /*AsExpression=*/true); 2514 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 2515 CaptureExpr->getExprLoc()); 2516 } 2517 ExprResult Res = Ref; 2518 if (!S.getLangOpts().CPlusPlus && 2519 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 2520 Ref->getType()->isPointerType()) { 2521 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 2522 if (!Res.isUsable()) 2523 return ExprError(); 2524 } 2525 return S.DefaultLvalueConversion(Res.get()); 2526 } 2527 2528 namespace { 2529 // OpenMP directives parsed in this section are represented as a 2530 // CapturedStatement with an associated statement. If a syntax error 2531 // is detected during the parsing of the associated statement, the 2532 // compiler must abort processing and close the CapturedStatement. 2533 // 2534 // Combined directives such as 'target parallel' have more than one 2535 // nested CapturedStatements. This RAII ensures that we unwind out 2536 // of all the nested CapturedStatements when an error is found. 2537 class CaptureRegionUnwinderRAII { 2538 private: 2539 Sema &S; 2540 bool &ErrorFound; 2541 OpenMPDirectiveKind DKind; 2542 2543 public: 2544 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 2545 OpenMPDirectiveKind DKind) 2546 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 2547 ~CaptureRegionUnwinderRAII() { 2548 if (ErrorFound) { 2549 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 2550 while (--ThisCaptureLevel >= 0) 2551 S.ActOnCapturedRegionError(); 2552 } 2553 } 2554 }; 2555 } // namespace 2556 2557 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 2558 ArrayRef<OMPClause *> Clauses) { 2559 bool ErrorFound = false; 2560 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 2561 *this, ErrorFound, DSAStack->getCurrentDirective()); 2562 if (!S.isUsable()) { 2563 ErrorFound = true; 2564 return StmtError(); 2565 } 2566 2567 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2568 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 2569 OMPOrderedClause *OC = nullptr; 2570 OMPScheduleClause *SC = nullptr; 2571 SmallVector<OMPLinearClause *, 4> LCs; 2572 SmallVector<OMPClauseWithPreInit *, 8> PICs; 2573 // This is required for proper codegen. 2574 for (auto *Clause : Clauses) { 2575 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) && 2576 Clause->getClauseKind() == OMPC_in_reduction) { 2577 // Capture taskgroup task_reduction descriptors inside the tasking regions 2578 // with the corresponding in_reduction items. 2579 auto *IRC = cast<OMPInReductionClause>(Clause); 2580 for (auto *E : IRC->taskgroup_descriptors()) 2581 if (E) 2582 MarkDeclarationsReferencedInExpr(E); 2583 } 2584 if (isOpenMPPrivate(Clause->getClauseKind()) || 2585 Clause->getClauseKind() == OMPC_copyprivate || 2586 (getLangOpts().OpenMPUseTLS && 2587 getASTContext().getTargetInfo().isTLSSupported() && 2588 Clause->getClauseKind() == OMPC_copyin)) { 2589 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 2590 // Mark all variables in private list clauses as used in inner region. 2591 for (auto *VarRef : Clause->children()) { 2592 if (auto *E = cast_or_null<Expr>(VarRef)) { 2593 MarkDeclarationsReferencedInExpr(E); 2594 } 2595 } 2596 DSAStack->setForceVarCapturing(/*V=*/false); 2597 } else if (CaptureRegions.size() > 1 || 2598 CaptureRegions.back() != OMPD_unknown) { 2599 if (auto *C = OMPClauseWithPreInit::get(Clause)) 2600 PICs.push_back(C); 2601 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 2602 if (auto *E = C->getPostUpdateExpr()) 2603 MarkDeclarationsReferencedInExpr(E); 2604 } 2605 } 2606 if (Clause->getClauseKind() == OMPC_schedule) 2607 SC = cast<OMPScheduleClause>(Clause); 2608 else if (Clause->getClauseKind() == OMPC_ordered) 2609 OC = cast<OMPOrderedClause>(Clause); 2610 else if (Clause->getClauseKind() == OMPC_linear) 2611 LCs.push_back(cast<OMPLinearClause>(Clause)); 2612 } 2613 // OpenMP, 2.7.1 Loop Construct, Restrictions 2614 // The nonmonotonic modifier cannot be specified if an ordered clause is 2615 // specified. 2616 if (SC && 2617 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 2618 SC->getSecondScheduleModifier() == 2619 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 2620 OC) { 2621 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 2622 ? SC->getFirstScheduleModifierLoc() 2623 : SC->getSecondScheduleModifierLoc(), 2624 diag::err_omp_schedule_nonmonotonic_ordered) 2625 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 2626 ErrorFound = true; 2627 } 2628 if (!LCs.empty() && OC && OC->getNumForLoops()) { 2629 for (auto *C : LCs) { 2630 Diag(C->getLocStart(), diag::err_omp_linear_ordered) 2631 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 2632 } 2633 ErrorFound = true; 2634 } 2635 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 2636 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 2637 OC->getNumForLoops()) { 2638 Diag(OC->getLocStart(), diag::err_omp_ordered_simd) 2639 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 2640 ErrorFound = true; 2641 } 2642 if (ErrorFound) { 2643 return StmtError(); 2644 } 2645 StmtResult SR = S; 2646 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 2647 // Mark all variables in private list clauses as used in inner region. 2648 // Required for proper codegen of combined directives. 2649 // TODO: add processing for other clauses. 2650 if (ThisCaptureRegion != OMPD_unknown) { 2651 for (auto *C : PICs) { 2652 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 2653 // Find the particular capture region for the clause if the 2654 // directive is a combined one with multiple capture regions. 2655 // If the directive is not a combined one, the capture region 2656 // associated with the clause is OMPD_unknown and is generated 2657 // only once. 2658 if (CaptureRegion == ThisCaptureRegion || 2659 CaptureRegion == OMPD_unknown) { 2660 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 2661 for (auto *D : DS->decls()) 2662 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 2663 } 2664 } 2665 } 2666 } 2667 SR = ActOnCapturedRegionEnd(SR.get()); 2668 } 2669 return SR; 2670 } 2671 2672 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 2673 OpenMPDirectiveKind CancelRegion, 2674 SourceLocation StartLoc) { 2675 // CancelRegion is only needed for cancel and cancellation_point. 2676 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 2677 return false; 2678 2679 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 2680 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 2681 return false; 2682 2683 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 2684 << getOpenMPDirectiveName(CancelRegion); 2685 return true; 2686 } 2687 2688 static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack, 2689 OpenMPDirectiveKind CurrentRegion, 2690 const DeclarationNameInfo &CurrentName, 2691 OpenMPDirectiveKind CancelRegion, 2692 SourceLocation StartLoc) { 2693 if (Stack->getCurScope()) { 2694 auto ParentRegion = Stack->getParentDirective(); 2695 auto OffendingRegion = ParentRegion; 2696 bool NestingProhibited = false; 2697 bool CloseNesting = true; 2698 bool OrphanSeen = false; 2699 enum { 2700 NoRecommend, 2701 ShouldBeInParallelRegion, 2702 ShouldBeInOrderedRegion, 2703 ShouldBeInTargetRegion, 2704 ShouldBeInTeamsRegion 2705 } Recommend = NoRecommend; 2706 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { 2707 // OpenMP [2.16, Nesting of Regions] 2708 // OpenMP constructs may not be nested inside a simd region. 2709 // OpenMP [2.8.1,simd Construct, Restrictions] 2710 // An ordered construct with the simd clause is the only OpenMP 2711 // construct that can appear in the simd region. 2712 // Allowing a SIMD construct nested in another SIMD construct is an 2713 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 2714 // message. 2715 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 2716 ? diag::err_omp_prohibited_region_simd 2717 : diag::warn_omp_nesting_simd); 2718 return CurrentRegion != OMPD_simd; 2719 } 2720 if (ParentRegion == OMPD_atomic) { 2721 // OpenMP [2.16, Nesting of Regions] 2722 // OpenMP constructs may not be nested inside an atomic region. 2723 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 2724 return true; 2725 } 2726 if (CurrentRegion == OMPD_section) { 2727 // OpenMP [2.7.2, sections Construct, Restrictions] 2728 // Orphaned section directives are prohibited. That is, the section 2729 // directives must appear within the sections construct and must not be 2730 // encountered elsewhere in the sections region. 2731 if (ParentRegion != OMPD_sections && 2732 ParentRegion != OMPD_parallel_sections) { 2733 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 2734 << (ParentRegion != OMPD_unknown) 2735 << getOpenMPDirectiveName(ParentRegion); 2736 return true; 2737 } 2738 return false; 2739 } 2740 // Allow some constructs (except teams) to be orphaned (they could be 2741 // used in functions, called from OpenMP regions with the required 2742 // preconditions). 2743 if (ParentRegion == OMPD_unknown && 2744 !isOpenMPNestingTeamsDirective(CurrentRegion)) 2745 return false; 2746 if (CurrentRegion == OMPD_cancellation_point || 2747 CurrentRegion == OMPD_cancel) { 2748 // OpenMP [2.16, Nesting of Regions] 2749 // A cancellation point construct for which construct-type-clause is 2750 // taskgroup must be nested inside a task construct. A cancellation 2751 // point construct for which construct-type-clause is not taskgroup must 2752 // be closely nested inside an OpenMP construct that matches the type 2753 // specified in construct-type-clause. 2754 // A cancel construct for which construct-type-clause is taskgroup must be 2755 // nested inside a task construct. A cancel construct for which 2756 // construct-type-clause is not taskgroup must be closely nested inside an 2757 // OpenMP construct that matches the type specified in 2758 // construct-type-clause. 2759 NestingProhibited = 2760 !((CancelRegion == OMPD_parallel && 2761 (ParentRegion == OMPD_parallel || 2762 ParentRegion == OMPD_target_parallel)) || 2763 (CancelRegion == OMPD_for && 2764 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 2765 ParentRegion == OMPD_target_parallel_for || 2766 ParentRegion == OMPD_distribute_parallel_for || 2767 ParentRegion == OMPD_teams_distribute_parallel_for || 2768 ParentRegion == OMPD_target_teams_distribute_parallel_for)) || 2769 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || 2770 (CancelRegion == OMPD_sections && 2771 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 2772 ParentRegion == OMPD_parallel_sections))); 2773 } else if (CurrentRegion == OMPD_master) { 2774 // OpenMP [2.16, Nesting of Regions] 2775 // A master region may not be closely nested inside a worksharing, 2776 // atomic, or explicit task region. 2777 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2778 isOpenMPTaskingDirective(ParentRegion); 2779 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 2780 // OpenMP [2.16, Nesting of Regions] 2781 // A critical region may not be nested (closely or otherwise) inside a 2782 // critical region with the same name. Note that this restriction is not 2783 // sufficient to prevent deadlock. 2784 SourceLocation PreviousCriticalLoc; 2785 bool DeadLock = Stack->hasDirective( 2786 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 2787 const DeclarationNameInfo &DNI, 2788 SourceLocation Loc) -> bool { 2789 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 2790 PreviousCriticalLoc = Loc; 2791 return true; 2792 } else 2793 return false; 2794 }, 2795 false /* skip top directive */); 2796 if (DeadLock) { 2797 SemaRef.Diag(StartLoc, 2798 diag::err_omp_prohibited_region_critical_same_name) 2799 << CurrentName.getName(); 2800 if (PreviousCriticalLoc.isValid()) 2801 SemaRef.Diag(PreviousCriticalLoc, 2802 diag::note_omp_previous_critical_region); 2803 return true; 2804 } 2805 } else if (CurrentRegion == OMPD_barrier) { 2806 // OpenMP [2.16, Nesting of Regions] 2807 // A barrier region may not be closely nested inside a worksharing, 2808 // explicit task, critical, ordered, atomic, or master region. 2809 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2810 isOpenMPTaskingDirective(ParentRegion) || 2811 ParentRegion == OMPD_master || 2812 ParentRegion == OMPD_critical || 2813 ParentRegion == OMPD_ordered; 2814 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 2815 !isOpenMPParallelDirective(CurrentRegion) && 2816 !isOpenMPTeamsDirective(CurrentRegion)) { 2817 // OpenMP [2.16, Nesting of Regions] 2818 // A worksharing region may not be closely nested inside a worksharing, 2819 // explicit task, critical, ordered, atomic, or master region. 2820 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2821 isOpenMPTaskingDirective(ParentRegion) || 2822 ParentRegion == OMPD_master || 2823 ParentRegion == OMPD_critical || 2824 ParentRegion == OMPD_ordered; 2825 Recommend = ShouldBeInParallelRegion; 2826 } else if (CurrentRegion == OMPD_ordered) { 2827 // OpenMP [2.16, Nesting of Regions] 2828 // An ordered region may not be closely nested inside a critical, 2829 // atomic, or explicit task region. 2830 // An ordered region must be closely nested inside a loop region (or 2831 // parallel loop region) with an ordered clause. 2832 // OpenMP [2.8.1,simd Construct, Restrictions] 2833 // An ordered construct with the simd clause is the only OpenMP construct 2834 // that can appear in the simd region. 2835 NestingProhibited = ParentRegion == OMPD_critical || 2836 isOpenMPTaskingDirective(ParentRegion) || 2837 !(isOpenMPSimdDirective(ParentRegion) || 2838 Stack->isParentOrderedRegion()); 2839 Recommend = ShouldBeInOrderedRegion; 2840 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 2841 // OpenMP [2.16, Nesting of Regions] 2842 // If specified, a teams construct must be contained within a target 2843 // construct. 2844 NestingProhibited = ParentRegion != OMPD_target; 2845 OrphanSeen = ParentRegion == OMPD_unknown; 2846 Recommend = ShouldBeInTargetRegion; 2847 } 2848 if (!NestingProhibited && 2849 !isOpenMPTargetExecutionDirective(CurrentRegion) && 2850 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 2851 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 2852 // OpenMP [2.16, Nesting of Regions] 2853 // distribute, parallel, parallel sections, parallel workshare, and the 2854 // parallel loop and parallel loop SIMD constructs are the only OpenMP 2855 // constructs that can be closely nested in the teams region. 2856 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 2857 !isOpenMPDistributeDirective(CurrentRegion); 2858 Recommend = ShouldBeInParallelRegion; 2859 } 2860 if (!NestingProhibited && 2861 isOpenMPNestingDistributeDirective(CurrentRegion)) { 2862 // OpenMP 4.5 [2.17 Nesting of Regions] 2863 // The region associated with the distribute construct must be strictly 2864 // nested inside a teams region 2865 NestingProhibited = 2866 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 2867 Recommend = ShouldBeInTeamsRegion; 2868 } 2869 if (!NestingProhibited && 2870 (isOpenMPTargetExecutionDirective(CurrentRegion) || 2871 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 2872 // OpenMP 4.5 [2.17 Nesting of Regions] 2873 // If a target, target update, target data, target enter data, or 2874 // target exit data construct is encountered during execution of a 2875 // target region, the behavior is unspecified. 2876 NestingProhibited = Stack->hasDirective( 2877 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 2878 SourceLocation) -> bool { 2879 if (isOpenMPTargetExecutionDirective(K)) { 2880 OffendingRegion = K; 2881 return true; 2882 } else 2883 return false; 2884 }, 2885 false /* don't skip top directive */); 2886 CloseNesting = false; 2887 } 2888 if (NestingProhibited) { 2889 if (OrphanSeen) { 2890 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 2891 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 2892 } else { 2893 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 2894 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 2895 << Recommend << getOpenMPDirectiveName(CurrentRegion); 2896 } 2897 return true; 2898 } 2899 } 2900 return false; 2901 } 2902 2903 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 2904 ArrayRef<OMPClause *> Clauses, 2905 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 2906 bool ErrorFound = false; 2907 unsigned NamedModifiersNumber = 0; 2908 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers( 2909 OMPD_unknown + 1); 2910 SmallVector<SourceLocation, 4> NameModifierLoc; 2911 for (const auto *C : Clauses) { 2912 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 2913 // At most one if clause without a directive-name-modifier can appear on 2914 // the directive. 2915 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 2916 if (FoundNameModifiers[CurNM]) { 2917 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause) 2918 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 2919 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 2920 ErrorFound = true; 2921 } else if (CurNM != OMPD_unknown) { 2922 NameModifierLoc.push_back(IC->getNameModifierLoc()); 2923 ++NamedModifiersNumber; 2924 } 2925 FoundNameModifiers[CurNM] = IC; 2926 if (CurNM == OMPD_unknown) 2927 continue; 2928 // Check if the specified name modifier is allowed for the current 2929 // directive. 2930 // At most one if clause with the particular directive-name-modifier can 2931 // appear on the directive. 2932 bool MatchFound = false; 2933 for (auto NM : AllowedNameModifiers) { 2934 if (CurNM == NM) { 2935 MatchFound = true; 2936 break; 2937 } 2938 } 2939 if (!MatchFound) { 2940 S.Diag(IC->getNameModifierLoc(), 2941 diag::err_omp_wrong_if_directive_name_modifier) 2942 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 2943 ErrorFound = true; 2944 } 2945 } 2946 } 2947 // If any if clause on the directive includes a directive-name-modifier then 2948 // all if clauses on the directive must include a directive-name-modifier. 2949 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 2950 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 2951 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(), 2952 diag::err_omp_no_more_if_clause); 2953 } else { 2954 std::string Values; 2955 std::string Sep(", "); 2956 unsigned AllowedCnt = 0; 2957 unsigned TotalAllowedNum = 2958 AllowedNameModifiers.size() - NamedModifiersNumber; 2959 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 2960 ++Cnt) { 2961 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 2962 if (!FoundNameModifiers[NM]) { 2963 Values += "'"; 2964 Values += getOpenMPDirectiveName(NM); 2965 Values += "'"; 2966 if (AllowedCnt + 2 == TotalAllowedNum) 2967 Values += " or "; 2968 else if (AllowedCnt + 1 != TotalAllowedNum) 2969 Values += Sep; 2970 ++AllowedCnt; 2971 } 2972 } 2973 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(), 2974 diag::err_omp_unnamed_if_clause) 2975 << (TotalAllowedNum > 1) << Values; 2976 } 2977 for (auto Loc : NameModifierLoc) { 2978 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 2979 } 2980 ErrorFound = true; 2981 } 2982 return ErrorFound; 2983 } 2984 2985 StmtResult Sema::ActOnOpenMPExecutableDirective( 2986 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 2987 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 2988 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 2989 StmtResult Res = StmtError(); 2990 // First check CancelRegion which is then used in checkNestingOfRegions. 2991 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 2992 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 2993 StartLoc)) 2994 return StmtError(); 2995 2996 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 2997 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 2998 bool ErrorFound = false; 2999 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 3000 if (AStmt && !CurContext->isDependentContext()) { 3001 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 3002 3003 // Check default data sharing attributes for referenced variables. 3004 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 3005 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 3006 Stmt *S = AStmt; 3007 while (--ThisCaptureLevel >= 0) 3008 S = cast<CapturedStmt>(S)->getCapturedStmt(); 3009 DSAChecker.Visit(S); 3010 if (DSAChecker.isErrorFound()) 3011 return StmtError(); 3012 // Generate list of implicitly defined firstprivate variables. 3013 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 3014 3015 SmallVector<Expr *, 4> ImplicitFirstprivates( 3016 DSAChecker.getImplicitFirstprivate().begin(), 3017 DSAChecker.getImplicitFirstprivate().end()); 3018 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(), 3019 DSAChecker.getImplicitMap().end()); 3020 // Mark taskgroup task_reduction descriptors as implicitly firstprivate. 3021 for (auto *C : Clauses) { 3022 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) { 3023 for (auto *E : IRC->taskgroup_descriptors()) 3024 if (E) 3025 ImplicitFirstprivates.emplace_back(E); 3026 } 3027 } 3028 if (!ImplicitFirstprivates.empty()) { 3029 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 3030 ImplicitFirstprivates, SourceLocation(), SourceLocation(), 3031 SourceLocation())) { 3032 ClausesWithImplicit.push_back(Implicit); 3033 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 3034 ImplicitFirstprivates.size(); 3035 } else 3036 ErrorFound = true; 3037 } 3038 if (!ImplicitMaps.empty()) { 3039 if (OMPClause *Implicit = ActOnOpenMPMapClause( 3040 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, 3041 SourceLocation(), SourceLocation(), ImplicitMaps, 3042 SourceLocation(), SourceLocation(), SourceLocation())) { 3043 ClausesWithImplicit.emplace_back(Implicit); 3044 ErrorFound |= 3045 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size(); 3046 } else 3047 ErrorFound = true; 3048 } 3049 } 3050 3051 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 3052 switch (Kind) { 3053 case OMPD_parallel: 3054 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 3055 EndLoc); 3056 AllowedNameModifiers.push_back(OMPD_parallel); 3057 break; 3058 case OMPD_simd: 3059 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 3060 VarsWithInheritedDSA); 3061 break; 3062 case OMPD_for: 3063 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 3064 VarsWithInheritedDSA); 3065 break; 3066 case OMPD_for_simd: 3067 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3068 EndLoc, VarsWithInheritedDSA); 3069 break; 3070 case OMPD_sections: 3071 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 3072 EndLoc); 3073 break; 3074 case OMPD_section: 3075 assert(ClausesWithImplicit.empty() && 3076 "No clauses are allowed for 'omp section' directive"); 3077 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 3078 break; 3079 case OMPD_single: 3080 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 3081 EndLoc); 3082 break; 3083 case OMPD_master: 3084 assert(ClausesWithImplicit.empty() && 3085 "No clauses are allowed for 'omp master' directive"); 3086 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 3087 break; 3088 case OMPD_critical: 3089 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 3090 StartLoc, EndLoc); 3091 break; 3092 case OMPD_parallel_for: 3093 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 3094 EndLoc, VarsWithInheritedDSA); 3095 AllowedNameModifiers.push_back(OMPD_parallel); 3096 break; 3097 case OMPD_parallel_for_simd: 3098 Res = ActOnOpenMPParallelForSimdDirective( 3099 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3100 AllowedNameModifiers.push_back(OMPD_parallel); 3101 break; 3102 case OMPD_parallel_sections: 3103 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 3104 StartLoc, EndLoc); 3105 AllowedNameModifiers.push_back(OMPD_parallel); 3106 break; 3107 case OMPD_task: 3108 Res = 3109 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 3110 AllowedNameModifiers.push_back(OMPD_task); 3111 break; 3112 case OMPD_taskyield: 3113 assert(ClausesWithImplicit.empty() && 3114 "No clauses are allowed for 'omp taskyield' directive"); 3115 assert(AStmt == nullptr && 3116 "No associated statement allowed for 'omp taskyield' directive"); 3117 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 3118 break; 3119 case OMPD_barrier: 3120 assert(ClausesWithImplicit.empty() && 3121 "No clauses are allowed for 'omp barrier' directive"); 3122 assert(AStmt == nullptr && 3123 "No associated statement allowed for 'omp barrier' directive"); 3124 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 3125 break; 3126 case OMPD_taskwait: 3127 assert(ClausesWithImplicit.empty() && 3128 "No clauses are allowed for 'omp taskwait' directive"); 3129 assert(AStmt == nullptr && 3130 "No associated statement allowed for 'omp taskwait' directive"); 3131 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 3132 break; 3133 case OMPD_taskgroup: 3134 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, 3135 EndLoc); 3136 break; 3137 case OMPD_flush: 3138 assert(AStmt == nullptr && 3139 "No associated statement allowed for 'omp flush' directive"); 3140 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 3141 break; 3142 case OMPD_ordered: 3143 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 3144 EndLoc); 3145 break; 3146 case OMPD_atomic: 3147 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 3148 EndLoc); 3149 break; 3150 case OMPD_teams: 3151 Res = 3152 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 3153 break; 3154 case OMPD_target: 3155 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 3156 EndLoc); 3157 AllowedNameModifiers.push_back(OMPD_target); 3158 break; 3159 case OMPD_target_parallel: 3160 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 3161 StartLoc, EndLoc); 3162 AllowedNameModifiers.push_back(OMPD_target); 3163 AllowedNameModifiers.push_back(OMPD_parallel); 3164 break; 3165 case OMPD_target_parallel_for: 3166 Res = ActOnOpenMPTargetParallelForDirective( 3167 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3168 AllowedNameModifiers.push_back(OMPD_target); 3169 AllowedNameModifiers.push_back(OMPD_parallel); 3170 break; 3171 case OMPD_cancellation_point: 3172 assert(ClausesWithImplicit.empty() && 3173 "No clauses are allowed for 'omp cancellation point' directive"); 3174 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 3175 "cancellation point' directive"); 3176 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 3177 break; 3178 case OMPD_cancel: 3179 assert(AStmt == nullptr && 3180 "No associated statement allowed for 'omp cancel' directive"); 3181 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 3182 CancelRegion); 3183 AllowedNameModifiers.push_back(OMPD_cancel); 3184 break; 3185 case OMPD_target_data: 3186 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 3187 EndLoc); 3188 AllowedNameModifiers.push_back(OMPD_target_data); 3189 break; 3190 case OMPD_target_enter_data: 3191 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 3192 EndLoc, AStmt); 3193 AllowedNameModifiers.push_back(OMPD_target_enter_data); 3194 break; 3195 case OMPD_target_exit_data: 3196 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 3197 EndLoc, AStmt); 3198 AllowedNameModifiers.push_back(OMPD_target_exit_data); 3199 break; 3200 case OMPD_taskloop: 3201 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 3202 EndLoc, VarsWithInheritedDSA); 3203 AllowedNameModifiers.push_back(OMPD_taskloop); 3204 break; 3205 case OMPD_taskloop_simd: 3206 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3207 EndLoc, VarsWithInheritedDSA); 3208 AllowedNameModifiers.push_back(OMPD_taskloop); 3209 break; 3210 case OMPD_distribute: 3211 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 3212 EndLoc, VarsWithInheritedDSA); 3213 break; 3214 case OMPD_target_update: 3215 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, 3216 EndLoc, AStmt); 3217 AllowedNameModifiers.push_back(OMPD_target_update); 3218 break; 3219 case OMPD_distribute_parallel_for: 3220 Res = ActOnOpenMPDistributeParallelForDirective( 3221 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3222 AllowedNameModifiers.push_back(OMPD_parallel); 3223 break; 3224 case OMPD_distribute_parallel_for_simd: 3225 Res = ActOnOpenMPDistributeParallelForSimdDirective( 3226 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3227 AllowedNameModifiers.push_back(OMPD_parallel); 3228 break; 3229 case OMPD_distribute_simd: 3230 Res = ActOnOpenMPDistributeSimdDirective( 3231 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3232 break; 3233 case OMPD_target_parallel_for_simd: 3234 Res = ActOnOpenMPTargetParallelForSimdDirective( 3235 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3236 AllowedNameModifiers.push_back(OMPD_target); 3237 AllowedNameModifiers.push_back(OMPD_parallel); 3238 break; 3239 case OMPD_target_simd: 3240 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 3241 EndLoc, VarsWithInheritedDSA); 3242 AllowedNameModifiers.push_back(OMPD_target); 3243 break; 3244 case OMPD_teams_distribute: 3245 Res = ActOnOpenMPTeamsDistributeDirective( 3246 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3247 break; 3248 case OMPD_teams_distribute_simd: 3249 Res = ActOnOpenMPTeamsDistributeSimdDirective( 3250 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3251 break; 3252 case OMPD_teams_distribute_parallel_for_simd: 3253 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 3254 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3255 AllowedNameModifiers.push_back(OMPD_parallel); 3256 break; 3257 case OMPD_teams_distribute_parallel_for: 3258 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 3259 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3260 AllowedNameModifiers.push_back(OMPD_parallel); 3261 break; 3262 case OMPD_target_teams: 3263 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 3264 EndLoc); 3265 AllowedNameModifiers.push_back(OMPD_target); 3266 break; 3267 case OMPD_target_teams_distribute: 3268 Res = ActOnOpenMPTargetTeamsDistributeDirective( 3269 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3270 AllowedNameModifiers.push_back(OMPD_target); 3271 break; 3272 case OMPD_target_teams_distribute_parallel_for: 3273 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 3274 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3275 AllowedNameModifiers.push_back(OMPD_target); 3276 AllowedNameModifiers.push_back(OMPD_parallel); 3277 break; 3278 case OMPD_target_teams_distribute_parallel_for_simd: 3279 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 3280 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3281 AllowedNameModifiers.push_back(OMPD_target); 3282 AllowedNameModifiers.push_back(OMPD_parallel); 3283 break; 3284 case OMPD_target_teams_distribute_simd: 3285 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 3286 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 3287 AllowedNameModifiers.push_back(OMPD_target); 3288 break; 3289 case OMPD_declare_target: 3290 case OMPD_end_declare_target: 3291 case OMPD_threadprivate: 3292 case OMPD_declare_reduction: 3293 case OMPD_declare_simd: 3294 llvm_unreachable("OpenMP Directive is not allowed"); 3295 case OMPD_unknown: 3296 llvm_unreachable("Unknown OpenMP directive"); 3297 } 3298 3299 for (auto P : VarsWithInheritedDSA) { 3300 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 3301 << P.first << P.second->getSourceRange(); 3302 } 3303 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound; 3304 3305 if (!AllowedNameModifiers.empty()) 3306 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 3307 ErrorFound; 3308 3309 if (ErrorFound) 3310 return StmtError(); 3311 return Res; 3312 } 3313 3314 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 3315 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 3316 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 3317 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 3318 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 3319 assert(Aligneds.size() == Alignments.size()); 3320 assert(Linears.size() == LinModifiers.size()); 3321 assert(Linears.size() == Steps.size()); 3322 if (!DG || DG.get().isNull()) 3323 return DeclGroupPtrTy(); 3324 3325 if (!DG.get().isSingleDecl()) { 3326 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd); 3327 return DG; 3328 } 3329 auto *ADecl = DG.get().getSingleDecl(); 3330 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 3331 ADecl = FTD->getTemplatedDecl(); 3332 3333 auto *FD = dyn_cast<FunctionDecl>(ADecl); 3334 if (!FD) { 3335 Diag(ADecl->getLocation(), diag::err_omp_function_expected); 3336 return DeclGroupPtrTy(); 3337 } 3338 3339 // OpenMP [2.8.2, declare simd construct, Description] 3340 // The parameter of the simdlen clause must be a constant positive integer 3341 // expression. 3342 ExprResult SL; 3343 if (Simdlen) 3344 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 3345 // OpenMP [2.8.2, declare simd construct, Description] 3346 // The special this pointer can be used as if was one of the arguments to the 3347 // function in any of the linear, aligned, or uniform clauses. 3348 // The uniform clause declares one or more arguments to have an invariant 3349 // value for all concurrent invocations of the function in the execution of a 3350 // single SIMD loop. 3351 llvm::DenseMap<Decl *, Expr *> UniformedArgs; 3352 Expr *UniformedLinearThis = nullptr; 3353 for (auto *E : Uniforms) { 3354 E = E->IgnoreParenImpCasts(); 3355 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 3356 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 3357 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3358 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3359 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 3360 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E)); 3361 continue; 3362 } 3363 if (isa<CXXThisExpr>(E)) { 3364 UniformedLinearThis = E; 3365 continue; 3366 } 3367 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3368 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3369 } 3370 // OpenMP [2.8.2, declare simd construct, Description] 3371 // The aligned clause declares that the object to which each list item points 3372 // is aligned to the number of bytes expressed in the optional parameter of 3373 // the aligned clause. 3374 // The special this pointer can be used as if was one of the arguments to the 3375 // function in any of the linear, aligned, or uniform clauses. 3376 // The type of list items appearing in the aligned clause must be array, 3377 // pointer, reference to array, or reference to pointer. 3378 llvm::DenseMap<Decl *, Expr *> AlignedArgs; 3379 Expr *AlignedThis = nullptr; 3380 for (auto *E : Aligneds) { 3381 E = E->IgnoreParenImpCasts(); 3382 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 3383 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3384 auto *CanonPVD = PVD->getCanonicalDecl(); 3385 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3386 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3387 ->getCanonicalDecl() == CanonPVD) { 3388 // OpenMP [2.8.1, simd construct, Restrictions] 3389 // A list-item cannot appear in more than one aligned clause. 3390 if (AlignedArgs.count(CanonPVD) > 0) { 3391 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3392 << 1 << E->getSourceRange(); 3393 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 3394 diag::note_omp_explicit_dsa) 3395 << getOpenMPClauseName(OMPC_aligned); 3396 continue; 3397 } 3398 AlignedArgs[CanonPVD] = E; 3399 QualType QTy = PVD->getType() 3400 .getNonReferenceType() 3401 .getUnqualifiedType() 3402 .getCanonicalType(); 3403 const Type *Ty = QTy.getTypePtrOrNull(); 3404 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 3405 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 3406 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 3407 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 3408 } 3409 continue; 3410 } 3411 } 3412 if (isa<CXXThisExpr>(E)) { 3413 if (AlignedThis) { 3414 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3415 << 2 << E->getSourceRange(); 3416 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 3417 << getOpenMPClauseName(OMPC_aligned); 3418 } 3419 AlignedThis = E; 3420 continue; 3421 } 3422 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3423 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3424 } 3425 // The optional parameter of the aligned clause, alignment, must be a constant 3426 // positive integer expression. If no optional parameter is specified, 3427 // implementation-defined default alignments for SIMD instructions on the 3428 // target platforms are assumed. 3429 SmallVector<Expr *, 4> NewAligns; 3430 for (auto *E : Alignments) { 3431 ExprResult Align; 3432 if (E) 3433 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 3434 NewAligns.push_back(Align.get()); 3435 } 3436 // OpenMP [2.8.2, declare simd construct, Description] 3437 // The linear clause declares one or more list items to be private to a SIMD 3438 // lane and to have a linear relationship with respect to the iteration space 3439 // of a loop. 3440 // The special this pointer can be used as if was one of the arguments to the 3441 // function in any of the linear, aligned, or uniform clauses. 3442 // When a linear-step expression is specified in a linear clause it must be 3443 // either a constant integer expression or an integer-typed parameter that is 3444 // specified in a uniform clause on the directive. 3445 llvm::DenseMap<Decl *, Expr *> LinearArgs; 3446 const bool IsUniformedThis = UniformedLinearThis != nullptr; 3447 auto MI = LinModifiers.begin(); 3448 for (auto *E : Linears) { 3449 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 3450 ++MI; 3451 E = E->IgnoreParenImpCasts(); 3452 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 3453 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3454 auto *CanonPVD = PVD->getCanonicalDecl(); 3455 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3456 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3457 ->getCanonicalDecl() == CanonPVD) { 3458 // OpenMP [2.15.3.7, linear Clause, Restrictions] 3459 // A list-item cannot appear in more than one linear clause. 3460 if (LinearArgs.count(CanonPVD) > 0) { 3461 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3462 << getOpenMPClauseName(OMPC_linear) 3463 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 3464 Diag(LinearArgs[CanonPVD]->getExprLoc(), 3465 diag::note_omp_explicit_dsa) 3466 << getOpenMPClauseName(OMPC_linear); 3467 continue; 3468 } 3469 // Each argument can appear in at most one uniform or linear clause. 3470 if (UniformedArgs.count(CanonPVD) > 0) { 3471 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3472 << getOpenMPClauseName(OMPC_linear) 3473 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 3474 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 3475 diag::note_omp_explicit_dsa) 3476 << getOpenMPClauseName(OMPC_uniform); 3477 continue; 3478 } 3479 LinearArgs[CanonPVD] = E; 3480 if (E->isValueDependent() || E->isTypeDependent() || 3481 E->isInstantiationDependent() || 3482 E->containsUnexpandedParameterPack()) 3483 continue; 3484 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 3485 PVD->getOriginalType()); 3486 continue; 3487 } 3488 } 3489 if (isa<CXXThisExpr>(E)) { 3490 if (UniformedLinearThis) { 3491 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3492 << getOpenMPClauseName(OMPC_linear) 3493 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 3494 << E->getSourceRange(); 3495 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 3496 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 3497 : OMPC_linear); 3498 continue; 3499 } 3500 UniformedLinearThis = E; 3501 if (E->isValueDependent() || E->isTypeDependent() || 3502 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 3503 continue; 3504 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 3505 E->getType()); 3506 continue; 3507 } 3508 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3509 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3510 } 3511 Expr *Step = nullptr; 3512 Expr *NewStep = nullptr; 3513 SmallVector<Expr *, 4> NewSteps; 3514 for (auto *E : Steps) { 3515 // Skip the same step expression, it was checked already. 3516 if (Step == E || !E) { 3517 NewSteps.push_back(E ? NewStep : nullptr); 3518 continue; 3519 } 3520 Step = E; 3521 if (auto *DRE = dyn_cast<DeclRefExpr>(Step)) 3522 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3523 auto *CanonPVD = PVD->getCanonicalDecl(); 3524 if (UniformedArgs.count(CanonPVD) == 0) { 3525 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 3526 << Step->getSourceRange(); 3527 } else if (E->isValueDependent() || E->isTypeDependent() || 3528 E->isInstantiationDependent() || 3529 E->containsUnexpandedParameterPack() || 3530 CanonPVD->getType()->hasIntegerRepresentation()) 3531 NewSteps.push_back(Step); 3532 else { 3533 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 3534 << Step->getSourceRange(); 3535 } 3536 continue; 3537 } 3538 NewStep = Step; 3539 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 3540 !Step->isInstantiationDependent() && 3541 !Step->containsUnexpandedParameterPack()) { 3542 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 3543 .get(); 3544 if (NewStep) 3545 NewStep = VerifyIntegerConstantExpression(NewStep).get(); 3546 } 3547 NewSteps.push_back(NewStep); 3548 } 3549 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 3550 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 3551 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 3552 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 3553 const_cast<Expr **>(Linears.data()), Linears.size(), 3554 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 3555 NewSteps.data(), NewSteps.size(), SR); 3556 ADecl->addAttr(NewAttr); 3557 return ConvertDeclToDeclGroup(ADecl); 3558 } 3559 3560 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 3561 Stmt *AStmt, 3562 SourceLocation StartLoc, 3563 SourceLocation EndLoc) { 3564 if (!AStmt) 3565 return StmtError(); 3566 3567 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 3568 // 1.2.2 OpenMP Language Terminology 3569 // Structured block - An executable statement with a single entry at the 3570 // top and a single exit at the bottom. 3571 // The point of exit cannot be a branch out of the structured block. 3572 // longjmp() and throw() must not violate the entry/exit criteria. 3573 CS->getCapturedDecl()->setNothrow(); 3574 3575 setFunctionHasBranchProtectedScope(); 3576 3577 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 3578 DSAStack->isCancelRegion()); 3579 } 3580 3581 namespace { 3582 /// \brief Helper class for checking canonical form of the OpenMP loops and 3583 /// extracting iteration space of each loop in the loop nest, that will be used 3584 /// for IR generation. 3585 class OpenMPIterationSpaceChecker { 3586 /// \brief Reference to Sema. 3587 Sema &SemaRef; 3588 /// \brief A location for diagnostics (when there is no some better location). 3589 SourceLocation DefaultLoc; 3590 /// \brief A location for diagnostics (when increment is not compatible). 3591 SourceLocation ConditionLoc; 3592 /// \brief A source location for referring to loop init later. 3593 SourceRange InitSrcRange; 3594 /// \brief A source location for referring to condition later. 3595 SourceRange ConditionSrcRange; 3596 /// \brief A source location for referring to increment later. 3597 SourceRange IncrementSrcRange; 3598 /// \brief Loop variable. 3599 ValueDecl *LCDecl = nullptr; 3600 /// \brief Reference to loop variable. 3601 Expr *LCRef = nullptr; 3602 /// \brief Lower bound (initializer for the var). 3603 Expr *LB = nullptr; 3604 /// \brief Upper bound. 3605 Expr *UB = nullptr; 3606 /// \brief Loop step (increment). 3607 Expr *Step = nullptr; 3608 /// \brief This flag is true when condition is one of: 3609 /// Var < UB 3610 /// Var <= UB 3611 /// UB > Var 3612 /// UB >= Var 3613 bool TestIsLessOp = false; 3614 /// \brief This flag is true when condition is strict ( < or > ). 3615 bool TestIsStrictOp = false; 3616 /// \brief This flag is true when step is subtracted on each iteration. 3617 bool SubtractStep = false; 3618 3619 public: 3620 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) 3621 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 3622 /// \brief Check init-expr for canonical loop form and save loop counter 3623 /// variable - #Var and its initialization value - #LB. 3624 bool CheckInit(Stmt *S, bool EmitDiags = true); 3625 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags 3626 /// for less/greater and for strict/non-strict comparison. 3627 bool CheckCond(Expr *S); 3628 /// \brief Check incr-expr for canonical loop form and return true if it 3629 /// does not conform, otherwise save loop step (#Step). 3630 bool CheckInc(Expr *S); 3631 /// \brief Return the loop counter variable. 3632 ValueDecl *GetLoopDecl() const { return LCDecl; } 3633 /// \brief Return the reference expression to loop counter variable. 3634 Expr *GetLoopDeclRefExpr() const { return LCRef; } 3635 /// \brief Source range of the loop init. 3636 SourceRange GetInitSrcRange() const { return InitSrcRange; } 3637 /// \brief Source range of the loop condition. 3638 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; } 3639 /// \brief Source range of the loop increment. 3640 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; } 3641 /// \brief True if the step should be subtracted. 3642 bool ShouldSubtractStep() const { return SubtractStep; } 3643 /// \brief Build the expression to calculate the number of iterations. 3644 Expr * 3645 BuildNumIterations(Scope *S, const bool LimitedType, 3646 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 3647 /// \brief Build the precondition expression for the loops. 3648 Expr *BuildPreCond(Scope *S, Expr *Cond, 3649 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 3650 /// \brief Build reference expression to the counter be used for codegen. 3651 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures, 3652 DSAStackTy &DSA) const; 3653 /// \brief Build reference expression to the private counter be used for 3654 /// codegen. 3655 Expr *BuildPrivateCounterVar() const; 3656 /// \brief Build initialization of the counter be used for codegen. 3657 Expr *BuildCounterInit() const; 3658 /// \brief Build step of the counter be used for codegen. 3659 Expr *BuildCounterStep() const; 3660 /// \brief Return true if any expression is dependent. 3661 bool Dependent() const; 3662 3663 private: 3664 /// \brief Check the right-hand side of an assignment in the increment 3665 /// expression. 3666 bool CheckIncRHS(Expr *RHS); 3667 /// \brief Helper to set loop counter variable and its initializer. 3668 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB); 3669 /// \brief Helper to set upper bound. 3670 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR, 3671 SourceLocation SL); 3672 /// \brief Helper to set loop increment. 3673 bool SetStep(Expr *NewStep, bool Subtract); 3674 }; 3675 3676 bool OpenMPIterationSpaceChecker::Dependent() const { 3677 if (!LCDecl) { 3678 assert(!LB && !UB && !Step); 3679 return false; 3680 } 3681 return LCDecl->getType()->isDependentType() || 3682 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 3683 (Step && Step->isValueDependent()); 3684 } 3685 3686 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl, 3687 Expr *NewLCRefExpr, 3688 Expr *NewLB) { 3689 // State consistency checking to ensure correct usage. 3690 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 3691 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 3692 if (!NewLCDecl || !NewLB) 3693 return true; 3694 LCDecl = getCanonicalDecl(NewLCDecl); 3695 LCRef = NewLCRefExpr; 3696 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 3697 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 3698 if ((Ctor->isCopyOrMoveConstructor() || 3699 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 3700 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 3701 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 3702 LB = NewLB; 3703 return false; 3704 } 3705 3706 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp, 3707 SourceRange SR, SourceLocation SL) { 3708 // State consistency checking to ensure correct usage. 3709 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 3710 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 3711 if (!NewUB) 3712 return true; 3713 UB = NewUB; 3714 TestIsLessOp = LessOp; 3715 TestIsStrictOp = StrictOp; 3716 ConditionSrcRange = SR; 3717 ConditionLoc = SL; 3718 return false; 3719 } 3720 3721 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) { 3722 // State consistency checking to ensure correct usage. 3723 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 3724 if (!NewStep) 3725 return true; 3726 if (!NewStep->isValueDependent()) { 3727 // Check that the step is integer expression. 3728 SourceLocation StepLoc = NewStep->getLocStart(); 3729 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( 3730 StepLoc, getExprAsWritten(NewStep)); 3731 if (Val.isInvalid()) 3732 return true; 3733 NewStep = Val.get(); 3734 3735 // OpenMP [2.6, Canonical Loop Form, Restrictions] 3736 // If test-expr is of form var relational-op b and relational-op is < or 3737 // <= then incr-expr must cause var to increase on each iteration of the 3738 // loop. If test-expr is of form var relational-op b and relational-op is 3739 // > or >= then incr-expr must cause var to decrease on each iteration of 3740 // the loop. 3741 // If test-expr is of form b relational-op var and relational-op is < or 3742 // <= then incr-expr must cause var to decrease on each iteration of the 3743 // loop. If test-expr is of form b relational-op var and relational-op is 3744 // > or >= then incr-expr must cause var to increase on each iteration of 3745 // the loop. 3746 llvm::APSInt Result; 3747 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 3748 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 3749 bool IsConstNeg = 3750 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 3751 bool IsConstPos = 3752 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 3753 bool IsConstZero = IsConstant && !Result.getBoolValue(); 3754 if (UB && (IsConstZero || 3755 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract)) 3756 : (IsConstPos || (IsUnsigned && !Subtract))))) { 3757 SemaRef.Diag(NewStep->getExprLoc(), 3758 diag::err_omp_loop_incr_not_compatible) 3759 << LCDecl << TestIsLessOp << NewStep->getSourceRange(); 3760 SemaRef.Diag(ConditionLoc, 3761 diag::note_omp_loop_cond_requres_compatible_incr) 3762 << TestIsLessOp << ConditionSrcRange; 3763 return true; 3764 } 3765 if (TestIsLessOp == Subtract) { 3766 NewStep = 3767 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 3768 .get(); 3769 Subtract = !Subtract; 3770 } 3771 } 3772 3773 Step = NewStep; 3774 SubtractStep = Subtract; 3775 return false; 3776 } 3777 3778 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) { 3779 // Check init-expr for canonical loop form and save loop counter 3780 // variable - #Var and its initialization value - #LB. 3781 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 3782 // var = lb 3783 // integer-type var = lb 3784 // random-access-iterator-type var = lb 3785 // pointer-type var = lb 3786 // 3787 if (!S) { 3788 if (EmitDiags) { 3789 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 3790 } 3791 return true; 3792 } 3793 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3794 if (!ExprTemp->cleanupsHaveSideEffects()) 3795 S = ExprTemp->getSubExpr(); 3796 3797 InitSrcRange = S->getSourceRange(); 3798 if (Expr *E = dyn_cast<Expr>(S)) 3799 S = E->IgnoreParens(); 3800 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3801 if (BO->getOpcode() == BO_Assign) { 3802 auto *LHS = BO->getLHS()->IgnoreParens(); 3803 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3804 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3805 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3806 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3807 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS()); 3808 } 3809 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3810 if (ME->isArrow() && 3811 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3812 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3813 } 3814 } 3815 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 3816 if (DS->isSingleDecl()) { 3817 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 3818 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 3819 // Accept non-canonical init form here but emit ext. warning. 3820 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 3821 SemaRef.Diag(S->getLocStart(), 3822 diag::ext_omp_loop_not_canonical_init) 3823 << S->getSourceRange(); 3824 return SetLCDeclAndLB(Var, nullptr, Var->getInit()); 3825 } 3826 } 3827 } 3828 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3829 if (CE->getOperator() == OO_Equal) { 3830 auto *LHS = CE->getArg(0); 3831 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3832 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3833 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3834 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3835 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1)); 3836 } 3837 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3838 if (ME->isArrow() && 3839 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3840 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3841 } 3842 } 3843 } 3844 3845 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3846 return false; 3847 if (EmitDiags) { 3848 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init) 3849 << S->getSourceRange(); 3850 } 3851 return true; 3852 } 3853 3854 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the 3855 /// variable (which may be the loop variable) if possible. 3856 static const ValueDecl *GetInitLCDecl(Expr *E) { 3857 if (!E) 3858 return nullptr; 3859 E = getExprAsWritten(E); 3860 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 3861 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 3862 if ((Ctor->isCopyOrMoveConstructor() || 3863 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 3864 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 3865 E = CE->getArg(0)->IgnoreParenImpCasts(); 3866 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 3867 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 3868 return getCanonicalDecl(VD); 3869 } 3870 if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 3871 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3872 return getCanonicalDecl(ME->getMemberDecl()); 3873 return nullptr; 3874 } 3875 3876 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) { 3877 // Check test-expr for canonical form, save upper-bound UB, flags for 3878 // less/greater and for strict/non-strict comparison. 3879 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3880 // var relational-op b 3881 // b relational-op var 3882 // 3883 if (!S) { 3884 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl; 3885 return true; 3886 } 3887 S = getExprAsWritten(S); 3888 SourceLocation CondLoc = S->getLocStart(); 3889 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3890 if (BO->isRelationalOp()) { 3891 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3892 return SetUB(BO->getRHS(), 3893 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 3894 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3895 BO->getSourceRange(), BO->getOperatorLoc()); 3896 if (GetInitLCDecl(BO->getRHS()) == LCDecl) 3897 return SetUB(BO->getLHS(), 3898 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 3899 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3900 BO->getSourceRange(), BO->getOperatorLoc()); 3901 } 3902 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3903 if (CE->getNumArgs() == 2) { 3904 auto Op = CE->getOperator(); 3905 switch (Op) { 3906 case OO_Greater: 3907 case OO_GreaterEqual: 3908 case OO_Less: 3909 case OO_LessEqual: 3910 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3911 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 3912 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3913 CE->getOperatorLoc()); 3914 if (GetInitLCDecl(CE->getArg(1)) == LCDecl) 3915 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 3916 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3917 CE->getOperatorLoc()); 3918 break; 3919 default: 3920 break; 3921 } 3922 } 3923 } 3924 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3925 return false; 3926 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 3927 << S->getSourceRange() << LCDecl; 3928 return true; 3929 } 3930 3931 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) { 3932 // RHS of canonical loop form increment can be: 3933 // var + incr 3934 // incr + var 3935 // var - incr 3936 // 3937 RHS = RHS->IgnoreParenImpCasts(); 3938 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 3939 if (BO->isAdditiveOp()) { 3940 bool IsAdd = BO->getOpcode() == BO_Add; 3941 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3942 return SetStep(BO->getRHS(), !IsAdd); 3943 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl) 3944 return SetStep(BO->getLHS(), false); 3945 } 3946 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 3947 bool IsAdd = CE->getOperator() == OO_Plus; 3948 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 3949 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3950 return SetStep(CE->getArg(1), !IsAdd); 3951 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl) 3952 return SetStep(CE->getArg(0), false); 3953 } 3954 } 3955 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3956 return false; 3957 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3958 << RHS->getSourceRange() << LCDecl; 3959 return true; 3960 } 3961 3962 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) { 3963 // Check incr-expr for canonical loop form and return true if it 3964 // does not conform. 3965 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3966 // ++var 3967 // var++ 3968 // --var 3969 // var-- 3970 // var += incr 3971 // var -= incr 3972 // var = var + incr 3973 // var = incr + var 3974 // var = var - incr 3975 // 3976 if (!S) { 3977 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 3978 return true; 3979 } 3980 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3981 if (!ExprTemp->cleanupsHaveSideEffects()) 3982 S = ExprTemp->getSubExpr(); 3983 3984 IncrementSrcRange = S->getSourceRange(); 3985 S = S->IgnoreParens(); 3986 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 3987 if (UO->isIncrementDecrementOp() && 3988 GetInitLCDecl(UO->getSubExpr()) == LCDecl) 3989 return SetStep(SemaRef 3990 .ActOnIntegerConstant(UO->getLocStart(), 3991 (UO->isDecrementOp() ? -1 : 1)) 3992 .get(), 3993 false); 3994 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3995 switch (BO->getOpcode()) { 3996 case BO_AddAssign: 3997 case BO_SubAssign: 3998 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3999 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 4000 break; 4001 case BO_Assign: 4002 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 4003 return CheckIncRHS(BO->getRHS()); 4004 break; 4005 default: 4006 break; 4007 } 4008 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 4009 switch (CE->getOperator()) { 4010 case OO_PlusPlus: 4011 case OO_MinusMinus: 4012 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 4013 return SetStep(SemaRef 4014 .ActOnIntegerConstant( 4015 CE->getLocStart(), 4016 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 4017 .get(), 4018 false); 4019 break; 4020 case OO_PlusEqual: 4021 case OO_MinusEqual: 4022 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 4023 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 4024 break; 4025 case OO_Equal: 4026 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 4027 return CheckIncRHS(CE->getArg(1)); 4028 break; 4029 default: 4030 break; 4031 } 4032 } 4033 if (Dependent() || SemaRef.CurContext->isDependentContext()) 4034 return false; 4035 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr) 4036 << S->getSourceRange() << LCDecl; 4037 return true; 4038 } 4039 4040 static ExprResult 4041 tryBuildCapture(Sema &SemaRef, Expr *Capture, 4042 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4043 if (SemaRef.CurContext->isDependentContext()) 4044 return ExprResult(Capture); 4045 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 4046 return SemaRef.PerformImplicitConversion( 4047 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 4048 /*AllowExplicit=*/true); 4049 auto I = Captures.find(Capture); 4050 if (I != Captures.end()) 4051 return buildCapture(SemaRef, Capture, I->second); 4052 DeclRefExpr *Ref = nullptr; 4053 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 4054 Captures[Capture] = Ref; 4055 return Res; 4056 } 4057 4058 /// \brief Build the expression to calculate the number of iterations. 4059 Expr *OpenMPIterationSpaceChecker::BuildNumIterations( 4060 Scope *S, const bool LimitedType, 4061 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 4062 ExprResult Diff; 4063 auto VarType = LCDecl->getType().getNonReferenceType(); 4064 if (VarType->isIntegerType() || VarType->isPointerType() || 4065 SemaRef.getLangOpts().CPlusPlus) { 4066 // Upper - Lower 4067 auto *UBExpr = TestIsLessOp ? UB : LB; 4068 auto *LBExpr = TestIsLessOp ? LB : UB; 4069 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 4070 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 4071 if (!Upper || !Lower) 4072 return nullptr; 4073 4074 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 4075 4076 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 4077 // BuildBinOp already emitted error, this one is to point user to upper 4078 // and lower bound, and to tell what is passed to 'operator-'. 4079 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx) 4080 << Upper->getSourceRange() << Lower->getSourceRange(); 4081 return nullptr; 4082 } 4083 } 4084 4085 if (!Diff.isUsable()) 4086 return nullptr; 4087 4088 // Upper - Lower [- 1] 4089 if (TestIsStrictOp) 4090 Diff = SemaRef.BuildBinOp( 4091 S, DefaultLoc, BO_Sub, Diff.get(), 4092 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4093 if (!Diff.isUsable()) 4094 return nullptr; 4095 4096 // Upper - Lower [- 1] + Step 4097 auto NewStep = tryBuildCapture(SemaRef, Step, Captures); 4098 if (!NewStep.isUsable()) 4099 return nullptr; 4100 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 4101 if (!Diff.isUsable()) 4102 return nullptr; 4103 4104 // Parentheses (for dumping/debugging purposes only). 4105 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 4106 if (!Diff.isUsable()) 4107 return nullptr; 4108 4109 // (Upper - Lower [- 1] + Step) / Step 4110 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 4111 if (!Diff.isUsable()) 4112 return nullptr; 4113 4114 // OpenMP runtime requires 32-bit or 64-bit loop variables. 4115 QualType Type = Diff.get()->getType(); 4116 auto &C = SemaRef.Context; 4117 bool UseVarType = VarType->hasIntegerRepresentation() && 4118 C.getTypeSize(Type) > C.getTypeSize(VarType); 4119 if (!Type->isIntegerType() || UseVarType) { 4120 unsigned NewSize = 4121 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 4122 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 4123 : Type->hasSignedIntegerRepresentation(); 4124 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 4125 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 4126 Diff = SemaRef.PerformImplicitConversion( 4127 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 4128 if (!Diff.isUsable()) 4129 return nullptr; 4130 } 4131 } 4132 if (LimitedType) { 4133 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 4134 if (NewSize != C.getTypeSize(Type)) { 4135 if (NewSize < C.getTypeSize(Type)) { 4136 assert(NewSize == 64 && "incorrect loop var size"); 4137 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 4138 << InitSrcRange << ConditionSrcRange; 4139 } 4140 QualType NewType = C.getIntTypeForBitwidth( 4141 NewSize, Type->hasSignedIntegerRepresentation() || 4142 C.getTypeSize(Type) < NewSize); 4143 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 4144 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 4145 Sema::AA_Converting, true); 4146 if (!Diff.isUsable()) 4147 return nullptr; 4148 } 4149 } 4150 } 4151 4152 return Diff.get(); 4153 } 4154 4155 Expr *OpenMPIterationSpaceChecker::BuildPreCond( 4156 Scope *S, Expr *Cond, 4157 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 4158 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 4159 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 4160 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 4161 4162 auto NewLB = tryBuildCapture(SemaRef, LB, Captures); 4163 auto NewUB = tryBuildCapture(SemaRef, UB, Captures); 4164 if (!NewLB.isUsable() || !NewUB.isUsable()) 4165 return nullptr; 4166 4167 auto CondExpr = SemaRef.BuildBinOp( 4168 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE) 4169 : (TestIsStrictOp ? BO_GT : BO_GE), 4170 NewLB.get(), NewUB.get()); 4171 if (CondExpr.isUsable()) { 4172 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 4173 SemaRef.Context.BoolTy)) 4174 CondExpr = SemaRef.PerformImplicitConversion( 4175 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 4176 /*AllowExplicit=*/true); 4177 } 4178 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 4179 // Otherwise use original loop conditon and evaluate it in runtime. 4180 return CondExpr.isUsable() ? CondExpr.get() : Cond; 4181 } 4182 4183 /// \brief Build reference expression to the counter be used for codegen. 4184 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar( 4185 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const { 4186 auto *VD = dyn_cast<VarDecl>(LCDecl); 4187 if (!VD) { 4188 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl); 4189 auto *Ref = buildDeclRefExpr( 4190 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 4191 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false); 4192 // If the loop control decl is explicitly marked as private, do not mark it 4193 // as captured again. 4194 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 4195 Captures.insert(std::make_pair(LCRef, Ref)); 4196 return Ref; 4197 } 4198 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(), 4199 DefaultLoc); 4200 } 4201 4202 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const { 4203 if (LCDecl && !LCDecl->isInvalidDecl()) { 4204 auto Type = LCDecl->getType().getNonReferenceType(); 4205 auto *PrivateVar = 4206 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(), 4207 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr); 4208 if (PrivateVar->isInvalidDecl()) 4209 return nullptr; 4210 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 4211 } 4212 return nullptr; 4213 } 4214 4215 /// \brief Build initialization of the counter to be used for codegen. 4216 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; } 4217 4218 /// \brief Build step of the counter be used for codegen. 4219 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; } 4220 4221 /// \brief Iteration space of a single for loop. 4222 struct LoopIterationSpace final { 4223 /// \brief Condition of the loop. 4224 Expr *PreCond = nullptr; 4225 /// \brief This expression calculates the number of iterations in the loop. 4226 /// It is always possible to calculate it before starting the loop. 4227 Expr *NumIterations = nullptr; 4228 /// \brief The loop counter variable. 4229 Expr *CounterVar = nullptr; 4230 /// \brief Private loop counter variable. 4231 Expr *PrivateCounterVar = nullptr; 4232 /// \brief This is initializer for the initial value of #CounterVar. 4233 Expr *CounterInit = nullptr; 4234 /// \brief This is step for the #CounterVar used to generate its update: 4235 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 4236 Expr *CounterStep = nullptr; 4237 /// \brief Should step be subtracted? 4238 bool Subtract = false; 4239 /// \brief Source range of the loop init. 4240 SourceRange InitSrcRange; 4241 /// \brief Source range of the loop condition. 4242 SourceRange CondSrcRange; 4243 /// \brief Source range of the loop increment. 4244 SourceRange IncSrcRange; 4245 }; 4246 4247 } // namespace 4248 4249 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 4250 assert(getLangOpts().OpenMP && "OpenMP is not active."); 4251 assert(Init && "Expected loop in canonical form."); 4252 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 4253 if (AssociatedLoops > 0 && 4254 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 4255 OpenMPIterationSpaceChecker ISC(*this, ForLoc); 4256 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) { 4257 if (auto *D = ISC.GetLoopDecl()) { 4258 auto *VD = dyn_cast<VarDecl>(D); 4259 if (!VD) { 4260 if (auto *Private = IsOpenMPCapturedDecl(D)) 4261 VD = Private; 4262 else { 4263 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(), 4264 /*WithInit=*/false); 4265 VD = cast<VarDecl>(Ref->getDecl()); 4266 } 4267 } 4268 DSAStack->addLoopControlVariable(D, VD); 4269 } 4270 } 4271 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 4272 } 4273 } 4274 4275 /// \brief Called on a for stmt to check and extract its iteration space 4276 /// for further processing (such as collapsing). 4277 static bool CheckOpenMPIterationSpace( 4278 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 4279 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 4280 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr, 4281 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 4282 LoopIterationSpace &ResultIterSpace, 4283 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4284 // OpenMP [2.6, Canonical Loop Form] 4285 // for (init-expr; test-expr; incr-expr) structured-block 4286 auto *For = dyn_cast_or_null<ForStmt>(S); 4287 if (!For) { 4288 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for) 4289 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 4290 << getOpenMPDirectiveName(DKind) << NestedLoopCount 4291 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 4292 if (NestedLoopCount > 1) { 4293 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 4294 SemaRef.Diag(DSA.getConstructLoc(), 4295 diag::note_omp_collapse_ordered_expr) 4296 << 2 << CollapseLoopCountExpr->getSourceRange() 4297 << OrderedLoopCountExpr->getSourceRange(); 4298 else if (CollapseLoopCountExpr) 4299 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 4300 diag::note_omp_collapse_ordered_expr) 4301 << 0 << CollapseLoopCountExpr->getSourceRange(); 4302 else 4303 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 4304 diag::note_omp_collapse_ordered_expr) 4305 << 1 << OrderedLoopCountExpr->getSourceRange(); 4306 } 4307 return true; 4308 } 4309 assert(For->getBody()); 4310 4311 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); 4312 4313 // Check init. 4314 auto Init = For->getInit(); 4315 if (ISC.CheckInit(Init)) 4316 return true; 4317 4318 bool HasErrors = false; 4319 4320 // Check loop variable's type. 4321 if (auto *LCDecl = ISC.GetLoopDecl()) { 4322 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr(); 4323 4324 // OpenMP [2.6, Canonical Loop Form] 4325 // Var is one of the following: 4326 // A variable of signed or unsigned integer type. 4327 // For C++, a variable of a random access iterator type. 4328 // For C, a variable of a pointer type. 4329 auto VarType = LCDecl->getType().getNonReferenceType(); 4330 if (!VarType->isDependentType() && !VarType->isIntegerType() && 4331 !VarType->isPointerType() && 4332 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 4333 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type) 4334 << SemaRef.getLangOpts().CPlusPlus; 4335 HasErrors = true; 4336 } 4337 4338 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 4339 // a Construct 4340 // The loop iteration variable(s) in the associated for-loop(s) of a for or 4341 // parallel for construct is (are) private. 4342 // The loop iteration variable in the associated for-loop of a simd 4343 // construct with just one associated for-loop is linear with a 4344 // constant-linear-step that is the increment of the associated for-loop. 4345 // Exclude loop var from the list of variables with implicitly defined data 4346 // sharing attributes. 4347 VarsWithImplicitDSA.erase(LCDecl); 4348 4349 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 4350 // in a Construct, C/C++]. 4351 // The loop iteration variable in the associated for-loop of a simd 4352 // construct with just one associated for-loop may be listed in a linear 4353 // clause with a constant-linear-step that is the increment of the 4354 // associated for-loop. 4355 // The loop iteration variable(s) in the associated for-loop(s) of a for or 4356 // parallel for construct may be listed in a private or lastprivate clause. 4357 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false); 4358 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 4359 // declared in the loop and it is predetermined as a private. 4360 auto PredeterminedCKind = 4361 isOpenMPSimdDirective(DKind) 4362 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 4363 : OMPC_private; 4364 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 4365 DVar.CKind != PredeterminedCKind) || 4366 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 4367 isOpenMPDistributeDirective(DKind)) && 4368 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 4369 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 4370 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 4371 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa) 4372 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 4373 << getOpenMPClauseName(PredeterminedCKind); 4374 if (DVar.RefExpr == nullptr) 4375 DVar.CKind = PredeterminedCKind; 4376 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true); 4377 HasErrors = true; 4378 } else if (LoopDeclRefExpr != nullptr) { 4379 // Make the loop iteration variable private (for worksharing constructs), 4380 // linear (for simd directives with the only one associated loop) or 4381 // lastprivate (for simd directives with several collapsed or ordered 4382 // loops). 4383 if (DVar.CKind == OMPC_unknown) 4384 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate, 4385 [](OpenMPDirectiveKind) -> bool { return true; }, 4386 /*FromParent=*/false); 4387 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind); 4388 } 4389 4390 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 4391 4392 // Check test-expr. 4393 HasErrors |= ISC.CheckCond(For->getCond()); 4394 4395 // Check incr-expr. 4396 HasErrors |= ISC.CheckInc(For->getInc()); 4397 } 4398 4399 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 4400 return HasErrors; 4401 4402 // Build the loop's iteration space representation. 4403 ResultIterSpace.PreCond = 4404 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures); 4405 ResultIterSpace.NumIterations = ISC.BuildNumIterations( 4406 DSA.getCurScope(), 4407 (isOpenMPWorksharingDirective(DKind) || 4408 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)), 4409 Captures); 4410 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA); 4411 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar(); 4412 ResultIterSpace.CounterInit = ISC.BuildCounterInit(); 4413 ResultIterSpace.CounterStep = ISC.BuildCounterStep(); 4414 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange(); 4415 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange(); 4416 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange(); 4417 ResultIterSpace.Subtract = ISC.ShouldSubtractStep(); 4418 4419 HasErrors |= (ResultIterSpace.PreCond == nullptr || 4420 ResultIterSpace.NumIterations == nullptr || 4421 ResultIterSpace.CounterVar == nullptr || 4422 ResultIterSpace.PrivateCounterVar == nullptr || 4423 ResultIterSpace.CounterInit == nullptr || 4424 ResultIterSpace.CounterStep == nullptr); 4425 4426 return HasErrors; 4427 } 4428 4429 /// \brief Build 'VarRef = Start. 4430 static ExprResult 4431 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 4432 ExprResult Start, 4433 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4434 // Build 'VarRef = Start. 4435 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures); 4436 if (!NewStart.isUsable()) 4437 return ExprError(); 4438 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 4439 VarRef.get()->getType())) { 4440 NewStart = SemaRef.PerformImplicitConversion( 4441 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 4442 /*AllowExplicit=*/true); 4443 if (!NewStart.isUsable()) 4444 return ExprError(); 4445 } 4446 4447 auto Init = 4448 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 4449 return Init; 4450 } 4451 4452 /// \brief Build 'VarRef = Start + Iter * Step'. 4453 static ExprResult 4454 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc, 4455 ExprResult VarRef, ExprResult Start, ExprResult Iter, 4456 ExprResult Step, bool Subtract, 4457 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) { 4458 // Add parentheses (for debugging purposes only). 4459 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 4460 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 4461 !Step.isUsable()) 4462 return ExprError(); 4463 4464 ExprResult NewStep = Step; 4465 if (Captures) 4466 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 4467 if (NewStep.isInvalid()) 4468 return ExprError(); 4469 ExprResult Update = 4470 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 4471 if (!Update.isUsable()) 4472 return ExprError(); 4473 4474 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 4475 // 'VarRef = Start (+|-) Iter * Step'. 4476 ExprResult NewStart = Start; 4477 if (Captures) 4478 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 4479 if (NewStart.isInvalid()) 4480 return ExprError(); 4481 4482 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 4483 ExprResult SavedUpdate = Update; 4484 ExprResult UpdateVal; 4485 if (VarRef.get()->getType()->isOverloadableType() || 4486 NewStart.get()->getType()->isOverloadableType() || 4487 Update.get()->getType()->isOverloadableType()) { 4488 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 4489 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 4490 Update = 4491 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 4492 if (Update.isUsable()) { 4493 UpdateVal = 4494 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 4495 VarRef.get(), SavedUpdate.get()); 4496 if (UpdateVal.isUsable()) { 4497 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 4498 UpdateVal.get()); 4499 } 4500 } 4501 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 4502 } 4503 4504 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 4505 if (!Update.isUsable() || !UpdateVal.isUsable()) { 4506 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 4507 NewStart.get(), SavedUpdate.get()); 4508 if (!Update.isUsable()) 4509 return ExprError(); 4510 4511 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 4512 VarRef.get()->getType())) { 4513 Update = SemaRef.PerformImplicitConversion( 4514 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 4515 if (!Update.isUsable()) 4516 return ExprError(); 4517 } 4518 4519 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 4520 } 4521 return Update; 4522 } 4523 4524 /// \brief Convert integer expression \a E to make it have at least \a Bits 4525 /// bits. 4526 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 4527 if (E == nullptr) 4528 return ExprError(); 4529 auto &C = SemaRef.Context; 4530 QualType OldType = E->getType(); 4531 unsigned HasBits = C.getTypeSize(OldType); 4532 if (HasBits >= Bits) 4533 return ExprResult(E); 4534 // OK to convert to signed, because new type has more bits than old. 4535 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 4536 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 4537 true); 4538 } 4539 4540 /// \brief Check if the given expression \a E is a constant integer that fits 4541 /// into \a Bits bits. 4542 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) { 4543 if (E == nullptr) 4544 return false; 4545 llvm::APSInt Result; 4546 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 4547 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 4548 return false; 4549 } 4550 4551 /// Build preinits statement for the given declarations. 4552 static Stmt *buildPreInits(ASTContext &Context, 4553 MutableArrayRef<Decl *> PreInits) { 4554 if (!PreInits.empty()) { 4555 return new (Context) DeclStmt( 4556 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 4557 SourceLocation(), SourceLocation()); 4558 } 4559 return nullptr; 4560 } 4561 4562 /// Build preinits statement for the given declarations. 4563 static Stmt * 4564 buildPreInits(ASTContext &Context, 4565 const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4566 if (!Captures.empty()) { 4567 SmallVector<Decl *, 16> PreInits; 4568 for (auto &Pair : Captures) 4569 PreInits.push_back(Pair.second->getDecl()); 4570 return buildPreInits(Context, PreInits); 4571 } 4572 return nullptr; 4573 } 4574 4575 /// Build postupdate expression for the given list of postupdates expressions. 4576 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 4577 Expr *PostUpdate = nullptr; 4578 if (!PostUpdates.empty()) { 4579 for (auto *E : PostUpdates) { 4580 Expr *ConvE = S.BuildCStyleCastExpr( 4581 E->getExprLoc(), 4582 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 4583 E->getExprLoc(), E) 4584 .get(); 4585 PostUpdate = PostUpdate 4586 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 4587 PostUpdate, ConvE) 4588 .get() 4589 : ConvE; 4590 } 4591 } 4592 return PostUpdate; 4593 } 4594 4595 /// \brief Called on a for stmt to check itself and nested loops (if any). 4596 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 4597 /// number of collapsed loops otherwise. 4598 static unsigned 4599 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 4600 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 4601 DSAStackTy &DSA, 4602 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 4603 OMPLoopDirective::HelperExprs &Built) { 4604 unsigned NestedLoopCount = 1; 4605 if (CollapseLoopCountExpr) { 4606 // Found 'collapse' clause - calculate collapse number. 4607 llvm::APSInt Result; 4608 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) 4609 NestedLoopCount = Result.getLimitedValue(); 4610 } 4611 if (OrderedLoopCountExpr) { 4612 // Found 'ordered' clause - calculate collapse number. 4613 llvm::APSInt Result; 4614 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 4615 if (Result.getLimitedValue() < NestedLoopCount) { 4616 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 4617 diag::err_omp_wrong_ordered_loop_count) 4618 << OrderedLoopCountExpr->getSourceRange(); 4619 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 4620 diag::note_collapse_loop_count) 4621 << CollapseLoopCountExpr->getSourceRange(); 4622 } 4623 NestedLoopCount = Result.getLimitedValue(); 4624 } 4625 } 4626 // This is helper routine for loop directives (e.g., 'for', 'simd', 4627 // 'for simd', etc.). 4628 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 4629 SmallVector<LoopIterationSpace, 4> IterSpaces; 4630 IterSpaces.resize(NestedLoopCount); 4631 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 4632 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 4633 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt, 4634 NestedLoopCount, CollapseLoopCountExpr, 4635 OrderedLoopCountExpr, VarsWithImplicitDSA, 4636 IterSpaces[Cnt], Captures)) 4637 return 0; 4638 // Move on to the next nested for loop, or to the loop body. 4639 // OpenMP [2.8.1, simd construct, Restrictions] 4640 // All loops associated with the construct must be perfectly nested; that 4641 // is, there must be no intervening code nor any OpenMP directive between 4642 // any two loops. 4643 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 4644 } 4645 4646 Built.clear(/* size */ NestedLoopCount); 4647 4648 if (SemaRef.CurContext->isDependentContext()) 4649 return NestedLoopCount; 4650 4651 // An example of what is generated for the following code: 4652 // 4653 // #pragma omp simd collapse(2) ordered(2) 4654 // for (i = 0; i < NI; ++i) 4655 // for (k = 0; k < NK; ++k) 4656 // for (j = J0; j < NJ; j+=2) { 4657 // <loop body> 4658 // } 4659 // 4660 // We generate the code below. 4661 // Note: the loop body may be outlined in CodeGen. 4662 // Note: some counters may be C++ classes, operator- is used to find number of 4663 // iterations and operator+= to calculate counter value. 4664 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 4665 // or i64 is currently supported). 4666 // 4667 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 4668 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 4669 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 4670 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 4671 // // similar updates for vars in clauses (e.g. 'linear') 4672 // <loop body (using local i and j)> 4673 // } 4674 // i = NI; // assign final values of counters 4675 // j = NJ; 4676 // 4677 4678 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 4679 // the iteration counts of the collapsed for loops. 4680 // Precondition tests if there is at least one iteration (all conditions are 4681 // true). 4682 auto PreCond = ExprResult(IterSpaces[0].PreCond); 4683 auto N0 = IterSpaces[0].NumIterations; 4684 ExprResult LastIteration32 = WidenIterationCount( 4685 32 /* Bits */, SemaRef 4686 .PerformImplicitConversion( 4687 N0->IgnoreImpCasts(), N0->getType(), 4688 Sema::AA_Converting, /*AllowExplicit=*/true) 4689 .get(), 4690 SemaRef); 4691 ExprResult LastIteration64 = WidenIterationCount( 4692 64 /* Bits */, SemaRef 4693 .PerformImplicitConversion( 4694 N0->IgnoreImpCasts(), N0->getType(), 4695 Sema::AA_Converting, /*AllowExplicit=*/true) 4696 .get(), 4697 SemaRef); 4698 4699 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 4700 return NestedLoopCount; 4701 4702 auto &C = SemaRef.Context; 4703 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 4704 4705 Scope *CurScope = DSA.getCurScope(); 4706 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 4707 if (PreCond.isUsable()) { 4708 PreCond = 4709 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 4710 PreCond.get(), IterSpaces[Cnt].PreCond); 4711 } 4712 auto N = IterSpaces[Cnt].NumIterations; 4713 SourceLocation Loc = N->getExprLoc(); 4714 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 4715 if (LastIteration32.isUsable()) 4716 LastIteration32 = SemaRef.BuildBinOp( 4717 CurScope, Loc, BO_Mul, LastIteration32.get(), 4718 SemaRef 4719 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 4720 Sema::AA_Converting, 4721 /*AllowExplicit=*/true) 4722 .get()); 4723 if (LastIteration64.isUsable()) 4724 LastIteration64 = SemaRef.BuildBinOp( 4725 CurScope, Loc, BO_Mul, LastIteration64.get(), 4726 SemaRef 4727 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 4728 Sema::AA_Converting, 4729 /*AllowExplicit=*/true) 4730 .get()); 4731 } 4732 4733 // Choose either the 32-bit or 64-bit version. 4734 ExprResult LastIteration = LastIteration64; 4735 if (LastIteration32.isUsable() && 4736 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 4737 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 4738 FitsInto( 4739 32 /* Bits */, 4740 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 4741 LastIteration64.get(), SemaRef))) 4742 LastIteration = LastIteration32; 4743 QualType VType = LastIteration.get()->getType(); 4744 QualType RealVType = VType; 4745 QualType StrideVType = VType; 4746 if (isOpenMPTaskLoopDirective(DKind)) { 4747 VType = 4748 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 4749 StrideVType = 4750 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 4751 } 4752 4753 if (!LastIteration.isUsable()) 4754 return 0; 4755 4756 // Save the number of iterations. 4757 ExprResult NumIterations = LastIteration; 4758 { 4759 LastIteration = SemaRef.BuildBinOp( 4760 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 4761 LastIteration.get(), 4762 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4763 if (!LastIteration.isUsable()) 4764 return 0; 4765 } 4766 4767 // Calculate the last iteration number beforehand instead of doing this on 4768 // each iteration. Do not do this if the number of iterations may be kfold-ed. 4769 llvm::APSInt Result; 4770 bool IsConstant = 4771 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 4772 ExprResult CalcLastIteration; 4773 if (!IsConstant) { 4774 ExprResult SaveRef = 4775 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 4776 LastIteration = SaveRef; 4777 4778 // Prepare SaveRef + 1. 4779 NumIterations = SemaRef.BuildBinOp( 4780 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 4781 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4782 if (!NumIterations.isUsable()) 4783 return 0; 4784 } 4785 4786 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 4787 4788 // Build variables passed into runtime, necessary for worksharing directives. 4789 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 4790 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4791 isOpenMPDistributeDirective(DKind)) { 4792 // Lower bound variable, initialized with zero. 4793 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 4794 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 4795 SemaRef.AddInitializerToDecl(LBDecl, 4796 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4797 /*DirectInit*/ false); 4798 4799 // Upper bound variable, initialized with last iteration number. 4800 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 4801 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 4802 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 4803 /*DirectInit*/ false); 4804 4805 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 4806 // This will be used to implement clause 'lastprivate'. 4807 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 4808 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 4809 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 4810 SemaRef.AddInitializerToDecl(ILDecl, 4811 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4812 /*DirectInit*/ false); 4813 4814 // Stride variable returned by runtime (we initialize it to 1 by default). 4815 VarDecl *STDecl = 4816 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 4817 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 4818 SemaRef.AddInitializerToDecl(STDecl, 4819 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 4820 /*DirectInit*/ false); 4821 4822 // Build expression: UB = min(UB, LastIteration) 4823 // It is necessary for CodeGen of directives with static scheduling. 4824 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 4825 UB.get(), LastIteration.get()); 4826 ExprResult CondOp = SemaRef.ActOnConditionalOp( 4827 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get()); 4828 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 4829 CondOp.get()); 4830 EUB = SemaRef.ActOnFinishFullExpr(EUB.get()); 4831 4832 // If we have a combined directive that combines 'distribute', 'for' or 4833 // 'simd' we need to be able to access the bounds of the schedule of the 4834 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 4835 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 4836 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4837 4838 // Lower bound variable, initialized with zero. 4839 VarDecl *CombLBDecl = 4840 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 4841 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 4842 SemaRef.AddInitializerToDecl( 4843 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4844 /*DirectInit*/ false); 4845 4846 // Upper bound variable, initialized with last iteration number. 4847 VarDecl *CombUBDecl = 4848 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 4849 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 4850 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 4851 /*DirectInit*/ false); 4852 4853 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 4854 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 4855 ExprResult CombCondOp = 4856 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 4857 LastIteration.get(), CombUB.get()); 4858 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 4859 CombCondOp.get()); 4860 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get()); 4861 4862 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 4863 // We expect to have at least 2 more parameters than the 'parallel' 4864 // directive does - the lower and upper bounds of the previous schedule. 4865 assert(CD->getNumParams() >= 4 && 4866 "Unexpected number of parameters in loop combined directive"); 4867 4868 // Set the proper type for the bounds given what we learned from the 4869 // enclosed loops. 4870 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 4871 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 4872 4873 // Previous lower and upper bounds are obtained from the region 4874 // parameters. 4875 PrevLB = 4876 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 4877 PrevUB = 4878 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 4879 } 4880 } 4881 4882 // Build the iteration variable and its initialization before loop. 4883 ExprResult IV; 4884 ExprResult Init, CombInit; 4885 { 4886 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 4887 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 4888 Expr *RHS = 4889 (isOpenMPWorksharingDirective(DKind) || 4890 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4891 ? LB.get() 4892 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 4893 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 4894 Init = SemaRef.ActOnFinishFullExpr(Init.get()); 4895 4896 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4897 Expr *CombRHS = 4898 (isOpenMPWorksharingDirective(DKind) || 4899 isOpenMPTaskLoopDirective(DKind) || 4900 isOpenMPDistributeDirective(DKind)) 4901 ? CombLB.get() 4902 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 4903 CombInit = 4904 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 4905 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get()); 4906 } 4907 } 4908 4909 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops. 4910 SourceLocation CondLoc = AStmt->getLocStart(); 4911 ExprResult Cond = 4912 (isOpenMPWorksharingDirective(DKind) || 4913 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4914 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()) 4915 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 4916 NumIterations.get()); 4917 ExprResult CombCond; 4918 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4919 CombCond = 4920 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get()); 4921 } 4922 // Loop increment (IV = IV + 1) 4923 SourceLocation IncLoc = AStmt->getLocStart(); 4924 ExprResult Inc = 4925 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 4926 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 4927 if (!Inc.isUsable()) 4928 return 0; 4929 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 4930 Inc = SemaRef.ActOnFinishFullExpr(Inc.get()); 4931 if (!Inc.isUsable()) 4932 return 0; 4933 4934 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 4935 // Used for directives with static scheduling. 4936 // In combined construct, add combined version that use CombLB and CombUB 4937 // base variables for the update 4938 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 4939 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4940 isOpenMPDistributeDirective(DKind)) { 4941 // LB + ST 4942 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 4943 if (!NextLB.isUsable()) 4944 return 0; 4945 // LB = LB + ST 4946 NextLB = 4947 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 4948 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get()); 4949 if (!NextLB.isUsable()) 4950 return 0; 4951 // UB + ST 4952 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 4953 if (!NextUB.isUsable()) 4954 return 0; 4955 // UB = UB + ST 4956 NextUB = 4957 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 4958 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get()); 4959 if (!NextUB.isUsable()) 4960 return 0; 4961 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4962 CombNextLB = 4963 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 4964 if (!NextLB.isUsable()) 4965 return 0; 4966 // LB = LB + ST 4967 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 4968 CombNextLB.get()); 4969 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get()); 4970 if (!CombNextLB.isUsable()) 4971 return 0; 4972 // UB + ST 4973 CombNextUB = 4974 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 4975 if (!CombNextUB.isUsable()) 4976 return 0; 4977 // UB = UB + ST 4978 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 4979 CombNextUB.get()); 4980 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get()); 4981 if (!CombNextUB.isUsable()) 4982 return 0; 4983 } 4984 } 4985 4986 // Create increment expression for distribute loop when combined in a same 4987 // directive with for as IV = IV + ST; ensure upper bound expression based 4988 // on PrevUB instead of NumIterations - used to implement 'for' when found 4989 // in combination with 'distribute', like in 'distribute parallel for' 4990 SourceLocation DistIncLoc = AStmt->getLocStart(); 4991 ExprResult DistCond, DistInc, PrevEUB; 4992 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4993 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()); 4994 assert(DistCond.isUsable() && "distribute cond expr was not built"); 4995 4996 DistInc = 4997 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 4998 assert(DistInc.isUsable() && "distribute inc expr was not built"); 4999 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 5000 DistInc.get()); 5001 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get()); 5002 assert(DistInc.isUsable() && "distribute inc expr was not built"); 5003 5004 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 5005 // construct 5006 SourceLocation DistEUBLoc = AStmt->getLocStart(); 5007 ExprResult IsUBGreater = 5008 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get()); 5009 ExprResult CondOp = SemaRef.ActOnConditionalOp( 5010 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get()); 5011 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 5012 CondOp.get()); 5013 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get()); 5014 } 5015 5016 // Build updates and final values of the loop counters. 5017 bool HasErrors = false; 5018 Built.Counters.resize(NestedLoopCount); 5019 Built.Inits.resize(NestedLoopCount); 5020 Built.Updates.resize(NestedLoopCount); 5021 Built.Finals.resize(NestedLoopCount); 5022 SmallVector<Expr *, 4> LoopMultipliers; 5023 { 5024 ExprResult Div; 5025 // Go from inner nested loop to outer. 5026 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 5027 LoopIterationSpace &IS = IterSpaces[Cnt]; 5028 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 5029 // Build: Iter = (IV / Div) % IS.NumIters 5030 // where Div is product of previous iterations' IS.NumIters. 5031 ExprResult Iter; 5032 if (Div.isUsable()) { 5033 Iter = 5034 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get()); 5035 } else { 5036 Iter = IV; 5037 assert((Cnt == (int)NestedLoopCount - 1) && 5038 "unusable div expected on first iteration only"); 5039 } 5040 5041 if (Cnt != 0 && Iter.isUsable()) 5042 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(), 5043 IS.NumIterations); 5044 if (!Iter.isUsable()) { 5045 HasErrors = true; 5046 break; 5047 } 5048 5049 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 5050 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 5051 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(), 5052 IS.CounterVar->getExprLoc(), 5053 /*RefersToCapture=*/true); 5054 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 5055 IS.CounterInit, Captures); 5056 if (!Init.isUsable()) { 5057 HasErrors = true; 5058 break; 5059 } 5060 ExprResult Update = BuildCounterUpdate( 5061 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 5062 IS.CounterStep, IS.Subtract, &Captures); 5063 if (!Update.isUsable()) { 5064 HasErrors = true; 5065 break; 5066 } 5067 5068 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 5069 ExprResult Final = BuildCounterUpdate( 5070 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, 5071 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures); 5072 if (!Final.isUsable()) { 5073 HasErrors = true; 5074 break; 5075 } 5076 5077 // Build Div for the next iteration: Div <- Div * IS.NumIters 5078 if (Cnt != 0) { 5079 if (Div.isUnset()) 5080 Div = IS.NumIterations; 5081 else 5082 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(), 5083 IS.NumIterations); 5084 5085 // Add parentheses (for debugging purposes only). 5086 if (Div.isUsable()) 5087 Div = tryBuildCapture(SemaRef, Div.get(), Captures); 5088 if (!Div.isUsable()) { 5089 HasErrors = true; 5090 break; 5091 } 5092 LoopMultipliers.push_back(Div.get()); 5093 } 5094 if (!Update.isUsable() || !Final.isUsable()) { 5095 HasErrors = true; 5096 break; 5097 } 5098 // Save results 5099 Built.Counters[Cnt] = IS.CounterVar; 5100 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 5101 Built.Inits[Cnt] = Init.get(); 5102 Built.Updates[Cnt] = Update.get(); 5103 Built.Finals[Cnt] = Final.get(); 5104 } 5105 } 5106 5107 if (HasErrors) 5108 return 0; 5109 5110 // Save results 5111 Built.IterationVarRef = IV.get(); 5112 Built.LastIteration = LastIteration.get(); 5113 Built.NumIterations = NumIterations.get(); 5114 Built.CalcLastIteration = 5115 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get(); 5116 Built.PreCond = PreCond.get(); 5117 Built.PreInits = buildPreInits(C, Captures); 5118 Built.Cond = Cond.get(); 5119 Built.Init = Init.get(); 5120 Built.Inc = Inc.get(); 5121 Built.LB = LB.get(); 5122 Built.UB = UB.get(); 5123 Built.IL = IL.get(); 5124 Built.ST = ST.get(); 5125 Built.EUB = EUB.get(); 5126 Built.NLB = NextLB.get(); 5127 Built.NUB = NextUB.get(); 5128 Built.PrevLB = PrevLB.get(); 5129 Built.PrevUB = PrevUB.get(); 5130 Built.DistInc = DistInc.get(); 5131 Built.PrevEUB = PrevEUB.get(); 5132 Built.DistCombinedFields.LB = CombLB.get(); 5133 Built.DistCombinedFields.UB = CombUB.get(); 5134 Built.DistCombinedFields.EUB = CombEUB.get(); 5135 Built.DistCombinedFields.Init = CombInit.get(); 5136 Built.DistCombinedFields.Cond = CombCond.get(); 5137 Built.DistCombinedFields.NLB = CombNextLB.get(); 5138 Built.DistCombinedFields.NUB = CombNextUB.get(); 5139 5140 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get(); 5141 // Fill data for doacross depend clauses. 5142 for (auto Pair : DSA.getDoacrossDependClauses()) { 5143 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 5144 Pair.first->setCounterValue(CounterVal); 5145 else { 5146 if (NestedLoopCount != Pair.second.size() || 5147 NestedLoopCount != LoopMultipliers.size() + 1) { 5148 // Erroneous case - clause has some problems. 5149 Pair.first->setCounterValue(CounterVal); 5150 continue; 5151 } 5152 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink); 5153 auto I = Pair.second.rbegin(); 5154 auto IS = IterSpaces.rbegin(); 5155 auto ILM = LoopMultipliers.rbegin(); 5156 Expr *UpCounterVal = CounterVal; 5157 Expr *Multiplier = nullptr; 5158 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 5159 if (I->first) { 5160 assert(IS->CounterStep); 5161 Expr *NormalizedOffset = 5162 SemaRef 5163 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div, 5164 I->first, IS->CounterStep) 5165 .get(); 5166 if (Multiplier) { 5167 NormalizedOffset = 5168 SemaRef 5169 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul, 5170 NormalizedOffset, Multiplier) 5171 .get(); 5172 } 5173 assert(I->second == OO_Plus || I->second == OO_Minus); 5174 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub; 5175 UpCounterVal = SemaRef 5176 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK, 5177 UpCounterVal, NormalizedOffset) 5178 .get(); 5179 } 5180 Multiplier = *ILM; 5181 ++I; 5182 ++IS; 5183 ++ILM; 5184 } 5185 Pair.first->setCounterValue(UpCounterVal); 5186 } 5187 } 5188 5189 return NestedLoopCount; 5190 } 5191 5192 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 5193 auto CollapseClauses = 5194 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 5195 if (CollapseClauses.begin() != CollapseClauses.end()) 5196 return (*CollapseClauses.begin())->getNumForLoops(); 5197 return nullptr; 5198 } 5199 5200 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 5201 auto OrderedClauses = 5202 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 5203 if (OrderedClauses.begin() != OrderedClauses.end()) 5204 return (*OrderedClauses.begin())->getNumForLoops(); 5205 return nullptr; 5206 } 5207 5208 static bool checkSimdlenSafelenSpecified(Sema &S, 5209 const ArrayRef<OMPClause *> Clauses) { 5210 OMPSafelenClause *Safelen = nullptr; 5211 OMPSimdlenClause *Simdlen = nullptr; 5212 5213 for (auto *Clause : Clauses) { 5214 if (Clause->getClauseKind() == OMPC_safelen) 5215 Safelen = cast<OMPSafelenClause>(Clause); 5216 else if (Clause->getClauseKind() == OMPC_simdlen) 5217 Simdlen = cast<OMPSimdlenClause>(Clause); 5218 if (Safelen && Simdlen) 5219 break; 5220 } 5221 5222 if (Simdlen && Safelen) { 5223 llvm::APSInt SimdlenRes, SafelenRes; 5224 auto SimdlenLength = Simdlen->getSimdlen(); 5225 auto SafelenLength = Safelen->getSafelen(); 5226 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 5227 SimdlenLength->isInstantiationDependent() || 5228 SimdlenLength->containsUnexpandedParameterPack()) 5229 return false; 5230 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 5231 SafelenLength->isInstantiationDependent() || 5232 SafelenLength->containsUnexpandedParameterPack()) 5233 return false; 5234 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context); 5235 SafelenLength->EvaluateAsInt(SafelenRes, S.Context); 5236 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 5237 // If both simdlen and safelen clauses are specified, the value of the 5238 // simdlen parameter must be less than or equal to the value of the safelen 5239 // parameter. 5240 if (SimdlenRes > SafelenRes) { 5241 S.Diag(SimdlenLength->getExprLoc(), 5242 diag::err_omp_wrong_simdlen_safelen_values) 5243 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 5244 return true; 5245 } 5246 } 5247 return false; 5248 } 5249 5250 StmtResult Sema::ActOnOpenMPSimdDirective( 5251 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5252 SourceLocation EndLoc, 5253 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5254 if (!AStmt) 5255 return StmtError(); 5256 5257 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5258 OMPLoopDirective::HelperExprs B; 5259 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5260 // define the nested loops number. 5261 unsigned NestedLoopCount = CheckOpenMPLoop( 5262 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 5263 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 5264 if (NestedLoopCount == 0) 5265 return StmtError(); 5266 5267 assert((CurContext->isDependentContext() || B.builtAll()) && 5268 "omp simd loop exprs were not built"); 5269 5270 if (!CurContext->isDependentContext()) { 5271 // Finalize the clauses that need pre-built expressions for CodeGen. 5272 for (auto C : Clauses) { 5273 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5274 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5275 B.NumIterations, *this, CurScope, 5276 DSAStack)) 5277 return StmtError(); 5278 } 5279 } 5280 5281 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5282 return StmtError(); 5283 5284 setFunctionHasBranchProtectedScope(); 5285 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5286 Clauses, AStmt, B); 5287 } 5288 5289 StmtResult Sema::ActOnOpenMPForDirective( 5290 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5291 SourceLocation EndLoc, 5292 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5293 if (!AStmt) 5294 return StmtError(); 5295 5296 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5297 OMPLoopDirective::HelperExprs B; 5298 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5299 // define the nested loops number. 5300 unsigned NestedLoopCount = CheckOpenMPLoop( 5301 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 5302 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 5303 if (NestedLoopCount == 0) 5304 return StmtError(); 5305 5306 assert((CurContext->isDependentContext() || B.builtAll()) && 5307 "omp for loop exprs were not built"); 5308 5309 if (!CurContext->isDependentContext()) { 5310 // Finalize the clauses that need pre-built expressions for CodeGen. 5311 for (auto C : Clauses) { 5312 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5313 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5314 B.NumIterations, *this, CurScope, 5315 DSAStack)) 5316 return StmtError(); 5317 } 5318 } 5319 5320 setFunctionHasBranchProtectedScope(); 5321 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5322 Clauses, AStmt, B, DSAStack->isCancelRegion()); 5323 } 5324 5325 StmtResult Sema::ActOnOpenMPForSimdDirective( 5326 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5327 SourceLocation EndLoc, 5328 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5329 if (!AStmt) 5330 return StmtError(); 5331 5332 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5333 OMPLoopDirective::HelperExprs B; 5334 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5335 // define the nested loops number. 5336 unsigned NestedLoopCount = 5337 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 5338 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5339 VarsWithImplicitDSA, B); 5340 if (NestedLoopCount == 0) 5341 return StmtError(); 5342 5343 assert((CurContext->isDependentContext() || B.builtAll()) && 5344 "omp for simd loop exprs were not built"); 5345 5346 if (!CurContext->isDependentContext()) { 5347 // Finalize the clauses that need pre-built expressions for CodeGen. 5348 for (auto C : Clauses) { 5349 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5350 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5351 B.NumIterations, *this, CurScope, 5352 DSAStack)) 5353 return StmtError(); 5354 } 5355 } 5356 5357 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5358 return StmtError(); 5359 5360 setFunctionHasBranchProtectedScope(); 5361 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 5362 Clauses, AStmt, B); 5363 } 5364 5365 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 5366 Stmt *AStmt, 5367 SourceLocation StartLoc, 5368 SourceLocation EndLoc) { 5369 if (!AStmt) 5370 return StmtError(); 5371 5372 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5373 auto BaseStmt = AStmt; 5374 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 5375 BaseStmt = CS->getCapturedStmt(); 5376 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 5377 auto S = C->children(); 5378 if (S.begin() == S.end()) 5379 return StmtError(); 5380 // All associated statements must be '#pragma omp section' except for 5381 // the first one. 5382 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 5383 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 5384 if (SectionStmt) 5385 Diag(SectionStmt->getLocStart(), 5386 diag::err_omp_sections_substmt_not_section); 5387 return StmtError(); 5388 } 5389 cast<OMPSectionDirective>(SectionStmt) 5390 ->setHasCancel(DSAStack->isCancelRegion()); 5391 } 5392 } else { 5393 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt); 5394 return StmtError(); 5395 } 5396 5397 setFunctionHasBranchProtectedScope(); 5398 5399 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5400 DSAStack->isCancelRegion()); 5401 } 5402 5403 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 5404 SourceLocation StartLoc, 5405 SourceLocation EndLoc) { 5406 if (!AStmt) 5407 return StmtError(); 5408 5409 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5410 5411 setFunctionHasBranchProtectedScope(); 5412 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 5413 5414 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 5415 DSAStack->isCancelRegion()); 5416 } 5417 5418 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 5419 Stmt *AStmt, 5420 SourceLocation StartLoc, 5421 SourceLocation EndLoc) { 5422 if (!AStmt) 5423 return StmtError(); 5424 5425 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5426 5427 setFunctionHasBranchProtectedScope(); 5428 5429 // OpenMP [2.7.3, single Construct, Restrictions] 5430 // The copyprivate clause must not be used with the nowait clause. 5431 OMPClause *Nowait = nullptr; 5432 OMPClause *Copyprivate = nullptr; 5433 for (auto *Clause : Clauses) { 5434 if (Clause->getClauseKind() == OMPC_nowait) 5435 Nowait = Clause; 5436 else if (Clause->getClauseKind() == OMPC_copyprivate) 5437 Copyprivate = Clause; 5438 if (Copyprivate && Nowait) { 5439 Diag(Copyprivate->getLocStart(), 5440 diag::err_omp_single_copyprivate_with_nowait); 5441 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here); 5442 return StmtError(); 5443 } 5444 } 5445 5446 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5447 } 5448 5449 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 5450 SourceLocation StartLoc, 5451 SourceLocation EndLoc) { 5452 if (!AStmt) 5453 return StmtError(); 5454 5455 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5456 5457 setFunctionHasBranchProtectedScope(); 5458 5459 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 5460 } 5461 5462 StmtResult Sema::ActOnOpenMPCriticalDirective( 5463 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 5464 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 5465 if (!AStmt) 5466 return StmtError(); 5467 5468 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5469 5470 bool ErrorFound = false; 5471 llvm::APSInt Hint; 5472 SourceLocation HintLoc; 5473 bool DependentHint = false; 5474 for (auto *C : Clauses) { 5475 if (C->getClauseKind() == OMPC_hint) { 5476 if (!DirName.getName()) { 5477 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name); 5478 ErrorFound = true; 5479 } 5480 Expr *E = cast<OMPHintClause>(C)->getHint(); 5481 if (E->isTypeDependent() || E->isValueDependent() || 5482 E->isInstantiationDependent()) 5483 DependentHint = true; 5484 else { 5485 Hint = E->EvaluateKnownConstInt(Context); 5486 HintLoc = C->getLocStart(); 5487 } 5488 } 5489 } 5490 if (ErrorFound) 5491 return StmtError(); 5492 auto Pair = DSAStack->getCriticalWithHint(DirName); 5493 if (Pair.first && DirName.getName() && !DependentHint) { 5494 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 5495 Diag(StartLoc, diag::err_omp_critical_with_hint); 5496 if (HintLoc.isValid()) { 5497 Diag(HintLoc, diag::note_omp_critical_hint_here) 5498 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 5499 } else 5500 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 5501 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 5502 Diag(C->getLocStart(), diag::note_omp_critical_hint_here) 5503 << 1 5504 << C->getHint()->EvaluateKnownConstInt(Context).toString( 5505 /*Radix=*/10, /*Signed=*/false); 5506 } else 5507 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1; 5508 } 5509 } 5510 5511 setFunctionHasBranchProtectedScope(); 5512 5513 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 5514 Clauses, AStmt); 5515 if (!Pair.first && DirName.getName() && !DependentHint) 5516 DSAStack->addCriticalWithHint(Dir, Hint); 5517 return Dir; 5518 } 5519 5520 StmtResult Sema::ActOnOpenMPParallelForDirective( 5521 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5522 SourceLocation EndLoc, 5523 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5524 if (!AStmt) 5525 return StmtError(); 5526 5527 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5528 // 1.2.2 OpenMP Language Terminology 5529 // Structured block - An executable statement with a single entry at the 5530 // top and a single exit at the bottom. 5531 // The point of exit cannot be a branch out of the structured block. 5532 // longjmp() and throw() must not violate the entry/exit criteria. 5533 CS->getCapturedDecl()->setNothrow(); 5534 5535 OMPLoopDirective::HelperExprs B; 5536 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5537 // define the nested loops number. 5538 unsigned NestedLoopCount = 5539 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 5540 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5541 VarsWithImplicitDSA, B); 5542 if (NestedLoopCount == 0) 5543 return StmtError(); 5544 5545 assert((CurContext->isDependentContext() || B.builtAll()) && 5546 "omp parallel for loop exprs were not built"); 5547 5548 if (!CurContext->isDependentContext()) { 5549 // Finalize the clauses that need pre-built expressions for CodeGen. 5550 for (auto C : Clauses) { 5551 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5552 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5553 B.NumIterations, *this, CurScope, 5554 DSAStack)) 5555 return StmtError(); 5556 } 5557 } 5558 5559 setFunctionHasBranchProtectedScope(); 5560 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, 5561 NestedLoopCount, Clauses, AStmt, B, 5562 DSAStack->isCancelRegion()); 5563 } 5564 5565 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 5566 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5567 SourceLocation EndLoc, 5568 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5569 if (!AStmt) 5570 return StmtError(); 5571 5572 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5573 // 1.2.2 OpenMP Language Terminology 5574 // Structured block - An executable statement with a single entry at the 5575 // top and a single exit at the bottom. 5576 // The point of exit cannot be a branch out of the structured block. 5577 // longjmp() and throw() must not violate the entry/exit criteria. 5578 CS->getCapturedDecl()->setNothrow(); 5579 5580 OMPLoopDirective::HelperExprs B; 5581 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5582 // define the nested loops number. 5583 unsigned NestedLoopCount = 5584 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 5585 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5586 VarsWithImplicitDSA, B); 5587 if (NestedLoopCount == 0) 5588 return StmtError(); 5589 5590 if (!CurContext->isDependentContext()) { 5591 // Finalize the clauses that need pre-built expressions for CodeGen. 5592 for (auto C : Clauses) { 5593 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5594 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5595 B.NumIterations, *this, CurScope, 5596 DSAStack)) 5597 return StmtError(); 5598 } 5599 } 5600 5601 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5602 return StmtError(); 5603 5604 setFunctionHasBranchProtectedScope(); 5605 return OMPParallelForSimdDirective::Create( 5606 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 5607 } 5608 5609 StmtResult 5610 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 5611 Stmt *AStmt, SourceLocation StartLoc, 5612 SourceLocation EndLoc) { 5613 if (!AStmt) 5614 return StmtError(); 5615 5616 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5617 auto BaseStmt = AStmt; 5618 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 5619 BaseStmt = CS->getCapturedStmt(); 5620 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 5621 auto S = C->children(); 5622 if (S.begin() == S.end()) 5623 return StmtError(); 5624 // All associated statements must be '#pragma omp section' except for 5625 // the first one. 5626 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 5627 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 5628 if (SectionStmt) 5629 Diag(SectionStmt->getLocStart(), 5630 diag::err_omp_parallel_sections_substmt_not_section); 5631 return StmtError(); 5632 } 5633 cast<OMPSectionDirective>(SectionStmt) 5634 ->setHasCancel(DSAStack->isCancelRegion()); 5635 } 5636 } else { 5637 Diag(AStmt->getLocStart(), 5638 diag::err_omp_parallel_sections_not_compound_stmt); 5639 return StmtError(); 5640 } 5641 5642 setFunctionHasBranchProtectedScope(); 5643 5644 return OMPParallelSectionsDirective::Create( 5645 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); 5646 } 5647 5648 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 5649 Stmt *AStmt, SourceLocation StartLoc, 5650 SourceLocation EndLoc) { 5651 if (!AStmt) 5652 return StmtError(); 5653 5654 auto *CS = cast<CapturedStmt>(AStmt); 5655 // 1.2.2 OpenMP Language Terminology 5656 // Structured block - An executable statement with a single entry at the 5657 // top and a single exit at the bottom. 5658 // The point of exit cannot be a branch out of the structured block. 5659 // longjmp() and throw() must not violate the entry/exit criteria. 5660 CS->getCapturedDecl()->setNothrow(); 5661 5662 setFunctionHasBranchProtectedScope(); 5663 5664 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5665 DSAStack->isCancelRegion()); 5666 } 5667 5668 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 5669 SourceLocation EndLoc) { 5670 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 5671 } 5672 5673 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 5674 SourceLocation EndLoc) { 5675 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 5676 } 5677 5678 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 5679 SourceLocation EndLoc) { 5680 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 5681 } 5682 5683 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 5684 Stmt *AStmt, 5685 SourceLocation StartLoc, 5686 SourceLocation EndLoc) { 5687 if (!AStmt) 5688 return StmtError(); 5689 5690 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5691 5692 setFunctionHasBranchProtectedScope(); 5693 5694 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, 5695 AStmt, 5696 DSAStack->getTaskgroupReductionRef()); 5697 } 5698 5699 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 5700 SourceLocation StartLoc, 5701 SourceLocation EndLoc) { 5702 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 5703 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 5704 } 5705 5706 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 5707 Stmt *AStmt, 5708 SourceLocation StartLoc, 5709 SourceLocation EndLoc) { 5710 OMPClause *DependFound = nullptr; 5711 OMPClause *DependSourceClause = nullptr; 5712 OMPClause *DependSinkClause = nullptr; 5713 bool ErrorFound = false; 5714 OMPThreadsClause *TC = nullptr; 5715 OMPSIMDClause *SC = nullptr; 5716 for (auto *C : Clauses) { 5717 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 5718 DependFound = C; 5719 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 5720 if (DependSourceClause) { 5721 Diag(C->getLocStart(), diag::err_omp_more_one_clause) 5722 << getOpenMPDirectiveName(OMPD_ordered) 5723 << getOpenMPClauseName(OMPC_depend) << 2; 5724 ErrorFound = true; 5725 } else 5726 DependSourceClause = C; 5727 if (DependSinkClause) { 5728 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 5729 << 0; 5730 ErrorFound = true; 5731 } 5732 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 5733 if (DependSourceClause) { 5734 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 5735 << 1; 5736 ErrorFound = true; 5737 } 5738 DependSinkClause = C; 5739 } 5740 } else if (C->getClauseKind() == OMPC_threads) 5741 TC = cast<OMPThreadsClause>(C); 5742 else if (C->getClauseKind() == OMPC_simd) 5743 SC = cast<OMPSIMDClause>(C); 5744 } 5745 if (!ErrorFound && !SC && 5746 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 5747 // OpenMP [2.8.1,simd Construct, Restrictions] 5748 // An ordered construct with the simd clause is the only OpenMP construct 5749 // that can appear in the simd region. 5750 Diag(StartLoc, diag::err_omp_prohibited_region_simd); 5751 ErrorFound = true; 5752 } else if (DependFound && (TC || SC)) { 5753 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd) 5754 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 5755 ErrorFound = true; 5756 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) { 5757 Diag(DependFound->getLocStart(), 5758 diag::err_omp_ordered_directive_without_param); 5759 ErrorFound = true; 5760 } else if (TC || Clauses.empty()) { 5761 if (auto *Param = DSAStack->getParentOrderedRegionParam()) { 5762 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc; 5763 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 5764 << (TC != nullptr); 5765 Diag(Param->getLocStart(), diag::note_omp_ordered_param); 5766 ErrorFound = true; 5767 } 5768 } 5769 if ((!AStmt && !DependFound) || ErrorFound) 5770 return StmtError(); 5771 5772 if (AStmt) { 5773 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5774 5775 setFunctionHasBranchProtectedScope(); 5776 } 5777 5778 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5779 } 5780 5781 namespace { 5782 /// \brief Helper class for checking expression in 'omp atomic [update]' 5783 /// construct. 5784 class OpenMPAtomicUpdateChecker { 5785 /// \brief Error results for atomic update expressions. 5786 enum ExprAnalysisErrorCode { 5787 /// \brief A statement is not an expression statement. 5788 NotAnExpression, 5789 /// \brief Expression is not builtin binary or unary operation. 5790 NotABinaryOrUnaryExpression, 5791 /// \brief Unary operation is not post-/pre- increment/decrement operation. 5792 NotAnUnaryIncDecExpression, 5793 /// \brief An expression is not of scalar type. 5794 NotAScalarType, 5795 /// \brief A binary operation is not an assignment operation. 5796 NotAnAssignmentOp, 5797 /// \brief RHS part of the binary operation is not a binary expression. 5798 NotABinaryExpression, 5799 /// \brief RHS part is not additive/multiplicative/shift/biwise binary 5800 /// expression. 5801 NotABinaryOperator, 5802 /// \brief RHS binary operation does not have reference to the updated LHS 5803 /// part. 5804 NotAnUpdateExpression, 5805 /// \brief No errors is found. 5806 NoError 5807 }; 5808 /// \brief Reference to Sema. 5809 Sema &SemaRef; 5810 /// \brief A location for note diagnostics (when error is found). 5811 SourceLocation NoteLoc; 5812 /// \brief 'x' lvalue part of the source atomic expression. 5813 Expr *X; 5814 /// \brief 'expr' rvalue part of the source atomic expression. 5815 Expr *E; 5816 /// \brief Helper expression of the form 5817 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 5818 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 5819 Expr *UpdateExpr; 5820 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is 5821 /// important for non-associative operations. 5822 bool IsXLHSInRHSPart; 5823 BinaryOperatorKind Op; 5824 SourceLocation OpLoc; 5825 /// \brief true if the source expression is a postfix unary operation, false 5826 /// if it is a prefix unary operation. 5827 bool IsPostfixUpdate; 5828 5829 public: 5830 OpenMPAtomicUpdateChecker(Sema &SemaRef) 5831 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 5832 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 5833 /// \brief Check specified statement that it is suitable for 'atomic update' 5834 /// constructs and extract 'x', 'expr' and Operation from the original 5835 /// expression. If DiagId and NoteId == 0, then only check is performed 5836 /// without error notification. 5837 /// \param DiagId Diagnostic which should be emitted if error is found. 5838 /// \param NoteId Diagnostic note for the main error message. 5839 /// \return true if statement is not an update expression, false otherwise. 5840 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 5841 /// \brief Return the 'x' lvalue part of the source atomic expression. 5842 Expr *getX() const { return X; } 5843 /// \brief Return the 'expr' rvalue part of the source atomic expression. 5844 Expr *getExpr() const { return E; } 5845 /// \brief Return the update expression used in calculation of the updated 5846 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 5847 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 5848 Expr *getUpdateExpr() const { return UpdateExpr; } 5849 /// \brief Return true if 'x' is LHS in RHS part of full update expression, 5850 /// false otherwise. 5851 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 5852 5853 /// \brief true if the source expression is a postfix unary operation, false 5854 /// if it is a prefix unary operation. 5855 bool isPostfixUpdate() const { return IsPostfixUpdate; } 5856 5857 private: 5858 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 5859 unsigned NoteId = 0); 5860 }; 5861 } // namespace 5862 5863 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 5864 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 5865 ExprAnalysisErrorCode ErrorFound = NoError; 5866 SourceLocation ErrorLoc, NoteLoc; 5867 SourceRange ErrorRange, NoteRange; 5868 // Allowed constructs are: 5869 // x = x binop expr; 5870 // x = expr binop x; 5871 if (AtomicBinOp->getOpcode() == BO_Assign) { 5872 X = AtomicBinOp->getLHS(); 5873 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 5874 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 5875 if (AtomicInnerBinOp->isMultiplicativeOp() || 5876 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 5877 AtomicInnerBinOp->isBitwiseOp()) { 5878 Op = AtomicInnerBinOp->getOpcode(); 5879 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 5880 auto *LHS = AtomicInnerBinOp->getLHS(); 5881 auto *RHS = AtomicInnerBinOp->getRHS(); 5882 llvm::FoldingSetNodeID XId, LHSId, RHSId; 5883 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 5884 /*Canonical=*/true); 5885 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 5886 /*Canonical=*/true); 5887 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 5888 /*Canonical=*/true); 5889 if (XId == LHSId) { 5890 E = RHS; 5891 IsXLHSInRHSPart = true; 5892 } else if (XId == RHSId) { 5893 E = LHS; 5894 IsXLHSInRHSPart = false; 5895 } else { 5896 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 5897 ErrorRange = AtomicInnerBinOp->getSourceRange(); 5898 NoteLoc = X->getExprLoc(); 5899 NoteRange = X->getSourceRange(); 5900 ErrorFound = NotAnUpdateExpression; 5901 } 5902 } else { 5903 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 5904 ErrorRange = AtomicInnerBinOp->getSourceRange(); 5905 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 5906 NoteRange = SourceRange(NoteLoc, NoteLoc); 5907 ErrorFound = NotABinaryOperator; 5908 } 5909 } else { 5910 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 5911 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 5912 ErrorFound = NotABinaryExpression; 5913 } 5914 } else { 5915 ErrorLoc = AtomicBinOp->getExprLoc(); 5916 ErrorRange = AtomicBinOp->getSourceRange(); 5917 NoteLoc = AtomicBinOp->getOperatorLoc(); 5918 NoteRange = SourceRange(NoteLoc, NoteLoc); 5919 ErrorFound = NotAnAssignmentOp; 5920 } 5921 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5922 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5923 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5924 return true; 5925 } else if (SemaRef.CurContext->isDependentContext()) 5926 E = X = UpdateExpr = nullptr; 5927 return ErrorFound != NoError; 5928 } 5929 5930 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 5931 unsigned NoteId) { 5932 ExprAnalysisErrorCode ErrorFound = NoError; 5933 SourceLocation ErrorLoc, NoteLoc; 5934 SourceRange ErrorRange, NoteRange; 5935 // Allowed constructs are: 5936 // x++; 5937 // x--; 5938 // ++x; 5939 // --x; 5940 // x binop= expr; 5941 // x = x binop expr; 5942 // x = expr binop x; 5943 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 5944 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 5945 if (AtomicBody->getType()->isScalarType() || 5946 AtomicBody->isInstantiationDependent()) { 5947 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 5948 AtomicBody->IgnoreParenImpCasts())) { 5949 // Check for Compound Assignment Operation 5950 Op = BinaryOperator::getOpForCompoundAssignment( 5951 AtomicCompAssignOp->getOpcode()); 5952 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 5953 E = AtomicCompAssignOp->getRHS(); 5954 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 5955 IsXLHSInRHSPart = true; 5956 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 5957 AtomicBody->IgnoreParenImpCasts())) { 5958 // Check for Binary Operation 5959 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 5960 return true; 5961 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 5962 AtomicBody->IgnoreParenImpCasts())) { 5963 // Check for Unary Operation 5964 if (AtomicUnaryOp->isIncrementDecrementOp()) { 5965 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 5966 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 5967 OpLoc = AtomicUnaryOp->getOperatorLoc(); 5968 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 5969 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 5970 IsXLHSInRHSPart = true; 5971 } else { 5972 ErrorFound = NotAnUnaryIncDecExpression; 5973 ErrorLoc = AtomicUnaryOp->getExprLoc(); 5974 ErrorRange = AtomicUnaryOp->getSourceRange(); 5975 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 5976 NoteRange = SourceRange(NoteLoc, NoteLoc); 5977 } 5978 } else if (!AtomicBody->isInstantiationDependent()) { 5979 ErrorFound = NotABinaryOrUnaryExpression; 5980 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 5981 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 5982 } 5983 } else { 5984 ErrorFound = NotAScalarType; 5985 NoteLoc = ErrorLoc = AtomicBody->getLocStart(); 5986 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5987 } 5988 } else { 5989 ErrorFound = NotAnExpression; 5990 NoteLoc = ErrorLoc = S->getLocStart(); 5991 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5992 } 5993 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5994 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5995 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5996 return true; 5997 } else if (SemaRef.CurContext->isDependentContext()) 5998 E = X = UpdateExpr = nullptr; 5999 if (ErrorFound == NoError && E && X) { 6000 // Build an update expression of form 'OpaqueValueExpr(x) binop 6001 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 6002 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 6003 auto *OVEX = new (SemaRef.getASTContext()) 6004 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 6005 auto *OVEExpr = new (SemaRef.getASTContext()) 6006 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 6007 auto Update = 6008 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 6009 IsXLHSInRHSPart ? OVEExpr : OVEX); 6010 if (Update.isInvalid()) 6011 return true; 6012 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 6013 Sema::AA_Casting); 6014 if (Update.isInvalid()) 6015 return true; 6016 UpdateExpr = Update.get(); 6017 } 6018 return ErrorFound != NoError; 6019 } 6020 6021 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 6022 Stmt *AStmt, 6023 SourceLocation StartLoc, 6024 SourceLocation EndLoc) { 6025 if (!AStmt) 6026 return StmtError(); 6027 6028 auto *CS = cast<CapturedStmt>(AStmt); 6029 // 1.2.2 OpenMP Language Terminology 6030 // Structured block - An executable statement with a single entry at the 6031 // top and a single exit at the bottom. 6032 // The point of exit cannot be a branch out of the structured block. 6033 // longjmp() and throw() must not violate the entry/exit criteria. 6034 OpenMPClauseKind AtomicKind = OMPC_unknown; 6035 SourceLocation AtomicKindLoc; 6036 for (auto *C : Clauses) { 6037 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 6038 C->getClauseKind() == OMPC_update || 6039 C->getClauseKind() == OMPC_capture) { 6040 if (AtomicKind != OMPC_unknown) { 6041 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses) 6042 << SourceRange(C->getLocStart(), C->getLocEnd()); 6043 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 6044 << getOpenMPClauseName(AtomicKind); 6045 } else { 6046 AtomicKind = C->getClauseKind(); 6047 AtomicKindLoc = C->getLocStart(); 6048 } 6049 } 6050 } 6051 6052 auto Body = CS->getCapturedStmt(); 6053 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 6054 Body = EWC->getSubExpr(); 6055 6056 Expr *X = nullptr; 6057 Expr *V = nullptr; 6058 Expr *E = nullptr; 6059 Expr *UE = nullptr; 6060 bool IsXLHSInRHSPart = false; 6061 bool IsPostfixUpdate = false; 6062 // OpenMP [2.12.6, atomic Construct] 6063 // In the next expressions: 6064 // * x and v (as applicable) are both l-value expressions with scalar type. 6065 // * During the execution of an atomic region, multiple syntactic 6066 // occurrences of x must designate the same storage location. 6067 // * Neither of v and expr (as applicable) may access the storage location 6068 // designated by x. 6069 // * Neither of x and expr (as applicable) may access the storage location 6070 // designated by v. 6071 // * expr is an expression with scalar type. 6072 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 6073 // * binop, binop=, ++, and -- are not overloaded operators. 6074 // * The expression x binop expr must be numerically equivalent to x binop 6075 // (expr). This requirement is satisfied if the operators in expr have 6076 // precedence greater than binop, or by using parentheses around expr or 6077 // subexpressions of expr. 6078 // * The expression expr binop x must be numerically equivalent to (expr) 6079 // binop x. This requirement is satisfied if the operators in expr have 6080 // precedence equal to or greater than binop, or by using parentheses around 6081 // expr or subexpressions of expr. 6082 // * For forms that allow multiple occurrences of x, the number of times 6083 // that x is evaluated is unspecified. 6084 if (AtomicKind == OMPC_read) { 6085 enum { 6086 NotAnExpression, 6087 NotAnAssignmentOp, 6088 NotAScalarType, 6089 NotAnLValue, 6090 NoError 6091 } ErrorFound = NoError; 6092 SourceLocation ErrorLoc, NoteLoc; 6093 SourceRange ErrorRange, NoteRange; 6094 // If clause is read: 6095 // v = x; 6096 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 6097 auto *AtomicBinOp = 6098 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6099 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6100 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 6101 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 6102 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 6103 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 6104 if (!X->isLValue() || !V->isLValue()) { 6105 auto NotLValueExpr = X->isLValue() ? V : X; 6106 ErrorFound = NotAnLValue; 6107 ErrorLoc = AtomicBinOp->getExprLoc(); 6108 ErrorRange = AtomicBinOp->getSourceRange(); 6109 NoteLoc = NotLValueExpr->getExprLoc(); 6110 NoteRange = NotLValueExpr->getSourceRange(); 6111 } 6112 } else if (!X->isInstantiationDependent() || 6113 !V->isInstantiationDependent()) { 6114 auto NotScalarExpr = 6115 (X->isInstantiationDependent() || X->getType()->isScalarType()) 6116 ? V 6117 : X; 6118 ErrorFound = NotAScalarType; 6119 ErrorLoc = AtomicBinOp->getExprLoc(); 6120 ErrorRange = AtomicBinOp->getSourceRange(); 6121 NoteLoc = NotScalarExpr->getExprLoc(); 6122 NoteRange = NotScalarExpr->getSourceRange(); 6123 } 6124 } else if (!AtomicBody->isInstantiationDependent()) { 6125 ErrorFound = NotAnAssignmentOp; 6126 ErrorLoc = AtomicBody->getExprLoc(); 6127 ErrorRange = AtomicBody->getSourceRange(); 6128 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6129 : AtomicBody->getExprLoc(); 6130 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6131 : AtomicBody->getSourceRange(); 6132 } 6133 } else { 6134 ErrorFound = NotAnExpression; 6135 NoteLoc = ErrorLoc = Body->getLocStart(); 6136 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6137 } 6138 if (ErrorFound != NoError) { 6139 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 6140 << ErrorRange; 6141 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 6142 << NoteRange; 6143 return StmtError(); 6144 } else if (CurContext->isDependentContext()) 6145 V = X = nullptr; 6146 } else if (AtomicKind == OMPC_write) { 6147 enum { 6148 NotAnExpression, 6149 NotAnAssignmentOp, 6150 NotAScalarType, 6151 NotAnLValue, 6152 NoError 6153 } ErrorFound = NoError; 6154 SourceLocation ErrorLoc, NoteLoc; 6155 SourceRange ErrorRange, NoteRange; 6156 // If clause is write: 6157 // x = expr; 6158 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 6159 auto *AtomicBinOp = 6160 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6161 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6162 X = AtomicBinOp->getLHS(); 6163 E = AtomicBinOp->getRHS(); 6164 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 6165 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 6166 if (!X->isLValue()) { 6167 ErrorFound = NotAnLValue; 6168 ErrorLoc = AtomicBinOp->getExprLoc(); 6169 ErrorRange = AtomicBinOp->getSourceRange(); 6170 NoteLoc = X->getExprLoc(); 6171 NoteRange = X->getSourceRange(); 6172 } 6173 } else if (!X->isInstantiationDependent() || 6174 !E->isInstantiationDependent()) { 6175 auto NotScalarExpr = 6176 (X->isInstantiationDependent() || X->getType()->isScalarType()) 6177 ? E 6178 : X; 6179 ErrorFound = NotAScalarType; 6180 ErrorLoc = AtomicBinOp->getExprLoc(); 6181 ErrorRange = AtomicBinOp->getSourceRange(); 6182 NoteLoc = NotScalarExpr->getExprLoc(); 6183 NoteRange = NotScalarExpr->getSourceRange(); 6184 } 6185 } else if (!AtomicBody->isInstantiationDependent()) { 6186 ErrorFound = NotAnAssignmentOp; 6187 ErrorLoc = AtomicBody->getExprLoc(); 6188 ErrorRange = AtomicBody->getSourceRange(); 6189 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6190 : AtomicBody->getExprLoc(); 6191 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6192 : AtomicBody->getSourceRange(); 6193 } 6194 } else { 6195 ErrorFound = NotAnExpression; 6196 NoteLoc = ErrorLoc = Body->getLocStart(); 6197 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 6198 } 6199 if (ErrorFound != NoError) { 6200 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 6201 << ErrorRange; 6202 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 6203 << NoteRange; 6204 return StmtError(); 6205 } else if (CurContext->isDependentContext()) 6206 E = X = nullptr; 6207 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 6208 // If clause is update: 6209 // x++; 6210 // x--; 6211 // ++x; 6212 // --x; 6213 // x binop= expr; 6214 // x = x binop expr; 6215 // x = expr binop x; 6216 OpenMPAtomicUpdateChecker Checker(*this); 6217 if (Checker.checkStatement( 6218 Body, (AtomicKind == OMPC_update) 6219 ? diag::err_omp_atomic_update_not_expression_statement 6220 : diag::err_omp_atomic_not_expression_statement, 6221 diag::note_omp_atomic_update)) 6222 return StmtError(); 6223 if (!CurContext->isDependentContext()) { 6224 E = Checker.getExpr(); 6225 X = Checker.getX(); 6226 UE = Checker.getUpdateExpr(); 6227 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6228 } 6229 } else if (AtomicKind == OMPC_capture) { 6230 enum { 6231 NotAnAssignmentOp, 6232 NotACompoundStatement, 6233 NotTwoSubstatements, 6234 NotASpecificExpression, 6235 NoError 6236 } ErrorFound = NoError; 6237 SourceLocation ErrorLoc, NoteLoc; 6238 SourceRange ErrorRange, NoteRange; 6239 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 6240 // If clause is a capture: 6241 // v = x++; 6242 // v = x--; 6243 // v = ++x; 6244 // v = --x; 6245 // v = x binop= expr; 6246 // v = x = x binop expr; 6247 // v = x = expr binop x; 6248 auto *AtomicBinOp = 6249 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 6250 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 6251 V = AtomicBinOp->getLHS(); 6252 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 6253 OpenMPAtomicUpdateChecker Checker(*this); 6254 if (Checker.checkStatement( 6255 Body, diag::err_omp_atomic_capture_not_expression_statement, 6256 diag::note_omp_atomic_update)) 6257 return StmtError(); 6258 E = Checker.getExpr(); 6259 X = Checker.getX(); 6260 UE = Checker.getUpdateExpr(); 6261 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6262 IsPostfixUpdate = Checker.isPostfixUpdate(); 6263 } else if (!AtomicBody->isInstantiationDependent()) { 6264 ErrorLoc = AtomicBody->getExprLoc(); 6265 ErrorRange = AtomicBody->getSourceRange(); 6266 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 6267 : AtomicBody->getExprLoc(); 6268 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 6269 : AtomicBody->getSourceRange(); 6270 ErrorFound = NotAnAssignmentOp; 6271 } 6272 if (ErrorFound != NoError) { 6273 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 6274 << ErrorRange; 6275 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 6276 return StmtError(); 6277 } else if (CurContext->isDependentContext()) { 6278 UE = V = E = X = nullptr; 6279 } 6280 } else { 6281 // If clause is a capture: 6282 // { v = x; x = expr; } 6283 // { v = x; x++; } 6284 // { v = x; x--; } 6285 // { v = x; ++x; } 6286 // { v = x; --x; } 6287 // { v = x; x binop= expr; } 6288 // { v = x; x = x binop expr; } 6289 // { v = x; x = expr binop x; } 6290 // { x++; v = x; } 6291 // { x--; v = x; } 6292 // { ++x; v = x; } 6293 // { --x; v = x; } 6294 // { x binop= expr; v = x; } 6295 // { x = x binop expr; v = x; } 6296 // { x = expr binop x; v = x; } 6297 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 6298 // Check that this is { expr1; expr2; } 6299 if (CS->size() == 2) { 6300 auto *First = CS->body_front(); 6301 auto *Second = CS->body_back(); 6302 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 6303 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 6304 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 6305 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 6306 // Need to find what subexpression is 'v' and what is 'x'. 6307 OpenMPAtomicUpdateChecker Checker(*this); 6308 bool IsUpdateExprFound = !Checker.checkStatement(Second); 6309 BinaryOperator *BinOp = nullptr; 6310 if (IsUpdateExprFound) { 6311 BinOp = dyn_cast<BinaryOperator>(First); 6312 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 6313 } 6314 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 6315 // { v = x; x++; } 6316 // { v = x; x--; } 6317 // { v = x; ++x; } 6318 // { v = x; --x; } 6319 // { v = x; x binop= expr; } 6320 // { v = x; x = x binop expr; } 6321 // { v = x; x = expr binop x; } 6322 // Check that the first expression has form v = x. 6323 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 6324 llvm::FoldingSetNodeID XId, PossibleXId; 6325 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 6326 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 6327 IsUpdateExprFound = XId == PossibleXId; 6328 if (IsUpdateExprFound) { 6329 V = BinOp->getLHS(); 6330 X = Checker.getX(); 6331 E = Checker.getExpr(); 6332 UE = Checker.getUpdateExpr(); 6333 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6334 IsPostfixUpdate = true; 6335 } 6336 } 6337 if (!IsUpdateExprFound) { 6338 IsUpdateExprFound = !Checker.checkStatement(First); 6339 BinOp = nullptr; 6340 if (IsUpdateExprFound) { 6341 BinOp = dyn_cast<BinaryOperator>(Second); 6342 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 6343 } 6344 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 6345 // { x++; v = x; } 6346 // { x--; v = x; } 6347 // { ++x; v = x; } 6348 // { --x; v = x; } 6349 // { x binop= expr; v = x; } 6350 // { x = x binop expr; v = x; } 6351 // { x = expr binop x; v = x; } 6352 // Check that the second expression has form v = x. 6353 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 6354 llvm::FoldingSetNodeID XId, PossibleXId; 6355 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 6356 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 6357 IsUpdateExprFound = XId == PossibleXId; 6358 if (IsUpdateExprFound) { 6359 V = BinOp->getLHS(); 6360 X = Checker.getX(); 6361 E = Checker.getExpr(); 6362 UE = Checker.getUpdateExpr(); 6363 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 6364 IsPostfixUpdate = false; 6365 } 6366 } 6367 } 6368 if (!IsUpdateExprFound) { 6369 // { v = x; x = expr; } 6370 auto *FirstExpr = dyn_cast<Expr>(First); 6371 auto *SecondExpr = dyn_cast<Expr>(Second); 6372 if (!FirstExpr || !SecondExpr || 6373 !(FirstExpr->isInstantiationDependent() || 6374 SecondExpr->isInstantiationDependent())) { 6375 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 6376 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 6377 ErrorFound = NotAnAssignmentOp; 6378 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 6379 : First->getLocStart(); 6380 NoteRange = ErrorRange = FirstBinOp 6381 ? FirstBinOp->getSourceRange() 6382 : SourceRange(ErrorLoc, ErrorLoc); 6383 } else { 6384 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 6385 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 6386 ErrorFound = NotAnAssignmentOp; 6387 NoteLoc = ErrorLoc = SecondBinOp 6388 ? SecondBinOp->getOperatorLoc() 6389 : Second->getLocStart(); 6390 NoteRange = ErrorRange = 6391 SecondBinOp ? SecondBinOp->getSourceRange() 6392 : SourceRange(ErrorLoc, ErrorLoc); 6393 } else { 6394 auto *PossibleXRHSInFirst = 6395 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 6396 auto *PossibleXLHSInSecond = 6397 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 6398 llvm::FoldingSetNodeID X1Id, X2Id; 6399 PossibleXRHSInFirst->Profile(X1Id, Context, 6400 /*Canonical=*/true); 6401 PossibleXLHSInSecond->Profile(X2Id, Context, 6402 /*Canonical=*/true); 6403 IsUpdateExprFound = X1Id == X2Id; 6404 if (IsUpdateExprFound) { 6405 V = FirstBinOp->getLHS(); 6406 X = SecondBinOp->getLHS(); 6407 E = SecondBinOp->getRHS(); 6408 UE = nullptr; 6409 IsXLHSInRHSPart = false; 6410 IsPostfixUpdate = true; 6411 } else { 6412 ErrorFound = NotASpecificExpression; 6413 ErrorLoc = FirstBinOp->getExprLoc(); 6414 ErrorRange = FirstBinOp->getSourceRange(); 6415 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 6416 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 6417 } 6418 } 6419 } 6420 } 6421 } 6422 } else { 6423 NoteLoc = ErrorLoc = Body->getLocStart(); 6424 NoteRange = ErrorRange = 6425 SourceRange(Body->getLocStart(), Body->getLocStart()); 6426 ErrorFound = NotTwoSubstatements; 6427 } 6428 } else { 6429 NoteLoc = ErrorLoc = Body->getLocStart(); 6430 NoteRange = ErrorRange = 6431 SourceRange(Body->getLocStart(), Body->getLocStart()); 6432 ErrorFound = NotACompoundStatement; 6433 } 6434 if (ErrorFound != NoError) { 6435 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 6436 << ErrorRange; 6437 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 6438 return StmtError(); 6439 } else if (CurContext->isDependentContext()) { 6440 UE = V = E = X = nullptr; 6441 } 6442 } 6443 } 6444 6445 setFunctionHasBranchProtectedScope(); 6446 6447 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 6448 X, V, E, UE, IsXLHSInRHSPart, 6449 IsPostfixUpdate); 6450 } 6451 6452 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 6453 Stmt *AStmt, 6454 SourceLocation StartLoc, 6455 SourceLocation EndLoc) { 6456 if (!AStmt) 6457 return StmtError(); 6458 6459 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6460 // 1.2.2 OpenMP Language Terminology 6461 // Structured block - An executable statement with a single entry at the 6462 // top and a single exit at the bottom. 6463 // The point of exit cannot be a branch out of the structured block. 6464 // longjmp() and throw() must not violate the entry/exit criteria. 6465 CS->getCapturedDecl()->setNothrow(); 6466 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target); 6467 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6468 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6469 // 1.2.2 OpenMP Language Terminology 6470 // Structured block - An executable statement with a single entry at the 6471 // top and a single exit at the bottom. 6472 // The point of exit cannot be a branch out of the structured block. 6473 // longjmp() and throw() must not violate the entry/exit criteria. 6474 CS->getCapturedDecl()->setNothrow(); 6475 } 6476 6477 // OpenMP [2.16, Nesting of Regions] 6478 // If specified, a teams construct must be contained within a target 6479 // construct. That target construct must contain no statements or directives 6480 // outside of the teams construct. 6481 if (DSAStack->hasInnerTeamsRegion()) { 6482 Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true); 6483 bool OMPTeamsFound = true; 6484 if (auto *CS = dyn_cast<CompoundStmt>(S)) { 6485 auto I = CS->body_begin(); 6486 while (I != CS->body_end()) { 6487 auto *OED = dyn_cast<OMPExecutableDirective>(*I); 6488 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) { 6489 OMPTeamsFound = false; 6490 break; 6491 } 6492 ++I; 6493 } 6494 assert(I != CS->body_end() && "Not found statement"); 6495 S = *I; 6496 } else { 6497 auto *OED = dyn_cast<OMPExecutableDirective>(S); 6498 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 6499 } 6500 if (!OMPTeamsFound) { 6501 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 6502 Diag(DSAStack->getInnerTeamsRegionLoc(), 6503 diag::note_omp_nested_teams_construct_here); 6504 Diag(S->getLocStart(), diag::note_omp_nested_statement_here) 6505 << isa<OMPExecutableDirective>(S); 6506 return StmtError(); 6507 } 6508 } 6509 6510 setFunctionHasBranchProtectedScope(); 6511 6512 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6513 } 6514 6515 StmtResult 6516 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 6517 Stmt *AStmt, SourceLocation StartLoc, 6518 SourceLocation EndLoc) { 6519 if (!AStmt) 6520 return StmtError(); 6521 6522 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6523 // 1.2.2 OpenMP Language Terminology 6524 // Structured block - An executable statement with a single entry at the 6525 // top and a single exit at the bottom. 6526 // The point of exit cannot be a branch out of the structured block. 6527 // longjmp() and throw() must not violate the entry/exit criteria. 6528 CS->getCapturedDecl()->setNothrow(); 6529 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel); 6530 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6531 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6532 // 1.2.2 OpenMP Language Terminology 6533 // Structured block - An executable statement with a single entry at the 6534 // top and a single exit at the bottom. 6535 // The point of exit cannot be a branch out of the structured block. 6536 // longjmp() and throw() must not violate the entry/exit criteria. 6537 CS->getCapturedDecl()->setNothrow(); 6538 } 6539 6540 setFunctionHasBranchProtectedScope(); 6541 6542 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 6543 AStmt); 6544 } 6545 6546 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 6547 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6548 SourceLocation EndLoc, 6549 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6550 if (!AStmt) 6551 return StmtError(); 6552 6553 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6554 // 1.2.2 OpenMP Language Terminology 6555 // Structured block - An executable statement with a single entry at the 6556 // top and a single exit at the bottom. 6557 // The point of exit cannot be a branch out of the structured block. 6558 // longjmp() and throw() must not violate the entry/exit criteria. 6559 CS->getCapturedDecl()->setNothrow(); 6560 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 6561 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6562 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6563 // 1.2.2 OpenMP Language Terminology 6564 // Structured block - An executable statement with a single entry at the 6565 // top and a single exit at the bottom. 6566 // The point of exit cannot be a branch out of the structured block. 6567 // longjmp() and throw() must not violate the entry/exit criteria. 6568 CS->getCapturedDecl()->setNothrow(); 6569 } 6570 6571 OMPLoopDirective::HelperExprs B; 6572 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6573 // define the nested loops number. 6574 unsigned NestedLoopCount = 6575 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 6576 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 6577 VarsWithImplicitDSA, B); 6578 if (NestedLoopCount == 0) 6579 return StmtError(); 6580 6581 assert((CurContext->isDependentContext() || B.builtAll()) && 6582 "omp target parallel for loop exprs were not built"); 6583 6584 if (!CurContext->isDependentContext()) { 6585 // Finalize the clauses that need pre-built expressions for CodeGen. 6586 for (auto C : Clauses) { 6587 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6588 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6589 B.NumIterations, *this, CurScope, 6590 DSAStack)) 6591 return StmtError(); 6592 } 6593 } 6594 6595 setFunctionHasBranchProtectedScope(); 6596 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc, 6597 NestedLoopCount, Clauses, AStmt, 6598 B, DSAStack->isCancelRegion()); 6599 } 6600 6601 /// Check for existence of a map clause in the list of clauses. 6602 static bool hasClauses(ArrayRef<OMPClause *> Clauses, 6603 const OpenMPClauseKind K) { 6604 return llvm::any_of( 6605 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); 6606 } 6607 6608 template <typename... Params> 6609 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, 6610 const Params... ClauseTypes) { 6611 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); 6612 } 6613 6614 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 6615 Stmt *AStmt, 6616 SourceLocation StartLoc, 6617 SourceLocation EndLoc) { 6618 if (!AStmt) 6619 return StmtError(); 6620 6621 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6622 6623 // OpenMP [2.10.1, Restrictions, p. 97] 6624 // At least one map clause must appear on the directive. 6625 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) { 6626 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 6627 << "'map' or 'use_device_ptr'" 6628 << getOpenMPDirectiveName(OMPD_target_data); 6629 return StmtError(); 6630 } 6631 6632 setFunctionHasBranchProtectedScope(); 6633 6634 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 6635 AStmt); 6636 } 6637 6638 StmtResult 6639 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 6640 SourceLocation StartLoc, 6641 SourceLocation EndLoc, Stmt *AStmt) { 6642 if (!AStmt) 6643 return StmtError(); 6644 6645 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6646 // 1.2.2 OpenMP Language Terminology 6647 // Structured block - An executable statement with a single entry at the 6648 // top and a single exit at the bottom. 6649 // The point of exit cannot be a branch out of the structured block. 6650 // longjmp() and throw() must not violate the entry/exit criteria. 6651 CS->getCapturedDecl()->setNothrow(); 6652 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data); 6653 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6654 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6655 // 1.2.2 OpenMP Language Terminology 6656 // Structured block - An executable statement with a single entry at the 6657 // top and a single exit at the bottom. 6658 // The point of exit cannot be a branch out of the structured block. 6659 // longjmp() and throw() must not violate the entry/exit criteria. 6660 CS->getCapturedDecl()->setNothrow(); 6661 } 6662 6663 // OpenMP [2.10.2, Restrictions, p. 99] 6664 // At least one map clause must appear on the directive. 6665 if (!hasClauses(Clauses, OMPC_map)) { 6666 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 6667 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); 6668 return StmtError(); 6669 } 6670 6671 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 6672 AStmt); 6673 } 6674 6675 StmtResult 6676 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 6677 SourceLocation StartLoc, 6678 SourceLocation EndLoc, Stmt *AStmt) { 6679 if (!AStmt) 6680 return StmtError(); 6681 6682 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6683 // 1.2.2 OpenMP Language Terminology 6684 // Structured block - An executable statement with a single entry at the 6685 // top and a single exit at the bottom. 6686 // The point of exit cannot be a branch out of the structured block. 6687 // longjmp() and throw() must not violate the entry/exit criteria. 6688 CS->getCapturedDecl()->setNothrow(); 6689 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data); 6690 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6691 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6692 // 1.2.2 OpenMP Language Terminology 6693 // Structured block - An executable statement with a single entry at the 6694 // top and a single exit at the bottom. 6695 // The point of exit cannot be a branch out of the structured block. 6696 // longjmp() and throw() must not violate the entry/exit criteria. 6697 CS->getCapturedDecl()->setNothrow(); 6698 } 6699 6700 // OpenMP [2.10.3, Restrictions, p. 102] 6701 // At least one map clause must appear on the directive. 6702 if (!hasClauses(Clauses, OMPC_map)) { 6703 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 6704 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data); 6705 return StmtError(); 6706 } 6707 6708 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 6709 AStmt); 6710 } 6711 6712 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 6713 SourceLocation StartLoc, 6714 SourceLocation EndLoc, 6715 Stmt *AStmt) { 6716 if (!AStmt) 6717 return StmtError(); 6718 6719 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6720 // 1.2.2 OpenMP Language Terminology 6721 // Structured block - An executable statement with a single entry at the 6722 // top and a single exit at the bottom. 6723 // The point of exit cannot be a branch out of the structured block. 6724 // longjmp() and throw() must not violate the entry/exit criteria. 6725 CS->getCapturedDecl()->setNothrow(); 6726 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update); 6727 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6728 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6729 // 1.2.2 OpenMP Language Terminology 6730 // Structured block - An executable statement with a single entry at the 6731 // top and a single exit at the bottom. 6732 // The point of exit cannot be a branch out of the structured block. 6733 // longjmp() and throw() must not violate the entry/exit criteria. 6734 CS->getCapturedDecl()->setNothrow(); 6735 } 6736 6737 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { 6738 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 6739 return StmtError(); 6740 } 6741 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses, 6742 AStmt); 6743 } 6744 6745 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 6746 Stmt *AStmt, SourceLocation StartLoc, 6747 SourceLocation EndLoc) { 6748 if (!AStmt) 6749 return StmtError(); 6750 6751 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6752 // 1.2.2 OpenMP Language Terminology 6753 // Structured block - An executable statement with a single entry at the 6754 // top and a single exit at the bottom. 6755 // The point of exit cannot be a branch out of the structured block. 6756 // longjmp() and throw() must not violate the entry/exit criteria. 6757 CS->getCapturedDecl()->setNothrow(); 6758 6759 setFunctionHasBranchProtectedScope(); 6760 6761 DSAStack->setParentTeamsRegionLoc(StartLoc); 6762 6763 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6764 } 6765 6766 StmtResult 6767 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 6768 SourceLocation EndLoc, 6769 OpenMPDirectiveKind CancelRegion) { 6770 if (DSAStack->isParentNowaitRegion()) { 6771 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 6772 return StmtError(); 6773 } 6774 if (DSAStack->isParentOrderedRegion()) { 6775 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 6776 return StmtError(); 6777 } 6778 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 6779 CancelRegion); 6780 } 6781 6782 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 6783 SourceLocation StartLoc, 6784 SourceLocation EndLoc, 6785 OpenMPDirectiveKind CancelRegion) { 6786 if (DSAStack->isParentNowaitRegion()) { 6787 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 6788 return StmtError(); 6789 } 6790 if (DSAStack->isParentOrderedRegion()) { 6791 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 6792 return StmtError(); 6793 } 6794 DSAStack->setParentCancelRegion(/*Cancel=*/true); 6795 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 6796 CancelRegion); 6797 } 6798 6799 static bool checkGrainsizeNumTasksClauses(Sema &S, 6800 ArrayRef<OMPClause *> Clauses) { 6801 OMPClause *PrevClause = nullptr; 6802 bool ErrorFound = false; 6803 for (auto *C : Clauses) { 6804 if (C->getClauseKind() == OMPC_grainsize || 6805 C->getClauseKind() == OMPC_num_tasks) { 6806 if (!PrevClause) 6807 PrevClause = C; 6808 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 6809 S.Diag(C->getLocStart(), 6810 diag::err_omp_grainsize_num_tasks_mutually_exclusive) 6811 << getOpenMPClauseName(C->getClauseKind()) 6812 << getOpenMPClauseName(PrevClause->getClauseKind()); 6813 S.Diag(PrevClause->getLocStart(), 6814 diag::note_omp_previous_grainsize_num_tasks) 6815 << getOpenMPClauseName(PrevClause->getClauseKind()); 6816 ErrorFound = true; 6817 } 6818 } 6819 } 6820 return ErrorFound; 6821 } 6822 6823 static bool checkReductionClauseWithNogroup(Sema &S, 6824 ArrayRef<OMPClause *> Clauses) { 6825 OMPClause *ReductionClause = nullptr; 6826 OMPClause *NogroupClause = nullptr; 6827 for (auto *C : Clauses) { 6828 if (C->getClauseKind() == OMPC_reduction) { 6829 ReductionClause = C; 6830 if (NogroupClause) 6831 break; 6832 continue; 6833 } 6834 if (C->getClauseKind() == OMPC_nogroup) { 6835 NogroupClause = C; 6836 if (ReductionClause) 6837 break; 6838 continue; 6839 } 6840 } 6841 if (ReductionClause && NogroupClause) { 6842 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup) 6843 << SourceRange(NogroupClause->getLocStart(), 6844 NogroupClause->getLocEnd()); 6845 return true; 6846 } 6847 return false; 6848 } 6849 6850 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 6851 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6852 SourceLocation EndLoc, 6853 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6854 if (!AStmt) 6855 return StmtError(); 6856 6857 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6858 OMPLoopDirective::HelperExprs B; 6859 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6860 // define the nested loops number. 6861 unsigned NestedLoopCount = 6862 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 6863 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 6864 VarsWithImplicitDSA, B); 6865 if (NestedLoopCount == 0) 6866 return StmtError(); 6867 6868 assert((CurContext->isDependentContext() || B.builtAll()) && 6869 "omp for loop exprs were not built"); 6870 6871 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6872 // The grainsize clause and num_tasks clause are mutually exclusive and may 6873 // not appear on the same taskloop directive. 6874 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 6875 return StmtError(); 6876 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6877 // If a reduction clause is present on the taskloop directive, the nogroup 6878 // clause must not be specified. 6879 if (checkReductionClauseWithNogroup(*this, Clauses)) 6880 return StmtError(); 6881 6882 setFunctionHasBranchProtectedScope(); 6883 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 6884 NestedLoopCount, Clauses, AStmt, B); 6885 } 6886 6887 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 6888 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6889 SourceLocation EndLoc, 6890 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6891 if (!AStmt) 6892 return StmtError(); 6893 6894 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6895 OMPLoopDirective::HelperExprs B; 6896 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6897 // define the nested loops number. 6898 unsigned NestedLoopCount = 6899 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 6900 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 6901 VarsWithImplicitDSA, B); 6902 if (NestedLoopCount == 0) 6903 return StmtError(); 6904 6905 assert((CurContext->isDependentContext() || B.builtAll()) && 6906 "omp for loop exprs were not built"); 6907 6908 if (!CurContext->isDependentContext()) { 6909 // Finalize the clauses that need pre-built expressions for CodeGen. 6910 for (auto C : Clauses) { 6911 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6912 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6913 B.NumIterations, *this, CurScope, 6914 DSAStack)) 6915 return StmtError(); 6916 } 6917 } 6918 6919 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6920 // The grainsize clause and num_tasks clause are mutually exclusive and may 6921 // not appear on the same taskloop directive. 6922 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 6923 return StmtError(); 6924 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6925 // If a reduction clause is present on the taskloop directive, the nogroup 6926 // clause must not be specified. 6927 if (checkReductionClauseWithNogroup(*this, Clauses)) 6928 return StmtError(); 6929 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6930 return StmtError(); 6931 6932 setFunctionHasBranchProtectedScope(); 6933 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 6934 NestedLoopCount, Clauses, AStmt, B); 6935 } 6936 6937 StmtResult Sema::ActOnOpenMPDistributeDirective( 6938 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6939 SourceLocation EndLoc, 6940 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6941 if (!AStmt) 6942 return StmtError(); 6943 6944 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6945 OMPLoopDirective::HelperExprs B; 6946 // In presence of clause 'collapse' with number of loops, it will 6947 // define the nested loops number. 6948 unsigned NestedLoopCount = 6949 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 6950 nullptr /*ordered not a clause on distribute*/, AStmt, 6951 *this, *DSAStack, VarsWithImplicitDSA, B); 6952 if (NestedLoopCount == 0) 6953 return StmtError(); 6954 6955 assert((CurContext->isDependentContext() || B.builtAll()) && 6956 "omp for loop exprs were not built"); 6957 6958 setFunctionHasBranchProtectedScope(); 6959 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 6960 NestedLoopCount, Clauses, AStmt, B); 6961 } 6962 6963 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 6964 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6965 SourceLocation EndLoc, 6966 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6967 if (!AStmt) 6968 return StmtError(); 6969 6970 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6971 // 1.2.2 OpenMP Language Terminology 6972 // Structured block - An executable statement with a single entry at the 6973 // top and a single exit at the bottom. 6974 // The point of exit cannot be a branch out of the structured block. 6975 // longjmp() and throw() must not violate the entry/exit criteria. 6976 CS->getCapturedDecl()->setNothrow(); 6977 for (int ThisCaptureLevel = 6978 getOpenMPCaptureLevels(OMPD_distribute_parallel_for); 6979 ThisCaptureLevel > 1; --ThisCaptureLevel) { 6980 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 6981 // 1.2.2 OpenMP Language Terminology 6982 // Structured block - An executable statement with a single entry at the 6983 // top and a single exit at the bottom. 6984 // The point of exit cannot be a branch out of the structured block. 6985 // longjmp() and throw() must not violate the entry/exit criteria. 6986 CS->getCapturedDecl()->setNothrow(); 6987 } 6988 6989 OMPLoopDirective::HelperExprs B; 6990 // In presence of clause 'collapse' with number of loops, it will 6991 // define the nested loops number. 6992 unsigned NestedLoopCount = CheckOpenMPLoop( 6993 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 6994 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 6995 VarsWithImplicitDSA, B); 6996 if (NestedLoopCount == 0) 6997 return StmtError(); 6998 6999 assert((CurContext->isDependentContext() || B.builtAll()) && 7000 "omp for loop exprs were not built"); 7001 7002 setFunctionHasBranchProtectedScope(); 7003 return OMPDistributeParallelForDirective::Create( 7004 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 7005 DSAStack->isCancelRegion()); 7006 } 7007 7008 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 7009 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7010 SourceLocation EndLoc, 7011 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7012 if (!AStmt) 7013 return StmtError(); 7014 7015 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7016 // 1.2.2 OpenMP Language Terminology 7017 // Structured block - An executable statement with a single entry at the 7018 // top and a single exit at the bottom. 7019 // The point of exit cannot be a branch out of the structured block. 7020 // longjmp() and throw() must not violate the entry/exit criteria. 7021 CS->getCapturedDecl()->setNothrow(); 7022 for (int ThisCaptureLevel = 7023 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd); 7024 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7025 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7026 // 1.2.2 OpenMP Language Terminology 7027 // Structured block - An executable statement with a single entry at the 7028 // top and a single exit at the bottom. 7029 // The point of exit cannot be a branch out of the structured block. 7030 // longjmp() and throw() must not violate the entry/exit criteria. 7031 CS->getCapturedDecl()->setNothrow(); 7032 } 7033 7034 OMPLoopDirective::HelperExprs B; 7035 // In presence of clause 'collapse' with number of loops, it will 7036 // define the nested loops number. 7037 unsigned NestedLoopCount = CheckOpenMPLoop( 7038 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 7039 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7040 VarsWithImplicitDSA, B); 7041 if (NestedLoopCount == 0) 7042 return StmtError(); 7043 7044 assert((CurContext->isDependentContext() || B.builtAll()) && 7045 "omp for loop exprs were not built"); 7046 7047 if (!CurContext->isDependentContext()) { 7048 // Finalize the clauses that need pre-built expressions for CodeGen. 7049 for (auto C : Clauses) { 7050 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7051 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7052 B.NumIterations, *this, CurScope, 7053 DSAStack)) 7054 return StmtError(); 7055 } 7056 } 7057 7058 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7059 return StmtError(); 7060 7061 setFunctionHasBranchProtectedScope(); 7062 return OMPDistributeParallelForSimdDirective::Create( 7063 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7064 } 7065 7066 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 7067 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7068 SourceLocation EndLoc, 7069 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7070 if (!AStmt) 7071 return StmtError(); 7072 7073 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7074 // 1.2.2 OpenMP Language Terminology 7075 // Structured block - An executable statement with a single entry at the 7076 // top and a single exit at the bottom. 7077 // The point of exit cannot be a branch out of the structured block. 7078 // longjmp() and throw() must not violate the entry/exit criteria. 7079 CS->getCapturedDecl()->setNothrow(); 7080 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd); 7081 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7082 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7083 // 1.2.2 OpenMP Language Terminology 7084 // Structured block - An executable statement with a single entry at the 7085 // top and a single exit at the bottom. 7086 // The point of exit cannot be a branch out of the structured block. 7087 // longjmp() and throw() must not violate the entry/exit criteria. 7088 CS->getCapturedDecl()->setNothrow(); 7089 } 7090 7091 OMPLoopDirective::HelperExprs B; 7092 // In presence of clause 'collapse' with number of loops, it will 7093 // define the nested loops number. 7094 unsigned NestedLoopCount = 7095 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 7096 nullptr /*ordered not a clause on distribute*/, CS, *this, 7097 *DSAStack, VarsWithImplicitDSA, B); 7098 if (NestedLoopCount == 0) 7099 return StmtError(); 7100 7101 assert((CurContext->isDependentContext() || B.builtAll()) && 7102 "omp for loop exprs were not built"); 7103 7104 if (!CurContext->isDependentContext()) { 7105 // Finalize the clauses that need pre-built expressions for CodeGen. 7106 for (auto C : Clauses) { 7107 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7108 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7109 B.NumIterations, *this, CurScope, 7110 DSAStack)) 7111 return StmtError(); 7112 } 7113 } 7114 7115 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7116 return StmtError(); 7117 7118 setFunctionHasBranchProtectedScope(); 7119 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 7120 NestedLoopCount, Clauses, AStmt, B); 7121 } 7122 7123 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 7124 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7125 SourceLocation EndLoc, 7126 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7127 if (!AStmt) 7128 return StmtError(); 7129 7130 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7131 // 1.2.2 OpenMP Language Terminology 7132 // Structured block - An executable statement with a single entry at the 7133 // top and a single exit at the bottom. 7134 // The point of exit cannot be a branch out of the structured block. 7135 // longjmp() and throw() must not violate the entry/exit criteria. 7136 CS->getCapturedDecl()->setNothrow(); 7137 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for); 7138 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7139 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7140 // 1.2.2 OpenMP Language Terminology 7141 // Structured block - An executable statement with a single entry at the 7142 // top and a single exit at the bottom. 7143 // The point of exit cannot be a branch out of the structured block. 7144 // longjmp() and throw() must not violate the entry/exit criteria. 7145 CS->getCapturedDecl()->setNothrow(); 7146 } 7147 7148 OMPLoopDirective::HelperExprs B; 7149 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 7150 // define the nested loops number. 7151 unsigned NestedLoopCount = CheckOpenMPLoop( 7152 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 7153 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack, 7154 VarsWithImplicitDSA, B); 7155 if (NestedLoopCount == 0) 7156 return StmtError(); 7157 7158 assert((CurContext->isDependentContext() || B.builtAll()) && 7159 "omp target parallel for simd loop exprs were not built"); 7160 7161 if (!CurContext->isDependentContext()) { 7162 // Finalize the clauses that need pre-built expressions for CodeGen. 7163 for (auto C : Clauses) { 7164 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7165 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7166 B.NumIterations, *this, CurScope, 7167 DSAStack)) 7168 return StmtError(); 7169 } 7170 } 7171 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7172 return StmtError(); 7173 7174 setFunctionHasBranchProtectedScope(); 7175 return OMPTargetParallelForSimdDirective::Create( 7176 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7177 } 7178 7179 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 7180 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7181 SourceLocation EndLoc, 7182 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7183 if (!AStmt) 7184 return StmtError(); 7185 7186 CapturedStmt *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_simd); 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' with number of loops, it will define the 7206 // nested loops number. 7207 unsigned NestedLoopCount = 7208 CheckOpenMPLoop(OMPD_target_simd, 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 simd loop exprs were not built"); 7216 7217 if (!CurContext->isDependentContext()) { 7218 // Finalize the clauses that need pre-built expressions for CodeGen. 7219 for (auto 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 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7229 return StmtError(); 7230 7231 setFunctionHasBranchProtectedScope(); 7232 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 7233 NestedLoopCount, Clauses, AStmt, B); 7234 } 7235 7236 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 7237 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7238 SourceLocation EndLoc, 7239 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7240 if (!AStmt) 7241 return StmtError(); 7242 7243 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7244 // 1.2.2 OpenMP Language Terminology 7245 // Structured block - An executable statement with a single entry at the 7246 // top and a single exit at the bottom. 7247 // The point of exit cannot be a branch out of the structured block. 7248 // longjmp() and throw() must not violate the entry/exit criteria. 7249 CS->getCapturedDecl()->setNothrow(); 7250 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute); 7251 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7252 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7253 // 1.2.2 OpenMP Language Terminology 7254 // Structured block - An executable statement with a single entry at the 7255 // top and a single exit at the bottom. 7256 // The point of exit cannot be a branch out of the structured block. 7257 // longjmp() and throw() must not violate the entry/exit criteria. 7258 CS->getCapturedDecl()->setNothrow(); 7259 } 7260 7261 OMPLoopDirective::HelperExprs B; 7262 // In presence of clause 'collapse' with number of loops, it will 7263 // define the nested loops number. 7264 unsigned NestedLoopCount = 7265 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 7266 nullptr /*ordered not a clause on distribute*/, CS, *this, 7267 *DSAStack, VarsWithImplicitDSA, B); 7268 if (NestedLoopCount == 0) 7269 return StmtError(); 7270 7271 assert((CurContext->isDependentContext() || B.builtAll()) && 7272 "omp teams distribute loop exprs were not built"); 7273 7274 setFunctionHasBranchProtectedScope(); 7275 7276 DSAStack->setParentTeamsRegionLoc(StartLoc); 7277 7278 return OMPTeamsDistributeDirective::Create( 7279 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7280 } 7281 7282 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 7283 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7284 SourceLocation EndLoc, 7285 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7286 if (!AStmt) 7287 return StmtError(); 7288 7289 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7290 // 1.2.2 OpenMP Language Terminology 7291 // Structured block - An executable statement with a single entry at the 7292 // top and a single exit at the bottom. 7293 // The point of exit cannot be a branch out of the structured block. 7294 // longjmp() and throw() must not violate the entry/exit criteria. 7295 CS->getCapturedDecl()->setNothrow(); 7296 for (int ThisCaptureLevel = 7297 getOpenMPCaptureLevels(OMPD_teams_distribute_simd); 7298 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7299 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7300 // 1.2.2 OpenMP Language Terminology 7301 // Structured block - An executable statement with a single entry at the 7302 // top and a single exit at the bottom. 7303 // The point of exit cannot be a branch out of the structured block. 7304 // longjmp() and throw() must not violate the entry/exit criteria. 7305 CS->getCapturedDecl()->setNothrow(); 7306 } 7307 7308 7309 OMPLoopDirective::HelperExprs B; 7310 // In presence of clause 'collapse' with number of loops, it will 7311 // define the nested loops number. 7312 unsigned NestedLoopCount = CheckOpenMPLoop( 7313 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 7314 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7315 VarsWithImplicitDSA, B); 7316 7317 if (NestedLoopCount == 0) 7318 return StmtError(); 7319 7320 assert((CurContext->isDependentContext() || B.builtAll()) && 7321 "omp teams distribute simd loop exprs were not built"); 7322 7323 if (!CurContext->isDependentContext()) { 7324 // Finalize the clauses that need pre-built expressions for CodeGen. 7325 for (auto C : Clauses) { 7326 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7327 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7328 B.NumIterations, *this, CurScope, 7329 DSAStack)) 7330 return StmtError(); 7331 } 7332 } 7333 7334 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7335 return StmtError(); 7336 7337 setFunctionHasBranchProtectedScope(); 7338 7339 DSAStack->setParentTeamsRegionLoc(StartLoc); 7340 7341 return OMPTeamsDistributeSimdDirective::Create( 7342 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7343 } 7344 7345 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 7346 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7347 SourceLocation EndLoc, 7348 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7349 if (!AStmt) 7350 return StmtError(); 7351 7352 CapturedStmt *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 7360 for (int ThisCaptureLevel = 7361 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd); 7362 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7363 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7364 // 1.2.2 OpenMP Language Terminology 7365 // Structured block - An executable statement with a single entry at the 7366 // top and a single exit at the bottom. 7367 // The point of exit cannot be a branch out of the structured block. 7368 // longjmp() and throw() must not violate the entry/exit criteria. 7369 CS->getCapturedDecl()->setNothrow(); 7370 } 7371 7372 OMPLoopDirective::HelperExprs B; 7373 // In presence of clause 'collapse' with number of loops, it will 7374 // define the nested loops number. 7375 auto NestedLoopCount = CheckOpenMPLoop( 7376 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 7377 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7378 VarsWithImplicitDSA, B); 7379 7380 if (NestedLoopCount == 0) 7381 return StmtError(); 7382 7383 assert((CurContext->isDependentContext() || B.builtAll()) && 7384 "omp for loop exprs were not built"); 7385 7386 if (!CurContext->isDependentContext()) { 7387 // Finalize the clauses that need pre-built expressions for CodeGen. 7388 for (auto C : Clauses) { 7389 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7390 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7391 B.NumIterations, *this, CurScope, 7392 DSAStack)) 7393 return StmtError(); 7394 } 7395 } 7396 7397 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7398 return StmtError(); 7399 7400 setFunctionHasBranchProtectedScope(); 7401 7402 DSAStack->setParentTeamsRegionLoc(StartLoc); 7403 7404 return OMPTeamsDistributeParallelForSimdDirective::Create( 7405 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7406 } 7407 7408 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 7409 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7410 SourceLocation EndLoc, 7411 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7412 if (!AStmt) 7413 return StmtError(); 7414 7415 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7416 // 1.2.2 OpenMP Language Terminology 7417 // Structured block - An executable statement with a single entry at the 7418 // top and a single exit at the bottom. 7419 // The point of exit cannot be a branch out of the structured block. 7420 // longjmp() and throw() must not violate the entry/exit criteria. 7421 CS->getCapturedDecl()->setNothrow(); 7422 7423 for (int ThisCaptureLevel = 7424 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for); 7425 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7426 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7427 // 1.2.2 OpenMP Language Terminology 7428 // Structured block - An executable statement with a single entry at the 7429 // top and a single exit at the bottom. 7430 // The point of exit cannot be a branch out of the structured block. 7431 // longjmp() and throw() must not violate the entry/exit criteria. 7432 CS->getCapturedDecl()->setNothrow(); 7433 } 7434 7435 OMPLoopDirective::HelperExprs B; 7436 // In presence of clause 'collapse' with number of loops, it will 7437 // define the nested loops number. 7438 unsigned NestedLoopCount = CheckOpenMPLoop( 7439 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 7440 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7441 VarsWithImplicitDSA, B); 7442 7443 if (NestedLoopCount == 0) 7444 return StmtError(); 7445 7446 assert((CurContext->isDependentContext() || B.builtAll()) && 7447 "omp for loop exprs were not built"); 7448 7449 setFunctionHasBranchProtectedScope(); 7450 7451 DSAStack->setParentTeamsRegionLoc(StartLoc); 7452 7453 return OMPTeamsDistributeParallelForDirective::Create( 7454 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 7455 DSAStack->isCancelRegion()); 7456 } 7457 7458 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 7459 Stmt *AStmt, 7460 SourceLocation StartLoc, 7461 SourceLocation EndLoc) { 7462 if (!AStmt) 7463 return StmtError(); 7464 7465 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7466 // 1.2.2 OpenMP Language Terminology 7467 // Structured block - An executable statement with a single entry at the 7468 // top and a single exit at the bottom. 7469 // The point of exit cannot be a branch out of the structured block. 7470 // longjmp() and throw() must not violate the entry/exit criteria. 7471 CS->getCapturedDecl()->setNothrow(); 7472 7473 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams); 7474 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7475 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7476 // 1.2.2 OpenMP Language Terminology 7477 // Structured block - An executable statement with a single entry at the 7478 // top and a single exit at the bottom. 7479 // The point of exit cannot be a branch out of the structured block. 7480 // longjmp() and throw() must not violate the entry/exit criteria. 7481 CS->getCapturedDecl()->setNothrow(); 7482 } 7483 setFunctionHasBranchProtectedScope(); 7484 7485 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 7486 AStmt); 7487 } 7488 7489 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 7490 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7491 SourceLocation EndLoc, 7492 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7493 if (!AStmt) 7494 return StmtError(); 7495 7496 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7497 // 1.2.2 OpenMP Language Terminology 7498 // Structured block - An executable statement with a single entry at the 7499 // top and a single exit at the bottom. 7500 // The point of exit cannot be a branch out of the structured block. 7501 // longjmp() and throw() must not violate the entry/exit criteria. 7502 CS->getCapturedDecl()->setNothrow(); 7503 for (int ThisCaptureLevel = 7504 getOpenMPCaptureLevels(OMPD_target_teams_distribute); 7505 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7506 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7507 // 1.2.2 OpenMP Language Terminology 7508 // Structured block - An executable statement with a single entry at the 7509 // top and a single exit at the bottom. 7510 // The point of exit cannot be a branch out of the structured block. 7511 // longjmp() and throw() must not violate the entry/exit criteria. 7512 CS->getCapturedDecl()->setNothrow(); 7513 } 7514 7515 OMPLoopDirective::HelperExprs B; 7516 // In presence of clause 'collapse' with number of loops, it will 7517 // define the nested loops number. 7518 auto NestedLoopCount = CheckOpenMPLoop( 7519 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses), 7520 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7521 VarsWithImplicitDSA, B); 7522 if (NestedLoopCount == 0) 7523 return StmtError(); 7524 7525 assert((CurContext->isDependentContext() || B.builtAll()) && 7526 "omp target teams distribute loop exprs were not built"); 7527 7528 setFunctionHasBranchProtectedScope(); 7529 return OMPTargetTeamsDistributeDirective::Create( 7530 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7531 } 7532 7533 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 7534 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7535 SourceLocation EndLoc, 7536 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7537 if (!AStmt) 7538 return StmtError(); 7539 7540 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7541 // 1.2.2 OpenMP Language Terminology 7542 // Structured block - An executable statement with a single entry at the 7543 // top and a single exit at the bottom. 7544 // The point of exit cannot be a branch out of the structured block. 7545 // longjmp() and throw() must not violate the entry/exit criteria. 7546 CS->getCapturedDecl()->setNothrow(); 7547 for (int ThisCaptureLevel = 7548 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for); 7549 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7550 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7551 // 1.2.2 OpenMP Language Terminology 7552 // Structured block - An executable statement with a single entry at the 7553 // top and a single exit at the bottom. 7554 // The point of exit cannot be a branch out of the structured block. 7555 // longjmp() and throw() must not violate the entry/exit criteria. 7556 CS->getCapturedDecl()->setNothrow(); 7557 } 7558 7559 OMPLoopDirective::HelperExprs B; 7560 // In presence of clause 'collapse' with number of loops, it will 7561 // define the nested loops number. 7562 auto NestedLoopCount = CheckOpenMPLoop( 7563 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 7564 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7565 VarsWithImplicitDSA, B); 7566 if (NestedLoopCount == 0) 7567 return StmtError(); 7568 7569 assert((CurContext->isDependentContext() || B.builtAll()) && 7570 "omp target teams distribute parallel for loop exprs were not built"); 7571 7572 if (!CurContext->isDependentContext()) { 7573 // Finalize the clauses that need pre-built expressions for CodeGen. 7574 for (auto C : Clauses) { 7575 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7576 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7577 B.NumIterations, *this, CurScope, 7578 DSAStack)) 7579 return StmtError(); 7580 } 7581 } 7582 7583 setFunctionHasBranchProtectedScope(); 7584 return OMPTargetTeamsDistributeParallelForDirective::Create( 7585 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B, 7586 DSAStack->isCancelRegion()); 7587 } 7588 7589 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 7590 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7591 SourceLocation EndLoc, 7592 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7593 if (!AStmt) 7594 return StmtError(); 7595 7596 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 7597 // 1.2.2 OpenMP Language Terminology 7598 // Structured block - An executable statement with a single entry at the 7599 // top and a single exit at the bottom. 7600 // The point of exit cannot be a branch out of the structured block. 7601 // longjmp() and throw() must not violate the entry/exit criteria. 7602 CS->getCapturedDecl()->setNothrow(); 7603 for (int ThisCaptureLevel = getOpenMPCaptureLevels( 7604 OMPD_target_teams_distribute_parallel_for_simd); 7605 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7606 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7607 // 1.2.2 OpenMP Language Terminology 7608 // Structured block - An executable statement with a single entry at the 7609 // top and a single exit at the bottom. 7610 // The point of exit cannot be a branch out of the structured block. 7611 // longjmp() and throw() must not violate the entry/exit criteria. 7612 CS->getCapturedDecl()->setNothrow(); 7613 } 7614 7615 OMPLoopDirective::HelperExprs B; 7616 // In presence of clause 'collapse' with number of loops, it will 7617 // define the nested loops number. 7618 auto NestedLoopCount = 7619 CheckOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd, 7620 getCollapseNumberExpr(Clauses), 7621 nullptr /*ordered not a clause on distribute*/, CS, *this, 7622 *DSAStack, VarsWithImplicitDSA, B); 7623 if (NestedLoopCount == 0) 7624 return StmtError(); 7625 7626 assert((CurContext->isDependentContext() || B.builtAll()) && 7627 "omp target teams distribute parallel for simd loop exprs were not " 7628 "built"); 7629 7630 if (!CurContext->isDependentContext()) { 7631 // Finalize the clauses that need pre-built expressions for CodeGen. 7632 for (auto C : Clauses) { 7633 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7634 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7635 B.NumIterations, *this, CurScope, 7636 DSAStack)) 7637 return StmtError(); 7638 } 7639 } 7640 7641 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7642 return StmtError(); 7643 7644 setFunctionHasBranchProtectedScope(); 7645 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 7646 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7647 } 7648 7649 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 7650 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 7651 SourceLocation EndLoc, 7652 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 7653 if (!AStmt) 7654 return StmtError(); 7655 7656 auto *CS = cast<CapturedStmt>(AStmt); 7657 // 1.2.2 OpenMP Language Terminology 7658 // Structured block - An executable statement with a single entry at the 7659 // top and a single exit at the bottom. 7660 // The point of exit cannot be a branch out of the structured block. 7661 // longjmp() and throw() must not violate the entry/exit criteria. 7662 CS->getCapturedDecl()->setNothrow(); 7663 for (int ThisCaptureLevel = 7664 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd); 7665 ThisCaptureLevel > 1; --ThisCaptureLevel) { 7666 CS = cast<CapturedStmt>(CS->getCapturedStmt()); 7667 // 1.2.2 OpenMP Language Terminology 7668 // Structured block - An executable statement with a single entry at the 7669 // top and a single exit at the bottom. 7670 // The point of exit cannot be a branch out of the structured block. 7671 // longjmp() and throw() must not violate the entry/exit criteria. 7672 CS->getCapturedDecl()->setNothrow(); 7673 } 7674 7675 OMPLoopDirective::HelperExprs B; 7676 // In presence of clause 'collapse' with number of loops, it will 7677 // define the nested loops number. 7678 auto NestedLoopCount = CheckOpenMPLoop( 7679 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 7680 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack, 7681 VarsWithImplicitDSA, B); 7682 if (NestedLoopCount == 0) 7683 return StmtError(); 7684 7685 assert((CurContext->isDependentContext() || B.builtAll()) && 7686 "omp target teams distribute simd loop exprs were not built"); 7687 7688 if (!CurContext->isDependentContext()) { 7689 // Finalize the clauses that need pre-built expressions for CodeGen. 7690 for (auto C : Clauses) { 7691 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 7692 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 7693 B.NumIterations, *this, CurScope, 7694 DSAStack)) 7695 return StmtError(); 7696 } 7697 } 7698 7699 if (checkSimdlenSafelenSpecified(*this, Clauses)) 7700 return StmtError(); 7701 7702 setFunctionHasBranchProtectedScope(); 7703 return OMPTargetTeamsDistributeSimdDirective::Create( 7704 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7705 } 7706 7707 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 7708 SourceLocation StartLoc, 7709 SourceLocation LParenLoc, 7710 SourceLocation EndLoc) { 7711 OMPClause *Res = nullptr; 7712 switch (Kind) { 7713 case OMPC_final: 7714 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 7715 break; 7716 case OMPC_num_threads: 7717 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 7718 break; 7719 case OMPC_safelen: 7720 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 7721 break; 7722 case OMPC_simdlen: 7723 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 7724 break; 7725 case OMPC_collapse: 7726 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 7727 break; 7728 case OMPC_ordered: 7729 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 7730 break; 7731 case OMPC_device: 7732 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc); 7733 break; 7734 case OMPC_num_teams: 7735 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 7736 break; 7737 case OMPC_thread_limit: 7738 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 7739 break; 7740 case OMPC_priority: 7741 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 7742 break; 7743 case OMPC_grainsize: 7744 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 7745 break; 7746 case OMPC_num_tasks: 7747 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 7748 break; 7749 case OMPC_hint: 7750 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 7751 break; 7752 case OMPC_if: 7753 case OMPC_default: 7754 case OMPC_proc_bind: 7755 case OMPC_schedule: 7756 case OMPC_private: 7757 case OMPC_firstprivate: 7758 case OMPC_lastprivate: 7759 case OMPC_shared: 7760 case OMPC_reduction: 7761 case OMPC_task_reduction: 7762 case OMPC_in_reduction: 7763 case OMPC_linear: 7764 case OMPC_aligned: 7765 case OMPC_copyin: 7766 case OMPC_copyprivate: 7767 case OMPC_nowait: 7768 case OMPC_untied: 7769 case OMPC_mergeable: 7770 case OMPC_threadprivate: 7771 case OMPC_flush: 7772 case OMPC_read: 7773 case OMPC_write: 7774 case OMPC_update: 7775 case OMPC_capture: 7776 case OMPC_seq_cst: 7777 case OMPC_depend: 7778 case OMPC_threads: 7779 case OMPC_simd: 7780 case OMPC_map: 7781 case OMPC_nogroup: 7782 case OMPC_dist_schedule: 7783 case OMPC_defaultmap: 7784 case OMPC_unknown: 7785 case OMPC_uniform: 7786 case OMPC_to: 7787 case OMPC_from: 7788 case OMPC_use_device_ptr: 7789 case OMPC_is_device_ptr: 7790 llvm_unreachable("Clause is not allowed."); 7791 } 7792 return Res; 7793 } 7794 7795 // An OpenMP directive such as 'target parallel' has two captured regions: 7796 // for the 'target' and 'parallel' respectively. This function returns 7797 // the region in which to capture expressions associated with a clause. 7798 // A return value of OMPD_unknown signifies that the expression should not 7799 // be captured. 7800 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 7801 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 7802 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 7803 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 7804 switch (CKind) { 7805 case OMPC_if: 7806 switch (DKind) { 7807 case OMPD_target_parallel: 7808 case OMPD_target_parallel_for: 7809 case OMPD_target_parallel_for_simd: 7810 // If this clause applies to the nested 'parallel' region, capture within 7811 // the 'target' region, otherwise do not capture. 7812 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 7813 CaptureRegion = OMPD_target; 7814 break; 7815 case OMPD_target_teams_distribute_parallel_for: 7816 case OMPD_target_teams_distribute_parallel_for_simd: 7817 // If this clause applies to the nested 'parallel' region, capture within 7818 // the 'teams' region, otherwise do not capture. 7819 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 7820 CaptureRegion = OMPD_teams; 7821 break; 7822 case OMPD_teams_distribute_parallel_for: 7823 case OMPD_teams_distribute_parallel_for_simd: 7824 CaptureRegion = OMPD_teams; 7825 break; 7826 case OMPD_target_update: 7827 case OMPD_target_enter_data: 7828 case OMPD_target_exit_data: 7829 CaptureRegion = OMPD_task; 7830 break; 7831 case OMPD_cancel: 7832 case OMPD_parallel: 7833 case OMPD_parallel_sections: 7834 case OMPD_parallel_for: 7835 case OMPD_parallel_for_simd: 7836 case OMPD_target: 7837 case OMPD_target_simd: 7838 case OMPD_target_teams: 7839 case OMPD_target_teams_distribute: 7840 case OMPD_target_teams_distribute_simd: 7841 case OMPD_distribute_parallel_for: 7842 case OMPD_distribute_parallel_for_simd: 7843 case OMPD_task: 7844 case OMPD_taskloop: 7845 case OMPD_taskloop_simd: 7846 case OMPD_target_data: 7847 // Do not capture if-clause expressions. 7848 break; 7849 case OMPD_threadprivate: 7850 case OMPD_taskyield: 7851 case OMPD_barrier: 7852 case OMPD_taskwait: 7853 case OMPD_cancellation_point: 7854 case OMPD_flush: 7855 case OMPD_declare_reduction: 7856 case OMPD_declare_simd: 7857 case OMPD_declare_target: 7858 case OMPD_end_declare_target: 7859 case OMPD_teams: 7860 case OMPD_simd: 7861 case OMPD_for: 7862 case OMPD_for_simd: 7863 case OMPD_sections: 7864 case OMPD_section: 7865 case OMPD_single: 7866 case OMPD_master: 7867 case OMPD_critical: 7868 case OMPD_taskgroup: 7869 case OMPD_distribute: 7870 case OMPD_ordered: 7871 case OMPD_atomic: 7872 case OMPD_distribute_simd: 7873 case OMPD_teams_distribute: 7874 case OMPD_teams_distribute_simd: 7875 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 7876 case OMPD_unknown: 7877 llvm_unreachable("Unknown OpenMP directive"); 7878 } 7879 break; 7880 case OMPC_num_threads: 7881 switch (DKind) { 7882 case OMPD_target_parallel: 7883 case OMPD_target_parallel_for: 7884 case OMPD_target_parallel_for_simd: 7885 CaptureRegion = OMPD_target; 7886 break; 7887 case OMPD_teams_distribute_parallel_for: 7888 case OMPD_teams_distribute_parallel_for_simd: 7889 case OMPD_target_teams_distribute_parallel_for: 7890 case OMPD_target_teams_distribute_parallel_for_simd: 7891 CaptureRegion = OMPD_teams; 7892 break; 7893 case OMPD_parallel: 7894 case OMPD_parallel_sections: 7895 case OMPD_parallel_for: 7896 case OMPD_parallel_for_simd: 7897 case OMPD_distribute_parallel_for: 7898 case OMPD_distribute_parallel_for_simd: 7899 // Do not capture num_threads-clause expressions. 7900 break; 7901 case OMPD_target_data: 7902 case OMPD_target_enter_data: 7903 case OMPD_target_exit_data: 7904 case OMPD_target_update: 7905 case OMPD_target: 7906 case OMPD_target_simd: 7907 case OMPD_target_teams: 7908 case OMPD_target_teams_distribute: 7909 case OMPD_target_teams_distribute_simd: 7910 case OMPD_cancel: 7911 case OMPD_task: 7912 case OMPD_taskloop: 7913 case OMPD_taskloop_simd: 7914 case OMPD_threadprivate: 7915 case OMPD_taskyield: 7916 case OMPD_barrier: 7917 case OMPD_taskwait: 7918 case OMPD_cancellation_point: 7919 case OMPD_flush: 7920 case OMPD_declare_reduction: 7921 case OMPD_declare_simd: 7922 case OMPD_declare_target: 7923 case OMPD_end_declare_target: 7924 case OMPD_teams: 7925 case OMPD_simd: 7926 case OMPD_for: 7927 case OMPD_for_simd: 7928 case OMPD_sections: 7929 case OMPD_section: 7930 case OMPD_single: 7931 case OMPD_master: 7932 case OMPD_critical: 7933 case OMPD_taskgroup: 7934 case OMPD_distribute: 7935 case OMPD_ordered: 7936 case OMPD_atomic: 7937 case OMPD_distribute_simd: 7938 case OMPD_teams_distribute: 7939 case OMPD_teams_distribute_simd: 7940 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 7941 case OMPD_unknown: 7942 llvm_unreachable("Unknown OpenMP directive"); 7943 } 7944 break; 7945 case OMPC_num_teams: 7946 switch (DKind) { 7947 case OMPD_target_teams: 7948 case OMPD_target_teams_distribute: 7949 case OMPD_target_teams_distribute_simd: 7950 case OMPD_target_teams_distribute_parallel_for: 7951 case OMPD_target_teams_distribute_parallel_for_simd: 7952 CaptureRegion = OMPD_target; 7953 break; 7954 case OMPD_teams_distribute_parallel_for: 7955 case OMPD_teams_distribute_parallel_for_simd: 7956 case OMPD_teams: 7957 case OMPD_teams_distribute: 7958 case OMPD_teams_distribute_simd: 7959 // Do not capture num_teams-clause expressions. 7960 break; 7961 case OMPD_distribute_parallel_for: 7962 case OMPD_distribute_parallel_for_simd: 7963 case OMPD_task: 7964 case OMPD_taskloop: 7965 case OMPD_taskloop_simd: 7966 case OMPD_target_data: 7967 case OMPD_target_enter_data: 7968 case OMPD_target_exit_data: 7969 case OMPD_target_update: 7970 case OMPD_cancel: 7971 case OMPD_parallel: 7972 case OMPD_parallel_sections: 7973 case OMPD_parallel_for: 7974 case OMPD_parallel_for_simd: 7975 case OMPD_target: 7976 case OMPD_target_simd: 7977 case OMPD_target_parallel: 7978 case OMPD_target_parallel_for: 7979 case OMPD_target_parallel_for_simd: 7980 case OMPD_threadprivate: 7981 case OMPD_taskyield: 7982 case OMPD_barrier: 7983 case OMPD_taskwait: 7984 case OMPD_cancellation_point: 7985 case OMPD_flush: 7986 case OMPD_declare_reduction: 7987 case OMPD_declare_simd: 7988 case OMPD_declare_target: 7989 case OMPD_end_declare_target: 7990 case OMPD_simd: 7991 case OMPD_for: 7992 case OMPD_for_simd: 7993 case OMPD_sections: 7994 case OMPD_section: 7995 case OMPD_single: 7996 case OMPD_master: 7997 case OMPD_critical: 7998 case OMPD_taskgroup: 7999 case OMPD_distribute: 8000 case OMPD_ordered: 8001 case OMPD_atomic: 8002 case OMPD_distribute_simd: 8003 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 8004 case OMPD_unknown: 8005 llvm_unreachable("Unknown OpenMP directive"); 8006 } 8007 break; 8008 case OMPC_thread_limit: 8009 switch (DKind) { 8010 case OMPD_target_teams: 8011 case OMPD_target_teams_distribute: 8012 case OMPD_target_teams_distribute_simd: 8013 case OMPD_target_teams_distribute_parallel_for: 8014 case OMPD_target_teams_distribute_parallel_for_simd: 8015 CaptureRegion = OMPD_target; 8016 break; 8017 case OMPD_teams_distribute_parallel_for: 8018 case OMPD_teams_distribute_parallel_for_simd: 8019 case OMPD_teams: 8020 case OMPD_teams_distribute: 8021 case OMPD_teams_distribute_simd: 8022 // Do not capture thread_limit-clause expressions. 8023 break; 8024 case OMPD_distribute_parallel_for: 8025 case OMPD_distribute_parallel_for_simd: 8026 case OMPD_task: 8027 case OMPD_taskloop: 8028 case OMPD_taskloop_simd: 8029 case OMPD_target_data: 8030 case OMPD_target_enter_data: 8031 case OMPD_target_exit_data: 8032 case OMPD_target_update: 8033 case OMPD_cancel: 8034 case OMPD_parallel: 8035 case OMPD_parallel_sections: 8036 case OMPD_parallel_for: 8037 case OMPD_parallel_for_simd: 8038 case OMPD_target: 8039 case OMPD_target_simd: 8040 case OMPD_target_parallel: 8041 case OMPD_target_parallel_for: 8042 case OMPD_target_parallel_for_simd: 8043 case OMPD_threadprivate: 8044 case OMPD_taskyield: 8045 case OMPD_barrier: 8046 case OMPD_taskwait: 8047 case OMPD_cancellation_point: 8048 case OMPD_flush: 8049 case OMPD_declare_reduction: 8050 case OMPD_declare_simd: 8051 case OMPD_declare_target: 8052 case OMPD_end_declare_target: 8053 case OMPD_simd: 8054 case OMPD_for: 8055 case OMPD_for_simd: 8056 case OMPD_sections: 8057 case OMPD_section: 8058 case OMPD_single: 8059 case OMPD_master: 8060 case OMPD_critical: 8061 case OMPD_taskgroup: 8062 case OMPD_distribute: 8063 case OMPD_ordered: 8064 case OMPD_atomic: 8065 case OMPD_distribute_simd: 8066 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 8067 case OMPD_unknown: 8068 llvm_unreachable("Unknown OpenMP directive"); 8069 } 8070 break; 8071 case OMPC_schedule: 8072 switch (DKind) { 8073 case OMPD_parallel_for: 8074 case OMPD_parallel_for_simd: 8075 case OMPD_distribute_parallel_for: 8076 case OMPD_distribute_parallel_for_simd: 8077 case OMPD_teams_distribute_parallel_for: 8078 case OMPD_teams_distribute_parallel_for_simd: 8079 case OMPD_target_parallel_for: 8080 case OMPD_target_parallel_for_simd: 8081 case OMPD_target_teams_distribute_parallel_for: 8082 case OMPD_target_teams_distribute_parallel_for_simd: 8083 CaptureRegion = OMPD_parallel; 8084 break; 8085 case OMPD_for: 8086 case OMPD_for_simd: 8087 // Do not capture schedule-clause expressions. 8088 break; 8089 case OMPD_task: 8090 case OMPD_taskloop: 8091 case OMPD_taskloop_simd: 8092 case OMPD_target_data: 8093 case OMPD_target_enter_data: 8094 case OMPD_target_exit_data: 8095 case OMPD_target_update: 8096 case OMPD_teams: 8097 case OMPD_teams_distribute: 8098 case OMPD_teams_distribute_simd: 8099 case OMPD_target_teams_distribute: 8100 case OMPD_target_teams_distribute_simd: 8101 case OMPD_target: 8102 case OMPD_target_simd: 8103 case OMPD_target_parallel: 8104 case OMPD_cancel: 8105 case OMPD_parallel: 8106 case OMPD_parallel_sections: 8107 case OMPD_threadprivate: 8108 case OMPD_taskyield: 8109 case OMPD_barrier: 8110 case OMPD_taskwait: 8111 case OMPD_cancellation_point: 8112 case OMPD_flush: 8113 case OMPD_declare_reduction: 8114 case OMPD_declare_simd: 8115 case OMPD_declare_target: 8116 case OMPD_end_declare_target: 8117 case OMPD_simd: 8118 case OMPD_sections: 8119 case OMPD_section: 8120 case OMPD_single: 8121 case OMPD_master: 8122 case OMPD_critical: 8123 case OMPD_taskgroup: 8124 case OMPD_distribute: 8125 case OMPD_ordered: 8126 case OMPD_atomic: 8127 case OMPD_distribute_simd: 8128 case OMPD_target_teams: 8129 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 8130 case OMPD_unknown: 8131 llvm_unreachable("Unknown OpenMP directive"); 8132 } 8133 break; 8134 case OMPC_dist_schedule: 8135 switch (DKind) { 8136 case OMPD_teams_distribute_parallel_for: 8137 case OMPD_teams_distribute_parallel_for_simd: 8138 case OMPD_teams_distribute: 8139 case OMPD_teams_distribute_simd: 8140 case OMPD_target_teams_distribute_parallel_for: 8141 case OMPD_target_teams_distribute_parallel_for_simd: 8142 case OMPD_target_teams_distribute: 8143 case OMPD_target_teams_distribute_simd: 8144 CaptureRegion = OMPD_teams; 8145 break; 8146 case OMPD_distribute_parallel_for: 8147 case OMPD_distribute_parallel_for_simd: 8148 case OMPD_distribute: 8149 case OMPD_distribute_simd: 8150 // Do not capture thread_limit-clause expressions. 8151 break; 8152 case OMPD_parallel_for: 8153 case OMPD_parallel_for_simd: 8154 case OMPD_target_parallel_for_simd: 8155 case OMPD_target_parallel_for: 8156 case OMPD_task: 8157 case OMPD_taskloop: 8158 case OMPD_taskloop_simd: 8159 case OMPD_target_data: 8160 case OMPD_target_enter_data: 8161 case OMPD_target_exit_data: 8162 case OMPD_target_update: 8163 case OMPD_teams: 8164 case OMPD_target: 8165 case OMPD_target_simd: 8166 case OMPD_target_parallel: 8167 case OMPD_cancel: 8168 case OMPD_parallel: 8169 case OMPD_parallel_sections: 8170 case OMPD_threadprivate: 8171 case OMPD_taskyield: 8172 case OMPD_barrier: 8173 case OMPD_taskwait: 8174 case OMPD_cancellation_point: 8175 case OMPD_flush: 8176 case OMPD_declare_reduction: 8177 case OMPD_declare_simd: 8178 case OMPD_declare_target: 8179 case OMPD_end_declare_target: 8180 case OMPD_simd: 8181 case OMPD_for: 8182 case OMPD_for_simd: 8183 case OMPD_sections: 8184 case OMPD_section: 8185 case OMPD_single: 8186 case OMPD_master: 8187 case OMPD_critical: 8188 case OMPD_taskgroup: 8189 case OMPD_ordered: 8190 case OMPD_atomic: 8191 case OMPD_target_teams: 8192 llvm_unreachable("Unexpected OpenMP directive with schedule clause"); 8193 case OMPD_unknown: 8194 llvm_unreachable("Unknown OpenMP directive"); 8195 } 8196 break; 8197 case OMPC_device: 8198 switch (DKind) { 8199 case OMPD_target_update: 8200 case OMPD_target_enter_data: 8201 case OMPD_target_exit_data: 8202 case OMPD_target: 8203 case OMPD_target_simd: 8204 case OMPD_target_teams: 8205 case OMPD_target_parallel: 8206 case OMPD_target_teams_distribute: 8207 case OMPD_target_teams_distribute_simd: 8208 case OMPD_target_parallel_for: 8209 case OMPD_target_parallel_for_simd: 8210 case OMPD_target_teams_distribute_parallel_for: 8211 case OMPD_target_teams_distribute_parallel_for_simd: 8212 CaptureRegion = OMPD_task; 8213 break; 8214 case OMPD_target_data: 8215 // Do not capture device-clause expressions. 8216 break; 8217 case OMPD_teams_distribute_parallel_for: 8218 case OMPD_teams_distribute_parallel_for_simd: 8219 case OMPD_teams: 8220 case OMPD_teams_distribute: 8221 case OMPD_teams_distribute_simd: 8222 case OMPD_distribute_parallel_for: 8223 case OMPD_distribute_parallel_for_simd: 8224 case OMPD_task: 8225 case OMPD_taskloop: 8226 case OMPD_taskloop_simd: 8227 case OMPD_cancel: 8228 case OMPD_parallel: 8229 case OMPD_parallel_sections: 8230 case OMPD_parallel_for: 8231 case OMPD_parallel_for_simd: 8232 case OMPD_threadprivate: 8233 case OMPD_taskyield: 8234 case OMPD_barrier: 8235 case OMPD_taskwait: 8236 case OMPD_cancellation_point: 8237 case OMPD_flush: 8238 case OMPD_declare_reduction: 8239 case OMPD_declare_simd: 8240 case OMPD_declare_target: 8241 case OMPD_end_declare_target: 8242 case OMPD_simd: 8243 case OMPD_for: 8244 case OMPD_for_simd: 8245 case OMPD_sections: 8246 case OMPD_section: 8247 case OMPD_single: 8248 case OMPD_master: 8249 case OMPD_critical: 8250 case OMPD_taskgroup: 8251 case OMPD_distribute: 8252 case OMPD_ordered: 8253 case OMPD_atomic: 8254 case OMPD_distribute_simd: 8255 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 8256 case OMPD_unknown: 8257 llvm_unreachable("Unknown OpenMP directive"); 8258 } 8259 break; 8260 case OMPC_firstprivate: 8261 case OMPC_lastprivate: 8262 case OMPC_reduction: 8263 case OMPC_task_reduction: 8264 case OMPC_in_reduction: 8265 case OMPC_linear: 8266 case OMPC_default: 8267 case OMPC_proc_bind: 8268 case OMPC_final: 8269 case OMPC_safelen: 8270 case OMPC_simdlen: 8271 case OMPC_collapse: 8272 case OMPC_private: 8273 case OMPC_shared: 8274 case OMPC_aligned: 8275 case OMPC_copyin: 8276 case OMPC_copyprivate: 8277 case OMPC_ordered: 8278 case OMPC_nowait: 8279 case OMPC_untied: 8280 case OMPC_mergeable: 8281 case OMPC_threadprivate: 8282 case OMPC_flush: 8283 case OMPC_read: 8284 case OMPC_write: 8285 case OMPC_update: 8286 case OMPC_capture: 8287 case OMPC_seq_cst: 8288 case OMPC_depend: 8289 case OMPC_threads: 8290 case OMPC_simd: 8291 case OMPC_map: 8292 case OMPC_priority: 8293 case OMPC_grainsize: 8294 case OMPC_nogroup: 8295 case OMPC_num_tasks: 8296 case OMPC_hint: 8297 case OMPC_defaultmap: 8298 case OMPC_unknown: 8299 case OMPC_uniform: 8300 case OMPC_to: 8301 case OMPC_from: 8302 case OMPC_use_device_ptr: 8303 case OMPC_is_device_ptr: 8304 llvm_unreachable("Unexpected OpenMP clause."); 8305 } 8306 return CaptureRegion; 8307 } 8308 8309 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 8310 Expr *Condition, SourceLocation StartLoc, 8311 SourceLocation LParenLoc, 8312 SourceLocation NameModifierLoc, 8313 SourceLocation ColonLoc, 8314 SourceLocation EndLoc) { 8315 Expr *ValExpr = Condition; 8316 Stmt *HelperValStmt = nullptr; 8317 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 8318 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 8319 !Condition->isInstantiationDependent() && 8320 !Condition->containsUnexpandedParameterPack()) { 8321 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 8322 if (Val.isInvalid()) 8323 return nullptr; 8324 8325 ValExpr = Val.get(); 8326 8327 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 8328 CaptureRegion = 8329 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier); 8330 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 8331 ValExpr = MakeFullExpr(ValExpr).get(); 8332 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 8333 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 8334 HelperValStmt = buildPreInits(Context, Captures); 8335 } 8336 } 8337 8338 return new (Context) 8339 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 8340 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 8341 } 8342 8343 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 8344 SourceLocation StartLoc, 8345 SourceLocation LParenLoc, 8346 SourceLocation EndLoc) { 8347 Expr *ValExpr = Condition; 8348 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 8349 !Condition->isInstantiationDependent() && 8350 !Condition->containsUnexpandedParameterPack()) { 8351 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 8352 if (Val.isInvalid()) 8353 return nullptr; 8354 8355 ValExpr = MakeFullExpr(Val.get()).get(); 8356 } 8357 8358 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 8359 } 8360 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 8361 Expr *Op) { 8362 if (!Op) 8363 return ExprError(); 8364 8365 class IntConvertDiagnoser : public ICEConvertDiagnoser { 8366 public: 8367 IntConvertDiagnoser() 8368 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 8369 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 8370 QualType T) override { 8371 return S.Diag(Loc, diag::err_omp_not_integral) << T; 8372 } 8373 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 8374 QualType T) override { 8375 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 8376 } 8377 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 8378 QualType T, 8379 QualType ConvTy) override { 8380 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 8381 } 8382 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 8383 QualType ConvTy) override { 8384 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 8385 << ConvTy->isEnumeralType() << ConvTy; 8386 } 8387 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 8388 QualType T) override { 8389 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 8390 } 8391 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 8392 QualType ConvTy) override { 8393 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 8394 << ConvTy->isEnumeralType() << ConvTy; 8395 } 8396 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 8397 QualType) override { 8398 llvm_unreachable("conversion functions are permitted"); 8399 } 8400 } ConvertDiagnoser; 8401 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 8402 } 8403 8404 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, 8405 OpenMPClauseKind CKind, 8406 bool StrictlyPositive) { 8407 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 8408 !ValExpr->isInstantiationDependent()) { 8409 SourceLocation Loc = ValExpr->getExprLoc(); 8410 ExprResult Value = 8411 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 8412 if (Value.isInvalid()) 8413 return false; 8414 8415 ValExpr = Value.get(); 8416 // The expression must evaluate to a non-negative integer value. 8417 llvm::APSInt Result; 8418 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && 8419 Result.isSigned() && 8420 !((!StrictlyPositive && Result.isNonNegative()) || 8421 (StrictlyPositive && Result.isStrictlyPositive()))) { 8422 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 8423 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 8424 << ValExpr->getSourceRange(); 8425 return false; 8426 } 8427 } 8428 return true; 8429 } 8430 8431 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 8432 SourceLocation StartLoc, 8433 SourceLocation LParenLoc, 8434 SourceLocation EndLoc) { 8435 Expr *ValExpr = NumThreads; 8436 Stmt *HelperValStmt = nullptr; 8437 8438 // OpenMP [2.5, Restrictions] 8439 // The num_threads expression must evaluate to a positive integer value. 8440 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 8441 /*StrictlyPositive=*/true)) 8442 return nullptr; 8443 8444 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 8445 OpenMPDirectiveKind CaptureRegion = 8446 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads); 8447 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 8448 ValExpr = MakeFullExpr(ValExpr).get(); 8449 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 8450 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 8451 HelperValStmt = buildPreInits(Context, Captures); 8452 } 8453 8454 return new (Context) OMPNumThreadsClause( 8455 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 8456 } 8457 8458 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 8459 OpenMPClauseKind CKind, 8460 bool StrictlyPositive) { 8461 if (!E) 8462 return ExprError(); 8463 if (E->isValueDependent() || E->isTypeDependent() || 8464 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 8465 return E; 8466 llvm::APSInt Result; 8467 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 8468 if (ICE.isInvalid()) 8469 return ExprError(); 8470 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 8471 (!StrictlyPositive && !Result.isNonNegative())) { 8472 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 8473 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 8474 << E->getSourceRange(); 8475 return ExprError(); 8476 } 8477 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 8478 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 8479 << E->getSourceRange(); 8480 return ExprError(); 8481 } 8482 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 8483 DSAStack->setAssociatedLoops(Result.getExtValue()); 8484 else if (CKind == OMPC_ordered) 8485 DSAStack->setAssociatedLoops(Result.getExtValue()); 8486 return ICE; 8487 } 8488 8489 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 8490 SourceLocation LParenLoc, 8491 SourceLocation EndLoc) { 8492 // OpenMP [2.8.1, simd construct, Description] 8493 // The parameter of the safelen clause must be a constant 8494 // positive integer expression. 8495 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 8496 if (Safelen.isInvalid()) 8497 return nullptr; 8498 return new (Context) 8499 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 8500 } 8501 8502 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 8503 SourceLocation LParenLoc, 8504 SourceLocation EndLoc) { 8505 // OpenMP [2.8.1, simd construct, Description] 8506 // The parameter of the simdlen clause must be a constant 8507 // positive integer expression. 8508 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 8509 if (Simdlen.isInvalid()) 8510 return nullptr; 8511 return new (Context) 8512 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 8513 } 8514 8515 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 8516 SourceLocation StartLoc, 8517 SourceLocation LParenLoc, 8518 SourceLocation EndLoc) { 8519 // OpenMP [2.7.1, loop construct, Description] 8520 // OpenMP [2.8.1, simd construct, Description] 8521 // OpenMP [2.9.6, distribute construct, Description] 8522 // The parameter of the collapse clause must be a constant 8523 // positive integer expression. 8524 ExprResult NumForLoopsResult = 8525 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 8526 if (NumForLoopsResult.isInvalid()) 8527 return nullptr; 8528 return new (Context) 8529 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 8530 } 8531 8532 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 8533 SourceLocation EndLoc, 8534 SourceLocation LParenLoc, 8535 Expr *NumForLoops) { 8536 // OpenMP [2.7.1, loop construct, Description] 8537 // OpenMP [2.8.1, simd construct, Description] 8538 // OpenMP [2.9.6, distribute construct, Description] 8539 // The parameter of the ordered clause must be a constant 8540 // positive integer expression if any. 8541 if (NumForLoops && LParenLoc.isValid()) { 8542 ExprResult NumForLoopsResult = 8543 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 8544 if (NumForLoopsResult.isInvalid()) 8545 return nullptr; 8546 NumForLoops = NumForLoopsResult.get(); 8547 } else 8548 NumForLoops = nullptr; 8549 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops); 8550 return new (Context) 8551 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc); 8552 } 8553 8554 OMPClause *Sema::ActOnOpenMPSimpleClause( 8555 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 8556 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 8557 OMPClause *Res = nullptr; 8558 switch (Kind) { 8559 case OMPC_default: 8560 Res = 8561 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 8562 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 8563 break; 8564 case OMPC_proc_bind: 8565 Res = ActOnOpenMPProcBindClause( 8566 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 8567 LParenLoc, EndLoc); 8568 break; 8569 case OMPC_if: 8570 case OMPC_final: 8571 case OMPC_num_threads: 8572 case OMPC_safelen: 8573 case OMPC_simdlen: 8574 case OMPC_collapse: 8575 case OMPC_schedule: 8576 case OMPC_private: 8577 case OMPC_firstprivate: 8578 case OMPC_lastprivate: 8579 case OMPC_shared: 8580 case OMPC_reduction: 8581 case OMPC_task_reduction: 8582 case OMPC_in_reduction: 8583 case OMPC_linear: 8584 case OMPC_aligned: 8585 case OMPC_copyin: 8586 case OMPC_copyprivate: 8587 case OMPC_ordered: 8588 case OMPC_nowait: 8589 case OMPC_untied: 8590 case OMPC_mergeable: 8591 case OMPC_threadprivate: 8592 case OMPC_flush: 8593 case OMPC_read: 8594 case OMPC_write: 8595 case OMPC_update: 8596 case OMPC_capture: 8597 case OMPC_seq_cst: 8598 case OMPC_depend: 8599 case OMPC_device: 8600 case OMPC_threads: 8601 case OMPC_simd: 8602 case OMPC_map: 8603 case OMPC_num_teams: 8604 case OMPC_thread_limit: 8605 case OMPC_priority: 8606 case OMPC_grainsize: 8607 case OMPC_nogroup: 8608 case OMPC_num_tasks: 8609 case OMPC_hint: 8610 case OMPC_dist_schedule: 8611 case OMPC_defaultmap: 8612 case OMPC_unknown: 8613 case OMPC_uniform: 8614 case OMPC_to: 8615 case OMPC_from: 8616 case OMPC_use_device_ptr: 8617 case OMPC_is_device_ptr: 8618 llvm_unreachable("Clause is not allowed."); 8619 } 8620 return Res; 8621 } 8622 8623 static std::string 8624 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 8625 ArrayRef<unsigned> Exclude = llvm::None) { 8626 std::string Values; 8627 unsigned Bound = Last >= 2 ? Last - 2 : 0; 8628 unsigned Skipped = Exclude.size(); 8629 auto S = Exclude.begin(), E = Exclude.end(); 8630 for (unsigned i = First; i < Last; ++i) { 8631 if (std::find(S, E, i) != E) { 8632 --Skipped; 8633 continue; 8634 } 8635 Values += "'"; 8636 Values += getOpenMPSimpleClauseTypeName(K, i); 8637 Values += "'"; 8638 if (i == Bound - Skipped) 8639 Values += " or "; 8640 else if (i != Bound + 1 - Skipped) 8641 Values += ", "; 8642 } 8643 return Values; 8644 } 8645 8646 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 8647 SourceLocation KindKwLoc, 8648 SourceLocation StartLoc, 8649 SourceLocation LParenLoc, 8650 SourceLocation EndLoc) { 8651 if (Kind == OMPC_DEFAULT_unknown) { 8652 static_assert(OMPC_DEFAULT_unknown > 0, 8653 "OMPC_DEFAULT_unknown not greater than 0"); 8654 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 8655 << getListOfPossibleValues(OMPC_default, /*First=*/0, 8656 /*Last=*/OMPC_DEFAULT_unknown) 8657 << getOpenMPClauseName(OMPC_default); 8658 return nullptr; 8659 } 8660 switch (Kind) { 8661 case OMPC_DEFAULT_none: 8662 DSAStack->setDefaultDSANone(KindKwLoc); 8663 break; 8664 case OMPC_DEFAULT_shared: 8665 DSAStack->setDefaultDSAShared(KindKwLoc); 8666 break; 8667 case OMPC_DEFAULT_unknown: 8668 llvm_unreachable("Clause kind is not allowed."); 8669 break; 8670 } 8671 return new (Context) 8672 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 8673 } 8674 8675 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 8676 SourceLocation KindKwLoc, 8677 SourceLocation StartLoc, 8678 SourceLocation LParenLoc, 8679 SourceLocation EndLoc) { 8680 if (Kind == OMPC_PROC_BIND_unknown) { 8681 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 8682 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0, 8683 /*Last=*/OMPC_PROC_BIND_unknown) 8684 << getOpenMPClauseName(OMPC_proc_bind); 8685 return nullptr; 8686 } 8687 return new (Context) 8688 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 8689 } 8690 8691 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 8692 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 8693 SourceLocation StartLoc, SourceLocation LParenLoc, 8694 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 8695 SourceLocation EndLoc) { 8696 OMPClause *Res = nullptr; 8697 switch (Kind) { 8698 case OMPC_schedule: 8699 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 8700 assert(Argument.size() == NumberOfElements && 8701 ArgumentLoc.size() == NumberOfElements); 8702 Res = ActOnOpenMPScheduleClause( 8703 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 8704 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 8705 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 8706 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 8707 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 8708 break; 8709 case OMPC_if: 8710 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 8711 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 8712 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 8713 DelimLoc, EndLoc); 8714 break; 8715 case OMPC_dist_schedule: 8716 Res = ActOnOpenMPDistScheduleClause( 8717 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 8718 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 8719 break; 8720 case OMPC_defaultmap: 8721 enum { Modifier, DefaultmapKind }; 8722 Res = ActOnOpenMPDefaultmapClause( 8723 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 8724 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 8725 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 8726 EndLoc); 8727 break; 8728 case OMPC_final: 8729 case OMPC_num_threads: 8730 case OMPC_safelen: 8731 case OMPC_simdlen: 8732 case OMPC_collapse: 8733 case OMPC_default: 8734 case OMPC_proc_bind: 8735 case OMPC_private: 8736 case OMPC_firstprivate: 8737 case OMPC_lastprivate: 8738 case OMPC_shared: 8739 case OMPC_reduction: 8740 case OMPC_task_reduction: 8741 case OMPC_in_reduction: 8742 case OMPC_linear: 8743 case OMPC_aligned: 8744 case OMPC_copyin: 8745 case OMPC_copyprivate: 8746 case OMPC_ordered: 8747 case OMPC_nowait: 8748 case OMPC_untied: 8749 case OMPC_mergeable: 8750 case OMPC_threadprivate: 8751 case OMPC_flush: 8752 case OMPC_read: 8753 case OMPC_write: 8754 case OMPC_update: 8755 case OMPC_capture: 8756 case OMPC_seq_cst: 8757 case OMPC_depend: 8758 case OMPC_device: 8759 case OMPC_threads: 8760 case OMPC_simd: 8761 case OMPC_map: 8762 case OMPC_num_teams: 8763 case OMPC_thread_limit: 8764 case OMPC_priority: 8765 case OMPC_grainsize: 8766 case OMPC_nogroup: 8767 case OMPC_num_tasks: 8768 case OMPC_hint: 8769 case OMPC_unknown: 8770 case OMPC_uniform: 8771 case OMPC_to: 8772 case OMPC_from: 8773 case OMPC_use_device_ptr: 8774 case OMPC_is_device_ptr: 8775 llvm_unreachable("Clause is not allowed."); 8776 } 8777 return Res; 8778 } 8779 8780 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 8781 OpenMPScheduleClauseModifier M2, 8782 SourceLocation M1Loc, SourceLocation M2Loc) { 8783 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 8784 SmallVector<unsigned, 2> Excluded; 8785 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 8786 Excluded.push_back(M2); 8787 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 8788 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 8789 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 8790 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 8791 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 8792 << getListOfPossibleValues(OMPC_schedule, 8793 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 8794 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 8795 Excluded) 8796 << getOpenMPClauseName(OMPC_schedule); 8797 return true; 8798 } 8799 return false; 8800 } 8801 8802 OMPClause *Sema::ActOnOpenMPScheduleClause( 8803 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 8804 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 8805 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 8806 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 8807 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 8808 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 8809 return nullptr; 8810 // OpenMP, 2.7.1, Loop Construct, Restrictions 8811 // Either the monotonic modifier or the nonmonotonic modifier can be specified 8812 // but not both. 8813 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 8814 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 8815 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 8816 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 8817 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 8818 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 8819 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 8820 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 8821 return nullptr; 8822 } 8823 if (Kind == OMPC_SCHEDULE_unknown) { 8824 std::string Values; 8825 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 8826 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 8827 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 8828 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 8829 Exclude); 8830 } else { 8831 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 8832 /*Last=*/OMPC_SCHEDULE_unknown); 8833 } 8834 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 8835 << Values << getOpenMPClauseName(OMPC_schedule); 8836 return nullptr; 8837 } 8838 // OpenMP, 2.7.1, Loop Construct, Restrictions 8839 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 8840 // schedule(guided). 8841 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 8842 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 8843 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 8844 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 8845 diag::err_omp_schedule_nonmonotonic_static); 8846 return nullptr; 8847 } 8848 Expr *ValExpr = ChunkSize; 8849 Stmt *HelperValStmt = nullptr; 8850 if (ChunkSize) { 8851 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 8852 !ChunkSize->isInstantiationDependent() && 8853 !ChunkSize->containsUnexpandedParameterPack()) { 8854 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 8855 ExprResult Val = 8856 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 8857 if (Val.isInvalid()) 8858 return nullptr; 8859 8860 ValExpr = Val.get(); 8861 8862 // OpenMP [2.7.1, Restrictions] 8863 // chunk_size must be a loop invariant integer expression with a positive 8864 // value. 8865 llvm::APSInt Result; 8866 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 8867 if (Result.isSigned() && !Result.isStrictlyPositive()) { 8868 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 8869 << "schedule" << 1 << ChunkSize->getSourceRange(); 8870 return nullptr; 8871 } 8872 } else if (getOpenMPCaptureRegionForClause( 8873 DSAStack->getCurrentDirective(), OMPC_schedule) != 8874 OMPD_unknown && 8875 !CurContext->isDependentContext()) { 8876 ValExpr = MakeFullExpr(ValExpr).get(); 8877 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 8878 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 8879 HelperValStmt = buildPreInits(Context, Captures); 8880 } 8881 } 8882 } 8883 8884 return new (Context) 8885 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 8886 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 8887 } 8888 8889 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 8890 SourceLocation StartLoc, 8891 SourceLocation EndLoc) { 8892 OMPClause *Res = nullptr; 8893 switch (Kind) { 8894 case OMPC_ordered: 8895 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 8896 break; 8897 case OMPC_nowait: 8898 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 8899 break; 8900 case OMPC_untied: 8901 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 8902 break; 8903 case OMPC_mergeable: 8904 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 8905 break; 8906 case OMPC_read: 8907 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 8908 break; 8909 case OMPC_write: 8910 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 8911 break; 8912 case OMPC_update: 8913 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 8914 break; 8915 case OMPC_capture: 8916 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 8917 break; 8918 case OMPC_seq_cst: 8919 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 8920 break; 8921 case OMPC_threads: 8922 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 8923 break; 8924 case OMPC_simd: 8925 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 8926 break; 8927 case OMPC_nogroup: 8928 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 8929 break; 8930 case OMPC_if: 8931 case OMPC_final: 8932 case OMPC_num_threads: 8933 case OMPC_safelen: 8934 case OMPC_simdlen: 8935 case OMPC_collapse: 8936 case OMPC_schedule: 8937 case OMPC_private: 8938 case OMPC_firstprivate: 8939 case OMPC_lastprivate: 8940 case OMPC_shared: 8941 case OMPC_reduction: 8942 case OMPC_task_reduction: 8943 case OMPC_in_reduction: 8944 case OMPC_linear: 8945 case OMPC_aligned: 8946 case OMPC_copyin: 8947 case OMPC_copyprivate: 8948 case OMPC_default: 8949 case OMPC_proc_bind: 8950 case OMPC_threadprivate: 8951 case OMPC_flush: 8952 case OMPC_depend: 8953 case OMPC_device: 8954 case OMPC_map: 8955 case OMPC_num_teams: 8956 case OMPC_thread_limit: 8957 case OMPC_priority: 8958 case OMPC_grainsize: 8959 case OMPC_num_tasks: 8960 case OMPC_hint: 8961 case OMPC_dist_schedule: 8962 case OMPC_defaultmap: 8963 case OMPC_unknown: 8964 case OMPC_uniform: 8965 case OMPC_to: 8966 case OMPC_from: 8967 case OMPC_use_device_ptr: 8968 case OMPC_is_device_ptr: 8969 llvm_unreachable("Clause is not allowed."); 8970 } 8971 return Res; 8972 } 8973 8974 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 8975 SourceLocation EndLoc) { 8976 DSAStack->setNowaitRegion(); 8977 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 8978 } 8979 8980 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 8981 SourceLocation EndLoc) { 8982 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 8983 } 8984 8985 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 8986 SourceLocation EndLoc) { 8987 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 8988 } 8989 8990 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 8991 SourceLocation EndLoc) { 8992 return new (Context) OMPReadClause(StartLoc, EndLoc); 8993 } 8994 8995 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 8996 SourceLocation EndLoc) { 8997 return new (Context) OMPWriteClause(StartLoc, EndLoc); 8998 } 8999 9000 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 9001 SourceLocation EndLoc) { 9002 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 9003 } 9004 9005 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 9006 SourceLocation EndLoc) { 9007 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 9008 } 9009 9010 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 9011 SourceLocation EndLoc) { 9012 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 9013 } 9014 9015 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 9016 SourceLocation EndLoc) { 9017 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 9018 } 9019 9020 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 9021 SourceLocation EndLoc) { 9022 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 9023 } 9024 9025 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 9026 SourceLocation EndLoc) { 9027 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 9028 } 9029 9030 OMPClause *Sema::ActOnOpenMPVarListClause( 9031 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 9032 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 9033 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 9034 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind, 9035 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier, 9036 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 9037 SourceLocation DepLinMapLoc) { 9038 OMPClause *Res = nullptr; 9039 switch (Kind) { 9040 case OMPC_private: 9041 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 9042 break; 9043 case OMPC_firstprivate: 9044 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 9045 break; 9046 case OMPC_lastprivate: 9047 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 9048 break; 9049 case OMPC_shared: 9050 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 9051 break; 9052 case OMPC_reduction: 9053 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 9054 EndLoc, ReductionIdScopeSpec, ReductionId); 9055 break; 9056 case OMPC_task_reduction: 9057 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 9058 EndLoc, ReductionIdScopeSpec, 9059 ReductionId); 9060 break; 9061 case OMPC_in_reduction: 9062 Res = 9063 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 9064 EndLoc, ReductionIdScopeSpec, ReductionId); 9065 break; 9066 case OMPC_linear: 9067 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 9068 LinKind, DepLinMapLoc, ColonLoc, EndLoc); 9069 break; 9070 case OMPC_aligned: 9071 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 9072 ColonLoc, EndLoc); 9073 break; 9074 case OMPC_copyin: 9075 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 9076 break; 9077 case OMPC_copyprivate: 9078 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 9079 break; 9080 case OMPC_flush: 9081 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 9082 break; 9083 case OMPC_depend: 9084 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, 9085 StartLoc, LParenLoc, EndLoc); 9086 break; 9087 case OMPC_map: 9088 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit, 9089 DepLinMapLoc, ColonLoc, VarList, StartLoc, 9090 LParenLoc, EndLoc); 9091 break; 9092 case OMPC_to: 9093 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc); 9094 break; 9095 case OMPC_from: 9096 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc); 9097 break; 9098 case OMPC_use_device_ptr: 9099 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 9100 break; 9101 case OMPC_is_device_ptr: 9102 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 9103 break; 9104 case OMPC_if: 9105 case OMPC_final: 9106 case OMPC_num_threads: 9107 case OMPC_safelen: 9108 case OMPC_simdlen: 9109 case OMPC_collapse: 9110 case OMPC_default: 9111 case OMPC_proc_bind: 9112 case OMPC_schedule: 9113 case OMPC_ordered: 9114 case OMPC_nowait: 9115 case OMPC_untied: 9116 case OMPC_mergeable: 9117 case OMPC_threadprivate: 9118 case OMPC_read: 9119 case OMPC_write: 9120 case OMPC_update: 9121 case OMPC_capture: 9122 case OMPC_seq_cst: 9123 case OMPC_device: 9124 case OMPC_threads: 9125 case OMPC_simd: 9126 case OMPC_num_teams: 9127 case OMPC_thread_limit: 9128 case OMPC_priority: 9129 case OMPC_grainsize: 9130 case OMPC_nogroup: 9131 case OMPC_num_tasks: 9132 case OMPC_hint: 9133 case OMPC_dist_schedule: 9134 case OMPC_defaultmap: 9135 case OMPC_unknown: 9136 case OMPC_uniform: 9137 llvm_unreachable("Clause is not allowed."); 9138 } 9139 return Res; 9140 } 9141 9142 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 9143 ExprObjectKind OK, SourceLocation Loc) { 9144 ExprResult Res = BuildDeclRefExpr( 9145 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 9146 if (!Res.isUsable()) 9147 return ExprError(); 9148 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 9149 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 9150 if (!Res.isUsable()) 9151 return ExprError(); 9152 } 9153 if (VK != VK_LValue && Res.get()->isGLValue()) { 9154 Res = DefaultLvalueConversion(Res.get()); 9155 if (!Res.isUsable()) 9156 return ExprError(); 9157 } 9158 return Res; 9159 } 9160 9161 static std::pair<ValueDecl *, bool> 9162 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 9163 SourceRange &ERange, bool AllowArraySection = false) { 9164 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 9165 RefExpr->containsUnexpandedParameterPack()) 9166 return std::make_pair(nullptr, true); 9167 9168 // OpenMP [3.1, C/C++] 9169 // A list item is a variable name. 9170 // OpenMP [2.9.3.3, Restrictions, p.1] 9171 // A variable that is part of another variable (as an array or 9172 // structure element) cannot appear in a private clause. 9173 RefExpr = RefExpr->IgnoreParens(); 9174 enum { 9175 NoArrayExpr = -1, 9176 ArraySubscript = 0, 9177 OMPArraySection = 1 9178 } IsArrayExpr = NoArrayExpr; 9179 if (AllowArraySection) { 9180 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 9181 auto *Base = ASE->getBase()->IgnoreParenImpCasts(); 9182 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 9183 Base = TempASE->getBase()->IgnoreParenImpCasts(); 9184 RefExpr = Base; 9185 IsArrayExpr = ArraySubscript; 9186 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 9187 auto *Base = OASE->getBase()->IgnoreParenImpCasts(); 9188 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 9189 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 9190 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 9191 Base = TempASE->getBase()->IgnoreParenImpCasts(); 9192 RefExpr = Base; 9193 IsArrayExpr = OMPArraySection; 9194 } 9195 } 9196 ELoc = RefExpr->getExprLoc(); 9197 ERange = RefExpr->getSourceRange(); 9198 RefExpr = RefExpr->IgnoreParenImpCasts(); 9199 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 9200 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 9201 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 9202 (S.getCurrentThisType().isNull() || !ME || 9203 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 9204 !isa<FieldDecl>(ME->getMemberDecl()))) { 9205 if (IsArrayExpr != NoArrayExpr) 9206 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 9207 << ERange; 9208 else { 9209 S.Diag(ELoc, 9210 AllowArraySection 9211 ? diag::err_omp_expected_var_name_member_expr_or_array_item 9212 : diag::err_omp_expected_var_name_member_expr) 9213 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 9214 } 9215 return std::make_pair(nullptr, false); 9216 } 9217 return std::make_pair( 9218 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false); 9219 } 9220 9221 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 9222 SourceLocation StartLoc, 9223 SourceLocation LParenLoc, 9224 SourceLocation EndLoc) { 9225 SmallVector<Expr *, 8> Vars; 9226 SmallVector<Expr *, 8> PrivateCopies; 9227 for (auto &RefExpr : VarList) { 9228 assert(RefExpr && "NULL expr in OpenMP private clause."); 9229 SourceLocation ELoc; 9230 SourceRange ERange; 9231 Expr *SimpleRefExpr = RefExpr; 9232 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 9233 if (Res.second) { 9234 // It will be analyzed later. 9235 Vars.push_back(RefExpr); 9236 PrivateCopies.push_back(nullptr); 9237 } 9238 ValueDecl *D = Res.first; 9239 if (!D) 9240 continue; 9241 9242 QualType Type = D->getType(); 9243 auto *VD = dyn_cast<VarDecl>(D); 9244 9245 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 9246 // A variable that appears in a private clause must not have an incomplete 9247 // type or a reference type. 9248 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 9249 continue; 9250 Type = Type.getNonReferenceType(); 9251 9252 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 9253 // in a Construct] 9254 // Variables with the predetermined data-sharing attributes may not be 9255 // listed in data-sharing attributes clauses, except for the cases 9256 // listed below. For these exceptions only, listing a predetermined 9257 // variable in a data-sharing attribute clause is allowed and overrides 9258 // the variable's predetermined data-sharing attributes. 9259 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 9260 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 9261 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 9262 << getOpenMPClauseName(OMPC_private); 9263 ReportOriginalDSA(*this, DSAStack, D, DVar); 9264 continue; 9265 } 9266 9267 auto CurrDir = DSAStack->getCurrentDirective(); 9268 // Variably modified types are not supported for tasks. 9269 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 9270 isOpenMPTaskingDirective(CurrDir)) { 9271 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 9272 << getOpenMPClauseName(OMPC_private) << Type 9273 << getOpenMPDirectiveName(CurrDir); 9274 bool IsDecl = 9275 !VD || 9276 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9277 Diag(D->getLocation(), 9278 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9279 << D; 9280 continue; 9281 } 9282 9283 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 9284 // A list item cannot appear in both a map clause and a data-sharing 9285 // attribute clause on the same construct 9286 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || 9287 CurrDir == OMPD_target_teams || 9288 CurrDir == OMPD_target_teams_distribute || 9289 CurrDir == OMPD_target_teams_distribute_parallel_for || 9290 CurrDir == OMPD_target_teams_distribute_parallel_for_simd || 9291 CurrDir == OMPD_target_teams_distribute_simd || 9292 CurrDir == OMPD_target_parallel_for_simd || 9293 CurrDir == OMPD_target_parallel_for) { 9294 OpenMPClauseKind ConflictKind; 9295 if (DSAStack->checkMappableExprComponentListsForDecl( 9296 VD, /*CurrentRegionOnly=*/true, 9297 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 9298 OpenMPClauseKind WhereFoundClauseKind) -> bool { 9299 ConflictKind = WhereFoundClauseKind; 9300 return true; 9301 })) { 9302 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 9303 << getOpenMPClauseName(OMPC_private) 9304 << getOpenMPClauseName(ConflictKind) 9305 << getOpenMPDirectiveName(CurrDir); 9306 ReportOriginalDSA(*this, DSAStack, D, DVar); 9307 continue; 9308 } 9309 } 9310 9311 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 9312 // A variable of class type (or array thereof) that appears in a private 9313 // clause requires an accessible, unambiguous default constructor for the 9314 // class type. 9315 // Generate helper private variable and initialize it with the default 9316 // value. The address of the original variable is replaced by the address of 9317 // the new private variable in CodeGen. This new variable is not added to 9318 // IdResolver, so the code in the OpenMP region uses original variable for 9319 // proper diagnostics. 9320 Type = Type.getUnqualifiedType(); 9321 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 9322 D->hasAttrs() ? &D->getAttrs() : nullptr); 9323 ActOnUninitializedDecl(VDPrivate); 9324 if (VDPrivate->isInvalidDecl()) 9325 continue; 9326 auto VDPrivateRefExpr = buildDeclRefExpr( 9327 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 9328 9329 DeclRefExpr *Ref = nullptr; 9330 if (!VD && !CurContext->isDependentContext()) 9331 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 9332 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 9333 Vars.push_back((VD || CurContext->isDependentContext()) 9334 ? RefExpr->IgnoreParens() 9335 : Ref); 9336 PrivateCopies.push_back(VDPrivateRefExpr); 9337 } 9338 9339 if (Vars.empty()) 9340 return nullptr; 9341 9342 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 9343 PrivateCopies); 9344 } 9345 9346 namespace { 9347 class DiagsUninitializedSeveretyRAII { 9348 private: 9349 DiagnosticsEngine &Diags; 9350 SourceLocation SavedLoc; 9351 bool IsIgnored; 9352 9353 public: 9354 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 9355 bool IsIgnored) 9356 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 9357 if (!IsIgnored) { 9358 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 9359 /*Map*/ diag::Severity::Ignored, Loc); 9360 } 9361 } 9362 ~DiagsUninitializedSeveretyRAII() { 9363 if (!IsIgnored) 9364 Diags.popMappings(SavedLoc); 9365 } 9366 }; 9367 } 9368 9369 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 9370 SourceLocation StartLoc, 9371 SourceLocation LParenLoc, 9372 SourceLocation EndLoc) { 9373 SmallVector<Expr *, 8> Vars; 9374 SmallVector<Expr *, 8> PrivateCopies; 9375 SmallVector<Expr *, 8> Inits; 9376 SmallVector<Decl *, 4> ExprCaptures; 9377 bool IsImplicitClause = 9378 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 9379 auto ImplicitClauseLoc = DSAStack->getConstructLoc(); 9380 9381 for (auto &RefExpr : VarList) { 9382 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 9383 SourceLocation ELoc; 9384 SourceRange ERange; 9385 Expr *SimpleRefExpr = RefExpr; 9386 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 9387 if (Res.second) { 9388 // It will be analyzed later. 9389 Vars.push_back(RefExpr); 9390 PrivateCopies.push_back(nullptr); 9391 Inits.push_back(nullptr); 9392 } 9393 ValueDecl *D = Res.first; 9394 if (!D) 9395 continue; 9396 9397 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 9398 QualType Type = D->getType(); 9399 auto *VD = dyn_cast<VarDecl>(D); 9400 9401 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 9402 // A variable that appears in a private clause must not have an incomplete 9403 // type or a reference type. 9404 if (RequireCompleteType(ELoc, Type, 9405 diag::err_omp_firstprivate_incomplete_type)) 9406 continue; 9407 Type = Type.getNonReferenceType(); 9408 9409 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 9410 // A variable of class type (or array thereof) that appears in a private 9411 // clause requires an accessible, unambiguous copy constructor for the 9412 // class type. 9413 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 9414 9415 // If an implicit firstprivate variable found it was checked already. 9416 DSAStackTy::DSAVarData TopDVar; 9417 if (!IsImplicitClause) { 9418 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 9419 TopDVar = DVar; 9420 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 9421 bool IsConstant = ElemType.isConstant(Context); 9422 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 9423 // A list item that specifies a given variable may not appear in more 9424 // than one clause on the same directive, except that a variable may be 9425 // specified in both firstprivate and lastprivate clauses. 9426 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 9427 // A list item may appear in a firstprivate or lastprivate clause but not 9428 // both. 9429 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 9430 (isOpenMPDistributeDirective(CurrDir) || 9431 DVar.CKind != OMPC_lastprivate) && 9432 DVar.RefExpr) { 9433 Diag(ELoc, diag::err_omp_wrong_dsa) 9434 << getOpenMPClauseName(DVar.CKind) 9435 << getOpenMPClauseName(OMPC_firstprivate); 9436 ReportOriginalDSA(*this, DSAStack, D, DVar); 9437 continue; 9438 } 9439 9440 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 9441 // in a Construct] 9442 // Variables with the predetermined data-sharing attributes may not be 9443 // listed in data-sharing attributes clauses, except for the cases 9444 // listed below. For these exceptions only, listing a predetermined 9445 // variable in a data-sharing attribute clause is allowed and overrides 9446 // the variable's predetermined data-sharing attributes. 9447 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 9448 // in a Construct, C/C++, p.2] 9449 // Variables with const-qualified type having no mutable member may be 9450 // listed in a firstprivate clause, even if they are static data members. 9451 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 9452 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 9453 Diag(ELoc, diag::err_omp_wrong_dsa) 9454 << getOpenMPClauseName(DVar.CKind) 9455 << getOpenMPClauseName(OMPC_firstprivate); 9456 ReportOriginalDSA(*this, DSAStack, D, DVar); 9457 continue; 9458 } 9459 9460 // OpenMP [2.9.3.4, Restrictions, p.2] 9461 // A list item that is private within a parallel region must not appear 9462 // in a firstprivate clause on a worksharing construct if any of the 9463 // worksharing regions arising from the worksharing construct ever bind 9464 // to any of the parallel regions arising from the parallel construct. 9465 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 9466 // A list item that is private within a teams region must not appear in a 9467 // firstprivate clause on a distribute construct if any of the distribute 9468 // regions arising from the distribute construct ever bind to any of the 9469 // teams regions arising from the teams construct. 9470 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 9471 // A list item that appears in a reduction clause of a teams construct 9472 // must not appear in a firstprivate clause on a distribute construct if 9473 // any of the distribute regions arising from the distribute construct 9474 // ever bind to any of the teams regions arising from the teams construct. 9475 if ((isOpenMPWorksharingDirective(CurrDir) || 9476 isOpenMPDistributeDirective(CurrDir)) && 9477 !isOpenMPParallelDirective(CurrDir) && 9478 !isOpenMPTeamsDirective(CurrDir)) { 9479 DVar = DSAStack->getImplicitDSA(D, true); 9480 if (DVar.CKind != OMPC_shared && 9481 (isOpenMPParallelDirective(DVar.DKind) || 9482 isOpenMPTeamsDirective(DVar.DKind) || 9483 DVar.DKind == OMPD_unknown)) { 9484 Diag(ELoc, diag::err_omp_required_access) 9485 << getOpenMPClauseName(OMPC_firstprivate) 9486 << getOpenMPClauseName(OMPC_shared); 9487 ReportOriginalDSA(*this, DSAStack, D, DVar); 9488 continue; 9489 } 9490 } 9491 // OpenMP [2.9.3.4, Restrictions, p.3] 9492 // A list item that appears in a reduction clause of a parallel construct 9493 // must not appear in a firstprivate clause on a worksharing or task 9494 // construct if any of the worksharing or task regions arising from the 9495 // worksharing or task construct ever bind to any of the parallel regions 9496 // arising from the parallel construct. 9497 // OpenMP [2.9.3.4, Restrictions, p.4] 9498 // A list item that appears in a reduction clause in worksharing 9499 // construct must not appear in a firstprivate clause in a task construct 9500 // encountered during execution of any of the worksharing regions arising 9501 // from the worksharing construct. 9502 if (isOpenMPTaskingDirective(CurrDir)) { 9503 DVar = DSAStack->hasInnermostDSA( 9504 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 9505 [](OpenMPDirectiveKind K) -> bool { 9506 return isOpenMPParallelDirective(K) || 9507 isOpenMPWorksharingDirective(K) || 9508 isOpenMPTeamsDirective(K); 9509 }, 9510 /*FromParent=*/true); 9511 if (DVar.CKind == OMPC_reduction && 9512 (isOpenMPParallelDirective(DVar.DKind) || 9513 isOpenMPWorksharingDirective(DVar.DKind) || 9514 isOpenMPTeamsDirective(DVar.DKind))) { 9515 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 9516 << getOpenMPDirectiveName(DVar.DKind); 9517 ReportOriginalDSA(*this, DSAStack, D, DVar); 9518 continue; 9519 } 9520 } 9521 9522 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 9523 // A list item cannot appear in both a map clause and a data-sharing 9524 // attribute clause on the same construct 9525 if (isOpenMPTargetExecutionDirective(CurrDir)) { 9526 OpenMPClauseKind ConflictKind; 9527 if (DSAStack->checkMappableExprComponentListsForDecl( 9528 VD, /*CurrentRegionOnly=*/true, 9529 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 9530 OpenMPClauseKind WhereFoundClauseKind) -> bool { 9531 ConflictKind = WhereFoundClauseKind; 9532 return true; 9533 })) { 9534 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 9535 << getOpenMPClauseName(OMPC_firstprivate) 9536 << getOpenMPClauseName(ConflictKind) 9537 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 9538 ReportOriginalDSA(*this, DSAStack, D, DVar); 9539 continue; 9540 } 9541 } 9542 } 9543 9544 // Variably modified types are not supported for tasks. 9545 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 9546 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 9547 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 9548 << getOpenMPClauseName(OMPC_firstprivate) << Type 9549 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 9550 bool IsDecl = 9551 !VD || 9552 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9553 Diag(D->getLocation(), 9554 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9555 << D; 9556 continue; 9557 } 9558 9559 Type = Type.getUnqualifiedType(); 9560 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 9561 D->hasAttrs() ? &D->getAttrs() : nullptr); 9562 // Generate helper private variable and initialize it with the value of the 9563 // original variable. The address of the original variable is replaced by 9564 // the address of the new private variable in the CodeGen. This new variable 9565 // is not added to IdResolver, so the code in the OpenMP region uses 9566 // original variable for proper diagnostics and variable capturing. 9567 Expr *VDInitRefExpr = nullptr; 9568 // For arrays generate initializer for single element and replace it by the 9569 // original array element in CodeGen. 9570 if (Type->isArrayType()) { 9571 auto VDInit = 9572 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 9573 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 9574 auto Init = DefaultLvalueConversion(VDInitRefExpr).get(); 9575 ElemType = ElemType.getUnqualifiedType(); 9576 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 9577 ".firstprivate.temp"); 9578 InitializedEntity Entity = 9579 InitializedEntity::InitializeVariable(VDInitTemp); 9580 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 9581 9582 InitializationSequence InitSeq(*this, Entity, Kind, Init); 9583 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 9584 if (Result.isInvalid()) 9585 VDPrivate->setInvalidDecl(); 9586 else 9587 VDPrivate->setInit(Result.getAs<Expr>()); 9588 // Remove temp variable declaration. 9589 Context.Deallocate(VDInitTemp); 9590 } else { 9591 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 9592 ".firstprivate.temp"); 9593 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 9594 RefExpr->getExprLoc()); 9595 AddInitializerToDecl(VDPrivate, 9596 DefaultLvalueConversion(VDInitRefExpr).get(), 9597 /*DirectInit=*/false); 9598 } 9599 if (VDPrivate->isInvalidDecl()) { 9600 if (IsImplicitClause) { 9601 Diag(RefExpr->getExprLoc(), 9602 diag::note_omp_task_predetermined_firstprivate_here); 9603 } 9604 continue; 9605 } 9606 CurContext->addDecl(VDPrivate); 9607 auto VDPrivateRefExpr = buildDeclRefExpr( 9608 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 9609 RefExpr->getExprLoc()); 9610 DeclRefExpr *Ref = nullptr; 9611 if (!VD && !CurContext->isDependentContext()) { 9612 if (TopDVar.CKind == OMPC_lastprivate) 9613 Ref = TopDVar.PrivateCopy; 9614 else { 9615 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 9616 if (!IsOpenMPCapturedDecl(D)) 9617 ExprCaptures.push_back(Ref->getDecl()); 9618 } 9619 } 9620 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 9621 Vars.push_back((VD || CurContext->isDependentContext()) 9622 ? RefExpr->IgnoreParens() 9623 : Ref); 9624 PrivateCopies.push_back(VDPrivateRefExpr); 9625 Inits.push_back(VDInitRefExpr); 9626 } 9627 9628 if (Vars.empty()) 9629 return nullptr; 9630 9631 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 9632 Vars, PrivateCopies, Inits, 9633 buildPreInits(Context, ExprCaptures)); 9634 } 9635 9636 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 9637 SourceLocation StartLoc, 9638 SourceLocation LParenLoc, 9639 SourceLocation EndLoc) { 9640 SmallVector<Expr *, 8> Vars; 9641 SmallVector<Expr *, 8> SrcExprs; 9642 SmallVector<Expr *, 8> DstExprs; 9643 SmallVector<Expr *, 8> AssignmentOps; 9644 SmallVector<Decl *, 4> ExprCaptures; 9645 SmallVector<Expr *, 4> ExprPostUpdates; 9646 for (auto &RefExpr : VarList) { 9647 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 9648 SourceLocation ELoc; 9649 SourceRange ERange; 9650 Expr *SimpleRefExpr = RefExpr; 9651 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 9652 if (Res.second) { 9653 // It will be analyzed later. 9654 Vars.push_back(RefExpr); 9655 SrcExprs.push_back(nullptr); 9656 DstExprs.push_back(nullptr); 9657 AssignmentOps.push_back(nullptr); 9658 } 9659 ValueDecl *D = Res.first; 9660 if (!D) 9661 continue; 9662 9663 QualType Type = D->getType(); 9664 auto *VD = dyn_cast<VarDecl>(D); 9665 9666 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 9667 // A variable that appears in a lastprivate clause must not have an 9668 // incomplete type or a reference type. 9669 if (RequireCompleteType(ELoc, Type, 9670 diag::err_omp_lastprivate_incomplete_type)) 9671 continue; 9672 Type = Type.getNonReferenceType(); 9673 9674 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 9675 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 9676 // in a Construct] 9677 // Variables with the predetermined data-sharing attributes may not be 9678 // listed in data-sharing attributes clauses, except for the cases 9679 // listed below. 9680 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 9681 // A list item may appear in a firstprivate or lastprivate clause but not 9682 // both. 9683 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 9684 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 9685 (isOpenMPDistributeDirective(CurrDir) || 9686 DVar.CKind != OMPC_firstprivate) && 9687 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 9688 Diag(ELoc, diag::err_omp_wrong_dsa) 9689 << getOpenMPClauseName(DVar.CKind) 9690 << getOpenMPClauseName(OMPC_lastprivate); 9691 ReportOriginalDSA(*this, DSAStack, D, DVar); 9692 continue; 9693 } 9694 9695 // OpenMP [2.14.3.5, Restrictions, p.2] 9696 // A list item that is private within a parallel region, or that appears in 9697 // the reduction clause of a parallel construct, must not appear in a 9698 // lastprivate clause on a worksharing construct if any of the corresponding 9699 // worksharing regions ever binds to any of the corresponding parallel 9700 // regions. 9701 DSAStackTy::DSAVarData TopDVar = DVar; 9702 if (isOpenMPWorksharingDirective(CurrDir) && 9703 !isOpenMPParallelDirective(CurrDir) && 9704 !isOpenMPTeamsDirective(CurrDir)) { 9705 DVar = DSAStack->getImplicitDSA(D, true); 9706 if (DVar.CKind != OMPC_shared) { 9707 Diag(ELoc, diag::err_omp_required_access) 9708 << getOpenMPClauseName(OMPC_lastprivate) 9709 << getOpenMPClauseName(OMPC_shared); 9710 ReportOriginalDSA(*this, DSAStack, D, DVar); 9711 continue; 9712 } 9713 } 9714 9715 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 9716 // A variable of class type (or array thereof) that appears in a 9717 // lastprivate clause requires an accessible, unambiguous default 9718 // constructor for the class type, unless the list item is also specified 9719 // in a firstprivate clause. 9720 // A variable of class type (or array thereof) that appears in a 9721 // lastprivate clause requires an accessible, unambiguous copy assignment 9722 // operator for the class type. 9723 Type = Context.getBaseElementType(Type).getNonReferenceType(); 9724 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(), 9725 Type.getUnqualifiedType(), ".lastprivate.src", 9726 D->hasAttrs() ? &D->getAttrs() : nullptr); 9727 auto *PseudoSrcExpr = 9728 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 9729 auto *DstVD = 9730 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 9731 D->hasAttrs() ? &D->getAttrs() : nullptr); 9732 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 9733 // For arrays generate assignment operation for single element and replace 9734 // it by the original array element in CodeGen. 9735 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 9736 PseudoDstExpr, PseudoSrcExpr); 9737 if (AssignmentOp.isInvalid()) 9738 continue; 9739 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 9740 /*DiscardedValue=*/true); 9741 if (AssignmentOp.isInvalid()) 9742 continue; 9743 9744 DeclRefExpr *Ref = nullptr; 9745 if (!VD && !CurContext->isDependentContext()) { 9746 if (TopDVar.CKind == OMPC_firstprivate) 9747 Ref = TopDVar.PrivateCopy; 9748 else { 9749 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 9750 if (!IsOpenMPCapturedDecl(D)) 9751 ExprCaptures.push_back(Ref->getDecl()); 9752 } 9753 if (TopDVar.CKind == OMPC_firstprivate || 9754 (!IsOpenMPCapturedDecl(D) && 9755 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 9756 ExprResult RefRes = DefaultLvalueConversion(Ref); 9757 if (!RefRes.isUsable()) 9758 continue; 9759 ExprResult PostUpdateRes = 9760 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 9761 RefRes.get()); 9762 if (!PostUpdateRes.isUsable()) 9763 continue; 9764 ExprPostUpdates.push_back( 9765 IgnoredValueConversions(PostUpdateRes.get()).get()); 9766 } 9767 } 9768 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 9769 Vars.push_back((VD || CurContext->isDependentContext()) 9770 ? RefExpr->IgnoreParens() 9771 : Ref); 9772 SrcExprs.push_back(PseudoSrcExpr); 9773 DstExprs.push_back(PseudoDstExpr); 9774 AssignmentOps.push_back(AssignmentOp.get()); 9775 } 9776 9777 if (Vars.empty()) 9778 return nullptr; 9779 9780 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 9781 Vars, SrcExprs, DstExprs, AssignmentOps, 9782 buildPreInits(Context, ExprCaptures), 9783 buildPostUpdate(*this, ExprPostUpdates)); 9784 } 9785 9786 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 9787 SourceLocation StartLoc, 9788 SourceLocation LParenLoc, 9789 SourceLocation EndLoc) { 9790 SmallVector<Expr *, 8> Vars; 9791 for (auto &RefExpr : VarList) { 9792 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 9793 SourceLocation ELoc; 9794 SourceRange ERange; 9795 Expr *SimpleRefExpr = RefExpr; 9796 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 9797 if (Res.second) { 9798 // It will be analyzed later. 9799 Vars.push_back(RefExpr); 9800 } 9801 ValueDecl *D = Res.first; 9802 if (!D) 9803 continue; 9804 9805 auto *VD = dyn_cast<VarDecl>(D); 9806 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 9807 // in a Construct] 9808 // Variables with the predetermined data-sharing attributes may not be 9809 // listed in data-sharing attributes clauses, except for the cases 9810 // listed below. For these exceptions only, listing a predetermined 9811 // variable in a data-sharing attribute clause is allowed and overrides 9812 // the variable's predetermined data-sharing attributes. 9813 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 9814 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 9815 DVar.RefExpr) { 9816 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 9817 << getOpenMPClauseName(OMPC_shared); 9818 ReportOriginalDSA(*this, DSAStack, D, DVar); 9819 continue; 9820 } 9821 9822 DeclRefExpr *Ref = nullptr; 9823 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 9824 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 9825 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 9826 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 9827 ? RefExpr->IgnoreParens() 9828 : Ref); 9829 } 9830 9831 if (Vars.empty()) 9832 return nullptr; 9833 9834 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 9835 } 9836 9837 namespace { 9838 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 9839 DSAStackTy *Stack; 9840 9841 public: 9842 bool VisitDeclRefExpr(DeclRefExpr *E) { 9843 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { 9844 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false); 9845 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 9846 return false; 9847 if (DVar.CKind != OMPC_unknown) 9848 return true; 9849 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 9850 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 9851 /*FromParent=*/true); 9852 if (DVarPrivate.CKind != OMPC_unknown) 9853 return true; 9854 return false; 9855 } 9856 return false; 9857 } 9858 bool VisitStmt(Stmt *S) { 9859 for (auto Child : S->children()) { 9860 if (Child && Visit(Child)) 9861 return true; 9862 } 9863 return false; 9864 } 9865 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 9866 }; 9867 } // namespace 9868 9869 namespace { 9870 // Transform MemberExpression for specified FieldDecl of current class to 9871 // DeclRefExpr to specified OMPCapturedExprDecl. 9872 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 9873 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 9874 ValueDecl *Field; 9875 DeclRefExpr *CapturedExpr; 9876 9877 public: 9878 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 9879 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 9880 9881 ExprResult TransformMemberExpr(MemberExpr *E) { 9882 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 9883 E->getMemberDecl() == Field) { 9884 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 9885 return CapturedExpr; 9886 } 9887 return BaseTransform::TransformMemberExpr(E); 9888 } 9889 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 9890 }; 9891 } // namespace 9892 9893 template <typename T> 9894 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups, 9895 const llvm::function_ref<T(ValueDecl *)> &Gen) { 9896 for (auto &Set : Lookups) { 9897 for (auto *D : Set) { 9898 if (auto Res = Gen(cast<ValueDecl>(D))) 9899 return Res; 9900 } 9901 } 9902 return T(); 9903 } 9904 9905 static ExprResult 9906 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 9907 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 9908 const DeclarationNameInfo &ReductionId, QualType Ty, 9909 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 9910 if (ReductionIdScopeSpec.isInvalid()) 9911 return ExprError(); 9912 SmallVector<UnresolvedSet<8>, 4> Lookups; 9913 if (S) { 9914 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 9915 Lookup.suppressDiagnostics(); 9916 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 9917 auto *D = Lookup.getRepresentativeDecl(); 9918 do { 9919 S = S->getParent(); 9920 } while (S && !S->isDeclScope(D)); 9921 if (S) 9922 S = S->getParent(); 9923 Lookups.push_back(UnresolvedSet<8>()); 9924 Lookups.back().append(Lookup.begin(), Lookup.end()); 9925 Lookup.clear(); 9926 } 9927 } else if (auto *ULE = 9928 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 9929 Lookups.push_back(UnresolvedSet<8>()); 9930 Decl *PrevD = nullptr; 9931 for (auto *D : ULE->decls()) { 9932 if (D == PrevD) 9933 Lookups.push_back(UnresolvedSet<8>()); 9934 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D)) 9935 Lookups.back().addDecl(DRD); 9936 PrevD = D; 9937 } 9938 } 9939 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || 9940 Ty->isInstantiationDependentType() || 9941 Ty->containsUnexpandedParameterPack() || 9942 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool { 9943 return !D->isInvalidDecl() && 9944 (D->getType()->isDependentType() || 9945 D->getType()->isInstantiationDependentType() || 9946 D->getType()->containsUnexpandedParameterPack()); 9947 })) { 9948 UnresolvedSet<8> ResSet; 9949 for (auto &Set : Lookups) { 9950 ResSet.append(Set.begin(), Set.end()); 9951 // The last item marks the end of all declarations at the specified scope. 9952 ResSet.addDecl(Set[Set.size() - 1]); 9953 } 9954 return UnresolvedLookupExpr::Create( 9955 SemaRef.Context, /*NamingClass=*/nullptr, 9956 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 9957 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 9958 } 9959 if (auto *VD = filterLookupForUDR<ValueDecl *>( 9960 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 9961 if (!D->isInvalidDecl() && 9962 SemaRef.Context.hasSameType(D->getType(), Ty)) 9963 return D; 9964 return nullptr; 9965 })) 9966 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 9967 if (auto *VD = filterLookupForUDR<ValueDecl *>( 9968 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 9969 if (!D->isInvalidDecl() && 9970 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 9971 !Ty.isMoreQualifiedThan(D->getType())) 9972 return D; 9973 return nullptr; 9974 })) { 9975 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 9976 /*DetectVirtual=*/false); 9977 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 9978 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 9979 VD->getType().getUnqualifiedType()))) { 9980 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(), 9981 /*DiagID=*/0) != 9982 Sema::AR_inaccessible) { 9983 SemaRef.BuildBasePathArray(Paths, BasePath); 9984 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 9985 } 9986 } 9987 } 9988 } 9989 if (ReductionIdScopeSpec.isSet()) { 9990 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range; 9991 return ExprError(); 9992 } 9993 return ExprEmpty(); 9994 } 9995 9996 namespace { 9997 /// Data for the reduction-based clauses. 9998 struct ReductionData { 9999 /// List of original reduction items. 10000 SmallVector<Expr *, 8> Vars; 10001 /// List of private copies of the reduction items. 10002 SmallVector<Expr *, 8> Privates; 10003 /// LHS expressions for the reduction_op expressions. 10004 SmallVector<Expr *, 8> LHSs; 10005 /// RHS expressions for the reduction_op expressions. 10006 SmallVector<Expr *, 8> RHSs; 10007 /// Reduction operation expression. 10008 SmallVector<Expr *, 8> ReductionOps; 10009 /// Taskgroup descriptors for the corresponding reduction items in 10010 /// in_reduction clauses. 10011 SmallVector<Expr *, 8> TaskgroupDescriptors; 10012 /// List of captures for clause. 10013 SmallVector<Decl *, 4> ExprCaptures; 10014 /// List of postupdate expressions. 10015 SmallVector<Expr *, 4> ExprPostUpdates; 10016 ReductionData() = delete; 10017 /// Reserves required memory for the reduction data. 10018 ReductionData(unsigned Size) { 10019 Vars.reserve(Size); 10020 Privates.reserve(Size); 10021 LHSs.reserve(Size); 10022 RHSs.reserve(Size); 10023 ReductionOps.reserve(Size); 10024 TaskgroupDescriptors.reserve(Size); 10025 ExprCaptures.reserve(Size); 10026 ExprPostUpdates.reserve(Size); 10027 } 10028 /// Stores reduction item and reduction operation only (required for dependent 10029 /// reduction item). 10030 void push(Expr *Item, Expr *ReductionOp) { 10031 Vars.emplace_back(Item); 10032 Privates.emplace_back(nullptr); 10033 LHSs.emplace_back(nullptr); 10034 RHSs.emplace_back(nullptr); 10035 ReductionOps.emplace_back(ReductionOp); 10036 TaskgroupDescriptors.emplace_back(nullptr); 10037 } 10038 /// Stores reduction data. 10039 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp, 10040 Expr *TaskgroupDescriptor) { 10041 Vars.emplace_back(Item); 10042 Privates.emplace_back(Private); 10043 LHSs.emplace_back(LHS); 10044 RHSs.emplace_back(RHS); 10045 ReductionOps.emplace_back(ReductionOp); 10046 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor); 10047 } 10048 }; 10049 } // namespace 10050 10051 static bool CheckOMPArraySectionConstantForReduction( 10052 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement, 10053 SmallVectorImpl<llvm::APSInt> &ArraySizes) { 10054 const Expr *Length = OASE->getLength(); 10055 if (Length == nullptr) { 10056 // For array sections of the form [1:] or [:], we would need to analyze 10057 // the lower bound... 10058 if (OASE->getColonLoc().isValid()) 10059 return false; 10060 10061 // This is an array subscript which has implicit length 1! 10062 SingleElement = true; 10063 ArraySizes.push_back(llvm::APSInt::get(1)); 10064 } else { 10065 llvm::APSInt ConstantLengthValue; 10066 if (!Length->EvaluateAsInt(ConstantLengthValue, Context)) 10067 return false; 10068 10069 SingleElement = (ConstantLengthValue.getSExtValue() == 1); 10070 ArraySizes.push_back(ConstantLengthValue); 10071 } 10072 10073 // Get the base of this array section and walk up from there. 10074 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts(); 10075 10076 // We require length = 1 for all array sections except the right-most to 10077 // guarantee that the memory region is contiguous and has no holes in it. 10078 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) { 10079 Length = TempOASE->getLength(); 10080 if (Length == nullptr) { 10081 // For array sections of the form [1:] or [:], we would need to analyze 10082 // the lower bound... 10083 if (OASE->getColonLoc().isValid()) 10084 return false; 10085 10086 // This is an array subscript which has implicit length 1! 10087 ArraySizes.push_back(llvm::APSInt::get(1)); 10088 } else { 10089 llvm::APSInt ConstantLengthValue; 10090 if (!Length->EvaluateAsInt(ConstantLengthValue, Context) || 10091 ConstantLengthValue.getSExtValue() != 1) 10092 return false; 10093 10094 ArraySizes.push_back(ConstantLengthValue); 10095 } 10096 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 10097 } 10098 10099 // If we have a single element, we don't need to add the implicit lengths. 10100 if (!SingleElement) { 10101 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) { 10102 // Has implicit length 1! 10103 ArraySizes.push_back(llvm::APSInt::get(1)); 10104 Base = TempASE->getBase()->IgnoreParenImpCasts(); 10105 } 10106 } 10107 10108 // This array section can be privatized as a single value or as a constant 10109 // sized array. 10110 return true; 10111 } 10112 10113 static bool ActOnOMPReductionKindClause( 10114 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, 10115 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 10116 SourceLocation ColonLoc, SourceLocation EndLoc, 10117 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 10118 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { 10119 auto DN = ReductionId.getName(); 10120 auto OOK = DN.getCXXOverloadedOperator(); 10121 BinaryOperatorKind BOK = BO_Comma; 10122 10123 ASTContext &Context = S.Context; 10124 // OpenMP [2.14.3.6, reduction clause] 10125 // C 10126 // reduction-identifier is either an identifier or one of the following 10127 // operators: +, -, *, &, |, ^, && and || 10128 // C++ 10129 // reduction-identifier is either an id-expression or one of the following 10130 // operators: +, -, *, &, |, ^, && and || 10131 switch (OOK) { 10132 case OO_Plus: 10133 case OO_Minus: 10134 BOK = BO_Add; 10135 break; 10136 case OO_Star: 10137 BOK = BO_Mul; 10138 break; 10139 case OO_Amp: 10140 BOK = BO_And; 10141 break; 10142 case OO_Pipe: 10143 BOK = BO_Or; 10144 break; 10145 case OO_Caret: 10146 BOK = BO_Xor; 10147 break; 10148 case OO_AmpAmp: 10149 BOK = BO_LAnd; 10150 break; 10151 case OO_PipePipe: 10152 BOK = BO_LOr; 10153 break; 10154 case OO_New: 10155 case OO_Delete: 10156 case OO_Array_New: 10157 case OO_Array_Delete: 10158 case OO_Slash: 10159 case OO_Percent: 10160 case OO_Tilde: 10161 case OO_Exclaim: 10162 case OO_Equal: 10163 case OO_Less: 10164 case OO_Greater: 10165 case OO_LessEqual: 10166 case OO_GreaterEqual: 10167 case OO_PlusEqual: 10168 case OO_MinusEqual: 10169 case OO_StarEqual: 10170 case OO_SlashEqual: 10171 case OO_PercentEqual: 10172 case OO_CaretEqual: 10173 case OO_AmpEqual: 10174 case OO_PipeEqual: 10175 case OO_LessLess: 10176 case OO_GreaterGreater: 10177 case OO_LessLessEqual: 10178 case OO_GreaterGreaterEqual: 10179 case OO_EqualEqual: 10180 case OO_ExclaimEqual: 10181 case OO_Spaceship: 10182 case OO_PlusPlus: 10183 case OO_MinusMinus: 10184 case OO_Comma: 10185 case OO_ArrowStar: 10186 case OO_Arrow: 10187 case OO_Call: 10188 case OO_Subscript: 10189 case OO_Conditional: 10190 case OO_Coawait: 10191 case NUM_OVERLOADED_OPERATORS: 10192 llvm_unreachable("Unexpected reduction identifier"); 10193 case OO_None: 10194 if (auto *II = DN.getAsIdentifierInfo()) { 10195 if (II->isStr("max")) 10196 BOK = BO_GT; 10197 else if (II->isStr("min")) 10198 BOK = BO_LT; 10199 } 10200 break; 10201 } 10202 SourceRange ReductionIdRange; 10203 if (ReductionIdScopeSpec.isValid()) 10204 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 10205 else 10206 ReductionIdRange.setBegin(ReductionId.getBeginLoc()); 10207 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 10208 10209 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 10210 bool FirstIter = true; 10211 for (auto RefExpr : VarList) { 10212 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 10213 // OpenMP [2.1, C/C++] 10214 // A list item is a variable or array section, subject to the restrictions 10215 // specified in Section 2.4 on page 42 and in each of the sections 10216 // describing clauses and directives for which a list appears. 10217 // OpenMP [2.14.3.3, Restrictions, p.1] 10218 // A variable that is part of another variable (as an array or 10219 // structure element) cannot appear in a private clause. 10220 if (!FirstIter && IR != ER) 10221 ++IR; 10222 FirstIter = false; 10223 SourceLocation ELoc; 10224 SourceRange ERange; 10225 Expr *SimpleRefExpr = RefExpr; 10226 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 10227 /*AllowArraySection=*/true); 10228 if (Res.second) { 10229 // Try to find 'declare reduction' corresponding construct before using 10230 // builtin/overloaded operators. 10231 QualType Type = Context.DependentTy; 10232 CXXCastPath BasePath; 10233 ExprResult DeclareReductionRef = buildDeclareReductionRef( 10234 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 10235 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 10236 Expr *ReductionOp = nullptr; 10237 if (S.CurContext->isDependentContext() && 10238 (DeclareReductionRef.isUnset() || 10239 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 10240 ReductionOp = DeclareReductionRef.get(); 10241 // It will be analyzed later. 10242 RD.push(RefExpr, ReductionOp); 10243 } 10244 ValueDecl *D = Res.first; 10245 if (!D) 10246 continue; 10247 10248 Expr *TaskgroupDescriptor = nullptr; 10249 QualType Type; 10250 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 10251 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 10252 if (ASE) 10253 Type = ASE->getType().getNonReferenceType(); 10254 else if (OASE) { 10255 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 10256 if (auto *ATy = BaseType->getAsArrayTypeUnsafe()) 10257 Type = ATy->getElementType(); 10258 else 10259 Type = BaseType->getPointeeType(); 10260 Type = Type.getNonReferenceType(); 10261 } else 10262 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 10263 auto *VD = dyn_cast<VarDecl>(D); 10264 10265 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 10266 // A variable that appears in a private clause must not have an incomplete 10267 // type or a reference type. 10268 if (S.RequireCompleteType(ELoc, Type, 10269 diag::err_omp_reduction_incomplete_type)) 10270 continue; 10271 // OpenMP [2.14.3.6, reduction clause, Restrictions] 10272 // A list item that appears in a reduction clause must not be 10273 // const-qualified. 10274 if (Type.getNonReferenceType().isConstant(Context)) { 10275 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange; 10276 if (!ASE && !OASE) { 10277 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 10278 VarDecl::DeclarationOnly; 10279 S.Diag(D->getLocation(), 10280 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10281 << D; 10282 } 10283 continue; 10284 } 10285 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 10286 // If a list-item is a reference type then it must bind to the same object 10287 // for all threads of the team. 10288 if (!ASE && !OASE && VD) { 10289 VarDecl *VDDef = VD->getDefinition(); 10290 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 10291 DSARefChecker Check(Stack); 10292 if (Check.Visit(VDDef->getInit())) { 10293 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) 10294 << getOpenMPClauseName(ClauseKind) << ERange; 10295 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 10296 continue; 10297 } 10298 } 10299 } 10300 10301 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 10302 // in a Construct] 10303 // Variables with the predetermined data-sharing attributes may not be 10304 // listed in data-sharing attributes clauses, except for the cases 10305 // listed below. For these exceptions only, listing a predetermined 10306 // variable in a data-sharing attribute clause is allowed and overrides 10307 // the variable's predetermined data-sharing attributes. 10308 // OpenMP [2.14.3.6, Restrictions, p.3] 10309 // Any number of reduction clauses can be specified on the directive, 10310 // but a list item can appear only once in the reduction clauses for that 10311 // directive. 10312 DSAStackTy::DSAVarData DVar; 10313 DVar = Stack->getTopDSA(D, false); 10314 if (DVar.CKind == OMPC_reduction) { 10315 S.Diag(ELoc, diag::err_omp_once_referenced) 10316 << getOpenMPClauseName(ClauseKind); 10317 if (DVar.RefExpr) 10318 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 10319 continue; 10320 } else if (DVar.CKind != OMPC_unknown) { 10321 S.Diag(ELoc, diag::err_omp_wrong_dsa) 10322 << getOpenMPClauseName(DVar.CKind) 10323 << getOpenMPClauseName(OMPC_reduction); 10324 ReportOriginalDSA(S, Stack, D, DVar); 10325 continue; 10326 } 10327 10328 // OpenMP [2.14.3.6, Restrictions, p.1] 10329 // A list item that appears in a reduction clause of a worksharing 10330 // construct must be shared in the parallel regions to which any of the 10331 // worksharing regions arising from the worksharing construct bind. 10332 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); 10333 if (isOpenMPWorksharingDirective(CurrDir) && 10334 !isOpenMPParallelDirective(CurrDir) && 10335 !isOpenMPTeamsDirective(CurrDir)) { 10336 DVar = Stack->getImplicitDSA(D, true); 10337 if (DVar.CKind != OMPC_shared) { 10338 S.Diag(ELoc, diag::err_omp_required_access) 10339 << getOpenMPClauseName(OMPC_reduction) 10340 << getOpenMPClauseName(OMPC_shared); 10341 ReportOriginalDSA(S, Stack, D, DVar); 10342 continue; 10343 } 10344 } 10345 10346 // Try to find 'declare reduction' corresponding construct before using 10347 // builtin/overloaded operators. 10348 CXXCastPath BasePath; 10349 ExprResult DeclareReductionRef = buildDeclareReductionRef( 10350 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 10351 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 10352 if (DeclareReductionRef.isInvalid()) 10353 continue; 10354 if (S.CurContext->isDependentContext() && 10355 (DeclareReductionRef.isUnset() || 10356 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 10357 RD.push(RefExpr, DeclareReductionRef.get()); 10358 continue; 10359 } 10360 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 10361 // Not allowed reduction identifier is found. 10362 S.Diag(ReductionId.getLocStart(), 10363 diag::err_omp_unknown_reduction_identifier) 10364 << Type << ReductionIdRange; 10365 continue; 10366 } 10367 10368 // OpenMP [2.14.3.6, reduction clause, Restrictions] 10369 // The type of a list item that appears in a reduction clause must be valid 10370 // for the reduction-identifier. For a max or min reduction in C, the type 10371 // of the list item must be an allowed arithmetic data type: char, int, 10372 // float, double, or _Bool, possibly modified with long, short, signed, or 10373 // unsigned. For a max or min reduction in C++, the type of the list item 10374 // must be an allowed arithmetic data type: char, wchar_t, int, float, 10375 // double, or bool, possibly modified with long, short, signed, or unsigned. 10376 if (DeclareReductionRef.isUnset()) { 10377 if ((BOK == BO_GT || BOK == BO_LT) && 10378 !(Type->isScalarType() || 10379 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 10380 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 10381 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; 10382 if (!ASE && !OASE) { 10383 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 10384 VarDecl::DeclarationOnly; 10385 S.Diag(D->getLocation(), 10386 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10387 << D; 10388 } 10389 continue; 10390 } 10391 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 10392 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { 10393 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) 10394 << getOpenMPClauseName(ClauseKind); 10395 if (!ASE && !OASE) { 10396 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 10397 VarDecl::DeclarationOnly; 10398 S.Diag(D->getLocation(), 10399 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10400 << D; 10401 } 10402 continue; 10403 } 10404 } 10405 10406 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 10407 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", 10408 D->hasAttrs() ? &D->getAttrs() : nullptr); 10409 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), 10410 D->hasAttrs() ? &D->getAttrs() : nullptr); 10411 auto PrivateTy = Type; 10412 10413 // Try if we can determine constant lengths for all array sections and avoid 10414 // the VLA. 10415 bool ConstantLengthOASE = false; 10416 if (OASE) { 10417 bool SingleElement; 10418 llvm::SmallVector<llvm::APSInt, 4> ArraySizes; 10419 ConstantLengthOASE = CheckOMPArraySectionConstantForReduction( 10420 Context, OASE, SingleElement, ArraySizes); 10421 10422 // If we don't have a single element, we must emit a constant array type. 10423 if (ConstantLengthOASE && !SingleElement) { 10424 for (auto &Size : ArraySizes) { 10425 PrivateTy = Context.getConstantArrayType( 10426 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0); 10427 } 10428 } 10429 } 10430 10431 if ((OASE && !ConstantLengthOASE) || 10432 (!OASE && !ASE && 10433 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 10434 if (!Context.getTargetInfo().isVLASupported() && 10435 S.shouldDiagnoseTargetSupportFromOpenMP()) { 10436 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE; 10437 S.Diag(ELoc, diag::note_vla_unsupported); 10438 continue; 10439 } 10440 // For arrays/array sections only: 10441 // Create pseudo array type for private copy. The size for this array will 10442 // be generated during codegen. 10443 // For array subscripts or single variables Private Ty is the same as Type 10444 // (type of the variable or single array element). 10445 PrivateTy = Context.getVariableArrayType( 10446 Type, 10447 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue), 10448 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 10449 } else if (!ASE && !OASE && 10450 Context.getAsArrayType(D->getType().getNonReferenceType())) 10451 PrivateTy = D->getType().getNonReferenceType(); 10452 // Private copy. 10453 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(), 10454 D->hasAttrs() ? &D->getAttrs() : nullptr); 10455 // Add initializer for private variable. 10456 Expr *Init = nullptr; 10457 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); 10458 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); 10459 if (DeclareReductionRef.isUsable()) { 10460 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 10461 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 10462 if (DRD->getInitializer()) { 10463 Init = DRDRef; 10464 RHSVD->setInit(DRDRef); 10465 RHSVD->setInitStyle(VarDecl::CallInit); 10466 } 10467 } else { 10468 switch (BOK) { 10469 case BO_Add: 10470 case BO_Xor: 10471 case BO_Or: 10472 case BO_LOr: 10473 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 10474 if (Type->isScalarType() || Type->isAnyComplexType()) 10475 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 10476 break; 10477 case BO_Mul: 10478 case BO_LAnd: 10479 if (Type->isScalarType() || Type->isAnyComplexType()) { 10480 // '*' and '&&' reduction ops - initializer is '1'. 10481 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 10482 } 10483 break; 10484 case BO_And: { 10485 // '&' reduction op - initializer is '~0'. 10486 QualType OrigType = Type; 10487 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 10488 Type = ComplexTy->getElementType(); 10489 if (Type->isRealFloatingType()) { 10490 llvm::APFloat InitValue = 10491 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), 10492 /*isIEEE=*/true); 10493 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 10494 Type, ELoc); 10495 } else if (Type->isScalarType()) { 10496 auto Size = Context.getTypeSize(Type); 10497 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 10498 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 10499 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 10500 } 10501 if (Init && OrigType->isAnyComplexType()) { 10502 // Init = 0xFFFF + 0xFFFFi; 10503 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 10504 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 10505 } 10506 Type = OrigType; 10507 break; 10508 } 10509 case BO_LT: 10510 case BO_GT: { 10511 // 'min' reduction op - initializer is 'Largest representable number in 10512 // the reduction list item type'. 10513 // 'max' reduction op - initializer is 'Least representable number in 10514 // the reduction list item type'. 10515 if (Type->isIntegerType() || Type->isPointerType()) { 10516 bool IsSigned = Type->hasSignedIntegerRepresentation(); 10517 auto Size = Context.getTypeSize(Type); 10518 QualType IntTy = 10519 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 10520 llvm::APInt InitValue = 10521 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 10522 : llvm::APInt::getMinValue(Size) 10523 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 10524 : llvm::APInt::getMaxValue(Size); 10525 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 10526 if (Type->isPointerType()) { 10527 // Cast to pointer type. 10528 auto CastExpr = S.BuildCStyleCastExpr( 10529 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init); 10530 if (CastExpr.isInvalid()) 10531 continue; 10532 Init = CastExpr.get(); 10533 } 10534 } else if (Type->isRealFloatingType()) { 10535 llvm::APFloat InitValue = llvm::APFloat::getLargest( 10536 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 10537 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 10538 Type, ELoc); 10539 } 10540 break; 10541 } 10542 case BO_PtrMemD: 10543 case BO_PtrMemI: 10544 case BO_MulAssign: 10545 case BO_Div: 10546 case BO_Rem: 10547 case BO_Sub: 10548 case BO_Shl: 10549 case BO_Shr: 10550 case BO_LE: 10551 case BO_GE: 10552 case BO_EQ: 10553 case BO_NE: 10554 case BO_Cmp: 10555 case BO_AndAssign: 10556 case BO_XorAssign: 10557 case BO_OrAssign: 10558 case BO_Assign: 10559 case BO_AddAssign: 10560 case BO_SubAssign: 10561 case BO_DivAssign: 10562 case BO_RemAssign: 10563 case BO_ShlAssign: 10564 case BO_ShrAssign: 10565 case BO_Comma: 10566 llvm_unreachable("Unexpected reduction operation"); 10567 } 10568 } 10569 if (Init && DeclareReductionRef.isUnset()) 10570 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 10571 else if (!Init) 10572 S.ActOnUninitializedDecl(RHSVD); 10573 if (RHSVD->isInvalidDecl()) 10574 continue; 10575 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 10576 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) 10577 << Type << ReductionIdRange; 10578 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 10579 VarDecl::DeclarationOnly; 10580 S.Diag(D->getLocation(), 10581 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10582 << D; 10583 continue; 10584 } 10585 // Store initializer for single element in private copy. Will be used during 10586 // codegen. 10587 PrivateVD->setInit(RHSVD->getInit()); 10588 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 10589 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); 10590 ExprResult ReductionOp; 10591 if (DeclareReductionRef.isUsable()) { 10592 QualType RedTy = DeclareReductionRef.get()->getType(); 10593 QualType PtrRedTy = Context.getPointerType(RedTy); 10594 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 10595 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 10596 if (!BasePath.empty()) { 10597 LHS = S.DefaultLvalueConversion(LHS.get()); 10598 RHS = S.DefaultLvalueConversion(RHS.get()); 10599 LHS = ImplicitCastExpr::Create(Context, PtrRedTy, 10600 CK_UncheckedDerivedToBase, LHS.get(), 10601 &BasePath, LHS.get()->getValueKind()); 10602 RHS = ImplicitCastExpr::Create(Context, PtrRedTy, 10603 CK_UncheckedDerivedToBase, RHS.get(), 10604 &BasePath, RHS.get()->getValueKind()); 10605 } 10606 FunctionProtoType::ExtProtoInfo EPI; 10607 QualType Params[] = {PtrRedTy, PtrRedTy}; 10608 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 10609 auto *OVE = new (Context) OpaqueValueExpr( 10610 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 10611 S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); 10612 Expr *Args[] = {LHS.get(), RHS.get()}; 10613 ReductionOp = new (Context) 10614 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); 10615 } else { 10616 ReductionOp = S.BuildBinOp( 10617 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE); 10618 if (ReductionOp.isUsable()) { 10619 if (BOK != BO_LT && BOK != BO_GT) { 10620 ReductionOp = 10621 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(), 10622 BO_Assign, LHSDRE, ReductionOp.get()); 10623 } else { 10624 auto *ConditionalOp = new (Context) 10625 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE, 10626 Type, VK_LValue, OK_Ordinary); 10627 ReductionOp = 10628 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(), 10629 BO_Assign, LHSDRE, ConditionalOp); 10630 } 10631 if (ReductionOp.isUsable()) 10632 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get()); 10633 } 10634 if (!ReductionOp.isUsable()) 10635 continue; 10636 } 10637 10638 // OpenMP [2.15.4.6, Restrictions, p.2] 10639 // A list item that appears in an in_reduction clause of a task construct 10640 // must appear in a task_reduction clause of a construct associated with a 10641 // taskgroup region that includes the participating task in its taskgroup 10642 // set. The construct associated with the innermost region that meets this 10643 // condition must specify the same reduction-identifier as the in_reduction 10644 // clause. 10645 if (ClauseKind == OMPC_in_reduction) { 10646 SourceRange ParentSR; 10647 BinaryOperatorKind ParentBOK; 10648 const Expr *ParentReductionOp; 10649 Expr *ParentBOKTD, *ParentReductionOpTD; 10650 DSAStackTy::DSAVarData ParentBOKDSA = 10651 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK, 10652 ParentBOKTD); 10653 DSAStackTy::DSAVarData ParentReductionOpDSA = 10654 Stack->getTopMostTaskgroupReductionData( 10655 D, ParentSR, ParentReductionOp, ParentReductionOpTD); 10656 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown; 10657 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown; 10658 if (!IsParentBOK && !IsParentReductionOp) { 10659 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction); 10660 continue; 10661 } 10662 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) || 10663 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK || 10664 IsParentReductionOp) { 10665 bool EmitError = true; 10666 if (IsParentReductionOp && DeclareReductionRef.isUsable()) { 10667 llvm::FoldingSetNodeID RedId, ParentRedId; 10668 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true); 10669 DeclareReductionRef.get()->Profile(RedId, Context, 10670 /*Canonical=*/true); 10671 EmitError = RedId != ParentRedId; 10672 } 10673 if (EmitError) { 10674 S.Diag(ReductionId.getLocStart(), 10675 diag::err_omp_reduction_identifier_mismatch) 10676 << ReductionIdRange << RefExpr->getSourceRange(); 10677 S.Diag(ParentSR.getBegin(), 10678 diag::note_omp_previous_reduction_identifier) 10679 << ParentSR 10680 << (IsParentBOK ? ParentBOKDSA.RefExpr 10681 : ParentReductionOpDSA.RefExpr) 10682 ->getSourceRange(); 10683 continue; 10684 } 10685 } 10686 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD; 10687 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined."); 10688 } 10689 10690 DeclRefExpr *Ref = nullptr; 10691 Expr *VarsExpr = RefExpr->IgnoreParens(); 10692 if (!VD && !S.CurContext->isDependentContext()) { 10693 if (ASE || OASE) { 10694 TransformExprToCaptures RebuildToCapture(S, D); 10695 VarsExpr = 10696 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 10697 Ref = RebuildToCapture.getCapturedExpr(); 10698 } else { 10699 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); 10700 } 10701 if (!S.IsOpenMPCapturedDecl(D)) { 10702 RD.ExprCaptures.emplace_back(Ref->getDecl()); 10703 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 10704 ExprResult RefRes = S.DefaultLvalueConversion(Ref); 10705 if (!RefRes.isUsable()) 10706 continue; 10707 ExprResult PostUpdateRes = 10708 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 10709 RefRes.get()); 10710 if (!PostUpdateRes.isUsable()) 10711 continue; 10712 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 10713 Stack->getCurrentDirective() == OMPD_taskgroup) { 10714 S.Diag(RefExpr->getExprLoc(), 10715 diag::err_omp_reduction_non_addressable_expression) 10716 << RefExpr->getSourceRange(); 10717 continue; 10718 } 10719 RD.ExprPostUpdates.emplace_back( 10720 S.IgnoredValueConversions(PostUpdateRes.get()).get()); 10721 } 10722 } 10723 } 10724 // All reduction items are still marked as reduction (to do not increase 10725 // code base size). 10726 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref); 10727 if (CurrDir == OMPD_taskgroup) { 10728 if (DeclareReductionRef.isUsable()) 10729 Stack->addTaskgroupReductionData(D, ReductionIdRange, 10730 DeclareReductionRef.get()); 10731 else 10732 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK); 10733 } 10734 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(), 10735 TaskgroupDescriptor); 10736 } 10737 return RD.Vars.empty(); 10738 } 10739 10740 OMPClause *Sema::ActOnOpenMPReductionClause( 10741 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 10742 SourceLocation ColonLoc, SourceLocation EndLoc, 10743 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 10744 ArrayRef<Expr *> UnresolvedReductions) { 10745 ReductionData RD(VarList.size()); 10746 10747 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, 10748 StartLoc, LParenLoc, ColonLoc, EndLoc, 10749 ReductionIdScopeSpec, ReductionId, 10750 UnresolvedReductions, RD)) 10751 return nullptr; 10752 10753 return OMPReductionClause::Create( 10754 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 10755 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 10756 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 10757 buildPreInits(Context, RD.ExprCaptures), 10758 buildPostUpdate(*this, RD.ExprPostUpdates)); 10759 } 10760 10761 OMPClause *Sema::ActOnOpenMPTaskReductionClause( 10762 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 10763 SourceLocation ColonLoc, SourceLocation EndLoc, 10764 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 10765 ArrayRef<Expr *> UnresolvedReductions) { 10766 ReductionData RD(VarList.size()); 10767 10768 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, 10769 VarList, StartLoc, LParenLoc, ColonLoc, 10770 EndLoc, ReductionIdScopeSpec, ReductionId, 10771 UnresolvedReductions, RD)) 10772 return nullptr; 10773 10774 return OMPTaskReductionClause::Create( 10775 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 10776 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 10777 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 10778 buildPreInits(Context, RD.ExprCaptures), 10779 buildPostUpdate(*this, RD.ExprPostUpdates)); 10780 } 10781 10782 OMPClause *Sema::ActOnOpenMPInReductionClause( 10783 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 10784 SourceLocation ColonLoc, SourceLocation EndLoc, 10785 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 10786 ArrayRef<Expr *> UnresolvedReductions) { 10787 ReductionData RD(VarList.size()); 10788 10789 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList, 10790 StartLoc, LParenLoc, ColonLoc, EndLoc, 10791 ReductionIdScopeSpec, ReductionId, 10792 UnresolvedReductions, RD)) 10793 return nullptr; 10794 10795 return OMPInReductionClause::Create( 10796 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 10797 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 10798 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors, 10799 buildPreInits(Context, RD.ExprCaptures), 10800 buildPostUpdate(*this, RD.ExprPostUpdates)); 10801 } 10802 10803 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 10804 SourceLocation LinLoc) { 10805 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 10806 LinKind == OMPC_LINEAR_unknown) { 10807 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 10808 return true; 10809 } 10810 return false; 10811 } 10812 10813 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc, 10814 OpenMPLinearClauseKind LinKind, 10815 QualType Type) { 10816 auto *VD = dyn_cast_or_null<VarDecl>(D); 10817 // A variable must not have an incomplete type or a reference type. 10818 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 10819 return true; 10820 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 10821 !Type->isReferenceType()) { 10822 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 10823 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 10824 return true; 10825 } 10826 Type = Type.getNonReferenceType(); 10827 10828 // A list item must not be const-qualified. 10829 if (Type.isConstant(Context)) { 10830 Diag(ELoc, diag::err_omp_const_variable) 10831 << getOpenMPClauseName(OMPC_linear); 10832 if (D) { 10833 bool IsDecl = 10834 !VD || 10835 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10836 Diag(D->getLocation(), 10837 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10838 << D; 10839 } 10840 return true; 10841 } 10842 10843 // A list item must be of integral or pointer type. 10844 Type = Type.getUnqualifiedType().getCanonicalType(); 10845 const auto *Ty = Type.getTypePtrOrNull(); 10846 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 10847 !Ty->isPointerType())) { 10848 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 10849 if (D) { 10850 bool IsDecl = 10851 !VD || 10852 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10853 Diag(D->getLocation(), 10854 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10855 << D; 10856 } 10857 return true; 10858 } 10859 return false; 10860 } 10861 10862 OMPClause *Sema::ActOnOpenMPLinearClause( 10863 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 10864 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 10865 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 10866 SmallVector<Expr *, 8> Vars; 10867 SmallVector<Expr *, 8> Privates; 10868 SmallVector<Expr *, 8> Inits; 10869 SmallVector<Decl *, 4> ExprCaptures; 10870 SmallVector<Expr *, 4> ExprPostUpdates; 10871 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 10872 LinKind = OMPC_LINEAR_val; 10873 for (auto &RefExpr : VarList) { 10874 assert(RefExpr && "NULL expr in OpenMP linear clause."); 10875 SourceLocation ELoc; 10876 SourceRange ERange; 10877 Expr *SimpleRefExpr = RefExpr; 10878 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 10879 /*AllowArraySection=*/false); 10880 if (Res.second) { 10881 // It will be analyzed later. 10882 Vars.push_back(RefExpr); 10883 Privates.push_back(nullptr); 10884 Inits.push_back(nullptr); 10885 } 10886 ValueDecl *D = Res.first; 10887 if (!D) 10888 continue; 10889 10890 QualType Type = D->getType(); 10891 auto *VD = dyn_cast<VarDecl>(D); 10892 10893 // OpenMP [2.14.3.7, linear clause] 10894 // A list-item cannot appear in more than one linear clause. 10895 // A list-item that appears in a linear clause cannot appear in any 10896 // other data-sharing attribute clause. 10897 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 10898 if (DVar.RefExpr) { 10899 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 10900 << getOpenMPClauseName(OMPC_linear); 10901 ReportOriginalDSA(*this, DSAStack, D, DVar); 10902 continue; 10903 } 10904 10905 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 10906 continue; 10907 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 10908 10909 // Build private copy of original var. 10910 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(), 10911 D->hasAttrs() ? &D->getAttrs() : nullptr); 10912 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 10913 // Build var to save initial value. 10914 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 10915 Expr *InitExpr; 10916 DeclRefExpr *Ref = nullptr; 10917 if (!VD && !CurContext->isDependentContext()) { 10918 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 10919 if (!IsOpenMPCapturedDecl(D)) { 10920 ExprCaptures.push_back(Ref->getDecl()); 10921 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 10922 ExprResult RefRes = DefaultLvalueConversion(Ref); 10923 if (!RefRes.isUsable()) 10924 continue; 10925 ExprResult PostUpdateRes = 10926 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 10927 SimpleRefExpr, RefRes.get()); 10928 if (!PostUpdateRes.isUsable()) 10929 continue; 10930 ExprPostUpdates.push_back( 10931 IgnoredValueConversions(PostUpdateRes.get()).get()); 10932 } 10933 } 10934 } 10935 if (LinKind == OMPC_LINEAR_uval) 10936 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 10937 else 10938 InitExpr = VD ? SimpleRefExpr : Ref; 10939 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 10940 /*DirectInit=*/false); 10941 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 10942 10943 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 10944 Vars.push_back((VD || CurContext->isDependentContext()) 10945 ? RefExpr->IgnoreParens() 10946 : Ref); 10947 Privates.push_back(PrivateRef); 10948 Inits.push_back(InitRef); 10949 } 10950 10951 if (Vars.empty()) 10952 return nullptr; 10953 10954 Expr *StepExpr = Step; 10955 Expr *CalcStepExpr = nullptr; 10956 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 10957 !Step->isInstantiationDependent() && 10958 !Step->containsUnexpandedParameterPack()) { 10959 SourceLocation StepLoc = Step->getLocStart(); 10960 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 10961 if (Val.isInvalid()) 10962 return nullptr; 10963 StepExpr = Val.get(); 10964 10965 // Build var to save the step value. 10966 VarDecl *SaveVar = 10967 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 10968 ExprResult SaveRef = 10969 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 10970 ExprResult CalcStep = 10971 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 10972 CalcStep = ActOnFinishFullExpr(CalcStep.get()); 10973 10974 // Warn about zero linear step (it would be probably better specified as 10975 // making corresponding variables 'const'). 10976 llvm::APSInt Result; 10977 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); 10978 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) 10979 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 10980 << (Vars.size() > 1); 10981 if (!IsConstant && CalcStep.isUsable()) { 10982 // Calculate the step beforehand instead of doing this on each iteration. 10983 // (This is not used if the number of iterations may be kfold-ed). 10984 CalcStepExpr = CalcStep.get(); 10985 } 10986 } 10987 10988 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 10989 ColonLoc, EndLoc, Vars, Privates, Inits, 10990 StepExpr, CalcStepExpr, 10991 buildPreInits(Context, ExprCaptures), 10992 buildPostUpdate(*this, ExprPostUpdates)); 10993 } 10994 10995 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 10996 Expr *NumIterations, Sema &SemaRef, 10997 Scope *S, DSAStackTy *Stack) { 10998 // Walk the vars and build update/final expressions for the CodeGen. 10999 SmallVector<Expr *, 8> Updates; 11000 SmallVector<Expr *, 8> Finals; 11001 Expr *Step = Clause.getStep(); 11002 Expr *CalcStep = Clause.getCalcStep(); 11003 // OpenMP [2.14.3.7, linear clause] 11004 // If linear-step is not specified it is assumed to be 1. 11005 if (Step == nullptr) 11006 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 11007 else if (CalcStep) { 11008 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 11009 } 11010 bool HasErrors = false; 11011 auto CurInit = Clause.inits().begin(); 11012 auto CurPrivate = Clause.privates().begin(); 11013 auto LinKind = Clause.getModifier(); 11014 for (auto &RefExpr : Clause.varlists()) { 11015 SourceLocation ELoc; 11016 SourceRange ERange; 11017 Expr *SimpleRefExpr = RefExpr; 11018 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange, 11019 /*AllowArraySection=*/false); 11020 ValueDecl *D = Res.first; 11021 if (Res.second || !D) { 11022 Updates.push_back(nullptr); 11023 Finals.push_back(nullptr); 11024 HasErrors = true; 11025 continue; 11026 } 11027 auto &&Info = Stack->isLoopControlVariable(D); 11028 // OpenMP [2.15.11, distribute simd Construct] 11029 // A list item may not appear in a linear clause, unless it is the loop 11030 // iteration variable. 11031 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) && 11032 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) { 11033 SemaRef.Diag(ELoc, 11034 diag::err_omp_linear_distribute_var_non_loop_iteration); 11035 Updates.push_back(nullptr); 11036 Finals.push_back(nullptr); 11037 HasErrors = true; 11038 continue; 11039 } 11040 Expr *InitExpr = *CurInit; 11041 11042 // Build privatized reference to the current linear var. 11043 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 11044 Expr *CapturedRef; 11045 if (LinKind == OMPC_LINEAR_uval) 11046 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 11047 else 11048 CapturedRef = 11049 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 11050 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 11051 /*RefersToCapture=*/true); 11052 11053 // Build update: Var = InitExpr + IV * Step 11054 ExprResult Update; 11055 if (!Info.first) { 11056 Update = 11057 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, 11058 InitExpr, IV, Step, /* Subtract */ false); 11059 } else 11060 Update = *CurPrivate; 11061 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(), 11062 /*DiscardedValue=*/true); 11063 11064 // Build final: Var = InitExpr + NumIterations * Step 11065 ExprResult Final; 11066 if (!Info.first) { 11067 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 11068 InitExpr, NumIterations, Step, 11069 /* Subtract */ false); 11070 } else 11071 Final = *CurPrivate; 11072 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(), 11073 /*DiscardedValue=*/true); 11074 11075 if (!Update.isUsable() || !Final.isUsable()) { 11076 Updates.push_back(nullptr); 11077 Finals.push_back(nullptr); 11078 HasErrors = true; 11079 } else { 11080 Updates.push_back(Update.get()); 11081 Finals.push_back(Final.get()); 11082 } 11083 ++CurInit; 11084 ++CurPrivate; 11085 } 11086 Clause.setUpdates(Updates); 11087 Clause.setFinals(Finals); 11088 return HasErrors; 11089 } 11090 11091 OMPClause *Sema::ActOnOpenMPAlignedClause( 11092 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 11093 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 11094 11095 SmallVector<Expr *, 8> Vars; 11096 for (auto &RefExpr : VarList) { 11097 assert(RefExpr && "NULL expr in OpenMP linear clause."); 11098 SourceLocation ELoc; 11099 SourceRange ERange; 11100 Expr *SimpleRefExpr = RefExpr; 11101 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 11102 /*AllowArraySection=*/false); 11103 if (Res.second) { 11104 // It will be analyzed later. 11105 Vars.push_back(RefExpr); 11106 } 11107 ValueDecl *D = Res.first; 11108 if (!D) 11109 continue; 11110 11111 QualType QType = D->getType(); 11112 auto *VD = dyn_cast<VarDecl>(D); 11113 11114 // OpenMP [2.8.1, simd construct, Restrictions] 11115 // The type of list items appearing in the aligned clause must be 11116 // array, pointer, reference to array, or reference to pointer. 11117 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 11118 const Type *Ty = QType.getTypePtrOrNull(); 11119 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 11120 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 11121 << QType << getLangOpts().CPlusPlus << ERange; 11122 bool IsDecl = 11123 !VD || 11124 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 11125 Diag(D->getLocation(), 11126 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11127 << D; 11128 continue; 11129 } 11130 11131 // OpenMP [2.8.1, simd construct, Restrictions] 11132 // A list-item cannot appear in more than one aligned clause. 11133 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 11134 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange; 11135 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 11136 << getOpenMPClauseName(OMPC_aligned); 11137 continue; 11138 } 11139 11140 DeclRefExpr *Ref = nullptr; 11141 if (!VD && IsOpenMPCapturedDecl(D)) 11142 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 11143 Vars.push_back(DefaultFunctionArrayConversion( 11144 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 11145 .get()); 11146 } 11147 11148 // OpenMP [2.8.1, simd construct, Description] 11149 // The parameter of the aligned clause, alignment, must be a constant 11150 // positive integer expression. 11151 // If no optional parameter is specified, implementation-defined default 11152 // alignments for SIMD instructions on the target platforms are assumed. 11153 if (Alignment != nullptr) { 11154 ExprResult AlignResult = 11155 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 11156 if (AlignResult.isInvalid()) 11157 return nullptr; 11158 Alignment = AlignResult.get(); 11159 } 11160 if (Vars.empty()) 11161 return nullptr; 11162 11163 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 11164 EndLoc, Vars, Alignment); 11165 } 11166 11167 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 11168 SourceLocation StartLoc, 11169 SourceLocation LParenLoc, 11170 SourceLocation EndLoc) { 11171 SmallVector<Expr *, 8> Vars; 11172 SmallVector<Expr *, 8> SrcExprs; 11173 SmallVector<Expr *, 8> DstExprs; 11174 SmallVector<Expr *, 8> AssignmentOps; 11175 for (auto &RefExpr : VarList) { 11176 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 11177 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 11178 // It will be analyzed later. 11179 Vars.push_back(RefExpr); 11180 SrcExprs.push_back(nullptr); 11181 DstExprs.push_back(nullptr); 11182 AssignmentOps.push_back(nullptr); 11183 continue; 11184 } 11185 11186 SourceLocation ELoc = RefExpr->getExprLoc(); 11187 // OpenMP [2.1, C/C++] 11188 // A list item is a variable name. 11189 // OpenMP [2.14.4.1, Restrictions, p.1] 11190 // A list item that appears in a copyin clause must be threadprivate. 11191 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 11192 if (!DE || !isa<VarDecl>(DE->getDecl())) { 11193 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 11194 << 0 << RefExpr->getSourceRange(); 11195 continue; 11196 } 11197 11198 Decl *D = DE->getDecl(); 11199 VarDecl *VD = cast<VarDecl>(D); 11200 11201 QualType Type = VD->getType(); 11202 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 11203 // It will be analyzed later. 11204 Vars.push_back(DE); 11205 SrcExprs.push_back(nullptr); 11206 DstExprs.push_back(nullptr); 11207 AssignmentOps.push_back(nullptr); 11208 continue; 11209 } 11210 11211 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 11212 // A list item that appears in a copyin clause must be threadprivate. 11213 if (!DSAStack->isThreadPrivate(VD)) { 11214 Diag(ELoc, diag::err_omp_required_access) 11215 << getOpenMPClauseName(OMPC_copyin) 11216 << getOpenMPDirectiveName(OMPD_threadprivate); 11217 continue; 11218 } 11219 11220 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 11221 // A variable of class type (or array thereof) that appears in a 11222 // copyin clause requires an accessible, unambiguous copy assignment 11223 // operator for the class type. 11224 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 11225 auto *SrcVD = 11226 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(), 11227 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 11228 auto *PseudoSrcExpr = buildDeclRefExpr( 11229 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 11230 auto *DstVD = 11231 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst", 11232 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 11233 auto *PseudoDstExpr = 11234 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 11235 // For arrays generate assignment operation for single element and replace 11236 // it by the original array element in CodeGen. 11237 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, 11238 PseudoDstExpr, PseudoSrcExpr); 11239 if (AssignmentOp.isInvalid()) 11240 continue; 11241 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 11242 /*DiscardedValue=*/true); 11243 if (AssignmentOp.isInvalid()) 11244 continue; 11245 11246 DSAStack->addDSA(VD, DE, OMPC_copyin); 11247 Vars.push_back(DE); 11248 SrcExprs.push_back(PseudoSrcExpr); 11249 DstExprs.push_back(PseudoDstExpr); 11250 AssignmentOps.push_back(AssignmentOp.get()); 11251 } 11252 11253 if (Vars.empty()) 11254 return nullptr; 11255 11256 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 11257 SrcExprs, DstExprs, AssignmentOps); 11258 } 11259 11260 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 11261 SourceLocation StartLoc, 11262 SourceLocation LParenLoc, 11263 SourceLocation EndLoc) { 11264 SmallVector<Expr *, 8> Vars; 11265 SmallVector<Expr *, 8> SrcExprs; 11266 SmallVector<Expr *, 8> DstExprs; 11267 SmallVector<Expr *, 8> AssignmentOps; 11268 for (auto &RefExpr : VarList) { 11269 assert(RefExpr && "NULL expr in OpenMP linear clause."); 11270 SourceLocation ELoc; 11271 SourceRange ERange; 11272 Expr *SimpleRefExpr = RefExpr; 11273 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 11274 /*AllowArraySection=*/false); 11275 if (Res.second) { 11276 // It will be analyzed later. 11277 Vars.push_back(RefExpr); 11278 SrcExprs.push_back(nullptr); 11279 DstExprs.push_back(nullptr); 11280 AssignmentOps.push_back(nullptr); 11281 } 11282 ValueDecl *D = Res.first; 11283 if (!D) 11284 continue; 11285 11286 QualType Type = D->getType(); 11287 auto *VD = dyn_cast<VarDecl>(D); 11288 11289 // OpenMP [2.14.4.2, Restrictions, p.2] 11290 // A list item that appears in a copyprivate clause may not appear in a 11291 // private or firstprivate clause on the single construct. 11292 if (!VD || !DSAStack->isThreadPrivate(VD)) { 11293 auto DVar = DSAStack->getTopDSA(D, false); 11294 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 11295 DVar.RefExpr) { 11296 Diag(ELoc, diag::err_omp_wrong_dsa) 11297 << getOpenMPClauseName(DVar.CKind) 11298 << getOpenMPClauseName(OMPC_copyprivate); 11299 ReportOriginalDSA(*this, DSAStack, D, DVar); 11300 continue; 11301 } 11302 11303 // OpenMP [2.11.4.2, Restrictions, p.1] 11304 // All list items that appear in a copyprivate clause must be either 11305 // threadprivate or private in the enclosing context. 11306 if (DVar.CKind == OMPC_unknown) { 11307 DVar = DSAStack->getImplicitDSA(D, false); 11308 if (DVar.CKind == OMPC_shared) { 11309 Diag(ELoc, diag::err_omp_required_access) 11310 << getOpenMPClauseName(OMPC_copyprivate) 11311 << "threadprivate or private in the enclosing context"; 11312 ReportOriginalDSA(*this, DSAStack, D, DVar); 11313 continue; 11314 } 11315 } 11316 } 11317 11318 // Variably modified types are not supported. 11319 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 11320 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 11321 << getOpenMPClauseName(OMPC_copyprivate) << Type 11322 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 11323 bool IsDecl = 11324 !VD || 11325 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 11326 Diag(D->getLocation(), 11327 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 11328 << D; 11329 continue; 11330 } 11331 11332 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 11333 // A variable of class type (or array thereof) that appears in a 11334 // copyin clause requires an accessible, unambiguous copy assignment 11335 // operator for the class type. 11336 Type = Context.getBaseElementType(Type.getNonReferenceType()) 11337 .getUnqualifiedType(); 11338 auto *SrcVD = 11339 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src", 11340 D->hasAttrs() ? &D->getAttrs() : nullptr); 11341 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 11342 auto *DstVD = 11343 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst", 11344 D->hasAttrs() ? &D->getAttrs() : nullptr); 11345 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 11346 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 11347 PseudoDstExpr, PseudoSrcExpr); 11348 if (AssignmentOp.isInvalid()) 11349 continue; 11350 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 11351 /*DiscardedValue=*/true); 11352 if (AssignmentOp.isInvalid()) 11353 continue; 11354 11355 // No need to mark vars as copyprivate, they are already threadprivate or 11356 // implicitly private. 11357 assert(VD || IsOpenMPCapturedDecl(D)); 11358 Vars.push_back( 11359 VD ? RefExpr->IgnoreParens() 11360 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 11361 SrcExprs.push_back(PseudoSrcExpr); 11362 DstExprs.push_back(PseudoDstExpr); 11363 AssignmentOps.push_back(AssignmentOp.get()); 11364 } 11365 11366 if (Vars.empty()) 11367 return nullptr; 11368 11369 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11370 Vars, SrcExprs, DstExprs, AssignmentOps); 11371 } 11372 11373 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 11374 SourceLocation StartLoc, 11375 SourceLocation LParenLoc, 11376 SourceLocation EndLoc) { 11377 if (VarList.empty()) 11378 return nullptr; 11379 11380 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 11381 } 11382 11383 OMPClause * 11384 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, 11385 SourceLocation DepLoc, SourceLocation ColonLoc, 11386 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 11387 SourceLocation LParenLoc, SourceLocation EndLoc) { 11388 if (DSAStack->getCurrentDirective() == OMPD_ordered && 11389 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 11390 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 11391 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 11392 return nullptr; 11393 } 11394 if (DSAStack->getCurrentDirective() != OMPD_ordered && 11395 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 11396 DepKind == OMPC_DEPEND_sink)) { 11397 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink}; 11398 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 11399 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 11400 /*Last=*/OMPC_DEPEND_unknown, Except) 11401 << getOpenMPClauseName(OMPC_depend); 11402 return nullptr; 11403 } 11404 SmallVector<Expr *, 8> Vars; 11405 DSAStackTy::OperatorOffsetTy OpsOffs; 11406 llvm::APSInt DepCounter(/*BitWidth=*/32); 11407 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 11408 if (DepKind == OMPC_DEPEND_sink) { 11409 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) { 11410 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 11411 TotalDepCount.setIsUnsigned(/*Val=*/true); 11412 } 11413 } 11414 for (auto &RefExpr : VarList) { 11415 assert(RefExpr && "NULL expr in OpenMP shared clause."); 11416 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 11417 // It will be analyzed later. 11418 Vars.push_back(RefExpr); 11419 continue; 11420 } 11421 11422 SourceLocation ELoc = RefExpr->getExprLoc(); 11423 auto *SimpleExpr = RefExpr->IgnoreParenCasts(); 11424 if (DepKind == OMPC_DEPEND_sink) { 11425 if (DSAStack->getParentOrderedRegionParam() && 11426 DepCounter >= TotalDepCount) { 11427 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 11428 continue; 11429 } 11430 ++DepCounter; 11431 // OpenMP [2.13.9, Summary] 11432 // depend(dependence-type : vec), where dependence-type is: 11433 // 'sink' and where vec is the iteration vector, which has the form: 11434 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 11435 // where n is the value specified by the ordered clause in the loop 11436 // directive, xi denotes the loop iteration variable of the i-th nested 11437 // loop associated with the loop directive, and di is a constant 11438 // non-negative integer. 11439 if (CurContext->isDependentContext()) { 11440 // It will be analyzed later. 11441 Vars.push_back(RefExpr); 11442 continue; 11443 } 11444 SimpleExpr = SimpleExpr->IgnoreImplicit(); 11445 OverloadedOperatorKind OOK = OO_None; 11446 SourceLocation OOLoc; 11447 Expr *LHS = SimpleExpr; 11448 Expr *RHS = nullptr; 11449 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 11450 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 11451 OOLoc = BO->getOperatorLoc(); 11452 LHS = BO->getLHS()->IgnoreParenImpCasts(); 11453 RHS = BO->getRHS()->IgnoreParenImpCasts(); 11454 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 11455 OOK = OCE->getOperator(); 11456 OOLoc = OCE->getOperatorLoc(); 11457 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 11458 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 11459 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 11460 OOK = MCE->getMethodDecl() 11461 ->getNameInfo() 11462 .getName() 11463 .getCXXOverloadedOperator(); 11464 OOLoc = MCE->getCallee()->getExprLoc(); 11465 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 11466 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 11467 } 11468 SourceLocation ELoc; 11469 SourceRange ERange; 11470 auto Res = getPrivateItem(*this, LHS, ELoc, ERange, 11471 /*AllowArraySection=*/false); 11472 if (Res.second) { 11473 // It will be analyzed later. 11474 Vars.push_back(RefExpr); 11475 } 11476 ValueDecl *D = Res.first; 11477 if (!D) 11478 continue; 11479 11480 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 11481 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 11482 continue; 11483 } 11484 if (RHS) { 11485 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 11486 RHS, OMPC_depend, /*StrictlyPositive=*/false); 11487 if (RHSRes.isInvalid()) 11488 continue; 11489 } 11490 if (!CurContext->isDependentContext() && 11491 DSAStack->getParentOrderedRegionParam() && 11492 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 11493 ValueDecl *VD = 11494 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue()); 11495 if (VD) { 11496 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 11497 << 1 << VD; 11498 } else { 11499 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; 11500 } 11501 continue; 11502 } 11503 OpsOffs.push_back({RHS, OOK}); 11504 } else { 11505 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 11506 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 11507 (ASE && 11508 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() && 11509 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 11510 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 11511 << RefExpr->getSourceRange(); 11512 continue; 11513 } 11514 bool Suppress = getDiagnostics().getSuppressAllDiagnostics(); 11515 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 11516 ExprResult Res = 11517 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts()); 11518 getDiagnostics().setSuppressAllDiagnostics(Suppress); 11519 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) { 11520 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 11521 << RefExpr->getSourceRange(); 11522 continue; 11523 } 11524 } 11525 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 11526 } 11527 11528 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 11529 TotalDepCount > VarList.size() && 11530 DSAStack->getParentOrderedRegionParam() && 11531 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { 11532 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 11533 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 11534 } 11535 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 11536 Vars.empty()) 11537 return nullptr; 11538 11539 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11540 DepKind, DepLoc, ColonLoc, Vars); 11541 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) && 11542 DSAStack->isParentOrderedRegion()) 11543 DSAStack->addDoacrossDependClause(C, OpsOffs); 11544 return C; 11545 } 11546 11547 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, 11548 SourceLocation LParenLoc, 11549 SourceLocation EndLoc) { 11550 Expr *ValExpr = Device; 11551 Stmt *HelperValStmt = nullptr; 11552 11553 // OpenMP [2.9.1, Restrictions] 11554 // The device expression must evaluate to a non-negative integer value. 11555 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 11556 /*StrictlyPositive=*/false)) 11557 return nullptr; 11558 11559 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 11560 OpenMPDirectiveKind CaptureRegion = 11561 getOpenMPCaptureRegionForClause(DKind, OMPC_device); 11562 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 11563 ValExpr = MakeFullExpr(ValExpr).get(); 11564 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11565 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11566 HelperValStmt = buildPreInits(Context, Captures); 11567 } 11568 11569 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion, 11570 StartLoc, LParenLoc, EndLoc); 11571 } 11572 11573 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 11574 DSAStackTy *Stack, QualType QTy, 11575 bool FullCheck = true) { 11576 NamedDecl *ND; 11577 if (QTy->isIncompleteType(&ND)) { 11578 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 11579 return false; 11580 } 11581 if (FullCheck && !SemaRef.CurContext->isDependentContext() && 11582 !QTy.isTrivialType(SemaRef.Context)) 11583 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR; 11584 return true; 11585 } 11586 11587 /// \brief Return true if it can be proven that the provided array expression 11588 /// (array section or array subscript) does NOT specify the whole size of the 11589 /// array whose base type is \a BaseQTy. 11590 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 11591 const Expr *E, 11592 QualType BaseQTy) { 11593 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 11594 11595 // If this is an array subscript, it refers to the whole size if the size of 11596 // the dimension is constant and equals 1. Also, an array section assumes the 11597 // format of an array subscript if no colon is used. 11598 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) { 11599 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 11600 return ATy->getSize().getSExtValue() != 1; 11601 // Size can't be evaluated statically. 11602 return false; 11603 } 11604 11605 assert(OASE && "Expecting array section if not an array subscript."); 11606 auto *LowerBound = OASE->getLowerBound(); 11607 auto *Length = OASE->getLength(); 11608 11609 // If there is a lower bound that does not evaluates to zero, we are not 11610 // covering the whole dimension. 11611 if (LowerBound) { 11612 llvm::APSInt ConstLowerBound; 11613 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext())) 11614 return false; // Can't get the integer value as a constant. 11615 if (ConstLowerBound.getSExtValue()) 11616 return true; 11617 } 11618 11619 // If we don't have a length we covering the whole dimension. 11620 if (!Length) 11621 return false; 11622 11623 // If the base is a pointer, we don't have a way to get the size of the 11624 // pointee. 11625 if (BaseQTy->isPointerType()) 11626 return false; 11627 11628 // We can only check if the length is the same as the size of the dimension 11629 // if we have a constant array. 11630 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 11631 if (!CATy) 11632 return false; 11633 11634 llvm::APSInt ConstLength; 11635 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 11636 return false; // Can't get the integer value as a constant. 11637 11638 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 11639 } 11640 11641 // Return true if it can be proven that the provided array expression (array 11642 // section or array subscript) does NOT specify a single element of the array 11643 // whose base type is \a BaseQTy. 11644 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 11645 const Expr *E, 11646 QualType BaseQTy) { 11647 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 11648 11649 // An array subscript always refer to a single element. Also, an array section 11650 // assumes the format of an array subscript if no colon is used. 11651 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) 11652 return false; 11653 11654 assert(OASE && "Expecting array section if not an array subscript."); 11655 auto *Length = OASE->getLength(); 11656 11657 // If we don't have a length we have to check if the array has unitary size 11658 // for this dimension. Also, we should always expect a length if the base type 11659 // is pointer. 11660 if (!Length) { 11661 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 11662 return ATy->getSize().getSExtValue() != 1; 11663 // We cannot assume anything. 11664 return false; 11665 } 11666 11667 // Check if the length evaluates to 1. 11668 llvm::APSInt ConstLength; 11669 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 11670 return false; // Can't get the integer value as a constant. 11671 11672 return ConstLength.getSExtValue() != 1; 11673 } 11674 11675 // Return the expression of the base of the mappable expression or null if it 11676 // cannot be determined and do all the necessary checks to see if the expression 11677 // is valid as a standalone mappable expression. In the process, record all the 11678 // components of the expression. 11679 static Expr *CheckMapClauseExpressionBase( 11680 Sema &SemaRef, Expr *E, 11681 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 11682 OpenMPClauseKind CKind, bool NoDiagnose) { 11683 SourceLocation ELoc = E->getExprLoc(); 11684 SourceRange ERange = E->getSourceRange(); 11685 11686 // The base of elements of list in a map clause have to be either: 11687 // - a reference to variable or field. 11688 // - a member expression. 11689 // - an array expression. 11690 // 11691 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 11692 // reference to 'r'. 11693 // 11694 // If we have: 11695 // 11696 // struct SS { 11697 // Bla S; 11698 // foo() { 11699 // #pragma omp target map (S.Arr[:12]); 11700 // } 11701 // } 11702 // 11703 // We want to retrieve the member expression 'this->S'; 11704 11705 Expr *RelevantExpr = nullptr; 11706 11707 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2] 11708 // If a list item is an array section, it must specify contiguous storage. 11709 // 11710 // For this restriction it is sufficient that we make sure only references 11711 // to variables or fields and array expressions, and that no array sections 11712 // exist except in the rightmost expression (unless they cover the whole 11713 // dimension of the array). E.g. these would be invalid: 11714 // 11715 // r.ArrS[3:5].Arr[6:7] 11716 // 11717 // r.ArrS[3:5].x 11718 // 11719 // but these would be valid: 11720 // r.ArrS[3].Arr[6:7] 11721 // 11722 // r.ArrS[3].x 11723 11724 bool AllowUnitySizeArraySection = true; 11725 bool AllowWholeSizeArraySection = true; 11726 11727 while (!RelevantExpr) { 11728 E = E->IgnoreParenImpCasts(); 11729 11730 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) { 11731 if (!isa<VarDecl>(CurE->getDecl())) 11732 return nullptr; 11733 11734 RelevantExpr = CurE; 11735 11736 // If we got a reference to a declaration, we should not expect any array 11737 // section before that. 11738 AllowUnitySizeArraySection = false; 11739 AllowWholeSizeArraySection = false; 11740 11741 // Record the component. 11742 CurComponents.emplace_back(CurE, CurE->getDecl()); 11743 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) { 11744 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts(); 11745 11746 if (isa<CXXThisExpr>(BaseE)) 11747 // We found a base expression: this->Val. 11748 RelevantExpr = CurE; 11749 else 11750 E = BaseE; 11751 11752 if (!isa<FieldDecl>(CurE->getMemberDecl())) { 11753 if (!NoDiagnose) { 11754 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 11755 << CurE->getSourceRange(); 11756 return nullptr; 11757 } 11758 if (RelevantExpr) 11759 return nullptr; 11760 continue; 11761 } 11762 11763 auto *FD = cast<FieldDecl>(CurE->getMemberDecl()); 11764 11765 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 11766 // A bit-field cannot appear in a map clause. 11767 // 11768 if (FD->isBitField()) { 11769 if (!NoDiagnose) { 11770 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 11771 << CurE->getSourceRange() << getOpenMPClauseName(CKind); 11772 return nullptr; 11773 } 11774 if (RelevantExpr) 11775 return nullptr; 11776 continue; 11777 } 11778 11779 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 11780 // If the type of a list item is a reference to a type T then the type 11781 // will be considered to be T for all purposes of this clause. 11782 QualType CurType = BaseE->getType().getNonReferenceType(); 11783 11784 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 11785 // A list item cannot be a variable that is a member of a structure with 11786 // a union type. 11787 // 11788 if (auto *RT = CurType->getAs<RecordType>()) { 11789 if (RT->isUnionType()) { 11790 if (!NoDiagnose) { 11791 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 11792 << CurE->getSourceRange(); 11793 return nullptr; 11794 } 11795 continue; 11796 } 11797 } 11798 11799 // If we got a member expression, we should not expect any array section 11800 // before that: 11801 // 11802 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 11803 // If a list item is an element of a structure, only the rightmost symbol 11804 // of the variable reference can be an array section. 11805 // 11806 AllowUnitySizeArraySection = false; 11807 AllowWholeSizeArraySection = false; 11808 11809 // Record the component. 11810 CurComponents.emplace_back(CurE, FD); 11811 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) { 11812 E = CurE->getBase()->IgnoreParenImpCasts(); 11813 11814 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 11815 if (!NoDiagnose) { 11816 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 11817 << 0 << CurE->getSourceRange(); 11818 return nullptr; 11819 } 11820 continue; 11821 } 11822 11823 // If we got an array subscript that express the whole dimension we 11824 // can have any array expressions before. If it only expressing part of 11825 // the dimension, we can only have unitary-size array expressions. 11826 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, 11827 E->getType())) 11828 AllowWholeSizeArraySection = false; 11829 11830 // Record the component - we don't have any declaration associated. 11831 CurComponents.emplace_back(CurE, nullptr); 11832 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) { 11833 assert(!NoDiagnose && "Array sections cannot be implicitly mapped."); 11834 E = CurE->getBase()->IgnoreParenImpCasts(); 11835 11836 QualType CurType = 11837 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 11838 11839 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 11840 // If the type of a list item is a reference to a type T then the type 11841 // will be considered to be T for all purposes of this clause. 11842 if (CurType->isReferenceType()) 11843 CurType = CurType->getPointeeType(); 11844 11845 bool IsPointer = CurType->isAnyPointerType(); 11846 11847 if (!IsPointer && !CurType->isArrayType()) { 11848 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 11849 << 0 << CurE->getSourceRange(); 11850 return nullptr; 11851 } 11852 11853 bool NotWhole = 11854 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType); 11855 bool NotUnity = 11856 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType); 11857 11858 if (AllowWholeSizeArraySection) { 11859 // Any array section is currently allowed. Allowing a whole size array 11860 // section implies allowing a unity array section as well. 11861 // 11862 // If this array section refers to the whole dimension we can still 11863 // accept other array sections before this one, except if the base is a 11864 // pointer. Otherwise, only unitary sections are accepted. 11865 if (NotWhole || IsPointer) 11866 AllowWholeSizeArraySection = false; 11867 } else if (AllowUnitySizeArraySection && NotUnity) { 11868 // A unity or whole array section is not allowed and that is not 11869 // compatible with the properties of the current array section. 11870 SemaRef.Diag( 11871 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 11872 << CurE->getSourceRange(); 11873 return nullptr; 11874 } 11875 11876 // Record the component - we don't have any declaration associated. 11877 CurComponents.emplace_back(CurE, nullptr); 11878 } else { 11879 if (!NoDiagnose) { 11880 // If nothing else worked, this is not a valid map clause expression. 11881 SemaRef.Diag( 11882 ELoc, diag::err_omp_expected_named_var_member_or_array_expression) 11883 << ERange; 11884 } 11885 return nullptr; 11886 } 11887 } 11888 11889 return RelevantExpr; 11890 } 11891 11892 // Return true if expression E associated with value VD has conflicts with other 11893 // map information. 11894 static bool CheckMapConflicts( 11895 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E, 11896 bool CurrentRegionOnly, 11897 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 11898 OpenMPClauseKind CKind) { 11899 assert(VD && E); 11900 SourceLocation ELoc = E->getExprLoc(); 11901 SourceRange ERange = E->getSourceRange(); 11902 11903 // In order to easily check the conflicts we need to match each component of 11904 // the expression under test with the components of the expressions that are 11905 // already in the stack. 11906 11907 assert(!CurComponents.empty() && "Map clause expression with no components!"); 11908 assert(CurComponents.back().getAssociatedDeclaration() == VD && 11909 "Map clause expression with unexpected base!"); 11910 11911 // Variables to help detecting enclosing problems in data environment nests. 11912 bool IsEnclosedByDataEnvironmentExpr = false; 11913 const Expr *EnclosingExpr = nullptr; 11914 11915 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 11916 VD, CurrentRegionOnly, 11917 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 11918 StackComponents, 11919 OpenMPClauseKind) -> bool { 11920 11921 assert(!StackComponents.empty() && 11922 "Map clause expression with no components!"); 11923 assert(StackComponents.back().getAssociatedDeclaration() == VD && 11924 "Map clause expression with unexpected base!"); 11925 11926 // The whole expression in the stack. 11927 auto *RE = StackComponents.front().getAssociatedExpression(); 11928 11929 // Expressions must start from the same base. Here we detect at which 11930 // point both expressions diverge from each other and see if we can 11931 // detect if the memory referred to both expressions is contiguous and 11932 // do not overlap. 11933 auto CI = CurComponents.rbegin(); 11934 auto CE = CurComponents.rend(); 11935 auto SI = StackComponents.rbegin(); 11936 auto SE = StackComponents.rend(); 11937 for (; CI != CE && SI != SE; ++CI, ++SI) { 11938 11939 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 11940 // At most one list item can be an array item derived from a given 11941 // variable in map clauses of the same construct. 11942 if (CurrentRegionOnly && 11943 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 11944 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) && 11945 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 11946 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) { 11947 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 11948 diag::err_omp_multiple_array_items_in_map_clause) 11949 << CI->getAssociatedExpression()->getSourceRange(); 11950 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 11951 diag::note_used_here) 11952 << SI->getAssociatedExpression()->getSourceRange(); 11953 return true; 11954 } 11955 11956 // Do both expressions have the same kind? 11957 if (CI->getAssociatedExpression()->getStmtClass() != 11958 SI->getAssociatedExpression()->getStmtClass()) 11959 break; 11960 11961 // Are we dealing with different variables/fields? 11962 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 11963 break; 11964 } 11965 // Check if the extra components of the expressions in the enclosing 11966 // data environment are redundant for the current base declaration. 11967 // If they are, the maps completely overlap, which is legal. 11968 for (; SI != SE; ++SI) { 11969 QualType Type; 11970 if (auto *ASE = 11971 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 11972 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 11973 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>( 11974 SI->getAssociatedExpression())) { 11975 auto *E = OASE->getBase()->IgnoreParenImpCasts(); 11976 Type = 11977 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 11978 } 11979 if (Type.isNull() || Type->isAnyPointerType() || 11980 CheckArrayExpressionDoesNotReferToWholeSize( 11981 SemaRef, SI->getAssociatedExpression(), Type)) 11982 break; 11983 } 11984 11985 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 11986 // List items of map clauses in the same construct must not share 11987 // original storage. 11988 // 11989 // If the expressions are exactly the same or one is a subset of the 11990 // other, it means they are sharing storage. 11991 if (CI == CE && SI == SE) { 11992 if (CurrentRegionOnly) { 11993 if (CKind == OMPC_map) 11994 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 11995 else { 11996 assert(CKind == OMPC_to || CKind == OMPC_from); 11997 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 11998 << ERange; 11999 } 12000 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 12001 << RE->getSourceRange(); 12002 return true; 12003 } else { 12004 // If we find the same expression in the enclosing data environment, 12005 // that is legal. 12006 IsEnclosedByDataEnvironmentExpr = true; 12007 return false; 12008 } 12009 } 12010 12011 QualType DerivedType = 12012 std::prev(CI)->getAssociatedDeclaration()->getType(); 12013 SourceLocation DerivedLoc = 12014 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 12015 12016 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 12017 // If the type of a list item is a reference to a type T then the type 12018 // will be considered to be T for all purposes of this clause. 12019 DerivedType = DerivedType.getNonReferenceType(); 12020 12021 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 12022 // A variable for which the type is pointer and an array section 12023 // derived from that variable must not appear as list items of map 12024 // clauses of the same construct. 12025 // 12026 // Also, cover one of the cases in: 12027 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 12028 // If any part of the original storage of a list item has corresponding 12029 // storage in the device data environment, all of the original storage 12030 // must have corresponding storage in the device data environment. 12031 // 12032 if (DerivedType->isAnyPointerType()) { 12033 if (CI == CE || SI == SE) { 12034 SemaRef.Diag( 12035 DerivedLoc, 12036 diag::err_omp_pointer_mapped_along_with_derived_section) 12037 << DerivedLoc; 12038 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 12039 << RE->getSourceRange(); 12040 return true; 12041 } else if (CI->getAssociatedExpression()->getStmtClass() != 12042 SI->getAssociatedExpression()->getStmtClass() || 12043 CI->getAssociatedDeclaration()->getCanonicalDecl() == 12044 SI->getAssociatedDeclaration()->getCanonicalDecl()) { 12045 assert(CI != CE && SI != SE); 12046 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced) 12047 << DerivedLoc; 12048 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 12049 << RE->getSourceRange(); 12050 return true; 12051 } 12052 } 12053 12054 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 12055 // List items of map clauses in the same construct must not share 12056 // original storage. 12057 // 12058 // An expression is a subset of the other. 12059 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 12060 if (CKind == OMPC_map) 12061 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 12062 else { 12063 assert(CKind == OMPC_to || CKind == OMPC_from); 12064 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 12065 << ERange; 12066 } 12067 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 12068 << RE->getSourceRange(); 12069 return true; 12070 } 12071 12072 // The current expression uses the same base as other expression in the 12073 // data environment but does not contain it completely. 12074 if (!CurrentRegionOnly && SI != SE) 12075 EnclosingExpr = RE; 12076 12077 // The current expression is a subset of the expression in the data 12078 // environment. 12079 IsEnclosedByDataEnvironmentExpr |= 12080 (!CurrentRegionOnly && CI != CE && SI == SE); 12081 12082 return false; 12083 }); 12084 12085 if (CurrentRegionOnly) 12086 return FoundError; 12087 12088 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 12089 // If any part of the original storage of a list item has corresponding 12090 // storage in the device data environment, all of the original storage must 12091 // have corresponding storage in the device data environment. 12092 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 12093 // If a list item is an element of a structure, and a different element of 12094 // the structure has a corresponding list item in the device data environment 12095 // prior to a task encountering the construct associated with the map clause, 12096 // then the list item must also have a corresponding list item in the device 12097 // data environment prior to the task encountering the construct. 12098 // 12099 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 12100 SemaRef.Diag(ELoc, 12101 diag::err_omp_original_storage_is_shared_and_does_not_contain) 12102 << ERange; 12103 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 12104 << EnclosingExpr->getSourceRange(); 12105 return true; 12106 } 12107 12108 return FoundError; 12109 } 12110 12111 namespace { 12112 // Utility struct that gathers all the related lists associated with a mappable 12113 // expression. 12114 struct MappableVarListInfo final { 12115 // The list of expressions. 12116 ArrayRef<Expr *> VarList; 12117 // The list of processed expressions. 12118 SmallVector<Expr *, 16> ProcessedVarList; 12119 // The mappble components for each expression. 12120 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 12121 // The base declaration of the variable. 12122 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 12123 12124 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 12125 // We have a list of components and base declarations for each entry in the 12126 // variable list. 12127 VarComponents.reserve(VarList.size()); 12128 VarBaseDeclarations.reserve(VarList.size()); 12129 } 12130 }; 12131 } 12132 12133 // Check the validity of the provided variable list for the provided clause kind 12134 // \a CKind. In the check process the valid expressions, and mappable expression 12135 // components and variables are extracted and used to fill \a Vars, 12136 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and 12137 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'. 12138 static void 12139 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS, 12140 OpenMPClauseKind CKind, MappableVarListInfo &MVLI, 12141 SourceLocation StartLoc, 12142 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 12143 bool IsMapTypeImplicit = false) { 12144 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 12145 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 12146 "Unexpected clause kind with mappable expressions!"); 12147 12148 // Keep track of the mappable components and base declarations in this clause. 12149 // Each entry in the list is going to have a list of components associated. We 12150 // record each set of the components so that we can build the clause later on. 12151 // In the end we should have the same amount of declarations and component 12152 // lists. 12153 12154 for (auto &RE : MVLI.VarList) { 12155 assert(RE && "Null expr in omp to/from/map clause"); 12156 SourceLocation ELoc = RE->getExprLoc(); 12157 12158 auto *VE = RE->IgnoreParenLValueCasts(); 12159 12160 if (VE->isValueDependent() || VE->isTypeDependent() || 12161 VE->isInstantiationDependent() || 12162 VE->containsUnexpandedParameterPack()) { 12163 // We can only analyze this information once the missing information is 12164 // resolved. 12165 MVLI.ProcessedVarList.push_back(RE); 12166 continue; 12167 } 12168 12169 auto *SimpleExpr = RE->IgnoreParenCasts(); 12170 12171 if (!RE->IgnoreParenImpCasts()->isLValue()) { 12172 SemaRef.Diag(ELoc, 12173 diag::err_omp_expected_named_var_member_or_array_expression) 12174 << RE->getSourceRange(); 12175 continue; 12176 } 12177 12178 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 12179 ValueDecl *CurDeclaration = nullptr; 12180 12181 // Obtain the array or member expression bases if required. Also, fill the 12182 // components array with all the components identified in the process. 12183 auto *BE = CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, 12184 CKind, /*NoDiagnose=*/false); 12185 if (!BE) 12186 continue; 12187 12188 assert(!CurComponents.empty() && 12189 "Invalid mappable expression information."); 12190 12191 // For the following checks, we rely on the base declaration which is 12192 // expected to be associated with the last component. The declaration is 12193 // expected to be a variable or a field (if 'this' is being mapped). 12194 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 12195 assert(CurDeclaration && "Null decl on map clause."); 12196 assert( 12197 CurDeclaration->isCanonicalDecl() && 12198 "Expecting components to have associated only canonical declarations."); 12199 12200 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 12201 auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 12202 12203 assert((VD || FD) && "Only variables or fields are expected here!"); 12204 (void)FD; 12205 12206 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 12207 // threadprivate variables cannot appear in a map clause. 12208 // OpenMP 4.5 [2.10.5, target update Construct] 12209 // threadprivate variables cannot appear in a from clause. 12210 if (VD && DSAS->isThreadPrivate(VD)) { 12211 auto DVar = DSAS->getTopDSA(VD, false); 12212 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 12213 << getOpenMPClauseName(CKind); 12214 ReportOriginalDSA(SemaRef, DSAS, VD, DVar); 12215 continue; 12216 } 12217 12218 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 12219 // A list item cannot appear in both a map clause and a data-sharing 12220 // attribute clause on the same construct. 12221 12222 // Check conflicts with other map clause expressions. We check the conflicts 12223 // with the current construct separately from the enclosing data 12224 // environment, because the restrictions are different. We only have to 12225 // check conflicts across regions for the map clauses. 12226 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 12227 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 12228 break; 12229 if (CKind == OMPC_map && 12230 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 12231 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 12232 break; 12233 12234 // OpenMP 4.5 [2.10.5, target update Construct] 12235 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 12236 // If the type of a list item is a reference to a type T then the type will 12237 // be considered to be T for all purposes of this clause. 12238 QualType Type = CurDeclaration->getType().getNonReferenceType(); 12239 12240 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 12241 // A list item in a to or from clause must have a mappable type. 12242 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 12243 // A list item must have a mappable type. 12244 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 12245 DSAS, Type)) 12246 continue; 12247 12248 if (CKind == OMPC_map) { 12249 // target enter data 12250 // OpenMP [2.10.2, Restrictions, p. 99] 12251 // A map-type must be specified in all map clauses and must be either 12252 // to or alloc. 12253 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 12254 if (DKind == OMPD_target_enter_data && 12255 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 12256 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 12257 << (IsMapTypeImplicit ? 1 : 0) 12258 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 12259 << getOpenMPDirectiveName(DKind); 12260 continue; 12261 } 12262 12263 // target exit_data 12264 // OpenMP [2.10.3, Restrictions, p. 102] 12265 // A map-type must be specified in all map clauses and must be either 12266 // from, release, or delete. 12267 if (DKind == OMPD_target_exit_data && 12268 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 12269 MapType == OMPC_MAP_delete)) { 12270 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 12271 << (IsMapTypeImplicit ? 1 : 0) 12272 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 12273 << getOpenMPDirectiveName(DKind); 12274 continue; 12275 } 12276 12277 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 12278 // A list item cannot appear in both a map clause and a data-sharing 12279 // attribute clause on the same construct 12280 if ((DKind == OMPD_target || DKind == OMPD_target_teams || 12281 DKind == OMPD_target_teams_distribute || 12282 DKind == OMPD_target_teams_distribute_parallel_for || 12283 DKind == OMPD_target_teams_distribute_parallel_for_simd || 12284 DKind == OMPD_target_teams_distribute_simd) && VD) { 12285 auto DVar = DSAS->getTopDSA(VD, false); 12286 if (isOpenMPPrivate(DVar.CKind)) { 12287 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 12288 << getOpenMPClauseName(DVar.CKind) 12289 << getOpenMPClauseName(OMPC_map) 12290 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 12291 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar); 12292 continue; 12293 } 12294 } 12295 } 12296 12297 // Save the current expression. 12298 MVLI.ProcessedVarList.push_back(RE); 12299 12300 // Store the components in the stack so that they can be used to check 12301 // against other clauses later on. 12302 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 12303 /*WhereFoundClauseKind=*/OMPC_map); 12304 12305 // Save the components and declaration to create the clause. For purposes of 12306 // the clause creation, any component list that has has base 'this' uses 12307 // null as base declaration. 12308 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 12309 MVLI.VarComponents.back().append(CurComponents.begin(), 12310 CurComponents.end()); 12311 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 12312 : CurDeclaration); 12313 } 12314 } 12315 12316 OMPClause * 12317 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier, 12318 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 12319 SourceLocation MapLoc, SourceLocation ColonLoc, 12320 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 12321 SourceLocation LParenLoc, SourceLocation EndLoc) { 12322 MappableVarListInfo MVLI(VarList); 12323 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc, 12324 MapType, IsMapTypeImplicit); 12325 12326 // We need to produce a map clause even if we don't have variables so that 12327 // other diagnostics related with non-existing map clauses are accurate. 12328 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, 12329 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 12330 MVLI.VarComponents, MapTypeModifier, MapType, 12331 IsMapTypeImplicit, MapLoc); 12332 } 12333 12334 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 12335 TypeResult ParsedType) { 12336 assert(ParsedType.isUsable()); 12337 12338 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 12339 if (ReductionType.isNull()) 12340 return QualType(); 12341 12342 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 12343 // A type name in a declare reduction directive cannot be a function type, an 12344 // array type, a reference type, or a type qualified with const, volatile or 12345 // restrict. 12346 if (ReductionType.hasQualifiers()) { 12347 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 12348 return QualType(); 12349 } 12350 12351 if (ReductionType->isFunctionType()) { 12352 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 12353 return QualType(); 12354 } 12355 if (ReductionType->isReferenceType()) { 12356 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 12357 return QualType(); 12358 } 12359 if (ReductionType->isArrayType()) { 12360 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 12361 return QualType(); 12362 } 12363 return ReductionType; 12364 } 12365 12366 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 12367 Scope *S, DeclContext *DC, DeclarationName Name, 12368 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 12369 AccessSpecifier AS, Decl *PrevDeclInScope) { 12370 SmallVector<Decl *, 8> Decls; 12371 Decls.reserve(ReductionTypes.size()); 12372 12373 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 12374 forRedeclarationInCurContext()); 12375 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 12376 // A reduction-identifier may not be re-declared in the current scope for the 12377 // same type or for a type that is compatible according to the base language 12378 // rules. 12379 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 12380 OMPDeclareReductionDecl *PrevDRD = nullptr; 12381 bool InCompoundScope = true; 12382 if (S != nullptr) { 12383 // Find previous declaration with the same name not referenced in other 12384 // declarations. 12385 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 12386 InCompoundScope = 12387 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 12388 LookupName(Lookup, S); 12389 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 12390 /*AllowInlineNamespace=*/false); 12391 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 12392 auto Filter = Lookup.makeFilter(); 12393 while (Filter.hasNext()) { 12394 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 12395 if (InCompoundScope) { 12396 auto I = UsedAsPrevious.find(PrevDecl); 12397 if (I == UsedAsPrevious.end()) 12398 UsedAsPrevious[PrevDecl] = false; 12399 if (auto *D = PrevDecl->getPrevDeclInScope()) 12400 UsedAsPrevious[D] = true; 12401 } 12402 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 12403 PrevDecl->getLocation(); 12404 } 12405 Filter.done(); 12406 if (InCompoundScope) { 12407 for (auto &PrevData : UsedAsPrevious) { 12408 if (!PrevData.second) { 12409 PrevDRD = PrevData.first; 12410 break; 12411 } 12412 } 12413 } 12414 } else if (PrevDeclInScope != nullptr) { 12415 auto *PrevDRDInScope = PrevDRD = 12416 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 12417 do { 12418 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 12419 PrevDRDInScope->getLocation(); 12420 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 12421 } while (PrevDRDInScope != nullptr); 12422 } 12423 for (auto &TyData : ReductionTypes) { 12424 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 12425 bool Invalid = false; 12426 if (I != PreviousRedeclTypes.end()) { 12427 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 12428 << TyData.first; 12429 Diag(I->second, diag::note_previous_definition); 12430 Invalid = true; 12431 } 12432 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 12433 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 12434 Name, TyData.first, PrevDRD); 12435 DC->addDecl(DRD); 12436 DRD->setAccess(AS); 12437 Decls.push_back(DRD); 12438 if (Invalid) 12439 DRD->setInvalidDecl(); 12440 else 12441 PrevDRD = DRD; 12442 } 12443 12444 return DeclGroupPtrTy::make( 12445 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 12446 } 12447 12448 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 12449 auto *DRD = cast<OMPDeclareReductionDecl>(D); 12450 12451 // Enter new function scope. 12452 PushFunctionScope(); 12453 setFunctionHasBranchProtectedScope(); 12454 getCurFunction()->setHasOMPDeclareReductionCombiner(); 12455 12456 if (S != nullptr) 12457 PushDeclContext(S, DRD); 12458 else 12459 CurContext = DRD; 12460 12461 PushExpressionEvaluationContext( 12462 ExpressionEvaluationContext::PotentiallyEvaluated); 12463 12464 QualType ReductionType = DRD->getType(); 12465 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 12466 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 12467 // uses semantics of argument handles by value, but it should be passed by 12468 // reference. C lang does not support references, so pass all parameters as 12469 // pointers. 12470 // Create 'T omp_in;' variable. 12471 auto *OmpInParm = 12472 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 12473 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 12474 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 12475 // uses semantics of argument handles by value, but it should be passed by 12476 // reference. C lang does not support references, so pass all parameters as 12477 // pointers. 12478 // Create 'T omp_out;' variable. 12479 auto *OmpOutParm = 12480 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 12481 if (S != nullptr) { 12482 PushOnScopeChains(OmpInParm, S); 12483 PushOnScopeChains(OmpOutParm, S); 12484 } else { 12485 DRD->addDecl(OmpInParm); 12486 DRD->addDecl(OmpOutParm); 12487 } 12488 } 12489 12490 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 12491 auto *DRD = cast<OMPDeclareReductionDecl>(D); 12492 DiscardCleanupsInEvaluationContext(); 12493 PopExpressionEvaluationContext(); 12494 12495 PopDeclContext(); 12496 PopFunctionScopeInfo(); 12497 12498 if (Combiner != nullptr) 12499 DRD->setCombiner(Combiner); 12500 else 12501 DRD->setInvalidDecl(); 12502 } 12503 12504 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 12505 auto *DRD = cast<OMPDeclareReductionDecl>(D); 12506 12507 // Enter new function scope. 12508 PushFunctionScope(); 12509 setFunctionHasBranchProtectedScope(); 12510 12511 if (S != nullptr) 12512 PushDeclContext(S, DRD); 12513 else 12514 CurContext = DRD; 12515 12516 PushExpressionEvaluationContext( 12517 ExpressionEvaluationContext::PotentiallyEvaluated); 12518 12519 QualType ReductionType = DRD->getType(); 12520 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 12521 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 12522 // uses semantics of argument handles by value, but it should be passed by 12523 // reference. C lang does not support references, so pass all parameters as 12524 // pointers. 12525 // Create 'T omp_priv;' variable. 12526 auto *OmpPrivParm = 12527 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 12528 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 12529 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 12530 // uses semantics of argument handles by value, but it should be passed by 12531 // reference. C lang does not support references, so pass all parameters as 12532 // pointers. 12533 // Create 'T omp_orig;' variable. 12534 auto *OmpOrigParm = 12535 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 12536 if (S != nullptr) { 12537 PushOnScopeChains(OmpPrivParm, S); 12538 PushOnScopeChains(OmpOrigParm, S); 12539 } else { 12540 DRD->addDecl(OmpPrivParm); 12541 DRD->addDecl(OmpOrigParm); 12542 } 12543 return OmpPrivParm; 12544 } 12545 12546 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 12547 VarDecl *OmpPrivParm) { 12548 auto *DRD = cast<OMPDeclareReductionDecl>(D); 12549 DiscardCleanupsInEvaluationContext(); 12550 PopExpressionEvaluationContext(); 12551 12552 PopDeclContext(); 12553 PopFunctionScopeInfo(); 12554 12555 if (Initializer != nullptr) { 12556 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit); 12557 } else if (OmpPrivParm->hasInit()) { 12558 DRD->setInitializer(OmpPrivParm->getInit(), 12559 OmpPrivParm->isDirectInit() 12560 ? OMPDeclareReductionDecl::DirectInit 12561 : OMPDeclareReductionDecl::CopyInit); 12562 } else { 12563 DRD->setInvalidDecl(); 12564 } 12565 } 12566 12567 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 12568 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 12569 for (auto *D : DeclReductions.get()) { 12570 if (IsValid) { 12571 auto *DRD = cast<OMPDeclareReductionDecl>(D); 12572 if (S != nullptr) 12573 PushOnScopeChains(DRD, S, /*AddToContext=*/false); 12574 } else 12575 D->setInvalidDecl(); 12576 } 12577 return DeclReductions; 12578 } 12579 12580 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 12581 SourceLocation StartLoc, 12582 SourceLocation LParenLoc, 12583 SourceLocation EndLoc) { 12584 Expr *ValExpr = NumTeams; 12585 Stmt *HelperValStmt = nullptr; 12586 12587 // OpenMP [teams Constrcut, Restrictions] 12588 // The num_teams expression must evaluate to a positive integer value. 12589 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 12590 /*StrictlyPositive=*/true)) 12591 return nullptr; 12592 12593 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 12594 OpenMPDirectiveKind CaptureRegion = 12595 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams); 12596 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 12597 ValExpr = MakeFullExpr(ValExpr).get(); 12598 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 12599 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 12600 HelperValStmt = buildPreInits(Context, Captures); 12601 } 12602 12603 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 12604 StartLoc, LParenLoc, EndLoc); 12605 } 12606 12607 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 12608 SourceLocation StartLoc, 12609 SourceLocation LParenLoc, 12610 SourceLocation EndLoc) { 12611 Expr *ValExpr = ThreadLimit; 12612 Stmt *HelperValStmt = nullptr; 12613 12614 // OpenMP [teams Constrcut, Restrictions] 12615 // The thread_limit expression must evaluate to a positive integer value. 12616 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 12617 /*StrictlyPositive=*/true)) 12618 return nullptr; 12619 12620 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 12621 OpenMPDirectiveKind CaptureRegion = 12622 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit); 12623 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) { 12624 ValExpr = MakeFullExpr(ValExpr).get(); 12625 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 12626 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 12627 HelperValStmt = buildPreInits(Context, Captures); 12628 } 12629 12630 return new (Context) OMPThreadLimitClause( 12631 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 12632 } 12633 12634 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 12635 SourceLocation StartLoc, 12636 SourceLocation LParenLoc, 12637 SourceLocation EndLoc) { 12638 Expr *ValExpr = Priority; 12639 12640 // OpenMP [2.9.1, task Constrcut] 12641 // The priority-value is a non-negative numerical scalar expression. 12642 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority, 12643 /*StrictlyPositive=*/false)) 12644 return nullptr; 12645 12646 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc); 12647 } 12648 12649 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 12650 SourceLocation StartLoc, 12651 SourceLocation LParenLoc, 12652 SourceLocation EndLoc) { 12653 Expr *ValExpr = Grainsize; 12654 12655 // OpenMP [2.9.2, taskloop Constrcut] 12656 // The parameter of the grainsize clause must be a positive integer 12657 // expression. 12658 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize, 12659 /*StrictlyPositive=*/true)) 12660 return nullptr; 12661 12662 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc); 12663 } 12664 12665 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 12666 SourceLocation StartLoc, 12667 SourceLocation LParenLoc, 12668 SourceLocation EndLoc) { 12669 Expr *ValExpr = NumTasks; 12670 12671 // OpenMP [2.9.2, taskloop Constrcut] 12672 // The parameter of the num_tasks clause must be a positive integer 12673 // expression. 12674 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks, 12675 /*StrictlyPositive=*/true)) 12676 return nullptr; 12677 12678 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc); 12679 } 12680 12681 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 12682 SourceLocation LParenLoc, 12683 SourceLocation EndLoc) { 12684 // OpenMP [2.13.2, critical construct, Description] 12685 // ... where hint-expression is an integer constant expression that evaluates 12686 // to a valid lock hint. 12687 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 12688 if (HintExpr.isInvalid()) 12689 return nullptr; 12690 return new (Context) 12691 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 12692 } 12693 12694 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 12695 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 12696 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 12697 SourceLocation EndLoc) { 12698 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 12699 std::string Values; 12700 Values += "'"; 12701 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 12702 Values += "'"; 12703 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 12704 << Values << getOpenMPClauseName(OMPC_dist_schedule); 12705 return nullptr; 12706 } 12707 Expr *ValExpr = ChunkSize; 12708 Stmt *HelperValStmt = nullptr; 12709 if (ChunkSize) { 12710 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 12711 !ChunkSize->isInstantiationDependent() && 12712 !ChunkSize->containsUnexpandedParameterPack()) { 12713 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 12714 ExprResult Val = 12715 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 12716 if (Val.isInvalid()) 12717 return nullptr; 12718 12719 ValExpr = Val.get(); 12720 12721 // OpenMP [2.7.1, Restrictions] 12722 // chunk_size must be a loop invariant integer expression with a positive 12723 // value. 12724 llvm::APSInt Result; 12725 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 12726 if (Result.isSigned() && !Result.isStrictlyPositive()) { 12727 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 12728 << "dist_schedule" << ChunkSize->getSourceRange(); 12729 return nullptr; 12730 } 12731 } else if (getOpenMPCaptureRegionForClause( 12732 DSAStack->getCurrentDirective(), OMPC_dist_schedule) != 12733 OMPD_unknown && 12734 !CurContext->isDependentContext()) { 12735 ValExpr = MakeFullExpr(ValExpr).get(); 12736 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 12737 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 12738 HelperValStmt = buildPreInits(Context, Captures); 12739 } 12740 } 12741 } 12742 12743 return new (Context) 12744 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 12745 Kind, ValExpr, HelperValStmt); 12746 } 12747 12748 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 12749 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 12750 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 12751 SourceLocation KindLoc, SourceLocation EndLoc) { 12752 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)' 12753 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) { 12754 std::string Value; 12755 SourceLocation Loc; 12756 Value += "'"; 12757 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 12758 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 12759 OMPC_DEFAULTMAP_MODIFIER_tofrom); 12760 Loc = MLoc; 12761 } else { 12762 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 12763 OMPC_DEFAULTMAP_scalar); 12764 Loc = KindLoc; 12765 } 12766 Value += "'"; 12767 Diag(Loc, diag::err_omp_unexpected_clause_value) 12768 << Value << getOpenMPClauseName(OMPC_defaultmap); 12769 return nullptr; 12770 } 12771 DSAStack->setDefaultDMAToFromScalar(StartLoc); 12772 12773 return new (Context) 12774 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 12775 } 12776 12777 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 12778 DeclContext *CurLexicalContext = getCurLexicalContext(); 12779 if (!CurLexicalContext->isFileContext() && 12780 !CurLexicalContext->isExternCContext() && 12781 !CurLexicalContext->isExternCXXContext() && 12782 !isa<CXXRecordDecl>(CurLexicalContext) && 12783 !isa<ClassTemplateDecl>(CurLexicalContext) && 12784 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) && 12785 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) { 12786 Diag(Loc, diag::err_omp_region_not_file_context); 12787 return false; 12788 } 12789 if (IsInOpenMPDeclareTargetContext) { 12790 Diag(Loc, diag::err_omp_enclosed_declare_target); 12791 return false; 12792 } 12793 12794 IsInOpenMPDeclareTargetContext = true; 12795 return true; 12796 } 12797 12798 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 12799 assert(IsInOpenMPDeclareTargetContext && 12800 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 12801 12802 IsInOpenMPDeclareTargetContext = false; 12803 } 12804 12805 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, 12806 CXXScopeSpec &ScopeSpec, 12807 const DeclarationNameInfo &Id, 12808 OMPDeclareTargetDeclAttr::MapTypeTy MT, 12809 NamedDeclSetType &SameDirectiveDecls) { 12810 LookupResult Lookup(*this, Id, LookupOrdinaryName); 12811 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 12812 12813 if (Lookup.isAmbiguous()) 12814 return; 12815 Lookup.suppressDiagnostics(); 12816 12817 if (!Lookup.isSingleResult()) { 12818 if (TypoCorrection Corrected = 12819 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, 12820 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this), 12821 CTK_ErrorRecovery)) { 12822 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 12823 << Id.getName()); 12824 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 12825 return; 12826 } 12827 12828 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 12829 return; 12830 } 12831 12832 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 12833 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 12834 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 12835 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 12836 12837 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) { 12838 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT); 12839 ND->addAttr(A); 12840 if (ASTMutationListener *ML = Context.getASTMutationListener()) 12841 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 12842 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc()); 12843 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) { 12844 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link) 12845 << Id.getName(); 12846 } 12847 } else 12848 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 12849 } 12850 12851 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 12852 Sema &SemaRef, Decl *D) { 12853 if (!D) 12854 return; 12855 const Decl *LD = nullptr; 12856 if (isa<TagDecl>(D)) { 12857 LD = cast<TagDecl>(D)->getDefinition(); 12858 } else if (isa<VarDecl>(D)) { 12859 LD = cast<VarDecl>(D)->getDefinition(); 12860 12861 // If this is an implicit variable that is legal and we do not need to do 12862 // anything. 12863 if (cast<VarDecl>(D)->isImplicit()) { 12864 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 12865 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 12866 D->addAttr(A); 12867 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 12868 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 12869 return; 12870 } 12871 } else if (auto *F = dyn_cast<FunctionDecl>(D)) { 12872 const FunctionDecl *FD = nullptr; 12873 if (cast<FunctionDecl>(D)->hasBody(FD)) { 12874 LD = FD; 12875 // If the definition is associated with the current declaration in the 12876 // target region (it can be e.g. a lambda) that is legal and we do not 12877 // need to do anything else. 12878 if (LD == D) { 12879 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 12880 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 12881 D->addAttr(A); 12882 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 12883 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 12884 return; 12885 } 12886 } else if (F->isFunctionTemplateSpecialization() && 12887 F->getTemplateSpecializationKind() == 12888 TSK_ImplicitInstantiation) { 12889 // Check if the function is implicitly instantiated from the template 12890 // defined in the declare target region. 12891 const FunctionTemplateDecl *FTD = F->getPrimaryTemplate(); 12892 if (FTD && FTD->hasAttr<OMPDeclareTargetDeclAttr>()) 12893 return; 12894 } 12895 } 12896 if (!LD) 12897 LD = D; 12898 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() && 12899 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) { 12900 // Outlined declaration is not declared target. 12901 if (LD->isOutOfLine()) { 12902 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 12903 SemaRef.Diag(SL, diag::note_used_here) << SR; 12904 } else { 12905 const DeclContext *DC = LD->getDeclContext(); 12906 while (DC) { 12907 if (isa<FunctionDecl>(DC) && 12908 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>()) 12909 break; 12910 DC = DC->getParent(); 12911 } 12912 if (DC) 12913 return; 12914 12915 // Is not declared in target context. 12916 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 12917 SemaRef.Diag(SL, diag::note_used_here) << SR; 12918 } 12919 // Mark decl as declared target to prevent further diagnostic. 12920 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 12921 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 12922 D->addAttr(A); 12923 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 12924 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 12925 } 12926 } 12927 12928 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 12929 Sema &SemaRef, DSAStackTy *Stack, 12930 ValueDecl *VD) { 12931 if (VD->hasAttr<OMPDeclareTargetDeclAttr>()) 12932 return true; 12933 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType(), 12934 /*FullCheck=*/false)) 12935 return false; 12936 return true; 12937 } 12938 12939 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D, 12940 SourceLocation IdLoc) { 12941 if (!D || D->isInvalidDecl()) 12942 return; 12943 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 12944 SourceLocation SL = E ? E->getLocStart() : D->getLocation(); 12945 // 2.10.6: threadprivate variable cannot appear in a declare target directive. 12946 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 12947 if (DSAStack->isThreadPrivate(VD)) { 12948 Diag(SL, diag::err_omp_threadprivate_in_target); 12949 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 12950 return; 12951 } 12952 } 12953 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 12954 // Problem if any with var declared with incomplete type will be reported 12955 // as normal, so no need to check it here. 12956 if ((E || !VD->getType()->isIncompleteType()) && 12957 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) { 12958 // Mark decl as declared target to prevent further diagnostic. 12959 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD) || 12960 isa<FunctionTemplateDecl>(VD)) { 12961 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 12962 Context, OMPDeclareTargetDeclAttr::MT_To); 12963 VD->addAttr(A); 12964 if (ASTMutationListener *ML = Context.getASTMutationListener()) 12965 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A); 12966 } 12967 return; 12968 } 12969 } 12970 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 12971 if (FD->hasAttr<OMPDeclareTargetDeclAttr>() && 12972 (FD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() == 12973 OMPDeclareTargetDeclAttr::MT_Link)) { 12974 assert(IdLoc.isValid() && "Source location is expected"); 12975 Diag(IdLoc, diag::err_omp_function_in_link_clause); 12976 Diag(FD->getLocation(), diag::note_defined_here) << FD; 12977 return; 12978 } 12979 } 12980 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) { 12981 if (FTD->hasAttr<OMPDeclareTargetDeclAttr>() && 12982 (FTD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() == 12983 OMPDeclareTargetDeclAttr::MT_Link)) { 12984 assert(IdLoc.isValid() && "Source location is expected"); 12985 Diag(IdLoc, diag::err_omp_function_in_link_clause); 12986 Diag(FTD->getLocation(), diag::note_defined_here) << FTD; 12987 return; 12988 } 12989 } 12990 if (!E) { 12991 // Checking declaration inside declare target region. 12992 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() && 12993 (isa<VarDecl>(D) || isa<FunctionDecl>(D) || 12994 isa<FunctionTemplateDecl>(D))) { 12995 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 12996 Context, OMPDeclareTargetDeclAttr::MT_To); 12997 D->addAttr(A); 12998 if (ASTMutationListener *ML = Context.getASTMutationListener()) 12999 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 13000 } 13001 return; 13002 } 13003 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 13004 } 13005 13006 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, 13007 SourceLocation StartLoc, 13008 SourceLocation LParenLoc, 13009 SourceLocation EndLoc) { 13010 MappableVarListInfo MVLI(VarList); 13011 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc); 13012 if (MVLI.ProcessedVarList.empty()) 13013 return nullptr; 13014 13015 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc, 13016 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 13017 MVLI.VarComponents); 13018 } 13019 13020 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, 13021 SourceLocation StartLoc, 13022 SourceLocation LParenLoc, 13023 SourceLocation EndLoc) { 13024 MappableVarListInfo MVLI(VarList); 13025 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc); 13026 if (MVLI.ProcessedVarList.empty()) 13027 return nullptr; 13028 13029 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc, 13030 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 13031 MVLI.VarComponents); 13032 } 13033 13034 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 13035 SourceLocation StartLoc, 13036 SourceLocation LParenLoc, 13037 SourceLocation EndLoc) { 13038 MappableVarListInfo MVLI(VarList); 13039 SmallVector<Expr *, 8> PrivateCopies; 13040 SmallVector<Expr *, 8> Inits; 13041 13042 for (auto &RefExpr : VarList) { 13043 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 13044 SourceLocation ELoc; 13045 SourceRange ERange; 13046 Expr *SimpleRefExpr = RefExpr; 13047 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 13048 if (Res.second) { 13049 // It will be analyzed later. 13050 MVLI.ProcessedVarList.push_back(RefExpr); 13051 PrivateCopies.push_back(nullptr); 13052 Inits.push_back(nullptr); 13053 } 13054 ValueDecl *D = Res.first; 13055 if (!D) 13056 continue; 13057 13058 QualType Type = D->getType(); 13059 Type = Type.getNonReferenceType().getUnqualifiedType(); 13060 13061 auto *VD = dyn_cast<VarDecl>(D); 13062 13063 // Item should be a pointer or reference to pointer. 13064 if (!Type->isPointerType()) { 13065 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 13066 << 0 << RefExpr->getSourceRange(); 13067 continue; 13068 } 13069 13070 // Build the private variable and the expression that refers to it. 13071 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 13072 D->hasAttrs() ? &D->getAttrs() : nullptr); 13073 if (VDPrivate->isInvalidDecl()) 13074 continue; 13075 13076 CurContext->addDecl(VDPrivate); 13077 auto VDPrivateRefExpr = buildDeclRefExpr( 13078 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 13079 13080 // Add temporary variable to initialize the private copy of the pointer. 13081 auto *VDInit = 13082 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 13083 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 13084 RefExpr->getExprLoc()); 13085 AddInitializerToDecl(VDPrivate, 13086 DefaultLvalueConversion(VDInitRefExpr).get(), 13087 /*DirectInit=*/false); 13088 13089 // If required, build a capture to implement the privatization initialized 13090 // with the current list item value. 13091 DeclRefExpr *Ref = nullptr; 13092 if (!VD) 13093 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 13094 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 13095 PrivateCopies.push_back(VDPrivateRefExpr); 13096 Inits.push_back(VDInitRefExpr); 13097 13098 // We need to add a data sharing attribute for this variable to make sure it 13099 // is correctly captured. A variable that shows up in a use_device_ptr has 13100 // similar properties of a first private variable. 13101 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 13102 13103 // Create a mappable component for the list item. List items in this clause 13104 // only need a component. 13105 MVLI.VarBaseDeclarations.push_back(D); 13106 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 13107 MVLI.VarComponents.back().push_back( 13108 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D)); 13109 } 13110 13111 if (MVLI.ProcessedVarList.empty()) 13112 return nullptr; 13113 13114 return OMPUseDevicePtrClause::Create( 13115 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 13116 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents); 13117 } 13118 13119 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 13120 SourceLocation StartLoc, 13121 SourceLocation LParenLoc, 13122 SourceLocation EndLoc) { 13123 MappableVarListInfo MVLI(VarList); 13124 for (auto &RefExpr : VarList) { 13125 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 13126 SourceLocation ELoc; 13127 SourceRange ERange; 13128 Expr *SimpleRefExpr = RefExpr; 13129 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 13130 if (Res.second) { 13131 // It will be analyzed later. 13132 MVLI.ProcessedVarList.push_back(RefExpr); 13133 } 13134 ValueDecl *D = Res.first; 13135 if (!D) 13136 continue; 13137 13138 QualType Type = D->getType(); 13139 // item should be a pointer or array or reference to pointer or array 13140 if (!Type.getNonReferenceType()->isPointerType() && 13141 !Type.getNonReferenceType()->isArrayType()) { 13142 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 13143 << 0 << RefExpr->getSourceRange(); 13144 continue; 13145 } 13146 13147 // Check if the declaration in the clause does not show up in any data 13148 // sharing attribute. 13149 auto DVar = DSAStack->getTopDSA(D, false); 13150 if (isOpenMPPrivate(DVar.CKind)) { 13151 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 13152 << getOpenMPClauseName(DVar.CKind) 13153 << getOpenMPClauseName(OMPC_is_device_ptr) 13154 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 13155 ReportOriginalDSA(*this, DSAStack, D, DVar); 13156 continue; 13157 } 13158 13159 Expr *ConflictExpr; 13160 if (DSAStack->checkMappableExprComponentListsForDecl( 13161 D, /*CurrentRegionOnly=*/true, 13162 [&ConflictExpr]( 13163 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 13164 OpenMPClauseKind) -> bool { 13165 ConflictExpr = R.front().getAssociatedExpression(); 13166 return true; 13167 })) { 13168 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 13169 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 13170 << ConflictExpr->getSourceRange(); 13171 continue; 13172 } 13173 13174 // Store the components in the stack so that they can be used to check 13175 // against other clauses later on. 13176 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D); 13177 DSAStack->addMappableExpressionComponents( 13178 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 13179 13180 // Record the expression we've just processed. 13181 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 13182 13183 // Create a mappable component for the list item. List items in this clause 13184 // only need a component. We use a null declaration to signal fields in 13185 // 'this'. 13186 assert((isa<DeclRefExpr>(SimpleRefExpr) || 13187 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 13188 "Unexpected device pointer expression!"); 13189 MVLI.VarBaseDeclarations.push_back( 13190 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 13191 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 13192 MVLI.VarComponents.back().push_back(MC); 13193 } 13194 13195 if (MVLI.ProcessedVarList.empty()) 13196 return nullptr; 13197 13198 return OMPIsDevicePtrClause::Create( 13199 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 13200 MVLI.VarBaseDeclarations, MVLI.VarComponents); 13201 } 13202