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/AST/TypeOrdering.h" 26 #include "clang/Basic/OpenMPKinds.h" 27 #include "clang/Basic/TargetInfo.h" 28 #include "clang/Lex/Preprocessor.h" 29 #include "clang/Sema/Initialization.h" 30 #include "clang/Sema/Lookup.h" 31 #include "clang/Sema/Scope.h" 32 #include "clang/Sema/ScopeInfo.h" 33 #include "clang/Sema/SemaInternal.h" 34 using namespace clang; 35 36 //===----------------------------------------------------------------------===// 37 // Stack of data-sharing attributes for variables 38 //===----------------------------------------------------------------------===// 39 40 namespace { 41 /// \brief Default data sharing attributes, which can be applied to directive. 42 enum DefaultDataSharingAttributes { 43 DSA_unspecified = 0, /// \brief Data sharing attribute not specified. 44 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'. 45 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'. 46 }; 47 48 /// \brief Stack for tracking declarations used in OpenMP directives and 49 /// clauses and their data-sharing attributes. 50 class DSAStackTy final { 51 public: 52 struct DSAVarData final { 53 OpenMPDirectiveKind DKind = OMPD_unknown; 54 OpenMPClauseKind CKind = OMPC_unknown; 55 Expr *RefExpr = nullptr; 56 DeclRefExpr *PrivateCopy = nullptr; 57 SourceLocation ImplicitDSALoc; 58 DSAVarData() {} 59 }; 60 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4> 61 OperatorOffsetTy; 62 63 private: 64 struct DSAInfo final { 65 OpenMPClauseKind Attributes = OMPC_unknown; 66 /// Pointer to a reference expression and a flag which shows that the 67 /// variable is marked as lastprivate(true) or not (false). 68 llvm::PointerIntPair<Expr *, 1, bool> RefExpr; 69 DeclRefExpr *PrivateCopy = nullptr; 70 }; 71 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy; 72 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy; 73 typedef std::pair<unsigned, VarDecl *> LCDeclInfo; 74 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy; 75 /// Struct that associates a component with the clause kind where they are 76 /// found. 77 struct MappedExprComponentTy { 78 OMPClauseMappableExprCommon::MappableExprComponentLists Components; 79 OpenMPClauseKind Kind = OMPC_unknown; 80 }; 81 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy> 82 MappedExprComponentsTy; 83 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>> 84 CriticalsWithHintsTy; 85 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy> 86 DoacrossDependMapTy; 87 88 struct SharingMapTy final { 89 DeclSAMapTy SharingMap; 90 AlignedMapTy AlignedMap; 91 MappedExprComponentsTy MappedExprComponents; 92 LoopControlVariablesMapTy LCVMap; 93 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 94 SourceLocation DefaultAttrLoc; 95 OpenMPDirectiveKind Directive = OMPD_unknown; 96 DeclarationNameInfo DirectiveName; 97 Scope *CurScope = nullptr; 98 SourceLocation ConstructLoc; 99 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 100 /// get the data (loop counters etc.) about enclosing loop-based construct. 101 /// This data is required during codegen. 102 DoacrossDependMapTy DoacrossDepends; 103 /// \brief first argument (Expr *) contains optional argument of the 104 /// 'ordered' clause, the second one is true if the regions has 'ordered' 105 /// clause, false otherwise. 106 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion; 107 bool NowaitRegion = false; 108 bool CancelRegion = false; 109 unsigned AssociatedLoops = 1; 110 SourceLocation InnerTeamsRegionLoc; 111 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 112 Scope *CurScope, SourceLocation Loc) 113 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 114 ConstructLoc(Loc) {} 115 SharingMapTy() {} 116 }; 117 118 typedef SmallVector<SharingMapTy, 4> StackTy; 119 120 /// \brief Stack of used declaration and their data-sharing attributes. 121 DeclSAMapTy Threadprivates; 122 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr; 123 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack; 124 /// \brief true, if check for DSA must be from parent directive, false, if 125 /// from current directive. 126 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 127 Sema &SemaRef; 128 bool ForceCapturing = false; 129 CriticalsWithHintsTy Criticals; 130 131 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator; 132 133 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D); 134 135 /// \brief Checks if the variable is a local for OpenMP region. 136 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter); 137 138 bool isStackEmpty() const { 139 return Stack.empty() || 140 Stack.back().second != CurrentNonCapturingFunctionScope || 141 Stack.back().first.empty(); 142 } 143 144 public: 145 explicit DSAStackTy(Sema &S) : SemaRef(S) {} 146 147 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 148 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 149 150 bool isForceVarCapturing() const { return ForceCapturing; } 151 void setForceVarCapturing(bool V) { ForceCapturing = V; } 152 153 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 154 Scope *CurScope, SourceLocation Loc) { 155 if (Stack.empty() || 156 Stack.back().second != CurrentNonCapturingFunctionScope) 157 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope); 158 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc); 159 Stack.back().first.back().DefaultAttrLoc = Loc; 160 } 161 162 void pop() { 163 assert(!Stack.back().first.empty() && 164 "Data-sharing attributes stack is empty!"); 165 Stack.back().first.pop_back(); 166 } 167 168 /// Start new OpenMP region stack in new non-capturing function. 169 void pushFunction() { 170 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction(); 171 assert(!isa<CapturingScopeInfo>(CurFnScope)); 172 CurrentNonCapturingFunctionScope = CurFnScope; 173 } 174 /// Pop region stack for non-capturing function. 175 void popFunction(const FunctionScopeInfo *OldFSI) { 176 if (!Stack.empty() && Stack.back().second == OldFSI) { 177 assert(Stack.back().first.empty()); 178 Stack.pop_back(); 179 } 180 CurrentNonCapturingFunctionScope = nullptr; 181 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) { 182 if (!isa<CapturingScopeInfo>(FSI)) { 183 CurrentNonCapturingFunctionScope = FSI; 184 break; 185 } 186 } 187 } 188 189 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) { 190 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint); 191 } 192 const std::pair<OMPCriticalDirective *, llvm::APSInt> 193 getCriticalWithHint(const DeclarationNameInfo &Name) const { 194 auto I = Criticals.find(Name.getAsString()); 195 if (I != Criticals.end()) 196 return I->second; 197 return std::make_pair(nullptr, llvm::APSInt()); 198 } 199 /// \brief If 'aligned' declaration for given variable \a D was not seen yet, 200 /// add it and return NULL; otherwise return previous occurrence's expression 201 /// for diagnostics. 202 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE); 203 204 /// \brief Register specified variable as loop control variable. 205 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture); 206 /// \brief Check if the specified variable is a loop control variable for 207 /// current region. 208 /// \return The index of the loop control variable in the list of associated 209 /// for-loops (from outer to inner). 210 LCDeclInfo isLoopControlVariable(ValueDecl *D); 211 /// \brief Check if the specified variable is a loop control variable for 212 /// parent region. 213 /// \return The index of the loop control variable in the list of associated 214 /// for-loops (from outer to inner). 215 LCDeclInfo isParentLoopControlVariable(ValueDecl *D); 216 /// \brief Get the loop control variable for the I-th loop (or nullptr) in 217 /// parent directive. 218 ValueDecl *getParentLoopControlVariable(unsigned I); 219 220 /// \brief Adds explicit data sharing attribute to the specified declaration. 221 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, 222 DeclRefExpr *PrivateCopy = nullptr); 223 224 /// \brief Returns data sharing attributes from top of the stack for the 225 /// specified declaration. 226 DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 227 /// \brief Returns data-sharing attributes for the specified declaration. 228 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent); 229 /// \brief Checks if the specified variables has data-sharing attributes which 230 /// match specified \a CPred predicate in any directive which matches \a DPred 231 /// predicate. 232 DSAVarData hasDSA(ValueDecl *D, 233 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 234 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 235 bool FromParent); 236 /// \brief Checks if the specified variables has data-sharing attributes which 237 /// match specified \a CPred predicate in any innermost directive which 238 /// matches \a DPred predicate. 239 DSAVarData 240 hasInnermostDSA(ValueDecl *D, 241 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 242 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 243 bool FromParent); 244 /// \brief Checks if the specified variables has explicit data-sharing 245 /// attributes which match specified \a CPred predicate at the specified 246 /// OpenMP region. 247 bool hasExplicitDSA(ValueDecl *D, 248 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 249 unsigned Level, bool NotLastprivate = false); 250 251 /// \brief Returns true if the directive at level \Level matches in the 252 /// specified \a DPred predicate. 253 bool hasExplicitDirective( 254 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 255 unsigned Level); 256 257 /// \brief Finds a directive which matches specified \a DPred predicate. 258 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind, 259 const DeclarationNameInfo &, 260 SourceLocation)> &DPred, 261 bool FromParent); 262 263 /// \brief Returns currently analyzed directive. 264 OpenMPDirectiveKind getCurrentDirective() const { 265 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive; 266 } 267 /// \brief Returns parent directive. 268 OpenMPDirectiveKind getParentDirective() const { 269 if (isStackEmpty() || Stack.back().first.size() == 1) 270 return OMPD_unknown; 271 return std::next(Stack.back().first.rbegin())->Directive; 272 } 273 274 /// \brief Set default data sharing attribute to none. 275 void setDefaultDSANone(SourceLocation Loc) { 276 assert(!isStackEmpty()); 277 Stack.back().first.back().DefaultAttr = DSA_none; 278 Stack.back().first.back().DefaultAttrLoc = Loc; 279 } 280 /// \brief Set default data sharing attribute to shared. 281 void setDefaultDSAShared(SourceLocation Loc) { 282 assert(!isStackEmpty()); 283 Stack.back().first.back().DefaultAttr = DSA_shared; 284 Stack.back().first.back().DefaultAttrLoc = Loc; 285 } 286 287 DefaultDataSharingAttributes getDefaultDSA() const { 288 return isStackEmpty() ? DSA_unspecified 289 : Stack.back().first.back().DefaultAttr; 290 } 291 SourceLocation getDefaultDSALocation() const { 292 return isStackEmpty() ? SourceLocation() 293 : Stack.back().first.back().DefaultAttrLoc; 294 } 295 296 /// \brief Checks if the specified variable is a threadprivate. 297 bool isThreadPrivate(VarDecl *D) { 298 DSAVarData DVar = getTopDSA(D, false); 299 return isOpenMPThreadPrivate(DVar.CKind); 300 } 301 302 /// \brief Marks current region as ordered (it has an 'ordered' clause). 303 void setOrderedRegion(bool IsOrdered, Expr *Param) { 304 assert(!isStackEmpty()); 305 Stack.back().first.back().OrderedRegion.setInt(IsOrdered); 306 Stack.back().first.back().OrderedRegion.setPointer(Param); 307 } 308 /// \brief Returns true, if parent region is ordered (has associated 309 /// 'ordered' clause), false - otherwise. 310 bool isParentOrderedRegion() const { 311 if (isStackEmpty() || Stack.back().first.size() == 1) 312 return false; 313 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt(); 314 } 315 /// \brief Returns optional parameter for the ordered region. 316 Expr *getParentOrderedRegionParam() const { 317 if (isStackEmpty() || Stack.back().first.size() == 1) 318 return nullptr; 319 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer(); 320 } 321 /// \brief Marks current region as nowait (it has a 'nowait' clause). 322 void setNowaitRegion(bool IsNowait = true) { 323 assert(!isStackEmpty()); 324 Stack.back().first.back().NowaitRegion = IsNowait; 325 } 326 /// \brief Returns true, if parent region is nowait (has associated 327 /// 'nowait' clause), false - otherwise. 328 bool isParentNowaitRegion() const { 329 if (isStackEmpty() || Stack.back().first.size() == 1) 330 return false; 331 return std::next(Stack.back().first.rbegin())->NowaitRegion; 332 } 333 /// \brief Marks parent region as cancel region. 334 void setParentCancelRegion(bool Cancel = true) { 335 if (!isStackEmpty() && Stack.back().first.size() > 1) { 336 auto &StackElemRef = *std::next(Stack.back().first.rbegin()); 337 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel; 338 } 339 } 340 /// \brief Return true if current region has inner cancel construct. 341 bool isCancelRegion() const { 342 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion; 343 } 344 345 /// \brief Set collapse value for the region. 346 void setAssociatedLoops(unsigned Val) { 347 assert(!isStackEmpty()); 348 Stack.back().first.back().AssociatedLoops = Val; 349 } 350 /// \brief Return collapse value for region. 351 unsigned getAssociatedLoops() const { 352 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops; 353 } 354 355 /// \brief Marks current target region as one with closely nested teams 356 /// region. 357 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 358 if (!isStackEmpty() && Stack.back().first.size() > 1) { 359 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc = 360 TeamsRegionLoc; 361 } 362 } 363 /// \brief Returns true, if current region has closely nested teams region. 364 bool hasInnerTeamsRegion() const { 365 return getInnerTeamsRegionLoc().isValid(); 366 } 367 /// \brief Returns location of the nested teams region (if any). 368 SourceLocation getInnerTeamsRegionLoc() const { 369 return isStackEmpty() ? SourceLocation() 370 : Stack.back().first.back().InnerTeamsRegionLoc; 371 } 372 373 Scope *getCurScope() const { 374 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope; 375 } 376 Scope *getCurScope() { 377 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope; 378 } 379 SourceLocation getConstructLoc() { 380 return isStackEmpty() ? SourceLocation() 381 : Stack.back().first.back().ConstructLoc; 382 } 383 384 /// Do the check specified in \a Check to all component lists and return true 385 /// if any issue is found. 386 bool checkMappableExprComponentListsForDecl( 387 ValueDecl *VD, bool CurrentRegionOnly, 388 const llvm::function_ref< 389 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 390 OpenMPClauseKind)> &Check) { 391 if (isStackEmpty()) 392 return false; 393 auto SI = Stack.back().first.rbegin(); 394 auto SE = Stack.back().first.rend(); 395 396 if (SI == SE) 397 return false; 398 399 if (CurrentRegionOnly) { 400 SE = std::next(SI); 401 } else { 402 ++SI; 403 } 404 405 for (; SI != SE; ++SI) { 406 auto MI = SI->MappedExprComponents.find(VD); 407 if (MI != SI->MappedExprComponents.end()) 408 for (auto &L : MI->second.Components) 409 if (Check(L, MI->second.Kind)) 410 return true; 411 } 412 return false; 413 } 414 415 /// Do the check specified in \a Check to all component lists at a given level 416 /// and return true if any issue is found. 417 bool checkMappableExprComponentListsForDeclAtLevel( 418 ValueDecl *VD, unsigned Level, 419 const llvm::function_ref< 420 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 421 OpenMPClauseKind)> &Check) { 422 if (isStackEmpty()) 423 return false; 424 425 auto StartI = Stack.back().first.begin(); 426 auto EndI = Stack.back().first.end(); 427 if (std::distance(StartI, EndI) <= (int)Level) 428 return false; 429 std::advance(StartI, Level); 430 431 auto MI = StartI->MappedExprComponents.find(VD); 432 if (MI != StartI->MappedExprComponents.end()) 433 for (auto &L : MI->second.Components) 434 if (Check(L, MI->second.Kind)) 435 return true; 436 return false; 437 } 438 439 /// Create a new mappable expression component list associated with a given 440 /// declaration and initialize it with the provided list of components. 441 void addMappableExpressionComponents( 442 ValueDecl *VD, 443 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 444 OpenMPClauseKind WhereFoundClauseKind) { 445 assert(!isStackEmpty() && 446 "Not expecting to retrieve components from a empty stack!"); 447 auto &MEC = Stack.back().first.back().MappedExprComponents[VD]; 448 // Create new entry and append the new components there. 449 MEC.Components.resize(MEC.Components.size() + 1); 450 MEC.Components.back().append(Components.begin(), Components.end()); 451 MEC.Kind = WhereFoundClauseKind; 452 } 453 454 unsigned getNestingLevel() const { 455 assert(!isStackEmpty()); 456 return Stack.back().first.size() - 1; 457 } 458 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) { 459 assert(!isStackEmpty() && Stack.back().first.size() > 1); 460 auto &StackElem = *std::next(Stack.back().first.rbegin()); 461 assert(isOpenMPWorksharingDirective(StackElem.Directive)); 462 StackElem.DoacrossDepends.insert({C, OpsOffs}); 463 } 464 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 465 getDoacrossDependClauses() const { 466 assert(!isStackEmpty()); 467 auto &StackElem = Stack.back().first.back(); 468 if (isOpenMPWorksharingDirective(StackElem.Directive)) { 469 auto &Ref = StackElem.DoacrossDepends; 470 return llvm::make_range(Ref.begin(), Ref.end()); 471 } 472 return llvm::make_range(StackElem.DoacrossDepends.end(), 473 StackElem.DoacrossDepends.end()); 474 } 475 }; 476 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) { 477 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) || 478 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown; 479 } 480 } // namespace 481 482 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 483 auto *VD = dyn_cast<VarDecl>(D); 484 auto *FD = dyn_cast<FieldDecl>(D); 485 if (VD != nullptr) { 486 VD = VD->getCanonicalDecl(); 487 D = VD; 488 } else { 489 assert(FD); 490 FD = FD->getCanonicalDecl(); 491 D = FD; 492 } 493 return D; 494 } 495 496 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter, 497 ValueDecl *D) { 498 D = getCanonicalDecl(D); 499 auto *VD = dyn_cast<VarDecl>(D); 500 auto *FD = dyn_cast<FieldDecl>(D); 501 DSAVarData DVar; 502 if (isStackEmpty() || Iter == Stack.back().first.rend()) { 503 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 504 // in a region but not in construct] 505 // File-scope or namespace-scope variables referenced in called routines 506 // in the region are shared unless they appear in a threadprivate 507 // directive. 508 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D)) 509 DVar.CKind = OMPC_shared; 510 511 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 512 // in a region but not in construct] 513 // Variables with static storage duration that are declared in called 514 // routines in the region are shared. 515 if (VD && VD->hasGlobalStorage()) 516 DVar.CKind = OMPC_shared; 517 518 // Non-static data members are shared by default. 519 if (FD) 520 DVar.CKind = OMPC_shared; 521 522 return DVar; 523 } 524 525 DVar.DKind = Iter->Directive; 526 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 527 // in a Construct, C/C++, predetermined, p.1] 528 // Variables with automatic storage duration that are declared in a scope 529 // inside the construct are private. 530 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 531 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 532 DVar.CKind = OMPC_private; 533 return DVar; 534 } 535 536 // Explicitly specified attributes and local variables with predetermined 537 // attributes. 538 if (Iter->SharingMap.count(D)) { 539 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer(); 540 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy; 541 DVar.CKind = Iter->SharingMap[D].Attributes; 542 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 543 return DVar; 544 } 545 546 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 547 // in a Construct, C/C++, implicitly determined, p.1] 548 // In a parallel or task construct, the data-sharing attributes of these 549 // variables are determined by the default clause, if present. 550 switch (Iter->DefaultAttr) { 551 case DSA_shared: 552 DVar.CKind = OMPC_shared; 553 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 554 return DVar; 555 case DSA_none: 556 return DVar; 557 case DSA_unspecified: 558 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 559 // in a Construct, implicitly determined, p.2] 560 // In a parallel construct, if no default clause is present, these 561 // variables are shared. 562 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 563 if (isOpenMPParallelDirective(DVar.DKind) || 564 isOpenMPTeamsDirective(DVar.DKind)) { 565 DVar.CKind = OMPC_shared; 566 return DVar; 567 } 568 569 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 570 // in a Construct, implicitly determined, p.4] 571 // In a task construct, if no default clause is present, a variable that in 572 // the enclosing context is determined to be shared by all implicit tasks 573 // bound to the current team is shared. 574 if (isOpenMPTaskingDirective(DVar.DKind)) { 575 DSAVarData DVarTemp; 576 auto I = Iter, E = Stack.back().first.rend(); 577 do { 578 ++I; 579 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 580 // Referenced in a Construct, implicitly determined, p.6] 581 // In a task construct, if no default clause is present, a variable 582 // whose data-sharing attribute is not determined by the rules above is 583 // firstprivate. 584 DVarTemp = getDSA(I, D); 585 if (DVarTemp.CKind != OMPC_shared) { 586 DVar.RefExpr = nullptr; 587 DVar.CKind = OMPC_firstprivate; 588 return DVar; 589 } 590 } while (I != E && !isParallelOrTaskRegion(I->Directive)); 591 DVar.CKind = 592 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 593 return DVar; 594 } 595 } 596 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 597 // in a Construct, implicitly determined, p.3] 598 // For constructs other than task, if no default clause is present, these 599 // variables inherit their data-sharing attributes from the enclosing 600 // context. 601 return getDSA(++Iter, D); 602 } 603 604 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) { 605 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 606 D = getCanonicalDecl(D); 607 auto &StackElem = Stack.back().first.back(); 608 auto It = StackElem.AlignedMap.find(D); 609 if (It == StackElem.AlignedMap.end()) { 610 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 611 StackElem.AlignedMap[D] = NewDE; 612 return nullptr; 613 } else { 614 assert(It->second && "Unexpected nullptr expr in the aligned map"); 615 return It->second; 616 } 617 return nullptr; 618 } 619 620 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) { 621 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 622 D = getCanonicalDecl(D); 623 auto &StackElem = Stack.back().first.back(); 624 StackElem.LCVMap.insert( 625 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)}); 626 } 627 628 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) { 629 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 630 D = getCanonicalDecl(D); 631 auto &StackElem = Stack.back().first.back(); 632 auto It = StackElem.LCVMap.find(D); 633 if (It != StackElem.LCVMap.end()) 634 return It->second; 635 return {0, nullptr}; 636 } 637 638 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) { 639 assert(!isStackEmpty() && Stack.back().first.size() > 1 && 640 "Data-sharing attributes stack is empty"); 641 D = getCanonicalDecl(D); 642 auto &StackElem = *std::next(Stack.back().first.rbegin()); 643 auto It = StackElem.LCVMap.find(D); 644 if (It != StackElem.LCVMap.end()) 645 return It->second; 646 return {0, nullptr}; 647 } 648 649 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) { 650 assert(!isStackEmpty() && Stack.back().first.size() > 1 && 651 "Data-sharing attributes stack is empty"); 652 auto &StackElem = *std::next(Stack.back().first.rbegin()); 653 if (StackElem.LCVMap.size() < I) 654 return nullptr; 655 for (auto &Pair : StackElem.LCVMap) 656 if (Pair.second.first == I) 657 return Pair.first; 658 return nullptr; 659 } 660 661 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, 662 DeclRefExpr *PrivateCopy) { 663 D = getCanonicalDecl(D); 664 if (A == OMPC_threadprivate) { 665 auto &Data = Threadprivates[D]; 666 Data.Attributes = A; 667 Data.RefExpr.setPointer(E); 668 Data.PrivateCopy = nullptr; 669 } else { 670 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 671 auto &Data = Stack.back().first.back().SharingMap[D]; 672 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 673 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 674 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 675 (isLoopControlVariable(D).first && A == OMPC_private)); 676 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 677 Data.RefExpr.setInt(/*IntVal=*/true); 678 return; 679 } 680 const bool IsLastprivate = 681 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 682 Data.Attributes = A; 683 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 684 Data.PrivateCopy = PrivateCopy; 685 if (PrivateCopy) { 686 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()]; 687 Data.Attributes = A; 688 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 689 Data.PrivateCopy = nullptr; 690 } 691 } 692 } 693 694 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) { 695 D = D->getCanonicalDecl(); 696 if (!isStackEmpty() && Stack.back().first.size() > 1) { 697 reverse_iterator I = Iter, E = Stack.back().first.rend(); 698 Scope *TopScope = nullptr; 699 while (I != E && !isParallelOrTaskRegion(I->Directive)) 700 ++I; 701 if (I == E) 702 return false; 703 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; 704 Scope *CurScope = getCurScope(); 705 while (CurScope != TopScope && !CurScope->isDeclScope(D)) 706 CurScope = CurScope->getParent(); 707 return CurScope != TopScope; 708 } 709 return false; 710 } 711 712 /// \brief Build a variable declaration for OpenMP loop iteration variable. 713 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 714 StringRef Name, const AttrVec *Attrs = nullptr) { 715 DeclContext *DC = SemaRef.CurContext; 716 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 717 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 718 VarDecl *Decl = 719 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 720 if (Attrs) { 721 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 722 I != E; ++I) 723 Decl->addAttr(*I); 724 } 725 Decl->setImplicit(); 726 return Decl; 727 } 728 729 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 730 SourceLocation Loc, 731 bool RefersToCapture = false) { 732 D->setReferenced(); 733 D->markUsed(S.Context); 734 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 735 SourceLocation(), D, RefersToCapture, Loc, Ty, 736 VK_LValue); 737 } 738 739 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) { 740 D = getCanonicalDecl(D); 741 DSAVarData DVar; 742 743 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 744 // in a Construct, C/C++, predetermined, p.1] 745 // Variables appearing in threadprivate directives are threadprivate. 746 auto *VD = dyn_cast<VarDecl>(D); 747 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 748 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 749 SemaRef.getLangOpts().OpenMPUseTLS && 750 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 751 (VD && VD->getStorageClass() == SC_Register && 752 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 753 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 754 D->getLocation()), 755 OMPC_threadprivate); 756 } 757 auto TI = Threadprivates.find(D); 758 if (TI != Threadprivates.end()) { 759 DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); 760 DVar.CKind = OMPC_threadprivate; 761 return DVar; 762 } 763 764 if (isStackEmpty()) 765 // Not in OpenMP execution region and top scope was already checked. 766 return DVar; 767 768 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 769 // in a Construct, C/C++, predetermined, p.4] 770 // Static data members are shared. 771 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 772 // in a Construct, C/C++, predetermined, p.7] 773 // Variables with static storage duration that are declared in a scope 774 // inside the construct are shared. 775 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; }; 776 if (VD && VD->isStaticDataMember()) { 777 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent); 778 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 779 return DVar; 780 781 DVar.CKind = OMPC_shared; 782 return DVar; 783 } 784 785 QualType Type = D->getType().getNonReferenceType().getCanonicalType(); 786 bool IsConstant = Type.isConstant(SemaRef.getASTContext()); 787 Type = SemaRef.getASTContext().getBaseElementType(Type); 788 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 789 // in a Construct, C/C++, predetermined, p.6] 790 // Variables with const qualified type having no mutable member are 791 // shared. 792 CXXRecordDecl *RD = 793 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 794 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 795 if (auto *CTD = CTSD->getSpecializedTemplate()) 796 RD = CTD->getTemplatedDecl(); 797 if (IsConstant && 798 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() && 799 RD->hasMutableFields())) { 800 // Variables with const-qualified type having no mutable member may be 801 // listed in a firstprivate clause, even if they are static data members. 802 DSAVarData DVarTemp = hasDSA( 803 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; }, 804 MatchesAlways, FromParent); 805 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr) 806 return DVar; 807 808 DVar.CKind = OMPC_shared; 809 return DVar; 810 } 811 812 // Explicitly specified attributes and local variables with predetermined 813 // attributes. 814 auto StartI = std::next(Stack.back().first.rbegin()); 815 auto EndI = Stack.back().first.rend(); 816 if (FromParent && StartI != EndI) 817 StartI = std::next(StartI); 818 auto I = std::prev(StartI); 819 if (I->SharingMap.count(D)) { 820 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer(); 821 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy; 822 DVar.CKind = I->SharingMap[D].Attributes; 823 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 824 } 825 826 return DVar; 827 } 828 829 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 830 bool FromParent) { 831 if (isStackEmpty()) { 832 StackTy::reverse_iterator I; 833 return getDSA(I, D); 834 } 835 D = getCanonicalDecl(D); 836 auto StartI = Stack.back().first.rbegin(); 837 auto EndI = Stack.back().first.rend(); 838 if (FromParent && StartI != EndI) 839 StartI = std::next(StartI); 840 return getDSA(StartI, D); 841 } 842 843 DSAStackTy::DSAVarData 844 DSAStackTy::hasDSA(ValueDecl *D, 845 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 846 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 847 bool FromParent) { 848 if (isStackEmpty()) 849 return {}; 850 D = getCanonicalDecl(D); 851 auto I = (FromParent && Stack.back().first.size() > 1) 852 ? std::next(Stack.back().first.rbegin()) 853 : Stack.back().first.rbegin(); 854 auto EndI = Stack.back().first.rend(); 855 while (std::distance(I, EndI) > 1) { 856 std::advance(I, 1); 857 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive)) 858 continue; 859 DSAVarData DVar = getDSA(I, D); 860 if (CPred(DVar.CKind)) 861 return DVar; 862 } 863 return {}; 864 } 865 866 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 867 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 868 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 869 bool FromParent) { 870 if (isStackEmpty()) 871 return {}; 872 D = getCanonicalDecl(D); 873 auto StartI = std::next(Stack.back().first.rbegin()); 874 auto EndI = Stack.back().first.rend(); 875 if (FromParent && StartI != EndI) 876 StartI = std::next(StartI); 877 if (StartI == EndI || !DPred(StartI->Directive)) 878 return {}; 879 DSAVarData DVar = getDSA(StartI, D); 880 return CPred(DVar.CKind) ? DVar : DSAVarData(); 881 } 882 883 bool DSAStackTy::hasExplicitDSA( 884 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 885 unsigned Level, bool NotLastprivate) { 886 if (CPred(ClauseKindMode)) 887 return true; 888 if (isStackEmpty()) 889 return false; 890 D = getCanonicalDecl(D); 891 auto StartI = Stack.back().first.begin(); 892 auto EndI = Stack.back().first.end(); 893 if (std::distance(StartI, EndI) <= (int)Level) 894 return false; 895 std::advance(StartI, Level); 896 return (StartI->SharingMap.count(D) > 0) && 897 StartI->SharingMap[D].RefExpr.getPointer() && 898 CPred(StartI->SharingMap[D].Attributes) && 899 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt()); 900 } 901 902 bool DSAStackTy::hasExplicitDirective( 903 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 904 unsigned Level) { 905 if (isStackEmpty()) 906 return false; 907 auto StartI = Stack.back().first.begin(); 908 auto EndI = Stack.back().first.end(); 909 if (std::distance(StartI, EndI) <= (int)Level) 910 return false; 911 std::advance(StartI, Level); 912 return DPred(StartI->Directive); 913 } 914 915 bool DSAStackTy::hasDirective( 916 const llvm::function_ref<bool(OpenMPDirectiveKind, 917 const DeclarationNameInfo &, SourceLocation)> 918 &DPred, 919 bool FromParent) { 920 // We look only in the enclosing region. 921 if (isStackEmpty()) 922 return false; 923 auto StartI = std::next(Stack.back().first.rbegin()); 924 auto EndI = Stack.back().first.rend(); 925 if (FromParent && StartI != EndI) 926 StartI = std::next(StartI); 927 for (auto I = StartI, EE = EndI; I != EE; ++I) { 928 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 929 return true; 930 } 931 return false; 932 } 933 934 void Sema::InitDataSharingAttributesStack() { 935 VarDataSharingAttributesStack = new DSAStackTy(*this); 936 } 937 938 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 939 940 void Sema::pushOpenMPFunctionRegion() { 941 DSAStack->pushFunction(); 942 } 943 944 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 945 DSAStack->popFunction(OldFSI); 946 } 947 948 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) { 949 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 950 951 auto &Ctx = getASTContext(); 952 bool IsByRef = true; 953 954 // Find the directive that is associated with the provided scope. 955 auto Ty = D->getType(); 956 957 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 958 // This table summarizes how a given variable should be passed to the device 959 // given its type and the clauses where it appears. This table is based on 960 // the description in OpenMP 4.5 [2.10.4, target Construct] and 961 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 962 // 963 // ========================================================================= 964 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 965 // | |(tofrom:scalar)| | pvt | | | | 966 // ========================================================================= 967 // | scl | | | | - | | bycopy| 968 // | scl | | - | x | - | - | bycopy| 969 // | scl | | x | - | - | - | null | 970 // | scl | x | | | - | | byref | 971 // | scl | x | - | x | - | - | bycopy| 972 // | scl | x | x | - | - | - | null | 973 // | scl | | - | - | - | x | byref | 974 // | scl | x | - | - | - | x | byref | 975 // 976 // | agg | n.a. | | | - | | byref | 977 // | agg | n.a. | - | x | - | - | byref | 978 // | agg | n.a. | x | - | - | - | null | 979 // | agg | n.a. | - | - | - | x | byref | 980 // | agg | n.a. | - | - | - | x[] | byref | 981 // 982 // | ptr | n.a. | | | - | | bycopy| 983 // | ptr | n.a. | - | x | - | - | bycopy| 984 // | ptr | n.a. | x | - | - | - | null | 985 // | ptr | n.a. | - | - | - | x | byref | 986 // | ptr | n.a. | - | - | - | x[] | bycopy| 987 // | ptr | n.a. | - | - | x | | bycopy| 988 // | ptr | n.a. | - | - | x | x | bycopy| 989 // | ptr | n.a. | - | - | x | x[] | bycopy| 990 // ========================================================================= 991 // Legend: 992 // scl - scalar 993 // ptr - pointer 994 // agg - aggregate 995 // x - applies 996 // - - invalid in this combination 997 // [] - mapped with an array section 998 // byref - should be mapped by reference 999 // byval - should be mapped by value 1000 // null - initialize a local variable to null on the device 1001 // 1002 // Observations: 1003 // - All scalar declarations that show up in a map clause have to be passed 1004 // by reference, because they may have been mapped in the enclosing data 1005 // environment. 1006 // - If the scalar value does not fit the size of uintptr, it has to be 1007 // passed by reference, regardless the result in the table above. 1008 // - For pointers mapped by value that have either an implicit map or an 1009 // array section, the runtime library may pass the NULL value to the 1010 // device instead of the value passed to it by the compiler. 1011 1012 if (Ty->isReferenceType()) 1013 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 1014 1015 // Locate map clauses and see if the variable being captured is referred to 1016 // in any of those clauses. Here we only care about variables, not fields, 1017 // because fields are part of aggregates. 1018 bool IsVariableUsedInMapClause = false; 1019 bool IsVariableAssociatedWithSection = false; 1020 1021 DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1022 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 1023 MapExprComponents, 1024 OpenMPClauseKind WhereFoundClauseKind) { 1025 // Only the map clause information influences how a variable is 1026 // captured. E.g. is_device_ptr does not require changing the default 1027 // behavior. 1028 if (WhereFoundClauseKind != OMPC_map) 1029 return false; 1030 1031 auto EI = MapExprComponents.rbegin(); 1032 auto EE = MapExprComponents.rend(); 1033 1034 assert(EI != EE && "Invalid map expression!"); 1035 1036 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 1037 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 1038 1039 ++EI; 1040 if (EI == EE) 1041 return false; 1042 1043 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 1044 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 1045 isa<MemberExpr>(EI->getAssociatedExpression())) { 1046 IsVariableAssociatedWithSection = true; 1047 // There is nothing more we need to know about this variable. 1048 return true; 1049 } 1050 1051 // Keep looking for more map info. 1052 return false; 1053 }); 1054 1055 if (IsVariableUsedInMapClause) { 1056 // If variable is identified in a map clause it is always captured by 1057 // reference except if it is a pointer that is dereferenced somehow. 1058 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 1059 } else { 1060 // By default, all the data that has a scalar type is mapped by copy. 1061 IsByRef = !Ty->isScalarType(); 1062 } 1063 } 1064 1065 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 1066 IsByRef = !DSAStack->hasExplicitDSA( 1067 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; }, 1068 Level, /*NotLastprivate=*/true); 1069 } 1070 1071 // When passing data by copy, we need to make sure it fits the uintptr size 1072 // and alignment, because the runtime library only deals with uintptr types. 1073 // If it does not fit the uintptr size, we need to pass the data by reference 1074 // instead. 1075 if (!IsByRef && 1076 (Ctx.getTypeSizeInChars(Ty) > 1077 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 1078 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 1079 IsByRef = true; 1080 } 1081 1082 return IsByRef; 1083 } 1084 1085 unsigned Sema::getOpenMPNestingLevel() const { 1086 assert(getLangOpts().OpenMP); 1087 return DSAStack->getNestingLevel(); 1088 } 1089 1090 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) { 1091 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1092 D = getCanonicalDecl(D); 1093 1094 // If we are attempting to capture a global variable in a directive with 1095 // 'target' we return true so that this global is also mapped to the device. 1096 // 1097 // FIXME: If the declaration is enclosed in a 'declare target' directive, 1098 // then it should not be captured. Therefore, an extra check has to be 1099 // inserted here once support for 'declare target' is added. 1100 // 1101 auto *VD = dyn_cast<VarDecl>(D); 1102 if (VD && !VD->hasLocalStorage()) { 1103 if (DSAStack->getCurrentDirective() == OMPD_target && 1104 !DSAStack->isClauseParsingMode()) 1105 return VD; 1106 if (DSAStack->hasDirective( 1107 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 1108 SourceLocation) -> bool { 1109 return isOpenMPTargetExecutionDirective(K); 1110 }, 1111 false)) 1112 return VD; 1113 } 1114 1115 if (DSAStack->getCurrentDirective() != OMPD_unknown && 1116 (!DSAStack->isClauseParsingMode() || 1117 DSAStack->getParentDirective() != OMPD_unknown)) { 1118 auto &&Info = DSAStack->isLoopControlVariable(D); 1119 if (Info.first || 1120 (VD && VD->hasLocalStorage() && 1121 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) || 1122 (VD && DSAStack->isForceVarCapturing())) 1123 return VD ? VD : Info.second; 1124 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 1125 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind)) 1126 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1127 DVarPrivate = DSAStack->hasDSA( 1128 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 1129 DSAStack->isClauseParsingMode()); 1130 if (DVarPrivate.CKind != OMPC_unknown) 1131 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1132 } 1133 return nullptr; 1134 } 1135 1136 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) { 1137 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1138 return DSAStack->hasExplicitDSA( 1139 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level); 1140 } 1141 1142 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) { 1143 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1144 // Return true if the current level is no longer enclosed in a target region. 1145 1146 auto *VD = dyn_cast<VarDecl>(D); 1147 return VD && !VD->hasLocalStorage() && 1148 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1149 Level); 1150 } 1151 1152 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 1153 1154 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 1155 const DeclarationNameInfo &DirName, 1156 Scope *CurScope, SourceLocation Loc) { 1157 DSAStack->push(DKind, DirName, CurScope, Loc); 1158 PushExpressionEvaluationContext( 1159 ExpressionEvaluationContext::PotentiallyEvaluated); 1160 } 1161 1162 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 1163 DSAStack->setClauseParsingMode(K); 1164 } 1165 1166 void Sema::EndOpenMPClause() { 1167 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 1168 } 1169 1170 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 1171 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 1172 // A variable of class type (or array thereof) that appears in a lastprivate 1173 // clause requires an accessible, unambiguous default constructor for the 1174 // class type, unless the list item is also specified in a firstprivate 1175 // clause. 1176 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 1177 for (auto *C : D->clauses()) { 1178 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 1179 SmallVector<Expr *, 8> PrivateCopies; 1180 for (auto *DE : Clause->varlists()) { 1181 if (DE->isValueDependent() || DE->isTypeDependent()) { 1182 PrivateCopies.push_back(nullptr); 1183 continue; 1184 } 1185 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 1186 VarDecl *VD = cast<VarDecl>(DRE->getDecl()); 1187 QualType Type = VD->getType().getNonReferenceType(); 1188 auto DVar = DSAStack->getTopDSA(VD, false); 1189 if (DVar.CKind == OMPC_lastprivate) { 1190 // Generate helper private variable and initialize it with the 1191 // default value. The address of the original variable is replaced 1192 // by the address of the new private variable in CodeGen. This new 1193 // variable is not added to IdResolver, so the code in the OpenMP 1194 // region uses original variable for proper diagnostics. 1195 auto *VDPrivate = buildVarDecl( 1196 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 1197 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr); 1198 ActOnUninitializedDecl(VDPrivate); 1199 if (VDPrivate->isInvalidDecl()) 1200 continue; 1201 PrivateCopies.push_back(buildDeclRefExpr( 1202 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 1203 } else { 1204 // The variable is also a firstprivate, so initialization sequence 1205 // for private copy is generated already. 1206 PrivateCopies.push_back(nullptr); 1207 } 1208 } 1209 // Set initializers to private copies if no errors were found. 1210 if (PrivateCopies.size() == Clause->varlist_size()) 1211 Clause->setPrivateCopies(PrivateCopies); 1212 } 1213 } 1214 } 1215 1216 DSAStack->pop(); 1217 DiscardCleanupsInEvaluationContext(); 1218 PopExpressionEvaluationContext(); 1219 } 1220 1221 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 1222 Expr *NumIterations, Sema &SemaRef, 1223 Scope *S, DSAStackTy *Stack); 1224 1225 namespace { 1226 1227 class VarDeclFilterCCC : public CorrectionCandidateCallback { 1228 private: 1229 Sema &SemaRef; 1230 1231 public: 1232 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 1233 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1234 NamedDecl *ND = Candidate.getCorrectionDecl(); 1235 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 1236 return VD->hasGlobalStorage() && 1237 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1238 SemaRef.getCurScope()); 1239 } 1240 return false; 1241 } 1242 }; 1243 1244 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback { 1245 private: 1246 Sema &SemaRef; 1247 1248 public: 1249 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 1250 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1251 NamedDecl *ND = Candidate.getCorrectionDecl(); 1252 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 1253 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1254 SemaRef.getCurScope()); 1255 } 1256 return false; 1257 } 1258 }; 1259 1260 } // namespace 1261 1262 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 1263 CXXScopeSpec &ScopeSpec, 1264 const DeclarationNameInfo &Id) { 1265 LookupResult Lookup(*this, Id, LookupOrdinaryName); 1266 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 1267 1268 if (Lookup.isAmbiguous()) 1269 return ExprError(); 1270 1271 VarDecl *VD; 1272 if (!Lookup.isSingleResult()) { 1273 if (TypoCorrection Corrected = CorrectTypo( 1274 Id, LookupOrdinaryName, CurScope, nullptr, 1275 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) { 1276 diagnoseTypo(Corrected, 1277 PDiag(Lookup.empty() 1278 ? diag::err_undeclared_var_use_suggest 1279 : diag::err_omp_expected_var_arg_suggest) 1280 << Id.getName()); 1281 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 1282 } else { 1283 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 1284 : diag::err_omp_expected_var_arg) 1285 << Id.getName(); 1286 return ExprError(); 1287 } 1288 } else { 1289 if (!(VD = Lookup.getAsSingle<VarDecl>())) { 1290 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 1291 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 1292 return ExprError(); 1293 } 1294 } 1295 Lookup.suppressDiagnostics(); 1296 1297 // OpenMP [2.9.2, Syntax, C/C++] 1298 // Variables must be file-scope, namespace-scope, or static block-scope. 1299 if (!VD->hasGlobalStorage()) { 1300 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 1301 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal(); 1302 bool IsDecl = 1303 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1304 Diag(VD->getLocation(), 1305 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1306 << VD; 1307 return ExprError(); 1308 } 1309 1310 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 1311 NamedDecl *ND = cast<NamedDecl>(CanonicalVD); 1312 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 1313 // A threadprivate directive for file-scope variables must appear outside 1314 // any definition or declaration. 1315 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 1316 !getCurLexicalContext()->isTranslationUnit()) { 1317 Diag(Id.getLoc(), diag::err_omp_var_scope) 1318 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1319 bool IsDecl = 1320 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1321 Diag(VD->getLocation(), 1322 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1323 << VD; 1324 return ExprError(); 1325 } 1326 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 1327 // A threadprivate directive for static class member variables must appear 1328 // in the class definition, in the same scope in which the member 1329 // variables are declared. 1330 if (CanonicalVD->isStaticDataMember() && 1331 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 1332 Diag(Id.getLoc(), diag::err_omp_var_scope) 1333 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1334 bool IsDecl = 1335 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1336 Diag(VD->getLocation(), 1337 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1338 << VD; 1339 return ExprError(); 1340 } 1341 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 1342 // A threadprivate directive for namespace-scope variables must appear 1343 // outside any definition or declaration other than the namespace 1344 // definition itself. 1345 if (CanonicalVD->getDeclContext()->isNamespace() && 1346 (!getCurLexicalContext()->isFileContext() || 1347 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 1348 Diag(Id.getLoc(), diag::err_omp_var_scope) 1349 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1350 bool IsDecl = 1351 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1352 Diag(VD->getLocation(), 1353 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1354 << VD; 1355 return ExprError(); 1356 } 1357 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 1358 // A threadprivate directive for static block-scope variables must appear 1359 // in the scope of the variable and not in a nested scope. 1360 if (CanonicalVD->isStaticLocal() && CurScope && 1361 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 1362 Diag(Id.getLoc(), diag::err_omp_var_scope) 1363 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1364 bool IsDecl = 1365 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1366 Diag(VD->getLocation(), 1367 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1368 << VD; 1369 return ExprError(); 1370 } 1371 1372 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 1373 // A threadprivate directive must lexically precede all references to any 1374 // of the variables in its list. 1375 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) { 1376 Diag(Id.getLoc(), diag::err_omp_var_used) 1377 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1378 return ExprError(); 1379 } 1380 1381 QualType ExprType = VD->getType().getNonReferenceType(); 1382 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 1383 SourceLocation(), VD, 1384 /*RefersToEnclosingVariableOrCapture=*/false, 1385 Id.getLoc(), ExprType, VK_LValue); 1386 } 1387 1388 Sema::DeclGroupPtrTy 1389 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 1390 ArrayRef<Expr *> VarList) { 1391 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 1392 CurContext->addDecl(D); 1393 return DeclGroupPtrTy::make(DeclGroupRef(D)); 1394 } 1395 return nullptr; 1396 } 1397 1398 namespace { 1399 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> { 1400 Sema &SemaRef; 1401 1402 public: 1403 bool VisitDeclRefExpr(const DeclRefExpr *E) { 1404 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1405 if (VD->hasLocalStorage()) { 1406 SemaRef.Diag(E->getLocStart(), 1407 diag::err_omp_local_var_in_threadprivate_init) 1408 << E->getSourceRange(); 1409 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 1410 << VD << VD->getSourceRange(); 1411 return true; 1412 } 1413 } 1414 return false; 1415 } 1416 bool VisitStmt(const Stmt *S) { 1417 for (auto Child : S->children()) { 1418 if (Child && Visit(Child)) 1419 return true; 1420 } 1421 return false; 1422 } 1423 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 1424 }; 1425 } // namespace 1426 1427 OMPThreadPrivateDecl * 1428 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 1429 SmallVector<Expr *, 8> Vars; 1430 for (auto &RefExpr : VarList) { 1431 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr); 1432 VarDecl *VD = cast<VarDecl>(DE->getDecl()); 1433 SourceLocation ILoc = DE->getExprLoc(); 1434 1435 // Mark variable as used. 1436 VD->setReferenced(); 1437 VD->markUsed(Context); 1438 1439 QualType QType = VD->getType(); 1440 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 1441 // It will be analyzed later. 1442 Vars.push_back(DE); 1443 continue; 1444 } 1445 1446 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1447 // A threadprivate variable must not have an incomplete type. 1448 if (RequireCompleteType(ILoc, VD->getType(), 1449 diag::err_omp_threadprivate_incomplete_type)) { 1450 continue; 1451 } 1452 1453 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1454 // A threadprivate variable must not have a reference type. 1455 if (VD->getType()->isReferenceType()) { 1456 Diag(ILoc, diag::err_omp_ref_type_arg) 1457 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 1458 bool IsDecl = 1459 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1460 Diag(VD->getLocation(), 1461 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1462 << VD; 1463 continue; 1464 } 1465 1466 // Check if this is a TLS variable. If TLS is not being supported, produce 1467 // the corresponding diagnostic. 1468 if ((VD->getTLSKind() != VarDecl::TLS_None && 1469 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1470 getLangOpts().OpenMPUseTLS && 1471 getASTContext().getTargetInfo().isTLSSupported())) || 1472 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 1473 !VD->isLocalVarDecl())) { 1474 Diag(ILoc, diag::err_omp_var_thread_local) 1475 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 1476 bool IsDecl = 1477 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1478 Diag(VD->getLocation(), 1479 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1480 << VD; 1481 continue; 1482 } 1483 1484 // Check if initial value of threadprivate variable reference variable with 1485 // local storage (it is not supported by runtime). 1486 if (auto Init = VD->getAnyInitializer()) { 1487 LocalVarRefChecker Checker(*this); 1488 if (Checker.Visit(Init)) 1489 continue; 1490 } 1491 1492 Vars.push_back(RefExpr); 1493 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 1494 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 1495 Context, SourceRange(Loc, Loc))); 1496 if (auto *ML = Context.getASTMutationListener()) 1497 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 1498 } 1499 OMPThreadPrivateDecl *D = nullptr; 1500 if (!Vars.empty()) { 1501 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 1502 Vars); 1503 D->setAccess(AS_public); 1504 } 1505 return D; 1506 } 1507 1508 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack, 1509 const ValueDecl *D, DSAStackTy::DSAVarData DVar, 1510 bool IsLoopIterVar = false) { 1511 if (DVar.RefExpr) { 1512 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 1513 << getOpenMPClauseName(DVar.CKind); 1514 return; 1515 } 1516 enum { 1517 PDSA_StaticMemberShared, 1518 PDSA_StaticLocalVarShared, 1519 PDSA_LoopIterVarPrivate, 1520 PDSA_LoopIterVarLinear, 1521 PDSA_LoopIterVarLastprivate, 1522 PDSA_ConstVarShared, 1523 PDSA_GlobalVarShared, 1524 PDSA_TaskVarFirstprivate, 1525 PDSA_LocalVarPrivate, 1526 PDSA_Implicit 1527 } Reason = PDSA_Implicit; 1528 bool ReportHint = false; 1529 auto ReportLoc = D->getLocation(); 1530 auto *VD = dyn_cast<VarDecl>(D); 1531 if (IsLoopIterVar) { 1532 if (DVar.CKind == OMPC_private) 1533 Reason = PDSA_LoopIterVarPrivate; 1534 else if (DVar.CKind == OMPC_lastprivate) 1535 Reason = PDSA_LoopIterVarLastprivate; 1536 else 1537 Reason = PDSA_LoopIterVarLinear; 1538 } else if (isOpenMPTaskingDirective(DVar.DKind) && 1539 DVar.CKind == OMPC_firstprivate) { 1540 Reason = PDSA_TaskVarFirstprivate; 1541 ReportLoc = DVar.ImplicitDSALoc; 1542 } else if (VD && VD->isStaticLocal()) 1543 Reason = PDSA_StaticLocalVarShared; 1544 else if (VD && VD->isStaticDataMember()) 1545 Reason = PDSA_StaticMemberShared; 1546 else if (VD && VD->isFileVarDecl()) 1547 Reason = PDSA_GlobalVarShared; 1548 else if (D->getType().isConstant(SemaRef.getASTContext())) 1549 Reason = PDSA_ConstVarShared; 1550 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 1551 ReportHint = true; 1552 Reason = PDSA_LocalVarPrivate; 1553 } 1554 if (Reason != PDSA_Implicit) { 1555 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 1556 << Reason << ReportHint 1557 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 1558 } else if (DVar.ImplicitDSALoc.isValid()) { 1559 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 1560 << getOpenMPClauseName(DVar.CKind); 1561 } 1562 } 1563 1564 namespace { 1565 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> { 1566 DSAStackTy *Stack; 1567 Sema &SemaRef; 1568 bool ErrorFound; 1569 CapturedStmt *CS; 1570 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate; 1571 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 1572 1573 public: 1574 void VisitDeclRefExpr(DeclRefExpr *E) { 1575 if (E->isTypeDependent() || E->isValueDependent() || 1576 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1577 return; 1578 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1579 // Skip internally declared variables. 1580 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD)) 1581 return; 1582 1583 auto DVar = Stack->getTopDSA(VD, false); 1584 // Check if the variable has explicit DSA set and stop analysis if it so. 1585 if (DVar.RefExpr) 1586 return; 1587 1588 auto ELoc = E->getExprLoc(); 1589 auto DKind = Stack->getCurrentDirective(); 1590 // The default(none) clause requires that each variable that is referenced 1591 // in the construct, and does not have a predetermined data-sharing 1592 // attribute, must have its data-sharing attribute explicitly determined 1593 // by being listed in a data-sharing attribute clause. 1594 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && 1595 isParallelOrTaskRegion(DKind) && 1596 VarsWithInheritedDSA.count(VD) == 0) { 1597 VarsWithInheritedDSA[VD] = E; 1598 return; 1599 } 1600 1601 // OpenMP [2.9.3.6, Restrictions, p.2] 1602 // A list item that appears in a reduction clause of the innermost 1603 // enclosing worksharing or parallel construct may not be accessed in an 1604 // explicit task. 1605 DVar = Stack->hasInnermostDSA( 1606 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 1607 [](OpenMPDirectiveKind K) -> bool { 1608 return isOpenMPParallelDirective(K) || 1609 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 1610 }, 1611 false); 1612 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 1613 ErrorFound = true; 1614 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1615 ReportOriginalDSA(SemaRef, Stack, VD, DVar); 1616 return; 1617 } 1618 1619 // Define implicit data-sharing attributes for task. 1620 DVar = Stack->getImplicitDSA(VD, false); 1621 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 1622 !Stack->isLoopControlVariable(VD).first) 1623 ImplicitFirstprivate.push_back(E); 1624 } 1625 } 1626 void VisitMemberExpr(MemberExpr *E) { 1627 if (E->isTypeDependent() || E->isValueDependent() || 1628 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1629 return; 1630 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 1631 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 1632 auto DVar = Stack->getTopDSA(FD, false); 1633 // Check if the variable has explicit DSA set and stop analysis if it 1634 // so. 1635 if (DVar.RefExpr) 1636 return; 1637 1638 auto ELoc = E->getExprLoc(); 1639 auto DKind = Stack->getCurrentDirective(); 1640 // OpenMP [2.9.3.6, Restrictions, p.2] 1641 // A list item that appears in a reduction clause of the innermost 1642 // enclosing worksharing or parallel construct may not be accessed in 1643 // an explicit task. 1644 DVar = Stack->hasInnermostDSA( 1645 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 1646 [](OpenMPDirectiveKind K) -> bool { 1647 return isOpenMPParallelDirective(K) || 1648 isOpenMPWorksharingDirective(K) || 1649 isOpenMPTeamsDirective(K); 1650 }, 1651 false); 1652 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 1653 ErrorFound = true; 1654 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1655 ReportOriginalDSA(SemaRef, Stack, FD, DVar); 1656 return; 1657 } 1658 1659 // Define implicit data-sharing attributes for task. 1660 DVar = Stack->getImplicitDSA(FD, false); 1661 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 1662 !Stack->isLoopControlVariable(FD).first) 1663 ImplicitFirstprivate.push_back(E); 1664 } 1665 } else 1666 Visit(E->getBase()); 1667 } 1668 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 1669 for (auto *C : S->clauses()) { 1670 // Skip analysis of arguments of implicitly defined firstprivate clause 1671 // for task directives. 1672 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid())) 1673 for (auto *CC : C->children()) { 1674 if (CC) 1675 Visit(CC); 1676 } 1677 } 1678 } 1679 void VisitStmt(Stmt *S) { 1680 for (auto *C : S->children()) { 1681 if (C && !isa<OMPExecutableDirective>(C)) 1682 Visit(C); 1683 } 1684 } 1685 1686 bool isErrorFound() { return ErrorFound; } 1687 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; } 1688 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() { 1689 return VarsWithInheritedDSA; 1690 } 1691 1692 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 1693 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {} 1694 }; 1695 } // namespace 1696 1697 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 1698 switch (DKind) { 1699 case OMPD_parallel: 1700 case OMPD_parallel_for: 1701 case OMPD_parallel_for_simd: 1702 case OMPD_parallel_sections: 1703 case OMPD_teams: { 1704 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1705 QualType KmpInt32PtrTy = 1706 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1707 Sema::CapturedParamNameType Params[] = { 1708 std::make_pair(".global_tid.", KmpInt32PtrTy), 1709 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1710 std::make_pair(StringRef(), QualType()) // __context with shared vars 1711 }; 1712 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1713 Params); 1714 break; 1715 } 1716 case OMPD_target_teams: 1717 case OMPD_target_parallel: { 1718 Sema::CapturedParamNameType ParamsTarget[] = { 1719 std::make_pair(StringRef(), QualType()) // __context with shared vars 1720 }; 1721 // Start a captured region for 'target' with no implicit parameters. 1722 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1723 ParamsTarget); 1724 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1725 QualType KmpInt32PtrTy = 1726 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1727 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 1728 std::make_pair(".global_tid.", KmpInt32PtrTy), 1729 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1730 std::make_pair(StringRef(), QualType()) // __context with shared vars 1731 }; 1732 // Start a captured region for 'teams' or 'parallel'. Both regions have 1733 // the same implicit parameters. 1734 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1735 ParamsTeamsOrParallel); 1736 break; 1737 } 1738 case OMPD_simd: 1739 case OMPD_for: 1740 case OMPD_for_simd: 1741 case OMPD_sections: 1742 case OMPD_section: 1743 case OMPD_single: 1744 case OMPD_master: 1745 case OMPD_critical: 1746 case OMPD_taskgroup: 1747 case OMPD_distribute: 1748 case OMPD_ordered: 1749 case OMPD_atomic: 1750 case OMPD_target_data: 1751 case OMPD_target: 1752 case OMPD_target_parallel_for: 1753 case OMPD_target_parallel_for_simd: 1754 case OMPD_target_simd: { 1755 Sema::CapturedParamNameType Params[] = { 1756 std::make_pair(StringRef(), QualType()) // __context with shared vars 1757 }; 1758 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1759 Params); 1760 break; 1761 } 1762 case OMPD_task: { 1763 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1764 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 1765 FunctionProtoType::ExtProtoInfo EPI; 1766 EPI.Variadic = true; 1767 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 1768 Sema::CapturedParamNameType Params[] = { 1769 std::make_pair(".global_tid.", KmpInt32Ty), 1770 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 1771 std::make_pair(".privates.", Context.VoidPtrTy.withConst()), 1772 std::make_pair(".copy_fn.", 1773 Context.getPointerType(CopyFnType).withConst()), 1774 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 1775 std::make_pair(StringRef(), QualType()) // __context with shared vars 1776 }; 1777 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1778 Params); 1779 // Mark this captured region as inlined, because we don't use outlined 1780 // function directly. 1781 getCurCapturedRegion()->TheCapturedDecl->addAttr( 1782 AlwaysInlineAttr::CreateImplicit( 1783 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 1784 break; 1785 } 1786 case OMPD_taskloop: 1787 case OMPD_taskloop_simd: { 1788 QualType KmpInt32Ty = 1789 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 1790 QualType KmpUInt64Ty = 1791 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 1792 QualType KmpInt64Ty = 1793 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 1794 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 1795 FunctionProtoType::ExtProtoInfo EPI; 1796 EPI.Variadic = true; 1797 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 1798 Sema::CapturedParamNameType Params[] = { 1799 std::make_pair(".global_tid.", KmpInt32Ty), 1800 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 1801 std::make_pair(".privates.", 1802 Context.VoidPtrTy.withConst().withRestrict()), 1803 std::make_pair( 1804 ".copy_fn.", 1805 Context.getPointerType(CopyFnType).withConst().withRestrict()), 1806 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 1807 std::make_pair(".lb.", KmpUInt64Ty), 1808 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty), 1809 std::make_pair(".liter.", KmpInt32Ty), 1810 std::make_pair(".reductions.", 1811 Context.VoidPtrTy.withConst().withRestrict()), 1812 std::make_pair(StringRef(), QualType()) // __context with shared vars 1813 }; 1814 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1815 Params); 1816 // Mark this captured region as inlined, because we don't use outlined 1817 // function directly. 1818 getCurCapturedRegion()->TheCapturedDecl->addAttr( 1819 AlwaysInlineAttr::CreateImplicit( 1820 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 1821 break; 1822 } 1823 case OMPD_distribute_parallel_for_simd: 1824 case OMPD_distribute_simd: 1825 case OMPD_distribute_parallel_for: 1826 case OMPD_teams_distribute: 1827 case OMPD_teams_distribute_simd: 1828 case OMPD_teams_distribute_parallel_for_simd: 1829 case OMPD_teams_distribute_parallel_for: 1830 case OMPD_target_teams_distribute: 1831 case OMPD_target_teams_distribute_parallel_for: 1832 case OMPD_target_teams_distribute_parallel_for_simd: 1833 case OMPD_target_teams_distribute_simd: { 1834 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1835 QualType KmpInt32PtrTy = 1836 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1837 Sema::CapturedParamNameType Params[] = { 1838 std::make_pair(".global_tid.", KmpInt32PtrTy), 1839 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1840 std::make_pair(".previous.lb.", Context.getSizeType()), 1841 std::make_pair(".previous.ub.", Context.getSizeType()), 1842 std::make_pair(StringRef(), QualType()) // __context with shared vars 1843 }; 1844 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1845 Params); 1846 break; 1847 } 1848 case OMPD_threadprivate: 1849 case OMPD_taskyield: 1850 case OMPD_barrier: 1851 case OMPD_taskwait: 1852 case OMPD_cancellation_point: 1853 case OMPD_cancel: 1854 case OMPD_flush: 1855 case OMPD_target_enter_data: 1856 case OMPD_target_exit_data: 1857 case OMPD_declare_reduction: 1858 case OMPD_declare_simd: 1859 case OMPD_declare_target: 1860 case OMPD_end_declare_target: 1861 case OMPD_target_update: 1862 llvm_unreachable("OpenMP Directive is not allowed"); 1863 case OMPD_unknown: 1864 llvm_unreachable("Unknown OpenMP directive"); 1865 } 1866 } 1867 1868 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 1869 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 1870 getOpenMPCaptureRegions(CaptureRegions, DKind); 1871 return CaptureRegions.size(); 1872 } 1873 1874 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 1875 Expr *CaptureExpr, bool WithInit, 1876 bool AsExpression) { 1877 assert(CaptureExpr); 1878 ASTContext &C = S.getASTContext(); 1879 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 1880 QualType Ty = Init->getType(); 1881 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 1882 if (S.getLangOpts().CPlusPlus) 1883 Ty = C.getLValueReferenceType(Ty); 1884 else { 1885 Ty = C.getPointerType(Ty); 1886 ExprResult Res = 1887 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 1888 if (!Res.isUsable()) 1889 return nullptr; 1890 Init = Res.get(); 1891 } 1892 WithInit = true; 1893 } 1894 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 1895 CaptureExpr->getLocStart()); 1896 if (!WithInit) 1897 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange())); 1898 S.CurContext->addHiddenDecl(CED); 1899 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 1900 return CED; 1901 } 1902 1903 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 1904 bool WithInit) { 1905 OMPCapturedExprDecl *CD; 1906 if (auto *VD = S.IsOpenMPCapturedDecl(D)) 1907 CD = cast<OMPCapturedExprDecl>(VD); 1908 else 1909 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 1910 /*AsExpression=*/false); 1911 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 1912 CaptureExpr->getExprLoc()); 1913 } 1914 1915 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 1916 if (!Ref) { 1917 auto *CD = 1918 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."), 1919 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true); 1920 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 1921 CaptureExpr->getExprLoc()); 1922 } 1923 ExprResult Res = Ref; 1924 if (!S.getLangOpts().CPlusPlus && 1925 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 1926 Ref->getType()->isPointerType()) 1927 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 1928 if (!Res.isUsable()) 1929 return ExprError(); 1930 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get()); 1931 } 1932 1933 namespace { 1934 // OpenMP directives parsed in this section are represented as a 1935 // CapturedStatement with an associated statement. If a syntax error 1936 // is detected during the parsing of the associated statement, the 1937 // compiler must abort processing and close the CapturedStatement. 1938 // 1939 // Combined directives such as 'target parallel' have more than one 1940 // nested CapturedStatements. This RAII ensures that we unwind out 1941 // of all the nested CapturedStatements when an error is found. 1942 class CaptureRegionUnwinderRAII { 1943 private: 1944 Sema &S; 1945 bool &ErrorFound; 1946 OpenMPDirectiveKind DKind; 1947 1948 public: 1949 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 1950 OpenMPDirectiveKind DKind) 1951 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 1952 ~CaptureRegionUnwinderRAII() { 1953 if (ErrorFound) { 1954 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 1955 while (--ThisCaptureLevel >= 0) 1956 S.ActOnCapturedRegionError(); 1957 } 1958 } 1959 }; 1960 } // namespace 1961 1962 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 1963 ArrayRef<OMPClause *> Clauses) { 1964 bool ErrorFound = false; 1965 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 1966 *this, ErrorFound, DSAStack->getCurrentDirective()); 1967 if (!S.isUsable()) { 1968 ErrorFound = true; 1969 return StmtError(); 1970 } 1971 1972 OMPOrderedClause *OC = nullptr; 1973 OMPScheduleClause *SC = nullptr; 1974 SmallVector<OMPLinearClause *, 4> LCs; 1975 SmallVector<OMPClauseWithPreInit *, 8> PICs; 1976 // This is required for proper codegen. 1977 for (auto *Clause : Clauses) { 1978 if (isOpenMPPrivate(Clause->getClauseKind()) || 1979 Clause->getClauseKind() == OMPC_copyprivate || 1980 (getLangOpts().OpenMPUseTLS && 1981 getASTContext().getTargetInfo().isTLSSupported() && 1982 Clause->getClauseKind() == OMPC_copyin)) { 1983 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 1984 // Mark all variables in private list clauses as used in inner region. 1985 for (auto *VarRef : Clause->children()) { 1986 if (auto *E = cast_or_null<Expr>(VarRef)) { 1987 MarkDeclarationsReferencedInExpr(E); 1988 } 1989 } 1990 DSAStack->setForceVarCapturing(/*V=*/false); 1991 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { 1992 if (auto *C = OMPClauseWithPreInit::get(Clause)) 1993 PICs.push_back(C); 1994 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 1995 if (auto *E = C->getPostUpdateExpr()) 1996 MarkDeclarationsReferencedInExpr(E); 1997 } 1998 } 1999 if (Clause->getClauseKind() == OMPC_schedule) 2000 SC = cast<OMPScheduleClause>(Clause); 2001 else if (Clause->getClauseKind() == OMPC_ordered) 2002 OC = cast<OMPOrderedClause>(Clause); 2003 else if (Clause->getClauseKind() == OMPC_linear) 2004 LCs.push_back(cast<OMPLinearClause>(Clause)); 2005 } 2006 // OpenMP, 2.7.1 Loop Construct, Restrictions 2007 // The nonmonotonic modifier cannot be specified if an ordered clause is 2008 // specified. 2009 if (SC && 2010 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 2011 SC->getSecondScheduleModifier() == 2012 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 2013 OC) { 2014 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 2015 ? SC->getFirstScheduleModifierLoc() 2016 : SC->getSecondScheduleModifierLoc(), 2017 diag::err_omp_schedule_nonmonotonic_ordered) 2018 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 2019 ErrorFound = true; 2020 } 2021 if (!LCs.empty() && OC && OC->getNumForLoops()) { 2022 for (auto *C : LCs) { 2023 Diag(C->getLocStart(), diag::err_omp_linear_ordered) 2024 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 2025 } 2026 ErrorFound = true; 2027 } 2028 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 2029 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 2030 OC->getNumForLoops()) { 2031 Diag(OC->getLocStart(), diag::err_omp_ordered_simd) 2032 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 2033 ErrorFound = true; 2034 } 2035 if (ErrorFound) { 2036 return StmtError(); 2037 } 2038 StmtResult SR = S; 2039 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2040 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 2041 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 2042 // Mark all variables in private list clauses as used in inner region. 2043 // Required for proper codegen of combined directives. 2044 // TODO: add processing for other clauses. 2045 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { 2046 for (auto *C : PICs) { 2047 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 2048 // Find the particular capture region for the clause if the 2049 // directive is a combined one with multiple capture regions. 2050 // If the directive is not a combined one, the capture region 2051 // associated with the clause is OMPD_unknown and is generated 2052 // only once. 2053 if (CaptureRegion == ThisCaptureRegion || 2054 CaptureRegion == OMPD_unknown) { 2055 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 2056 for (auto *D : DS->decls()) 2057 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 2058 } 2059 } 2060 } 2061 } 2062 SR = ActOnCapturedRegionEnd(SR.get()); 2063 } 2064 return SR; 2065 } 2066 2067 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 2068 OpenMPDirectiveKind CancelRegion, 2069 SourceLocation StartLoc) { 2070 // CancelRegion is only needed for cancel and cancellation_point. 2071 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 2072 return false; 2073 2074 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 2075 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 2076 return false; 2077 2078 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 2079 << getOpenMPDirectiveName(CancelRegion); 2080 return true; 2081 } 2082 2083 static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack, 2084 OpenMPDirectiveKind CurrentRegion, 2085 const DeclarationNameInfo &CurrentName, 2086 OpenMPDirectiveKind CancelRegion, 2087 SourceLocation StartLoc) { 2088 if (Stack->getCurScope()) { 2089 auto ParentRegion = Stack->getParentDirective(); 2090 auto OffendingRegion = ParentRegion; 2091 bool NestingProhibited = false; 2092 bool CloseNesting = true; 2093 bool OrphanSeen = false; 2094 enum { 2095 NoRecommend, 2096 ShouldBeInParallelRegion, 2097 ShouldBeInOrderedRegion, 2098 ShouldBeInTargetRegion, 2099 ShouldBeInTeamsRegion 2100 } Recommend = NoRecommend; 2101 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { 2102 // OpenMP [2.16, Nesting of Regions] 2103 // OpenMP constructs may not be nested inside a simd region. 2104 // OpenMP [2.8.1,simd Construct, Restrictions] 2105 // An ordered construct with the simd clause is the only OpenMP 2106 // construct that can appear in the simd region. 2107 // Allowing a SIMD construct nested in another SIMD construct is an 2108 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 2109 // message. 2110 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 2111 ? diag::err_omp_prohibited_region_simd 2112 : diag::warn_omp_nesting_simd); 2113 return CurrentRegion != OMPD_simd; 2114 } 2115 if (ParentRegion == OMPD_atomic) { 2116 // OpenMP [2.16, Nesting of Regions] 2117 // OpenMP constructs may not be nested inside an atomic region. 2118 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 2119 return true; 2120 } 2121 if (CurrentRegion == OMPD_section) { 2122 // OpenMP [2.7.2, sections Construct, Restrictions] 2123 // Orphaned section directives are prohibited. That is, the section 2124 // directives must appear within the sections construct and must not be 2125 // encountered elsewhere in the sections region. 2126 if (ParentRegion != OMPD_sections && 2127 ParentRegion != OMPD_parallel_sections) { 2128 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 2129 << (ParentRegion != OMPD_unknown) 2130 << getOpenMPDirectiveName(ParentRegion); 2131 return true; 2132 } 2133 return false; 2134 } 2135 // Allow some constructs (except teams) to be orphaned (they could be 2136 // used in functions, called from OpenMP regions with the required 2137 // preconditions). 2138 if (ParentRegion == OMPD_unknown && 2139 !isOpenMPNestingTeamsDirective(CurrentRegion)) 2140 return false; 2141 if (CurrentRegion == OMPD_cancellation_point || 2142 CurrentRegion == OMPD_cancel) { 2143 // OpenMP [2.16, Nesting of Regions] 2144 // A cancellation point construct for which construct-type-clause is 2145 // taskgroup must be nested inside a task construct. A cancellation 2146 // point construct for which construct-type-clause is not taskgroup must 2147 // be closely nested inside an OpenMP construct that matches the type 2148 // specified in construct-type-clause. 2149 // A cancel construct for which construct-type-clause is taskgroup must be 2150 // nested inside a task construct. A cancel construct for which 2151 // construct-type-clause is not taskgroup must be closely nested inside an 2152 // OpenMP construct that matches the type specified in 2153 // construct-type-clause. 2154 NestingProhibited = 2155 !((CancelRegion == OMPD_parallel && 2156 (ParentRegion == OMPD_parallel || 2157 ParentRegion == OMPD_target_parallel)) || 2158 (CancelRegion == OMPD_for && 2159 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 2160 ParentRegion == OMPD_target_parallel_for)) || 2161 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || 2162 (CancelRegion == OMPD_sections && 2163 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 2164 ParentRegion == OMPD_parallel_sections))); 2165 } else if (CurrentRegion == OMPD_master) { 2166 // OpenMP [2.16, Nesting of Regions] 2167 // A master region may not be closely nested inside a worksharing, 2168 // atomic, or explicit task region. 2169 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2170 isOpenMPTaskingDirective(ParentRegion); 2171 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 2172 // OpenMP [2.16, Nesting of Regions] 2173 // A critical region may not be nested (closely or otherwise) inside a 2174 // critical region with the same name. Note that this restriction is not 2175 // sufficient to prevent deadlock. 2176 SourceLocation PreviousCriticalLoc; 2177 bool DeadLock = Stack->hasDirective( 2178 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 2179 const DeclarationNameInfo &DNI, 2180 SourceLocation Loc) -> bool { 2181 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 2182 PreviousCriticalLoc = Loc; 2183 return true; 2184 } else 2185 return false; 2186 }, 2187 false /* skip top directive */); 2188 if (DeadLock) { 2189 SemaRef.Diag(StartLoc, 2190 diag::err_omp_prohibited_region_critical_same_name) 2191 << CurrentName.getName(); 2192 if (PreviousCriticalLoc.isValid()) 2193 SemaRef.Diag(PreviousCriticalLoc, 2194 diag::note_omp_previous_critical_region); 2195 return true; 2196 } 2197 } else if (CurrentRegion == OMPD_barrier) { 2198 // OpenMP [2.16, Nesting of Regions] 2199 // A barrier region may not be closely nested inside a worksharing, 2200 // explicit task, critical, ordered, atomic, or master region. 2201 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2202 isOpenMPTaskingDirective(ParentRegion) || 2203 ParentRegion == OMPD_master || 2204 ParentRegion == OMPD_critical || 2205 ParentRegion == OMPD_ordered; 2206 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 2207 !isOpenMPParallelDirective(CurrentRegion) && 2208 !isOpenMPTeamsDirective(CurrentRegion)) { 2209 // OpenMP [2.16, Nesting of Regions] 2210 // A worksharing region may not be closely nested inside a worksharing, 2211 // explicit task, critical, ordered, atomic, or master region. 2212 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2213 isOpenMPTaskingDirective(ParentRegion) || 2214 ParentRegion == OMPD_master || 2215 ParentRegion == OMPD_critical || 2216 ParentRegion == OMPD_ordered; 2217 Recommend = ShouldBeInParallelRegion; 2218 } else if (CurrentRegion == OMPD_ordered) { 2219 // OpenMP [2.16, Nesting of Regions] 2220 // An ordered region may not be closely nested inside a critical, 2221 // atomic, or explicit task region. 2222 // An ordered region must be closely nested inside a loop region (or 2223 // parallel loop region) with an ordered clause. 2224 // OpenMP [2.8.1,simd Construct, Restrictions] 2225 // An ordered construct with the simd clause is the only OpenMP construct 2226 // that can appear in the simd region. 2227 NestingProhibited = ParentRegion == OMPD_critical || 2228 isOpenMPTaskingDirective(ParentRegion) || 2229 !(isOpenMPSimdDirective(ParentRegion) || 2230 Stack->isParentOrderedRegion()); 2231 Recommend = ShouldBeInOrderedRegion; 2232 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 2233 // OpenMP [2.16, Nesting of Regions] 2234 // If specified, a teams construct must be contained within a target 2235 // construct. 2236 NestingProhibited = ParentRegion != OMPD_target; 2237 OrphanSeen = ParentRegion == OMPD_unknown; 2238 Recommend = ShouldBeInTargetRegion; 2239 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc()); 2240 } 2241 if (!NestingProhibited && 2242 !isOpenMPTargetExecutionDirective(CurrentRegion) && 2243 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 2244 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 2245 // OpenMP [2.16, Nesting of Regions] 2246 // distribute, parallel, parallel sections, parallel workshare, and the 2247 // parallel loop and parallel loop SIMD constructs are the only OpenMP 2248 // constructs that can be closely nested in the teams region. 2249 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 2250 !isOpenMPDistributeDirective(CurrentRegion); 2251 Recommend = ShouldBeInParallelRegion; 2252 } 2253 if (!NestingProhibited && 2254 isOpenMPNestingDistributeDirective(CurrentRegion)) { 2255 // OpenMP 4.5 [2.17 Nesting of Regions] 2256 // The region associated with the distribute construct must be strictly 2257 // nested inside a teams region 2258 NestingProhibited = 2259 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 2260 Recommend = ShouldBeInTeamsRegion; 2261 } 2262 if (!NestingProhibited && 2263 (isOpenMPTargetExecutionDirective(CurrentRegion) || 2264 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 2265 // OpenMP 4.5 [2.17 Nesting of Regions] 2266 // If a target, target update, target data, target enter data, or 2267 // target exit data construct is encountered during execution of a 2268 // target region, the behavior is unspecified. 2269 NestingProhibited = Stack->hasDirective( 2270 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 2271 SourceLocation) -> bool { 2272 if (isOpenMPTargetExecutionDirective(K)) { 2273 OffendingRegion = K; 2274 return true; 2275 } else 2276 return false; 2277 }, 2278 false /* don't skip top directive */); 2279 CloseNesting = false; 2280 } 2281 if (NestingProhibited) { 2282 if (OrphanSeen) { 2283 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 2284 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 2285 } else { 2286 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 2287 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 2288 << Recommend << getOpenMPDirectiveName(CurrentRegion); 2289 } 2290 return true; 2291 } 2292 } 2293 return false; 2294 } 2295 2296 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 2297 ArrayRef<OMPClause *> Clauses, 2298 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 2299 bool ErrorFound = false; 2300 unsigned NamedModifiersNumber = 0; 2301 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers( 2302 OMPD_unknown + 1); 2303 SmallVector<SourceLocation, 4> NameModifierLoc; 2304 for (const auto *C : Clauses) { 2305 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 2306 // At most one if clause without a directive-name-modifier can appear on 2307 // the directive. 2308 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 2309 if (FoundNameModifiers[CurNM]) { 2310 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause) 2311 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 2312 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 2313 ErrorFound = true; 2314 } else if (CurNM != OMPD_unknown) { 2315 NameModifierLoc.push_back(IC->getNameModifierLoc()); 2316 ++NamedModifiersNumber; 2317 } 2318 FoundNameModifiers[CurNM] = IC; 2319 if (CurNM == OMPD_unknown) 2320 continue; 2321 // Check if the specified name modifier is allowed for the current 2322 // directive. 2323 // At most one if clause with the particular directive-name-modifier can 2324 // appear on the directive. 2325 bool MatchFound = false; 2326 for (auto NM : AllowedNameModifiers) { 2327 if (CurNM == NM) { 2328 MatchFound = true; 2329 break; 2330 } 2331 } 2332 if (!MatchFound) { 2333 S.Diag(IC->getNameModifierLoc(), 2334 diag::err_omp_wrong_if_directive_name_modifier) 2335 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 2336 ErrorFound = true; 2337 } 2338 } 2339 } 2340 // If any if clause on the directive includes a directive-name-modifier then 2341 // all if clauses on the directive must include a directive-name-modifier. 2342 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 2343 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 2344 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(), 2345 diag::err_omp_no_more_if_clause); 2346 } else { 2347 std::string Values; 2348 std::string Sep(", "); 2349 unsigned AllowedCnt = 0; 2350 unsigned TotalAllowedNum = 2351 AllowedNameModifiers.size() - NamedModifiersNumber; 2352 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 2353 ++Cnt) { 2354 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 2355 if (!FoundNameModifiers[NM]) { 2356 Values += "'"; 2357 Values += getOpenMPDirectiveName(NM); 2358 Values += "'"; 2359 if (AllowedCnt + 2 == TotalAllowedNum) 2360 Values += " or "; 2361 else if (AllowedCnt + 1 != TotalAllowedNum) 2362 Values += Sep; 2363 ++AllowedCnt; 2364 } 2365 } 2366 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(), 2367 diag::err_omp_unnamed_if_clause) 2368 << (TotalAllowedNum > 1) << Values; 2369 } 2370 for (auto Loc : NameModifierLoc) { 2371 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 2372 } 2373 ErrorFound = true; 2374 } 2375 return ErrorFound; 2376 } 2377 2378 StmtResult Sema::ActOnOpenMPExecutableDirective( 2379 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 2380 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 2381 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 2382 StmtResult Res = StmtError(); 2383 // First check CancelRegion which is then used in checkNestingOfRegions. 2384 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 2385 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 2386 StartLoc)) 2387 return StmtError(); 2388 2389 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 2390 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 2391 bool ErrorFound = false; 2392 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 2393 if (AStmt) { 2394 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 2395 2396 // Check default data sharing attributes for referenced variables. 2397 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 2398 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 2399 Stmt *S = AStmt; 2400 while (--ThisCaptureLevel >= 0) 2401 S = cast<CapturedStmt>(S)->getCapturedStmt(); 2402 DSAChecker.Visit(S); 2403 if (DSAChecker.isErrorFound()) 2404 return StmtError(); 2405 // Generate list of implicitly defined firstprivate variables. 2406 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 2407 2408 if (!DSAChecker.getImplicitFirstprivate().empty()) { 2409 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 2410 DSAChecker.getImplicitFirstprivate(), SourceLocation(), 2411 SourceLocation(), SourceLocation())) { 2412 ClausesWithImplicit.push_back(Implicit); 2413 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 2414 DSAChecker.getImplicitFirstprivate().size(); 2415 } else 2416 ErrorFound = true; 2417 } 2418 } 2419 2420 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 2421 switch (Kind) { 2422 case OMPD_parallel: 2423 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 2424 EndLoc); 2425 AllowedNameModifiers.push_back(OMPD_parallel); 2426 break; 2427 case OMPD_simd: 2428 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2429 VarsWithInheritedDSA); 2430 break; 2431 case OMPD_for: 2432 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2433 VarsWithInheritedDSA); 2434 break; 2435 case OMPD_for_simd: 2436 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2437 EndLoc, VarsWithInheritedDSA); 2438 break; 2439 case OMPD_sections: 2440 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 2441 EndLoc); 2442 break; 2443 case OMPD_section: 2444 assert(ClausesWithImplicit.empty() && 2445 "No clauses are allowed for 'omp section' directive"); 2446 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 2447 break; 2448 case OMPD_single: 2449 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 2450 EndLoc); 2451 break; 2452 case OMPD_master: 2453 assert(ClausesWithImplicit.empty() && 2454 "No clauses are allowed for 'omp master' directive"); 2455 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 2456 break; 2457 case OMPD_critical: 2458 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 2459 StartLoc, EndLoc); 2460 break; 2461 case OMPD_parallel_for: 2462 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 2463 EndLoc, VarsWithInheritedDSA); 2464 AllowedNameModifiers.push_back(OMPD_parallel); 2465 break; 2466 case OMPD_parallel_for_simd: 2467 Res = ActOnOpenMPParallelForSimdDirective( 2468 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2469 AllowedNameModifiers.push_back(OMPD_parallel); 2470 break; 2471 case OMPD_parallel_sections: 2472 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 2473 StartLoc, EndLoc); 2474 AllowedNameModifiers.push_back(OMPD_parallel); 2475 break; 2476 case OMPD_task: 2477 Res = 2478 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 2479 AllowedNameModifiers.push_back(OMPD_task); 2480 break; 2481 case OMPD_taskyield: 2482 assert(ClausesWithImplicit.empty() && 2483 "No clauses are allowed for 'omp taskyield' directive"); 2484 assert(AStmt == nullptr && 2485 "No associated statement allowed for 'omp taskyield' directive"); 2486 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 2487 break; 2488 case OMPD_barrier: 2489 assert(ClausesWithImplicit.empty() && 2490 "No clauses are allowed for 'omp barrier' directive"); 2491 assert(AStmt == nullptr && 2492 "No associated statement allowed for 'omp barrier' directive"); 2493 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 2494 break; 2495 case OMPD_taskwait: 2496 assert(ClausesWithImplicit.empty() && 2497 "No clauses are allowed for 'omp taskwait' directive"); 2498 assert(AStmt == nullptr && 2499 "No associated statement allowed for 'omp taskwait' directive"); 2500 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 2501 break; 2502 case OMPD_taskgroup: 2503 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, 2504 EndLoc); 2505 break; 2506 case OMPD_flush: 2507 assert(AStmt == nullptr && 2508 "No associated statement allowed for 'omp flush' directive"); 2509 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 2510 break; 2511 case OMPD_ordered: 2512 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 2513 EndLoc); 2514 break; 2515 case OMPD_atomic: 2516 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 2517 EndLoc); 2518 break; 2519 case OMPD_teams: 2520 Res = 2521 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 2522 break; 2523 case OMPD_target: 2524 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 2525 EndLoc); 2526 AllowedNameModifiers.push_back(OMPD_target); 2527 break; 2528 case OMPD_target_parallel: 2529 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 2530 StartLoc, EndLoc); 2531 AllowedNameModifiers.push_back(OMPD_target); 2532 AllowedNameModifiers.push_back(OMPD_parallel); 2533 break; 2534 case OMPD_target_parallel_for: 2535 Res = ActOnOpenMPTargetParallelForDirective( 2536 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2537 AllowedNameModifiers.push_back(OMPD_target); 2538 AllowedNameModifiers.push_back(OMPD_parallel); 2539 break; 2540 case OMPD_cancellation_point: 2541 assert(ClausesWithImplicit.empty() && 2542 "No clauses are allowed for 'omp cancellation point' directive"); 2543 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 2544 "cancellation point' directive"); 2545 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 2546 break; 2547 case OMPD_cancel: 2548 assert(AStmt == nullptr && 2549 "No associated statement allowed for 'omp cancel' directive"); 2550 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 2551 CancelRegion); 2552 AllowedNameModifiers.push_back(OMPD_cancel); 2553 break; 2554 case OMPD_target_data: 2555 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 2556 EndLoc); 2557 AllowedNameModifiers.push_back(OMPD_target_data); 2558 break; 2559 case OMPD_target_enter_data: 2560 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 2561 EndLoc); 2562 AllowedNameModifiers.push_back(OMPD_target_enter_data); 2563 break; 2564 case OMPD_target_exit_data: 2565 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 2566 EndLoc); 2567 AllowedNameModifiers.push_back(OMPD_target_exit_data); 2568 break; 2569 case OMPD_taskloop: 2570 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 2571 EndLoc, VarsWithInheritedDSA); 2572 AllowedNameModifiers.push_back(OMPD_taskloop); 2573 break; 2574 case OMPD_taskloop_simd: 2575 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2576 EndLoc, VarsWithInheritedDSA); 2577 AllowedNameModifiers.push_back(OMPD_taskloop); 2578 break; 2579 case OMPD_distribute: 2580 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 2581 EndLoc, VarsWithInheritedDSA); 2582 break; 2583 case OMPD_target_update: 2584 assert(!AStmt && "Statement is not allowed for target update"); 2585 Res = 2586 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc); 2587 AllowedNameModifiers.push_back(OMPD_target_update); 2588 break; 2589 case OMPD_distribute_parallel_for: 2590 Res = ActOnOpenMPDistributeParallelForDirective( 2591 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2592 AllowedNameModifiers.push_back(OMPD_parallel); 2593 break; 2594 case OMPD_distribute_parallel_for_simd: 2595 Res = ActOnOpenMPDistributeParallelForSimdDirective( 2596 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2597 AllowedNameModifiers.push_back(OMPD_parallel); 2598 break; 2599 case OMPD_distribute_simd: 2600 Res = ActOnOpenMPDistributeSimdDirective( 2601 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2602 break; 2603 case OMPD_target_parallel_for_simd: 2604 Res = ActOnOpenMPTargetParallelForSimdDirective( 2605 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2606 AllowedNameModifiers.push_back(OMPD_target); 2607 AllowedNameModifiers.push_back(OMPD_parallel); 2608 break; 2609 case OMPD_target_simd: 2610 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2611 EndLoc, VarsWithInheritedDSA); 2612 AllowedNameModifiers.push_back(OMPD_target); 2613 break; 2614 case OMPD_teams_distribute: 2615 Res = ActOnOpenMPTeamsDistributeDirective( 2616 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2617 break; 2618 case OMPD_teams_distribute_simd: 2619 Res = ActOnOpenMPTeamsDistributeSimdDirective( 2620 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2621 break; 2622 case OMPD_teams_distribute_parallel_for_simd: 2623 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 2624 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2625 AllowedNameModifiers.push_back(OMPD_parallel); 2626 break; 2627 case OMPD_teams_distribute_parallel_for: 2628 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 2629 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2630 AllowedNameModifiers.push_back(OMPD_parallel); 2631 break; 2632 case OMPD_target_teams: 2633 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 2634 EndLoc); 2635 AllowedNameModifiers.push_back(OMPD_target); 2636 break; 2637 case OMPD_target_teams_distribute: 2638 Res = ActOnOpenMPTargetTeamsDistributeDirective( 2639 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2640 AllowedNameModifiers.push_back(OMPD_target); 2641 break; 2642 case OMPD_target_teams_distribute_parallel_for: 2643 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 2644 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2645 AllowedNameModifiers.push_back(OMPD_target); 2646 AllowedNameModifiers.push_back(OMPD_parallel); 2647 break; 2648 case OMPD_target_teams_distribute_parallel_for_simd: 2649 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 2650 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2651 AllowedNameModifiers.push_back(OMPD_target); 2652 AllowedNameModifiers.push_back(OMPD_parallel); 2653 break; 2654 case OMPD_target_teams_distribute_simd: 2655 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 2656 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2657 AllowedNameModifiers.push_back(OMPD_target); 2658 break; 2659 case OMPD_declare_target: 2660 case OMPD_end_declare_target: 2661 case OMPD_threadprivate: 2662 case OMPD_declare_reduction: 2663 case OMPD_declare_simd: 2664 llvm_unreachable("OpenMP Directive is not allowed"); 2665 case OMPD_unknown: 2666 llvm_unreachable("Unknown OpenMP directive"); 2667 } 2668 2669 for (auto P : VarsWithInheritedDSA) { 2670 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 2671 << P.first << P.second->getSourceRange(); 2672 } 2673 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound; 2674 2675 if (!AllowedNameModifiers.empty()) 2676 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 2677 ErrorFound; 2678 2679 if (ErrorFound) 2680 return StmtError(); 2681 return Res; 2682 } 2683 2684 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 2685 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 2686 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 2687 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 2688 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 2689 assert(Aligneds.size() == Alignments.size()); 2690 assert(Linears.size() == LinModifiers.size()); 2691 assert(Linears.size() == Steps.size()); 2692 if (!DG || DG.get().isNull()) 2693 return DeclGroupPtrTy(); 2694 2695 if (!DG.get().isSingleDecl()) { 2696 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd); 2697 return DG; 2698 } 2699 auto *ADecl = DG.get().getSingleDecl(); 2700 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 2701 ADecl = FTD->getTemplatedDecl(); 2702 2703 auto *FD = dyn_cast<FunctionDecl>(ADecl); 2704 if (!FD) { 2705 Diag(ADecl->getLocation(), diag::err_omp_function_expected); 2706 return DeclGroupPtrTy(); 2707 } 2708 2709 // OpenMP [2.8.2, declare simd construct, Description] 2710 // The parameter of the simdlen clause must be a constant positive integer 2711 // expression. 2712 ExprResult SL; 2713 if (Simdlen) 2714 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 2715 // OpenMP [2.8.2, declare simd construct, Description] 2716 // The special this pointer can be used as if was one of the arguments to the 2717 // function in any of the linear, aligned, or uniform clauses. 2718 // The uniform clause declares one or more arguments to have an invariant 2719 // value for all concurrent invocations of the function in the execution of a 2720 // single SIMD loop. 2721 llvm::DenseMap<Decl *, Expr *> UniformedArgs; 2722 Expr *UniformedLinearThis = nullptr; 2723 for (auto *E : Uniforms) { 2724 E = E->IgnoreParenImpCasts(); 2725 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 2726 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 2727 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 2728 FD->getParamDecl(PVD->getFunctionScopeIndex()) 2729 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 2730 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E)); 2731 continue; 2732 } 2733 if (isa<CXXThisExpr>(E)) { 2734 UniformedLinearThis = E; 2735 continue; 2736 } 2737 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 2738 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 2739 } 2740 // OpenMP [2.8.2, declare simd construct, Description] 2741 // The aligned clause declares that the object to which each list item points 2742 // is aligned to the number of bytes expressed in the optional parameter of 2743 // the aligned clause. 2744 // The special this pointer can be used as if was one of the arguments to the 2745 // function in any of the linear, aligned, or uniform clauses. 2746 // The type of list items appearing in the aligned clause must be array, 2747 // pointer, reference to array, or reference to pointer. 2748 llvm::DenseMap<Decl *, Expr *> AlignedArgs; 2749 Expr *AlignedThis = nullptr; 2750 for (auto *E : Aligneds) { 2751 E = E->IgnoreParenImpCasts(); 2752 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 2753 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 2754 auto *CanonPVD = PVD->getCanonicalDecl(); 2755 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 2756 FD->getParamDecl(PVD->getFunctionScopeIndex()) 2757 ->getCanonicalDecl() == CanonPVD) { 2758 // OpenMP [2.8.1, simd construct, Restrictions] 2759 // A list-item cannot appear in more than one aligned clause. 2760 if (AlignedArgs.count(CanonPVD) > 0) { 2761 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 2762 << 1 << E->getSourceRange(); 2763 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 2764 diag::note_omp_explicit_dsa) 2765 << getOpenMPClauseName(OMPC_aligned); 2766 continue; 2767 } 2768 AlignedArgs[CanonPVD] = E; 2769 QualType QTy = PVD->getType() 2770 .getNonReferenceType() 2771 .getUnqualifiedType() 2772 .getCanonicalType(); 2773 const Type *Ty = QTy.getTypePtrOrNull(); 2774 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 2775 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 2776 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 2777 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 2778 } 2779 continue; 2780 } 2781 } 2782 if (isa<CXXThisExpr>(E)) { 2783 if (AlignedThis) { 2784 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 2785 << 2 << E->getSourceRange(); 2786 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 2787 << getOpenMPClauseName(OMPC_aligned); 2788 } 2789 AlignedThis = E; 2790 continue; 2791 } 2792 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 2793 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 2794 } 2795 // The optional parameter of the aligned clause, alignment, must be a constant 2796 // positive integer expression. If no optional parameter is specified, 2797 // implementation-defined default alignments for SIMD instructions on the 2798 // target platforms are assumed. 2799 SmallVector<Expr *, 4> NewAligns; 2800 for (auto *E : Alignments) { 2801 ExprResult Align; 2802 if (E) 2803 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 2804 NewAligns.push_back(Align.get()); 2805 } 2806 // OpenMP [2.8.2, declare simd construct, Description] 2807 // The linear clause declares one or more list items to be private to a SIMD 2808 // lane and to have a linear relationship with respect to the iteration space 2809 // of a loop. 2810 // The special this pointer can be used as if was one of the arguments to the 2811 // function in any of the linear, aligned, or uniform clauses. 2812 // When a linear-step expression is specified in a linear clause it must be 2813 // either a constant integer expression or an integer-typed parameter that is 2814 // specified in a uniform clause on the directive. 2815 llvm::DenseMap<Decl *, Expr *> LinearArgs; 2816 const bool IsUniformedThis = UniformedLinearThis != nullptr; 2817 auto MI = LinModifiers.begin(); 2818 for (auto *E : Linears) { 2819 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 2820 ++MI; 2821 E = E->IgnoreParenImpCasts(); 2822 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 2823 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 2824 auto *CanonPVD = PVD->getCanonicalDecl(); 2825 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 2826 FD->getParamDecl(PVD->getFunctionScopeIndex()) 2827 ->getCanonicalDecl() == CanonPVD) { 2828 // OpenMP [2.15.3.7, linear Clause, Restrictions] 2829 // A list-item cannot appear in more than one linear clause. 2830 if (LinearArgs.count(CanonPVD) > 0) { 2831 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 2832 << getOpenMPClauseName(OMPC_linear) 2833 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 2834 Diag(LinearArgs[CanonPVD]->getExprLoc(), 2835 diag::note_omp_explicit_dsa) 2836 << getOpenMPClauseName(OMPC_linear); 2837 continue; 2838 } 2839 // Each argument can appear in at most one uniform or linear clause. 2840 if (UniformedArgs.count(CanonPVD) > 0) { 2841 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 2842 << getOpenMPClauseName(OMPC_linear) 2843 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 2844 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 2845 diag::note_omp_explicit_dsa) 2846 << getOpenMPClauseName(OMPC_uniform); 2847 continue; 2848 } 2849 LinearArgs[CanonPVD] = E; 2850 if (E->isValueDependent() || E->isTypeDependent() || 2851 E->isInstantiationDependent() || 2852 E->containsUnexpandedParameterPack()) 2853 continue; 2854 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 2855 PVD->getOriginalType()); 2856 continue; 2857 } 2858 } 2859 if (isa<CXXThisExpr>(E)) { 2860 if (UniformedLinearThis) { 2861 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 2862 << getOpenMPClauseName(OMPC_linear) 2863 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 2864 << E->getSourceRange(); 2865 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 2866 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 2867 : OMPC_linear); 2868 continue; 2869 } 2870 UniformedLinearThis = E; 2871 if (E->isValueDependent() || E->isTypeDependent() || 2872 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 2873 continue; 2874 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 2875 E->getType()); 2876 continue; 2877 } 2878 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 2879 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 2880 } 2881 Expr *Step = nullptr; 2882 Expr *NewStep = nullptr; 2883 SmallVector<Expr *, 4> NewSteps; 2884 for (auto *E : Steps) { 2885 // Skip the same step expression, it was checked already. 2886 if (Step == E || !E) { 2887 NewSteps.push_back(E ? NewStep : nullptr); 2888 continue; 2889 } 2890 Step = E; 2891 if (auto *DRE = dyn_cast<DeclRefExpr>(Step)) 2892 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 2893 auto *CanonPVD = PVD->getCanonicalDecl(); 2894 if (UniformedArgs.count(CanonPVD) == 0) { 2895 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 2896 << Step->getSourceRange(); 2897 } else if (E->isValueDependent() || E->isTypeDependent() || 2898 E->isInstantiationDependent() || 2899 E->containsUnexpandedParameterPack() || 2900 CanonPVD->getType()->hasIntegerRepresentation()) 2901 NewSteps.push_back(Step); 2902 else { 2903 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 2904 << Step->getSourceRange(); 2905 } 2906 continue; 2907 } 2908 NewStep = Step; 2909 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 2910 !Step->isInstantiationDependent() && 2911 !Step->containsUnexpandedParameterPack()) { 2912 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 2913 .get(); 2914 if (NewStep) 2915 NewStep = VerifyIntegerConstantExpression(NewStep).get(); 2916 } 2917 NewSteps.push_back(NewStep); 2918 } 2919 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 2920 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 2921 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 2922 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 2923 const_cast<Expr **>(Linears.data()), Linears.size(), 2924 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 2925 NewSteps.data(), NewSteps.size(), SR); 2926 ADecl->addAttr(NewAttr); 2927 return ConvertDeclToDeclGroup(ADecl); 2928 } 2929 2930 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 2931 Stmt *AStmt, 2932 SourceLocation StartLoc, 2933 SourceLocation EndLoc) { 2934 if (!AStmt) 2935 return StmtError(); 2936 2937 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 2938 // 1.2.2 OpenMP Language Terminology 2939 // Structured block - An executable statement with a single entry at the 2940 // top and a single exit at the bottom. 2941 // The point of exit cannot be a branch out of the structured block. 2942 // longjmp() and throw() must not violate the entry/exit criteria. 2943 CS->getCapturedDecl()->setNothrow(); 2944 2945 getCurFunction()->setHasBranchProtectedScope(); 2946 2947 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 2948 DSAStack->isCancelRegion()); 2949 } 2950 2951 namespace { 2952 /// \brief Helper class for checking canonical form of the OpenMP loops and 2953 /// extracting iteration space of each loop in the loop nest, that will be used 2954 /// for IR generation. 2955 class OpenMPIterationSpaceChecker { 2956 /// \brief Reference to Sema. 2957 Sema &SemaRef; 2958 /// \brief A location for diagnostics (when there is no some better location). 2959 SourceLocation DefaultLoc; 2960 /// \brief A location for diagnostics (when increment is not compatible). 2961 SourceLocation ConditionLoc; 2962 /// \brief A source location for referring to loop init later. 2963 SourceRange InitSrcRange; 2964 /// \brief A source location for referring to condition later. 2965 SourceRange ConditionSrcRange; 2966 /// \brief A source location for referring to increment later. 2967 SourceRange IncrementSrcRange; 2968 /// \brief Loop variable. 2969 ValueDecl *LCDecl = nullptr; 2970 /// \brief Reference to loop variable. 2971 Expr *LCRef = nullptr; 2972 /// \brief Lower bound (initializer for the var). 2973 Expr *LB = nullptr; 2974 /// \brief Upper bound. 2975 Expr *UB = nullptr; 2976 /// \brief Loop step (increment). 2977 Expr *Step = nullptr; 2978 /// \brief This flag is true when condition is one of: 2979 /// Var < UB 2980 /// Var <= UB 2981 /// UB > Var 2982 /// UB >= Var 2983 bool TestIsLessOp = false; 2984 /// \brief This flag is true when condition is strict ( < or > ). 2985 bool TestIsStrictOp = false; 2986 /// \brief This flag is true when step is subtracted on each iteration. 2987 bool SubtractStep = false; 2988 2989 public: 2990 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) 2991 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 2992 /// \brief Check init-expr for canonical loop form and save loop counter 2993 /// variable - #Var and its initialization value - #LB. 2994 bool CheckInit(Stmt *S, bool EmitDiags = true); 2995 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags 2996 /// for less/greater and for strict/non-strict comparison. 2997 bool CheckCond(Expr *S); 2998 /// \brief Check incr-expr for canonical loop form and return true if it 2999 /// does not conform, otherwise save loop step (#Step). 3000 bool CheckInc(Expr *S); 3001 /// \brief Return the loop counter variable. 3002 ValueDecl *GetLoopDecl() const { return LCDecl; } 3003 /// \brief Return the reference expression to loop counter variable. 3004 Expr *GetLoopDeclRefExpr() const { return LCRef; } 3005 /// \brief Source range of the loop init. 3006 SourceRange GetInitSrcRange() const { return InitSrcRange; } 3007 /// \brief Source range of the loop condition. 3008 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; } 3009 /// \brief Source range of the loop increment. 3010 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; } 3011 /// \brief True if the step should be subtracted. 3012 bool ShouldSubtractStep() const { return SubtractStep; } 3013 /// \brief Build the expression to calculate the number of iterations. 3014 Expr * 3015 BuildNumIterations(Scope *S, const bool LimitedType, 3016 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 3017 /// \brief Build the precondition expression for the loops. 3018 Expr *BuildPreCond(Scope *S, Expr *Cond, 3019 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 3020 /// \brief Build reference expression to the counter be used for codegen. 3021 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures, 3022 DSAStackTy &DSA) const; 3023 /// \brief Build reference expression to the private counter be used for 3024 /// codegen. 3025 Expr *BuildPrivateCounterVar() const; 3026 /// \brief Build initialization of the counter be used for codegen. 3027 Expr *BuildCounterInit() const; 3028 /// \brief Build step of the counter be used for codegen. 3029 Expr *BuildCounterStep() const; 3030 /// \brief Return true if any expression is dependent. 3031 bool Dependent() const; 3032 3033 private: 3034 /// \brief Check the right-hand side of an assignment in the increment 3035 /// expression. 3036 bool CheckIncRHS(Expr *RHS); 3037 /// \brief Helper to set loop counter variable and its initializer. 3038 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB); 3039 /// \brief Helper to set upper bound. 3040 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR, 3041 SourceLocation SL); 3042 /// \brief Helper to set loop increment. 3043 bool SetStep(Expr *NewStep, bool Subtract); 3044 }; 3045 3046 bool OpenMPIterationSpaceChecker::Dependent() const { 3047 if (!LCDecl) { 3048 assert(!LB && !UB && !Step); 3049 return false; 3050 } 3051 return LCDecl->getType()->isDependentType() || 3052 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 3053 (Step && Step->isValueDependent()); 3054 } 3055 3056 static Expr *getExprAsWritten(Expr *E) { 3057 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E)) 3058 E = ExprTemp->getSubExpr(); 3059 3060 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 3061 E = MTE->GetTemporaryExpr(); 3062 3063 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 3064 E = Binder->getSubExpr(); 3065 3066 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 3067 E = ICE->getSubExprAsWritten(); 3068 return E->IgnoreParens(); 3069 } 3070 3071 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl, 3072 Expr *NewLCRefExpr, 3073 Expr *NewLB) { 3074 // State consistency checking to ensure correct usage. 3075 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 3076 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 3077 if (!NewLCDecl || !NewLB) 3078 return true; 3079 LCDecl = getCanonicalDecl(NewLCDecl); 3080 LCRef = NewLCRefExpr; 3081 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 3082 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 3083 if ((Ctor->isCopyOrMoveConstructor() || 3084 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 3085 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 3086 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 3087 LB = NewLB; 3088 return false; 3089 } 3090 3091 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp, 3092 SourceRange SR, SourceLocation SL) { 3093 // State consistency checking to ensure correct usage. 3094 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 3095 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 3096 if (!NewUB) 3097 return true; 3098 UB = NewUB; 3099 TestIsLessOp = LessOp; 3100 TestIsStrictOp = StrictOp; 3101 ConditionSrcRange = SR; 3102 ConditionLoc = SL; 3103 return false; 3104 } 3105 3106 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) { 3107 // State consistency checking to ensure correct usage. 3108 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 3109 if (!NewStep) 3110 return true; 3111 if (!NewStep->isValueDependent()) { 3112 // Check that the step is integer expression. 3113 SourceLocation StepLoc = NewStep->getLocStart(); 3114 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( 3115 StepLoc, getExprAsWritten(NewStep)); 3116 if (Val.isInvalid()) 3117 return true; 3118 NewStep = Val.get(); 3119 3120 // OpenMP [2.6, Canonical Loop Form, Restrictions] 3121 // If test-expr is of form var relational-op b and relational-op is < or 3122 // <= then incr-expr must cause var to increase on each iteration of the 3123 // loop. If test-expr is of form var relational-op b and relational-op is 3124 // > or >= then incr-expr must cause var to decrease on each iteration of 3125 // the loop. 3126 // If test-expr is of form b relational-op var and relational-op is < or 3127 // <= then incr-expr must cause var to decrease on each iteration of the 3128 // loop. If test-expr is of form b relational-op var and relational-op is 3129 // > or >= then incr-expr must cause var to increase on each iteration of 3130 // the loop. 3131 llvm::APSInt Result; 3132 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 3133 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 3134 bool IsConstNeg = 3135 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 3136 bool IsConstPos = 3137 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 3138 bool IsConstZero = IsConstant && !Result.getBoolValue(); 3139 if (UB && (IsConstZero || 3140 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract)) 3141 : (IsConstPos || (IsUnsigned && !Subtract))))) { 3142 SemaRef.Diag(NewStep->getExprLoc(), 3143 diag::err_omp_loop_incr_not_compatible) 3144 << LCDecl << TestIsLessOp << NewStep->getSourceRange(); 3145 SemaRef.Diag(ConditionLoc, 3146 diag::note_omp_loop_cond_requres_compatible_incr) 3147 << TestIsLessOp << ConditionSrcRange; 3148 return true; 3149 } 3150 if (TestIsLessOp == Subtract) { 3151 NewStep = 3152 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 3153 .get(); 3154 Subtract = !Subtract; 3155 } 3156 } 3157 3158 Step = NewStep; 3159 SubtractStep = Subtract; 3160 return false; 3161 } 3162 3163 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) { 3164 // Check init-expr for canonical loop form and save loop counter 3165 // variable - #Var and its initialization value - #LB. 3166 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 3167 // var = lb 3168 // integer-type var = lb 3169 // random-access-iterator-type var = lb 3170 // pointer-type var = lb 3171 // 3172 if (!S) { 3173 if (EmitDiags) { 3174 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 3175 } 3176 return true; 3177 } 3178 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3179 if (!ExprTemp->cleanupsHaveSideEffects()) 3180 S = ExprTemp->getSubExpr(); 3181 3182 InitSrcRange = S->getSourceRange(); 3183 if (Expr *E = dyn_cast<Expr>(S)) 3184 S = E->IgnoreParens(); 3185 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3186 if (BO->getOpcode() == BO_Assign) { 3187 auto *LHS = BO->getLHS()->IgnoreParens(); 3188 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3189 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3190 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3191 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3192 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS()); 3193 } 3194 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3195 if (ME->isArrow() && 3196 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3197 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3198 } 3199 } 3200 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 3201 if (DS->isSingleDecl()) { 3202 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 3203 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 3204 // Accept non-canonical init form here but emit ext. warning. 3205 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 3206 SemaRef.Diag(S->getLocStart(), 3207 diag::ext_omp_loop_not_canonical_init) 3208 << S->getSourceRange(); 3209 return SetLCDeclAndLB(Var, nullptr, Var->getInit()); 3210 } 3211 } 3212 } 3213 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3214 if (CE->getOperator() == OO_Equal) { 3215 auto *LHS = CE->getArg(0); 3216 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3217 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3218 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3219 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3220 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1)); 3221 } 3222 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3223 if (ME->isArrow() && 3224 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3225 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3226 } 3227 } 3228 } 3229 3230 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3231 return false; 3232 if (EmitDiags) { 3233 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init) 3234 << S->getSourceRange(); 3235 } 3236 return true; 3237 } 3238 3239 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the 3240 /// variable (which may be the loop variable) if possible. 3241 static const ValueDecl *GetInitLCDecl(Expr *E) { 3242 if (!E) 3243 return nullptr; 3244 E = getExprAsWritten(E); 3245 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 3246 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 3247 if ((Ctor->isCopyOrMoveConstructor() || 3248 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 3249 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 3250 E = CE->getArg(0)->IgnoreParenImpCasts(); 3251 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 3252 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 3253 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD)) 3254 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3255 return getCanonicalDecl(ME->getMemberDecl()); 3256 return getCanonicalDecl(VD); 3257 } 3258 } 3259 if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 3260 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3261 return getCanonicalDecl(ME->getMemberDecl()); 3262 return nullptr; 3263 } 3264 3265 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) { 3266 // Check test-expr for canonical form, save upper-bound UB, flags for 3267 // less/greater and for strict/non-strict comparison. 3268 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3269 // var relational-op b 3270 // b relational-op var 3271 // 3272 if (!S) { 3273 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl; 3274 return true; 3275 } 3276 S = getExprAsWritten(S); 3277 SourceLocation CondLoc = S->getLocStart(); 3278 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3279 if (BO->isRelationalOp()) { 3280 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3281 return SetUB(BO->getRHS(), 3282 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 3283 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3284 BO->getSourceRange(), BO->getOperatorLoc()); 3285 if (GetInitLCDecl(BO->getRHS()) == LCDecl) 3286 return SetUB(BO->getLHS(), 3287 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 3288 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3289 BO->getSourceRange(), BO->getOperatorLoc()); 3290 } 3291 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3292 if (CE->getNumArgs() == 2) { 3293 auto Op = CE->getOperator(); 3294 switch (Op) { 3295 case OO_Greater: 3296 case OO_GreaterEqual: 3297 case OO_Less: 3298 case OO_LessEqual: 3299 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3300 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 3301 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3302 CE->getOperatorLoc()); 3303 if (GetInitLCDecl(CE->getArg(1)) == LCDecl) 3304 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 3305 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3306 CE->getOperatorLoc()); 3307 break; 3308 default: 3309 break; 3310 } 3311 } 3312 } 3313 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3314 return false; 3315 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 3316 << S->getSourceRange() << LCDecl; 3317 return true; 3318 } 3319 3320 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) { 3321 // RHS of canonical loop form increment can be: 3322 // var + incr 3323 // incr + var 3324 // var - incr 3325 // 3326 RHS = RHS->IgnoreParenImpCasts(); 3327 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 3328 if (BO->isAdditiveOp()) { 3329 bool IsAdd = BO->getOpcode() == BO_Add; 3330 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3331 return SetStep(BO->getRHS(), !IsAdd); 3332 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl) 3333 return SetStep(BO->getLHS(), false); 3334 } 3335 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 3336 bool IsAdd = CE->getOperator() == OO_Plus; 3337 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 3338 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3339 return SetStep(CE->getArg(1), !IsAdd); 3340 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl) 3341 return SetStep(CE->getArg(0), false); 3342 } 3343 } 3344 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3345 return false; 3346 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3347 << RHS->getSourceRange() << LCDecl; 3348 return true; 3349 } 3350 3351 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) { 3352 // Check incr-expr for canonical loop form and return true if it 3353 // does not conform. 3354 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3355 // ++var 3356 // var++ 3357 // --var 3358 // var-- 3359 // var += incr 3360 // var -= incr 3361 // var = var + incr 3362 // var = incr + var 3363 // var = var - incr 3364 // 3365 if (!S) { 3366 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 3367 return true; 3368 } 3369 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3370 if (!ExprTemp->cleanupsHaveSideEffects()) 3371 S = ExprTemp->getSubExpr(); 3372 3373 IncrementSrcRange = S->getSourceRange(); 3374 S = S->IgnoreParens(); 3375 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 3376 if (UO->isIncrementDecrementOp() && 3377 GetInitLCDecl(UO->getSubExpr()) == LCDecl) 3378 return SetStep(SemaRef 3379 .ActOnIntegerConstant(UO->getLocStart(), 3380 (UO->isDecrementOp() ? -1 : 1)) 3381 .get(), 3382 false); 3383 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3384 switch (BO->getOpcode()) { 3385 case BO_AddAssign: 3386 case BO_SubAssign: 3387 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3388 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 3389 break; 3390 case BO_Assign: 3391 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3392 return CheckIncRHS(BO->getRHS()); 3393 break; 3394 default: 3395 break; 3396 } 3397 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3398 switch (CE->getOperator()) { 3399 case OO_PlusPlus: 3400 case OO_MinusMinus: 3401 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3402 return SetStep(SemaRef 3403 .ActOnIntegerConstant( 3404 CE->getLocStart(), 3405 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 3406 .get(), 3407 false); 3408 break; 3409 case OO_PlusEqual: 3410 case OO_MinusEqual: 3411 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3412 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 3413 break; 3414 case OO_Equal: 3415 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3416 return CheckIncRHS(CE->getArg(1)); 3417 break; 3418 default: 3419 break; 3420 } 3421 } 3422 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3423 return false; 3424 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3425 << S->getSourceRange() << LCDecl; 3426 return true; 3427 } 3428 3429 static ExprResult 3430 tryBuildCapture(Sema &SemaRef, Expr *Capture, 3431 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3432 if (SemaRef.CurContext->isDependentContext()) 3433 return ExprResult(Capture); 3434 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 3435 return SemaRef.PerformImplicitConversion( 3436 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 3437 /*AllowExplicit=*/true); 3438 auto I = Captures.find(Capture); 3439 if (I != Captures.end()) 3440 return buildCapture(SemaRef, Capture, I->second); 3441 DeclRefExpr *Ref = nullptr; 3442 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 3443 Captures[Capture] = Ref; 3444 return Res; 3445 } 3446 3447 /// \brief Build the expression to calculate the number of iterations. 3448 Expr *OpenMPIterationSpaceChecker::BuildNumIterations( 3449 Scope *S, const bool LimitedType, 3450 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 3451 ExprResult Diff; 3452 auto VarType = LCDecl->getType().getNonReferenceType(); 3453 if (VarType->isIntegerType() || VarType->isPointerType() || 3454 SemaRef.getLangOpts().CPlusPlus) { 3455 // Upper - Lower 3456 auto *UBExpr = TestIsLessOp ? UB : LB; 3457 auto *LBExpr = TestIsLessOp ? LB : UB; 3458 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 3459 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 3460 if (!Upper || !Lower) 3461 return nullptr; 3462 3463 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 3464 3465 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 3466 // BuildBinOp already emitted error, this one is to point user to upper 3467 // and lower bound, and to tell what is passed to 'operator-'. 3468 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx) 3469 << Upper->getSourceRange() << Lower->getSourceRange(); 3470 return nullptr; 3471 } 3472 } 3473 3474 if (!Diff.isUsable()) 3475 return nullptr; 3476 3477 // Upper - Lower [- 1] 3478 if (TestIsStrictOp) 3479 Diff = SemaRef.BuildBinOp( 3480 S, DefaultLoc, BO_Sub, Diff.get(), 3481 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 3482 if (!Diff.isUsable()) 3483 return nullptr; 3484 3485 // Upper - Lower [- 1] + Step 3486 auto NewStep = tryBuildCapture(SemaRef, Step, Captures); 3487 if (!NewStep.isUsable()) 3488 return nullptr; 3489 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 3490 if (!Diff.isUsable()) 3491 return nullptr; 3492 3493 // Parentheses (for dumping/debugging purposes only). 3494 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 3495 if (!Diff.isUsable()) 3496 return nullptr; 3497 3498 // (Upper - Lower [- 1] + Step) / Step 3499 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 3500 if (!Diff.isUsable()) 3501 return nullptr; 3502 3503 // OpenMP runtime requires 32-bit or 64-bit loop variables. 3504 QualType Type = Diff.get()->getType(); 3505 auto &C = SemaRef.Context; 3506 bool UseVarType = VarType->hasIntegerRepresentation() && 3507 C.getTypeSize(Type) > C.getTypeSize(VarType); 3508 if (!Type->isIntegerType() || UseVarType) { 3509 unsigned NewSize = 3510 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 3511 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 3512 : Type->hasSignedIntegerRepresentation(); 3513 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 3514 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 3515 Diff = SemaRef.PerformImplicitConversion( 3516 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 3517 if (!Diff.isUsable()) 3518 return nullptr; 3519 } 3520 } 3521 if (LimitedType) { 3522 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 3523 if (NewSize != C.getTypeSize(Type)) { 3524 if (NewSize < C.getTypeSize(Type)) { 3525 assert(NewSize == 64 && "incorrect loop var size"); 3526 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 3527 << InitSrcRange << ConditionSrcRange; 3528 } 3529 QualType NewType = C.getIntTypeForBitwidth( 3530 NewSize, Type->hasSignedIntegerRepresentation() || 3531 C.getTypeSize(Type) < NewSize); 3532 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 3533 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 3534 Sema::AA_Converting, true); 3535 if (!Diff.isUsable()) 3536 return nullptr; 3537 } 3538 } 3539 } 3540 3541 return Diff.get(); 3542 } 3543 3544 Expr *OpenMPIterationSpaceChecker::BuildPreCond( 3545 Scope *S, Expr *Cond, 3546 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 3547 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 3548 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 3549 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 3550 3551 auto NewLB = tryBuildCapture(SemaRef, LB, Captures); 3552 auto NewUB = tryBuildCapture(SemaRef, UB, Captures); 3553 if (!NewLB.isUsable() || !NewUB.isUsable()) 3554 return nullptr; 3555 3556 auto CondExpr = SemaRef.BuildBinOp( 3557 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE) 3558 : (TestIsStrictOp ? BO_GT : BO_GE), 3559 NewLB.get(), NewUB.get()); 3560 if (CondExpr.isUsable()) { 3561 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 3562 SemaRef.Context.BoolTy)) 3563 CondExpr = SemaRef.PerformImplicitConversion( 3564 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 3565 /*AllowExplicit=*/true); 3566 } 3567 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 3568 // Otherwise use original loop conditon and evaluate it in runtime. 3569 return CondExpr.isUsable() ? CondExpr.get() : Cond; 3570 } 3571 3572 /// \brief Build reference expression to the counter be used for codegen. 3573 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar( 3574 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const { 3575 auto *VD = dyn_cast<VarDecl>(LCDecl); 3576 if (!VD) { 3577 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl); 3578 auto *Ref = buildDeclRefExpr( 3579 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 3580 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false); 3581 // If the loop control decl is explicitly marked as private, do not mark it 3582 // as captured again. 3583 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 3584 Captures.insert(std::make_pair(LCRef, Ref)); 3585 return Ref; 3586 } 3587 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(), 3588 DefaultLoc); 3589 } 3590 3591 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const { 3592 if (LCDecl && !LCDecl->isInvalidDecl()) { 3593 auto Type = LCDecl->getType().getNonReferenceType(); 3594 auto *PrivateVar = 3595 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(), 3596 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr); 3597 if (PrivateVar->isInvalidDecl()) 3598 return nullptr; 3599 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 3600 } 3601 return nullptr; 3602 } 3603 3604 /// \brief Build initialization of the counter to be used for codegen. 3605 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; } 3606 3607 /// \brief Build step of the counter be used for codegen. 3608 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; } 3609 3610 /// \brief Iteration space of a single for loop. 3611 struct LoopIterationSpace final { 3612 /// \brief Condition of the loop. 3613 Expr *PreCond = nullptr; 3614 /// \brief This expression calculates the number of iterations in the loop. 3615 /// It is always possible to calculate it before starting the loop. 3616 Expr *NumIterations = nullptr; 3617 /// \brief The loop counter variable. 3618 Expr *CounterVar = nullptr; 3619 /// \brief Private loop counter variable. 3620 Expr *PrivateCounterVar = nullptr; 3621 /// \brief This is initializer for the initial value of #CounterVar. 3622 Expr *CounterInit = nullptr; 3623 /// \brief This is step for the #CounterVar used to generate its update: 3624 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 3625 Expr *CounterStep = nullptr; 3626 /// \brief Should step be subtracted? 3627 bool Subtract = false; 3628 /// \brief Source range of the loop init. 3629 SourceRange InitSrcRange; 3630 /// \brief Source range of the loop condition. 3631 SourceRange CondSrcRange; 3632 /// \brief Source range of the loop increment. 3633 SourceRange IncSrcRange; 3634 }; 3635 3636 } // namespace 3637 3638 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 3639 assert(getLangOpts().OpenMP && "OpenMP is not active."); 3640 assert(Init && "Expected loop in canonical form."); 3641 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 3642 if (AssociatedLoops > 0 && 3643 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 3644 OpenMPIterationSpaceChecker ISC(*this, ForLoc); 3645 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) { 3646 if (auto *D = ISC.GetLoopDecl()) { 3647 auto *VD = dyn_cast<VarDecl>(D); 3648 if (!VD) { 3649 if (auto *Private = IsOpenMPCapturedDecl(D)) 3650 VD = Private; 3651 else { 3652 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(), 3653 /*WithInit=*/false); 3654 VD = cast<VarDecl>(Ref->getDecl()); 3655 } 3656 } 3657 DSAStack->addLoopControlVariable(D, VD); 3658 } 3659 } 3660 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 3661 } 3662 } 3663 3664 /// \brief Called on a for stmt to check and extract its iteration space 3665 /// for further processing (such as collapsing). 3666 static bool CheckOpenMPIterationSpace( 3667 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 3668 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 3669 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr, 3670 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 3671 LoopIterationSpace &ResultIterSpace, 3672 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3673 // OpenMP [2.6, Canonical Loop Form] 3674 // for (init-expr; test-expr; incr-expr) structured-block 3675 auto *For = dyn_cast_or_null<ForStmt>(S); 3676 if (!For) { 3677 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for) 3678 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 3679 << getOpenMPDirectiveName(DKind) << NestedLoopCount 3680 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 3681 if (NestedLoopCount > 1) { 3682 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 3683 SemaRef.Diag(DSA.getConstructLoc(), 3684 diag::note_omp_collapse_ordered_expr) 3685 << 2 << CollapseLoopCountExpr->getSourceRange() 3686 << OrderedLoopCountExpr->getSourceRange(); 3687 else if (CollapseLoopCountExpr) 3688 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 3689 diag::note_omp_collapse_ordered_expr) 3690 << 0 << CollapseLoopCountExpr->getSourceRange(); 3691 else 3692 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 3693 diag::note_omp_collapse_ordered_expr) 3694 << 1 << OrderedLoopCountExpr->getSourceRange(); 3695 } 3696 return true; 3697 } 3698 assert(For->getBody()); 3699 3700 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); 3701 3702 // Check init. 3703 auto Init = For->getInit(); 3704 if (ISC.CheckInit(Init)) 3705 return true; 3706 3707 bool HasErrors = false; 3708 3709 // Check loop variable's type. 3710 if (auto *LCDecl = ISC.GetLoopDecl()) { 3711 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr(); 3712 3713 // OpenMP [2.6, Canonical Loop Form] 3714 // Var is one of the following: 3715 // A variable of signed or unsigned integer type. 3716 // For C++, a variable of a random access iterator type. 3717 // For C, a variable of a pointer type. 3718 auto VarType = LCDecl->getType().getNonReferenceType(); 3719 if (!VarType->isDependentType() && !VarType->isIntegerType() && 3720 !VarType->isPointerType() && 3721 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 3722 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type) 3723 << SemaRef.getLangOpts().CPlusPlus; 3724 HasErrors = true; 3725 } 3726 3727 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 3728 // a Construct 3729 // The loop iteration variable(s) in the associated for-loop(s) of a for or 3730 // parallel for construct is (are) private. 3731 // The loop iteration variable in the associated for-loop of a simd 3732 // construct with just one associated for-loop is linear with a 3733 // constant-linear-step that is the increment of the associated for-loop. 3734 // Exclude loop var from the list of variables with implicitly defined data 3735 // sharing attributes. 3736 VarsWithImplicitDSA.erase(LCDecl); 3737 3738 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 3739 // in a Construct, C/C++]. 3740 // The loop iteration variable in the associated for-loop of a simd 3741 // construct with just one associated for-loop may be listed in a linear 3742 // clause with a constant-linear-step that is the increment of the 3743 // associated for-loop. 3744 // The loop iteration variable(s) in the associated for-loop(s) of a for or 3745 // parallel for construct may be listed in a private or lastprivate clause. 3746 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false); 3747 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 3748 // declared in the loop and it is predetermined as a private. 3749 auto PredeterminedCKind = 3750 isOpenMPSimdDirective(DKind) 3751 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 3752 : OMPC_private; 3753 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 3754 DVar.CKind != PredeterminedCKind) || 3755 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 3756 isOpenMPDistributeDirective(DKind)) && 3757 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 3758 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 3759 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 3760 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa) 3761 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 3762 << getOpenMPClauseName(PredeterminedCKind); 3763 if (DVar.RefExpr == nullptr) 3764 DVar.CKind = PredeterminedCKind; 3765 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true); 3766 HasErrors = true; 3767 } else if (LoopDeclRefExpr != nullptr) { 3768 // Make the loop iteration variable private (for worksharing constructs), 3769 // linear (for simd directives with the only one associated loop) or 3770 // lastprivate (for simd directives with several collapsed or ordered 3771 // loops). 3772 if (DVar.CKind == OMPC_unknown) 3773 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate, 3774 [](OpenMPDirectiveKind) -> bool { return true; }, 3775 /*FromParent=*/false); 3776 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind); 3777 } 3778 3779 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 3780 3781 // Check test-expr. 3782 HasErrors |= ISC.CheckCond(For->getCond()); 3783 3784 // Check incr-expr. 3785 HasErrors |= ISC.CheckInc(For->getInc()); 3786 } 3787 3788 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 3789 return HasErrors; 3790 3791 // Build the loop's iteration space representation. 3792 ResultIterSpace.PreCond = 3793 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures); 3794 ResultIterSpace.NumIterations = ISC.BuildNumIterations( 3795 DSA.getCurScope(), 3796 (isOpenMPWorksharingDirective(DKind) || 3797 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)), 3798 Captures); 3799 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA); 3800 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar(); 3801 ResultIterSpace.CounterInit = ISC.BuildCounterInit(); 3802 ResultIterSpace.CounterStep = ISC.BuildCounterStep(); 3803 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange(); 3804 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange(); 3805 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange(); 3806 ResultIterSpace.Subtract = ISC.ShouldSubtractStep(); 3807 3808 HasErrors |= (ResultIterSpace.PreCond == nullptr || 3809 ResultIterSpace.NumIterations == nullptr || 3810 ResultIterSpace.CounterVar == nullptr || 3811 ResultIterSpace.PrivateCounterVar == nullptr || 3812 ResultIterSpace.CounterInit == nullptr || 3813 ResultIterSpace.CounterStep == nullptr); 3814 3815 return HasErrors; 3816 } 3817 3818 /// \brief Build 'VarRef = Start. 3819 static ExprResult 3820 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 3821 ExprResult Start, 3822 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3823 // Build 'VarRef = Start. 3824 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures); 3825 if (!NewStart.isUsable()) 3826 return ExprError(); 3827 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 3828 VarRef.get()->getType())) { 3829 NewStart = SemaRef.PerformImplicitConversion( 3830 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 3831 /*AllowExplicit=*/true); 3832 if (!NewStart.isUsable()) 3833 return ExprError(); 3834 } 3835 3836 auto Init = 3837 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 3838 return Init; 3839 } 3840 3841 /// \brief Build 'VarRef = Start + Iter * Step'. 3842 static ExprResult 3843 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc, 3844 ExprResult VarRef, ExprResult Start, ExprResult Iter, 3845 ExprResult Step, bool Subtract, 3846 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) { 3847 // Add parentheses (for debugging purposes only). 3848 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 3849 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 3850 !Step.isUsable()) 3851 return ExprError(); 3852 3853 ExprResult NewStep = Step; 3854 if (Captures) 3855 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 3856 if (NewStep.isInvalid()) 3857 return ExprError(); 3858 ExprResult Update = 3859 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 3860 if (!Update.isUsable()) 3861 return ExprError(); 3862 3863 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 3864 // 'VarRef = Start (+|-) Iter * Step'. 3865 ExprResult NewStart = Start; 3866 if (Captures) 3867 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 3868 if (NewStart.isInvalid()) 3869 return ExprError(); 3870 3871 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 3872 ExprResult SavedUpdate = Update; 3873 ExprResult UpdateVal; 3874 if (VarRef.get()->getType()->isOverloadableType() || 3875 NewStart.get()->getType()->isOverloadableType() || 3876 Update.get()->getType()->isOverloadableType()) { 3877 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 3878 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 3879 Update = 3880 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 3881 if (Update.isUsable()) { 3882 UpdateVal = 3883 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 3884 VarRef.get(), SavedUpdate.get()); 3885 if (UpdateVal.isUsable()) { 3886 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 3887 UpdateVal.get()); 3888 } 3889 } 3890 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 3891 } 3892 3893 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 3894 if (!Update.isUsable() || !UpdateVal.isUsable()) { 3895 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 3896 NewStart.get(), SavedUpdate.get()); 3897 if (!Update.isUsable()) 3898 return ExprError(); 3899 3900 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 3901 VarRef.get()->getType())) { 3902 Update = SemaRef.PerformImplicitConversion( 3903 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 3904 if (!Update.isUsable()) 3905 return ExprError(); 3906 } 3907 3908 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 3909 } 3910 return Update; 3911 } 3912 3913 /// \brief Convert integer expression \a E to make it have at least \a Bits 3914 /// bits. 3915 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 3916 if (E == nullptr) 3917 return ExprError(); 3918 auto &C = SemaRef.Context; 3919 QualType OldType = E->getType(); 3920 unsigned HasBits = C.getTypeSize(OldType); 3921 if (HasBits >= Bits) 3922 return ExprResult(E); 3923 // OK to convert to signed, because new type has more bits than old. 3924 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 3925 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 3926 true); 3927 } 3928 3929 /// \brief Check if the given expression \a E is a constant integer that fits 3930 /// into \a Bits bits. 3931 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) { 3932 if (E == nullptr) 3933 return false; 3934 llvm::APSInt Result; 3935 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 3936 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 3937 return false; 3938 } 3939 3940 /// Build preinits statement for the given declarations. 3941 static Stmt *buildPreInits(ASTContext &Context, 3942 SmallVectorImpl<Decl *> &PreInits) { 3943 if (!PreInits.empty()) { 3944 return new (Context) DeclStmt( 3945 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 3946 SourceLocation(), SourceLocation()); 3947 } 3948 return nullptr; 3949 } 3950 3951 /// Build preinits statement for the given declarations. 3952 static Stmt *buildPreInits(ASTContext &Context, 3953 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3954 if (!Captures.empty()) { 3955 SmallVector<Decl *, 16> PreInits; 3956 for (auto &Pair : Captures) 3957 PreInits.push_back(Pair.second->getDecl()); 3958 return buildPreInits(Context, PreInits); 3959 } 3960 return nullptr; 3961 } 3962 3963 /// Build postupdate expression for the given list of postupdates expressions. 3964 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 3965 Expr *PostUpdate = nullptr; 3966 if (!PostUpdates.empty()) { 3967 for (auto *E : PostUpdates) { 3968 Expr *ConvE = S.BuildCStyleCastExpr( 3969 E->getExprLoc(), 3970 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 3971 E->getExprLoc(), E) 3972 .get(); 3973 PostUpdate = PostUpdate 3974 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 3975 PostUpdate, ConvE) 3976 .get() 3977 : ConvE; 3978 } 3979 } 3980 return PostUpdate; 3981 } 3982 3983 /// \brief Called on a for stmt to check itself and nested loops (if any). 3984 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 3985 /// number of collapsed loops otherwise. 3986 static unsigned 3987 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 3988 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 3989 DSAStackTy &DSA, 3990 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 3991 OMPLoopDirective::HelperExprs &Built) { 3992 unsigned NestedLoopCount = 1; 3993 if (CollapseLoopCountExpr) { 3994 // Found 'collapse' clause - calculate collapse number. 3995 llvm::APSInt Result; 3996 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) 3997 NestedLoopCount = Result.getLimitedValue(); 3998 } 3999 if (OrderedLoopCountExpr) { 4000 // Found 'ordered' clause - calculate collapse number. 4001 llvm::APSInt Result; 4002 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 4003 if (Result.getLimitedValue() < NestedLoopCount) { 4004 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 4005 diag::err_omp_wrong_ordered_loop_count) 4006 << OrderedLoopCountExpr->getSourceRange(); 4007 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 4008 diag::note_collapse_loop_count) 4009 << CollapseLoopCountExpr->getSourceRange(); 4010 } 4011 NestedLoopCount = Result.getLimitedValue(); 4012 } 4013 } 4014 // This is helper routine for loop directives (e.g., 'for', 'simd', 4015 // 'for simd', etc.). 4016 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 4017 SmallVector<LoopIterationSpace, 4> IterSpaces; 4018 IterSpaces.resize(NestedLoopCount); 4019 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 4020 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 4021 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt, 4022 NestedLoopCount, CollapseLoopCountExpr, 4023 OrderedLoopCountExpr, VarsWithImplicitDSA, 4024 IterSpaces[Cnt], Captures)) 4025 return 0; 4026 // Move on to the next nested for loop, or to the loop body. 4027 // OpenMP [2.8.1, simd construct, Restrictions] 4028 // All loops associated with the construct must be perfectly nested; that 4029 // is, there must be no intervening code nor any OpenMP directive between 4030 // any two loops. 4031 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 4032 } 4033 4034 Built.clear(/* size */ NestedLoopCount); 4035 4036 if (SemaRef.CurContext->isDependentContext()) 4037 return NestedLoopCount; 4038 4039 // An example of what is generated for the following code: 4040 // 4041 // #pragma omp simd collapse(2) ordered(2) 4042 // for (i = 0; i < NI; ++i) 4043 // for (k = 0; k < NK; ++k) 4044 // for (j = J0; j < NJ; j+=2) { 4045 // <loop body> 4046 // } 4047 // 4048 // We generate the code below. 4049 // Note: the loop body may be outlined in CodeGen. 4050 // Note: some counters may be C++ classes, operator- is used to find number of 4051 // iterations and operator+= to calculate counter value. 4052 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 4053 // or i64 is currently supported). 4054 // 4055 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 4056 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 4057 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 4058 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 4059 // // similar updates for vars in clauses (e.g. 'linear') 4060 // <loop body (using local i and j)> 4061 // } 4062 // i = NI; // assign final values of counters 4063 // j = NJ; 4064 // 4065 4066 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 4067 // the iteration counts of the collapsed for loops. 4068 // Precondition tests if there is at least one iteration (all conditions are 4069 // true). 4070 auto PreCond = ExprResult(IterSpaces[0].PreCond); 4071 auto N0 = IterSpaces[0].NumIterations; 4072 ExprResult LastIteration32 = WidenIterationCount( 4073 32 /* Bits */, SemaRef 4074 .PerformImplicitConversion( 4075 N0->IgnoreImpCasts(), N0->getType(), 4076 Sema::AA_Converting, /*AllowExplicit=*/true) 4077 .get(), 4078 SemaRef); 4079 ExprResult LastIteration64 = WidenIterationCount( 4080 64 /* Bits */, SemaRef 4081 .PerformImplicitConversion( 4082 N0->IgnoreImpCasts(), N0->getType(), 4083 Sema::AA_Converting, /*AllowExplicit=*/true) 4084 .get(), 4085 SemaRef); 4086 4087 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 4088 return NestedLoopCount; 4089 4090 auto &C = SemaRef.Context; 4091 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 4092 4093 Scope *CurScope = DSA.getCurScope(); 4094 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 4095 if (PreCond.isUsable()) { 4096 PreCond = 4097 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 4098 PreCond.get(), IterSpaces[Cnt].PreCond); 4099 } 4100 auto N = IterSpaces[Cnt].NumIterations; 4101 SourceLocation Loc = N->getExprLoc(); 4102 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 4103 if (LastIteration32.isUsable()) 4104 LastIteration32 = SemaRef.BuildBinOp( 4105 CurScope, Loc, BO_Mul, LastIteration32.get(), 4106 SemaRef 4107 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 4108 Sema::AA_Converting, 4109 /*AllowExplicit=*/true) 4110 .get()); 4111 if (LastIteration64.isUsable()) 4112 LastIteration64 = SemaRef.BuildBinOp( 4113 CurScope, Loc, BO_Mul, LastIteration64.get(), 4114 SemaRef 4115 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 4116 Sema::AA_Converting, 4117 /*AllowExplicit=*/true) 4118 .get()); 4119 } 4120 4121 // Choose either the 32-bit or 64-bit version. 4122 ExprResult LastIteration = LastIteration64; 4123 if (LastIteration32.isUsable() && 4124 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 4125 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 4126 FitsInto( 4127 32 /* Bits */, 4128 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 4129 LastIteration64.get(), SemaRef))) 4130 LastIteration = LastIteration32; 4131 QualType VType = LastIteration.get()->getType(); 4132 QualType RealVType = VType; 4133 QualType StrideVType = VType; 4134 if (isOpenMPTaskLoopDirective(DKind)) { 4135 VType = 4136 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 4137 StrideVType = 4138 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 4139 } 4140 4141 if (!LastIteration.isUsable()) 4142 return 0; 4143 4144 // Save the number of iterations. 4145 ExprResult NumIterations = LastIteration; 4146 { 4147 LastIteration = SemaRef.BuildBinOp( 4148 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 4149 LastIteration.get(), 4150 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4151 if (!LastIteration.isUsable()) 4152 return 0; 4153 } 4154 4155 // Calculate the last iteration number beforehand instead of doing this on 4156 // each iteration. Do not do this if the number of iterations may be kfold-ed. 4157 llvm::APSInt Result; 4158 bool IsConstant = 4159 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 4160 ExprResult CalcLastIteration; 4161 if (!IsConstant) { 4162 ExprResult SaveRef = 4163 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 4164 LastIteration = SaveRef; 4165 4166 // Prepare SaveRef + 1. 4167 NumIterations = SemaRef.BuildBinOp( 4168 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 4169 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4170 if (!NumIterations.isUsable()) 4171 return 0; 4172 } 4173 4174 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 4175 4176 // Build variables passed into runtime, necessary for worksharing directives. 4177 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 4178 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4179 isOpenMPDistributeDirective(DKind)) { 4180 // Lower bound variable, initialized with zero. 4181 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 4182 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 4183 SemaRef.AddInitializerToDecl(LBDecl, 4184 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4185 /*DirectInit*/ false); 4186 4187 // Upper bound variable, initialized with last iteration number. 4188 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 4189 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 4190 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 4191 /*DirectInit*/ false); 4192 4193 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 4194 // This will be used to implement clause 'lastprivate'. 4195 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 4196 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 4197 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 4198 SemaRef.AddInitializerToDecl(ILDecl, 4199 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4200 /*DirectInit*/ false); 4201 4202 // Stride variable returned by runtime (we initialize it to 1 by default). 4203 VarDecl *STDecl = 4204 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 4205 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 4206 SemaRef.AddInitializerToDecl(STDecl, 4207 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 4208 /*DirectInit*/ false); 4209 4210 // Build expression: UB = min(UB, LastIteration) 4211 // It is necessary for CodeGen of directives with static scheduling. 4212 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 4213 UB.get(), LastIteration.get()); 4214 ExprResult CondOp = SemaRef.ActOnConditionalOp( 4215 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get()); 4216 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 4217 CondOp.get()); 4218 EUB = SemaRef.ActOnFinishFullExpr(EUB.get()); 4219 4220 // If we have a combined directive that combines 'distribute', 'for' or 4221 // 'simd' we need to be able to access the bounds of the schedule of the 4222 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 4223 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 4224 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4225 4226 // Lower bound variable, initialized with zero. 4227 VarDecl *CombLBDecl = 4228 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 4229 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 4230 SemaRef.AddInitializerToDecl( 4231 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4232 /*DirectInit*/ false); 4233 4234 // Upper bound variable, initialized with last iteration number. 4235 VarDecl *CombUBDecl = 4236 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 4237 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 4238 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 4239 /*DirectInit*/ false); 4240 4241 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 4242 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 4243 ExprResult CombCondOp = 4244 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 4245 LastIteration.get(), CombUB.get()); 4246 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 4247 CombCondOp.get()); 4248 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get()); 4249 4250 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 4251 // We expect to have at least 2 more parameters than the 'parallel' 4252 // directive does - the lower and upper bounds of the previous schedule. 4253 assert(CD->getNumParams() >= 4 && 4254 "Unexpected number of parameters in loop combined directive"); 4255 4256 // Set the proper type for the bounds given what we learned from the 4257 // enclosed loops. 4258 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 4259 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 4260 4261 // Previous lower and upper bounds are obtained from the region 4262 // parameters. 4263 PrevLB = 4264 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 4265 PrevUB = 4266 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 4267 } 4268 } 4269 4270 // Build the iteration variable and its initialization before loop. 4271 ExprResult IV; 4272 ExprResult Init, CombInit; 4273 { 4274 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 4275 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 4276 Expr *RHS = 4277 (isOpenMPWorksharingDirective(DKind) || 4278 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4279 ? LB.get() 4280 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 4281 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 4282 Init = SemaRef.ActOnFinishFullExpr(Init.get()); 4283 4284 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4285 Expr *CombRHS = 4286 (isOpenMPWorksharingDirective(DKind) || 4287 isOpenMPTaskLoopDirective(DKind) || 4288 isOpenMPDistributeDirective(DKind)) 4289 ? CombLB.get() 4290 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 4291 CombInit = 4292 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 4293 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get()); 4294 } 4295 } 4296 4297 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops. 4298 SourceLocation CondLoc; 4299 ExprResult Cond = 4300 (isOpenMPWorksharingDirective(DKind) || 4301 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4302 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()) 4303 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 4304 NumIterations.get()); 4305 ExprResult CombCond; 4306 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4307 CombCond = 4308 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get()); 4309 } 4310 // Loop increment (IV = IV + 1) 4311 SourceLocation IncLoc; 4312 ExprResult Inc = 4313 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 4314 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 4315 if (!Inc.isUsable()) 4316 return 0; 4317 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 4318 Inc = SemaRef.ActOnFinishFullExpr(Inc.get()); 4319 if (!Inc.isUsable()) 4320 return 0; 4321 4322 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 4323 // Used for directives with static scheduling. 4324 // In combined construct, add combined version that use CombLB and CombUB 4325 // base variables for the update 4326 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 4327 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4328 isOpenMPDistributeDirective(DKind)) { 4329 // LB + ST 4330 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 4331 if (!NextLB.isUsable()) 4332 return 0; 4333 // LB = LB + ST 4334 NextLB = 4335 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 4336 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get()); 4337 if (!NextLB.isUsable()) 4338 return 0; 4339 // UB + ST 4340 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 4341 if (!NextUB.isUsable()) 4342 return 0; 4343 // UB = UB + ST 4344 NextUB = 4345 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 4346 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get()); 4347 if (!NextUB.isUsable()) 4348 return 0; 4349 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4350 CombNextLB = 4351 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 4352 if (!NextLB.isUsable()) 4353 return 0; 4354 // LB = LB + ST 4355 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 4356 CombNextLB.get()); 4357 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get()); 4358 if (!CombNextLB.isUsable()) 4359 return 0; 4360 // UB + ST 4361 CombNextUB = 4362 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 4363 if (!CombNextUB.isUsable()) 4364 return 0; 4365 // UB = UB + ST 4366 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 4367 CombNextUB.get()); 4368 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get()); 4369 if (!CombNextUB.isUsable()) 4370 return 0; 4371 } 4372 } 4373 4374 // Create increment expression for distribute loop when combined in a same 4375 // directive with for as IV = IV + ST; ensure upper bound expression based 4376 // on PrevUB instead of NumIterations - used to implement 'for' when found 4377 // in combination with 'distribute', like in 'distribute parallel for' 4378 SourceLocation DistIncLoc; 4379 ExprResult DistCond, DistInc, PrevEUB; 4380 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4381 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()); 4382 assert(DistCond.isUsable() && "distribute cond expr was not built"); 4383 4384 DistInc = 4385 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 4386 assert(DistInc.isUsable() && "distribute inc expr was not built"); 4387 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 4388 DistInc.get()); 4389 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get()); 4390 assert(DistInc.isUsable() && "distribute inc expr was not built"); 4391 4392 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 4393 // construct 4394 SourceLocation DistEUBLoc; 4395 ExprResult IsUBGreater = 4396 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get()); 4397 ExprResult CondOp = SemaRef.ActOnConditionalOp( 4398 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get()); 4399 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 4400 CondOp.get()); 4401 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get()); 4402 } 4403 4404 // Build updates and final values of the loop counters. 4405 bool HasErrors = false; 4406 Built.Counters.resize(NestedLoopCount); 4407 Built.Inits.resize(NestedLoopCount); 4408 Built.Updates.resize(NestedLoopCount); 4409 Built.Finals.resize(NestedLoopCount); 4410 SmallVector<Expr *, 4> LoopMultipliers; 4411 { 4412 ExprResult Div; 4413 // Go from inner nested loop to outer. 4414 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 4415 LoopIterationSpace &IS = IterSpaces[Cnt]; 4416 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 4417 // Build: Iter = (IV / Div) % IS.NumIters 4418 // where Div is product of previous iterations' IS.NumIters. 4419 ExprResult Iter; 4420 if (Div.isUsable()) { 4421 Iter = 4422 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get()); 4423 } else { 4424 Iter = IV; 4425 assert((Cnt == (int)NestedLoopCount - 1) && 4426 "unusable div expected on first iteration only"); 4427 } 4428 4429 if (Cnt != 0 && Iter.isUsable()) 4430 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(), 4431 IS.NumIterations); 4432 if (!Iter.isUsable()) { 4433 HasErrors = true; 4434 break; 4435 } 4436 4437 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 4438 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 4439 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(), 4440 IS.CounterVar->getExprLoc(), 4441 /*RefersToCapture=*/true); 4442 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 4443 IS.CounterInit, Captures); 4444 if (!Init.isUsable()) { 4445 HasErrors = true; 4446 break; 4447 } 4448 ExprResult Update = BuildCounterUpdate( 4449 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 4450 IS.CounterStep, IS.Subtract, &Captures); 4451 if (!Update.isUsable()) { 4452 HasErrors = true; 4453 break; 4454 } 4455 4456 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 4457 ExprResult Final = BuildCounterUpdate( 4458 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, 4459 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures); 4460 if (!Final.isUsable()) { 4461 HasErrors = true; 4462 break; 4463 } 4464 4465 // Build Div for the next iteration: Div <- Div * IS.NumIters 4466 if (Cnt != 0) { 4467 if (Div.isUnset()) 4468 Div = IS.NumIterations; 4469 else 4470 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(), 4471 IS.NumIterations); 4472 4473 // Add parentheses (for debugging purposes only). 4474 if (Div.isUsable()) 4475 Div = tryBuildCapture(SemaRef, Div.get(), Captures); 4476 if (!Div.isUsable()) { 4477 HasErrors = true; 4478 break; 4479 } 4480 LoopMultipliers.push_back(Div.get()); 4481 } 4482 if (!Update.isUsable() || !Final.isUsable()) { 4483 HasErrors = true; 4484 break; 4485 } 4486 // Save results 4487 Built.Counters[Cnt] = IS.CounterVar; 4488 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 4489 Built.Inits[Cnt] = Init.get(); 4490 Built.Updates[Cnt] = Update.get(); 4491 Built.Finals[Cnt] = Final.get(); 4492 } 4493 } 4494 4495 if (HasErrors) 4496 return 0; 4497 4498 // Save results 4499 Built.IterationVarRef = IV.get(); 4500 Built.LastIteration = LastIteration.get(); 4501 Built.NumIterations = NumIterations.get(); 4502 Built.CalcLastIteration = 4503 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get(); 4504 Built.PreCond = PreCond.get(); 4505 Built.PreInits = buildPreInits(C, Captures); 4506 Built.Cond = Cond.get(); 4507 Built.Init = Init.get(); 4508 Built.Inc = Inc.get(); 4509 Built.LB = LB.get(); 4510 Built.UB = UB.get(); 4511 Built.IL = IL.get(); 4512 Built.ST = ST.get(); 4513 Built.EUB = EUB.get(); 4514 Built.NLB = NextLB.get(); 4515 Built.NUB = NextUB.get(); 4516 Built.PrevLB = PrevLB.get(); 4517 Built.PrevUB = PrevUB.get(); 4518 Built.DistInc = DistInc.get(); 4519 Built.PrevEUB = PrevEUB.get(); 4520 Built.DistCombinedFields.LB = CombLB.get(); 4521 Built.DistCombinedFields.UB = CombUB.get(); 4522 Built.DistCombinedFields.EUB = CombEUB.get(); 4523 Built.DistCombinedFields.Init = CombInit.get(); 4524 Built.DistCombinedFields.Cond = CombCond.get(); 4525 Built.DistCombinedFields.NLB = CombNextLB.get(); 4526 Built.DistCombinedFields.NUB = CombNextUB.get(); 4527 4528 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get(); 4529 // Fill data for doacross depend clauses. 4530 for (auto Pair : DSA.getDoacrossDependClauses()) { 4531 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 4532 Pair.first->setCounterValue(CounterVal); 4533 else { 4534 if (NestedLoopCount != Pair.second.size() || 4535 NestedLoopCount != LoopMultipliers.size() + 1) { 4536 // Erroneous case - clause has some problems. 4537 Pair.first->setCounterValue(CounterVal); 4538 continue; 4539 } 4540 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink); 4541 auto I = Pair.second.rbegin(); 4542 auto IS = IterSpaces.rbegin(); 4543 auto ILM = LoopMultipliers.rbegin(); 4544 Expr *UpCounterVal = CounterVal; 4545 Expr *Multiplier = nullptr; 4546 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 4547 if (I->first) { 4548 assert(IS->CounterStep); 4549 Expr *NormalizedOffset = 4550 SemaRef 4551 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div, 4552 I->first, IS->CounterStep) 4553 .get(); 4554 if (Multiplier) { 4555 NormalizedOffset = 4556 SemaRef 4557 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul, 4558 NormalizedOffset, Multiplier) 4559 .get(); 4560 } 4561 assert(I->second == OO_Plus || I->second == OO_Minus); 4562 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub; 4563 UpCounterVal = SemaRef 4564 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK, 4565 UpCounterVal, NormalizedOffset) 4566 .get(); 4567 } 4568 Multiplier = *ILM; 4569 ++I; 4570 ++IS; 4571 ++ILM; 4572 } 4573 Pair.first->setCounterValue(UpCounterVal); 4574 } 4575 } 4576 4577 return NestedLoopCount; 4578 } 4579 4580 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 4581 auto CollapseClauses = 4582 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 4583 if (CollapseClauses.begin() != CollapseClauses.end()) 4584 return (*CollapseClauses.begin())->getNumForLoops(); 4585 return nullptr; 4586 } 4587 4588 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 4589 auto OrderedClauses = 4590 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 4591 if (OrderedClauses.begin() != OrderedClauses.end()) 4592 return (*OrderedClauses.begin())->getNumForLoops(); 4593 return nullptr; 4594 } 4595 4596 static bool checkSimdlenSafelenSpecified(Sema &S, 4597 const ArrayRef<OMPClause *> Clauses) { 4598 OMPSafelenClause *Safelen = nullptr; 4599 OMPSimdlenClause *Simdlen = nullptr; 4600 4601 for (auto *Clause : Clauses) { 4602 if (Clause->getClauseKind() == OMPC_safelen) 4603 Safelen = cast<OMPSafelenClause>(Clause); 4604 else if (Clause->getClauseKind() == OMPC_simdlen) 4605 Simdlen = cast<OMPSimdlenClause>(Clause); 4606 if (Safelen && Simdlen) 4607 break; 4608 } 4609 4610 if (Simdlen && Safelen) { 4611 llvm::APSInt SimdlenRes, SafelenRes; 4612 auto SimdlenLength = Simdlen->getSimdlen(); 4613 auto SafelenLength = Safelen->getSafelen(); 4614 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 4615 SimdlenLength->isInstantiationDependent() || 4616 SimdlenLength->containsUnexpandedParameterPack()) 4617 return false; 4618 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 4619 SafelenLength->isInstantiationDependent() || 4620 SafelenLength->containsUnexpandedParameterPack()) 4621 return false; 4622 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context); 4623 SafelenLength->EvaluateAsInt(SafelenRes, S.Context); 4624 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 4625 // If both simdlen and safelen clauses are specified, the value of the 4626 // simdlen parameter must be less than or equal to the value of the safelen 4627 // parameter. 4628 if (SimdlenRes > SafelenRes) { 4629 S.Diag(SimdlenLength->getExprLoc(), 4630 diag::err_omp_wrong_simdlen_safelen_values) 4631 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 4632 return true; 4633 } 4634 } 4635 return false; 4636 } 4637 4638 StmtResult Sema::ActOnOpenMPSimdDirective( 4639 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4640 SourceLocation EndLoc, 4641 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4642 if (!AStmt) 4643 return StmtError(); 4644 4645 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4646 OMPLoopDirective::HelperExprs B; 4647 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4648 // define the nested loops number. 4649 unsigned NestedLoopCount = CheckOpenMPLoop( 4650 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 4651 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 4652 if (NestedLoopCount == 0) 4653 return StmtError(); 4654 4655 assert((CurContext->isDependentContext() || B.builtAll()) && 4656 "omp simd loop exprs were not built"); 4657 4658 if (!CurContext->isDependentContext()) { 4659 // Finalize the clauses that need pre-built expressions for CodeGen. 4660 for (auto C : Clauses) { 4661 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4662 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4663 B.NumIterations, *this, CurScope, 4664 DSAStack)) 4665 return StmtError(); 4666 } 4667 } 4668 4669 if (checkSimdlenSafelenSpecified(*this, Clauses)) 4670 return StmtError(); 4671 4672 getCurFunction()->setHasBranchProtectedScope(); 4673 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4674 Clauses, AStmt, B); 4675 } 4676 4677 StmtResult Sema::ActOnOpenMPForDirective( 4678 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4679 SourceLocation EndLoc, 4680 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4681 if (!AStmt) 4682 return StmtError(); 4683 4684 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4685 OMPLoopDirective::HelperExprs B; 4686 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4687 // define the nested loops number. 4688 unsigned NestedLoopCount = CheckOpenMPLoop( 4689 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 4690 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 4691 if (NestedLoopCount == 0) 4692 return StmtError(); 4693 4694 assert((CurContext->isDependentContext() || B.builtAll()) && 4695 "omp for loop exprs were not built"); 4696 4697 if (!CurContext->isDependentContext()) { 4698 // Finalize the clauses that need pre-built expressions for CodeGen. 4699 for (auto C : Clauses) { 4700 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4701 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4702 B.NumIterations, *this, CurScope, 4703 DSAStack)) 4704 return StmtError(); 4705 } 4706 } 4707 4708 getCurFunction()->setHasBranchProtectedScope(); 4709 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4710 Clauses, AStmt, B, DSAStack->isCancelRegion()); 4711 } 4712 4713 StmtResult Sema::ActOnOpenMPForSimdDirective( 4714 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4715 SourceLocation EndLoc, 4716 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4717 if (!AStmt) 4718 return StmtError(); 4719 4720 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4721 OMPLoopDirective::HelperExprs B; 4722 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4723 // define the nested loops number. 4724 unsigned NestedLoopCount = 4725 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 4726 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4727 VarsWithImplicitDSA, B); 4728 if (NestedLoopCount == 0) 4729 return StmtError(); 4730 4731 assert((CurContext->isDependentContext() || B.builtAll()) && 4732 "omp for simd loop exprs were not built"); 4733 4734 if (!CurContext->isDependentContext()) { 4735 // Finalize the clauses that need pre-built expressions for CodeGen. 4736 for (auto C : Clauses) { 4737 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4738 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4739 B.NumIterations, *this, CurScope, 4740 DSAStack)) 4741 return StmtError(); 4742 } 4743 } 4744 4745 if (checkSimdlenSafelenSpecified(*this, Clauses)) 4746 return StmtError(); 4747 4748 getCurFunction()->setHasBranchProtectedScope(); 4749 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4750 Clauses, AStmt, B); 4751 } 4752 4753 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 4754 Stmt *AStmt, 4755 SourceLocation StartLoc, 4756 SourceLocation EndLoc) { 4757 if (!AStmt) 4758 return StmtError(); 4759 4760 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4761 auto BaseStmt = AStmt; 4762 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 4763 BaseStmt = CS->getCapturedStmt(); 4764 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 4765 auto S = C->children(); 4766 if (S.begin() == S.end()) 4767 return StmtError(); 4768 // All associated statements must be '#pragma omp section' except for 4769 // the first one. 4770 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 4771 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 4772 if (SectionStmt) 4773 Diag(SectionStmt->getLocStart(), 4774 diag::err_omp_sections_substmt_not_section); 4775 return StmtError(); 4776 } 4777 cast<OMPSectionDirective>(SectionStmt) 4778 ->setHasCancel(DSAStack->isCancelRegion()); 4779 } 4780 } else { 4781 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt); 4782 return StmtError(); 4783 } 4784 4785 getCurFunction()->setHasBranchProtectedScope(); 4786 4787 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 4788 DSAStack->isCancelRegion()); 4789 } 4790 4791 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 4792 SourceLocation StartLoc, 4793 SourceLocation EndLoc) { 4794 if (!AStmt) 4795 return StmtError(); 4796 4797 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4798 4799 getCurFunction()->setHasBranchProtectedScope(); 4800 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 4801 4802 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 4803 DSAStack->isCancelRegion()); 4804 } 4805 4806 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 4807 Stmt *AStmt, 4808 SourceLocation StartLoc, 4809 SourceLocation EndLoc) { 4810 if (!AStmt) 4811 return StmtError(); 4812 4813 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4814 4815 getCurFunction()->setHasBranchProtectedScope(); 4816 4817 // OpenMP [2.7.3, single Construct, Restrictions] 4818 // The copyprivate clause must not be used with the nowait clause. 4819 OMPClause *Nowait = nullptr; 4820 OMPClause *Copyprivate = nullptr; 4821 for (auto *Clause : Clauses) { 4822 if (Clause->getClauseKind() == OMPC_nowait) 4823 Nowait = Clause; 4824 else if (Clause->getClauseKind() == OMPC_copyprivate) 4825 Copyprivate = Clause; 4826 if (Copyprivate && Nowait) { 4827 Diag(Copyprivate->getLocStart(), 4828 diag::err_omp_single_copyprivate_with_nowait); 4829 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here); 4830 return StmtError(); 4831 } 4832 } 4833 4834 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 4835 } 4836 4837 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 4838 SourceLocation StartLoc, 4839 SourceLocation EndLoc) { 4840 if (!AStmt) 4841 return StmtError(); 4842 4843 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4844 4845 getCurFunction()->setHasBranchProtectedScope(); 4846 4847 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 4848 } 4849 4850 StmtResult Sema::ActOnOpenMPCriticalDirective( 4851 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 4852 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 4853 if (!AStmt) 4854 return StmtError(); 4855 4856 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4857 4858 bool ErrorFound = false; 4859 llvm::APSInt Hint; 4860 SourceLocation HintLoc; 4861 bool DependentHint = false; 4862 for (auto *C : Clauses) { 4863 if (C->getClauseKind() == OMPC_hint) { 4864 if (!DirName.getName()) { 4865 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name); 4866 ErrorFound = true; 4867 } 4868 Expr *E = cast<OMPHintClause>(C)->getHint(); 4869 if (E->isTypeDependent() || E->isValueDependent() || 4870 E->isInstantiationDependent()) 4871 DependentHint = true; 4872 else { 4873 Hint = E->EvaluateKnownConstInt(Context); 4874 HintLoc = C->getLocStart(); 4875 } 4876 } 4877 } 4878 if (ErrorFound) 4879 return StmtError(); 4880 auto Pair = DSAStack->getCriticalWithHint(DirName); 4881 if (Pair.first && DirName.getName() && !DependentHint) { 4882 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 4883 Diag(StartLoc, diag::err_omp_critical_with_hint); 4884 if (HintLoc.isValid()) { 4885 Diag(HintLoc, diag::note_omp_critical_hint_here) 4886 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 4887 } else 4888 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 4889 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 4890 Diag(C->getLocStart(), diag::note_omp_critical_hint_here) 4891 << 1 4892 << C->getHint()->EvaluateKnownConstInt(Context).toString( 4893 /*Radix=*/10, /*Signed=*/false); 4894 } else 4895 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1; 4896 } 4897 } 4898 4899 getCurFunction()->setHasBranchProtectedScope(); 4900 4901 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 4902 Clauses, AStmt); 4903 if (!Pair.first && DirName.getName() && !DependentHint) 4904 DSAStack->addCriticalWithHint(Dir, Hint); 4905 return Dir; 4906 } 4907 4908 StmtResult Sema::ActOnOpenMPParallelForDirective( 4909 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4910 SourceLocation EndLoc, 4911 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4912 if (!AStmt) 4913 return StmtError(); 4914 4915 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 4916 // 1.2.2 OpenMP Language Terminology 4917 // Structured block - An executable statement with a single entry at the 4918 // top and a single exit at the bottom. 4919 // The point of exit cannot be a branch out of the structured block. 4920 // longjmp() and throw() must not violate the entry/exit criteria. 4921 CS->getCapturedDecl()->setNothrow(); 4922 4923 OMPLoopDirective::HelperExprs B; 4924 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4925 // define the nested loops number. 4926 unsigned NestedLoopCount = 4927 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 4928 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4929 VarsWithImplicitDSA, B); 4930 if (NestedLoopCount == 0) 4931 return StmtError(); 4932 4933 assert((CurContext->isDependentContext() || B.builtAll()) && 4934 "omp parallel for loop exprs were not built"); 4935 4936 if (!CurContext->isDependentContext()) { 4937 // Finalize the clauses that need pre-built expressions for CodeGen. 4938 for (auto C : Clauses) { 4939 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4940 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4941 B.NumIterations, *this, CurScope, 4942 DSAStack)) 4943 return StmtError(); 4944 } 4945 } 4946 4947 getCurFunction()->setHasBranchProtectedScope(); 4948 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, 4949 NestedLoopCount, Clauses, AStmt, B, 4950 DSAStack->isCancelRegion()); 4951 } 4952 4953 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 4954 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4955 SourceLocation EndLoc, 4956 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4957 if (!AStmt) 4958 return StmtError(); 4959 4960 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 4961 // 1.2.2 OpenMP Language Terminology 4962 // Structured block - An executable statement with a single entry at the 4963 // top and a single exit at the bottom. 4964 // The point of exit cannot be a branch out of the structured block. 4965 // longjmp() and throw() must not violate the entry/exit criteria. 4966 CS->getCapturedDecl()->setNothrow(); 4967 4968 OMPLoopDirective::HelperExprs B; 4969 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4970 // define the nested loops number. 4971 unsigned NestedLoopCount = 4972 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 4973 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4974 VarsWithImplicitDSA, B); 4975 if (NestedLoopCount == 0) 4976 return StmtError(); 4977 4978 if (!CurContext->isDependentContext()) { 4979 // Finalize the clauses that need pre-built expressions for CodeGen. 4980 for (auto C : Clauses) { 4981 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4982 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4983 B.NumIterations, *this, CurScope, 4984 DSAStack)) 4985 return StmtError(); 4986 } 4987 } 4988 4989 if (checkSimdlenSafelenSpecified(*this, Clauses)) 4990 return StmtError(); 4991 4992 getCurFunction()->setHasBranchProtectedScope(); 4993 return OMPParallelForSimdDirective::Create( 4994 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 4995 } 4996 4997 StmtResult 4998 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 4999 Stmt *AStmt, SourceLocation StartLoc, 5000 SourceLocation EndLoc) { 5001 if (!AStmt) 5002 return StmtError(); 5003 5004 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5005 auto BaseStmt = AStmt; 5006 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 5007 BaseStmt = CS->getCapturedStmt(); 5008 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 5009 auto S = C->children(); 5010 if (S.begin() == S.end()) 5011 return StmtError(); 5012 // All associated statements must be '#pragma omp section' except for 5013 // the first one. 5014 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 5015 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 5016 if (SectionStmt) 5017 Diag(SectionStmt->getLocStart(), 5018 diag::err_omp_parallel_sections_substmt_not_section); 5019 return StmtError(); 5020 } 5021 cast<OMPSectionDirective>(SectionStmt) 5022 ->setHasCancel(DSAStack->isCancelRegion()); 5023 } 5024 } else { 5025 Diag(AStmt->getLocStart(), 5026 diag::err_omp_parallel_sections_not_compound_stmt); 5027 return StmtError(); 5028 } 5029 5030 getCurFunction()->setHasBranchProtectedScope(); 5031 5032 return OMPParallelSectionsDirective::Create( 5033 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); 5034 } 5035 5036 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 5037 Stmt *AStmt, SourceLocation StartLoc, 5038 SourceLocation EndLoc) { 5039 if (!AStmt) 5040 return StmtError(); 5041 5042 auto *CS = cast<CapturedStmt>(AStmt); 5043 // 1.2.2 OpenMP Language Terminology 5044 // Structured block - An executable statement with a single entry at the 5045 // top and a single exit at the bottom. 5046 // The point of exit cannot be a branch out of the structured block. 5047 // longjmp() and throw() must not violate the entry/exit criteria. 5048 CS->getCapturedDecl()->setNothrow(); 5049 5050 getCurFunction()->setHasBranchProtectedScope(); 5051 5052 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5053 DSAStack->isCancelRegion()); 5054 } 5055 5056 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 5057 SourceLocation EndLoc) { 5058 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 5059 } 5060 5061 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 5062 SourceLocation EndLoc) { 5063 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 5064 } 5065 5066 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 5067 SourceLocation EndLoc) { 5068 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 5069 } 5070 5071 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 5072 Stmt *AStmt, 5073 SourceLocation StartLoc, 5074 SourceLocation EndLoc) { 5075 if (!AStmt) 5076 return StmtError(); 5077 5078 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5079 5080 getCurFunction()->setHasBranchProtectedScope(); 5081 5082 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, 5083 AStmt); 5084 } 5085 5086 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 5087 SourceLocation StartLoc, 5088 SourceLocation EndLoc) { 5089 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 5090 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 5091 } 5092 5093 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 5094 Stmt *AStmt, 5095 SourceLocation StartLoc, 5096 SourceLocation EndLoc) { 5097 OMPClause *DependFound = nullptr; 5098 OMPClause *DependSourceClause = nullptr; 5099 OMPClause *DependSinkClause = nullptr; 5100 bool ErrorFound = false; 5101 OMPThreadsClause *TC = nullptr; 5102 OMPSIMDClause *SC = nullptr; 5103 for (auto *C : Clauses) { 5104 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 5105 DependFound = C; 5106 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 5107 if (DependSourceClause) { 5108 Diag(C->getLocStart(), diag::err_omp_more_one_clause) 5109 << getOpenMPDirectiveName(OMPD_ordered) 5110 << getOpenMPClauseName(OMPC_depend) << 2; 5111 ErrorFound = true; 5112 } else 5113 DependSourceClause = C; 5114 if (DependSinkClause) { 5115 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 5116 << 0; 5117 ErrorFound = true; 5118 } 5119 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 5120 if (DependSourceClause) { 5121 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 5122 << 1; 5123 ErrorFound = true; 5124 } 5125 DependSinkClause = C; 5126 } 5127 } else if (C->getClauseKind() == OMPC_threads) 5128 TC = cast<OMPThreadsClause>(C); 5129 else if (C->getClauseKind() == OMPC_simd) 5130 SC = cast<OMPSIMDClause>(C); 5131 } 5132 if (!ErrorFound && !SC && 5133 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 5134 // OpenMP [2.8.1,simd Construct, Restrictions] 5135 // An ordered construct with the simd clause is the only OpenMP construct 5136 // that can appear in the simd region. 5137 Diag(StartLoc, diag::err_omp_prohibited_region_simd); 5138 ErrorFound = true; 5139 } else if (DependFound && (TC || SC)) { 5140 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd) 5141 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 5142 ErrorFound = true; 5143 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) { 5144 Diag(DependFound->getLocStart(), 5145 diag::err_omp_ordered_directive_without_param); 5146 ErrorFound = true; 5147 } else if (TC || Clauses.empty()) { 5148 if (auto *Param = DSAStack->getParentOrderedRegionParam()) { 5149 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc; 5150 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 5151 << (TC != nullptr); 5152 Diag(Param->getLocStart(), diag::note_omp_ordered_param); 5153 ErrorFound = true; 5154 } 5155 } 5156 if ((!AStmt && !DependFound) || ErrorFound) 5157 return StmtError(); 5158 5159 if (AStmt) { 5160 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5161 5162 getCurFunction()->setHasBranchProtectedScope(); 5163 } 5164 5165 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5166 } 5167 5168 namespace { 5169 /// \brief Helper class for checking expression in 'omp atomic [update]' 5170 /// construct. 5171 class OpenMPAtomicUpdateChecker { 5172 /// \brief Error results for atomic update expressions. 5173 enum ExprAnalysisErrorCode { 5174 /// \brief A statement is not an expression statement. 5175 NotAnExpression, 5176 /// \brief Expression is not builtin binary or unary operation. 5177 NotABinaryOrUnaryExpression, 5178 /// \brief Unary operation is not post-/pre- increment/decrement operation. 5179 NotAnUnaryIncDecExpression, 5180 /// \brief An expression is not of scalar type. 5181 NotAScalarType, 5182 /// \brief A binary operation is not an assignment operation. 5183 NotAnAssignmentOp, 5184 /// \brief RHS part of the binary operation is not a binary expression. 5185 NotABinaryExpression, 5186 /// \brief RHS part is not additive/multiplicative/shift/biwise binary 5187 /// expression. 5188 NotABinaryOperator, 5189 /// \brief RHS binary operation does not have reference to the updated LHS 5190 /// part. 5191 NotAnUpdateExpression, 5192 /// \brief No errors is found. 5193 NoError 5194 }; 5195 /// \brief Reference to Sema. 5196 Sema &SemaRef; 5197 /// \brief A location for note diagnostics (when error is found). 5198 SourceLocation NoteLoc; 5199 /// \brief 'x' lvalue part of the source atomic expression. 5200 Expr *X; 5201 /// \brief 'expr' rvalue part of the source atomic expression. 5202 Expr *E; 5203 /// \brief Helper expression of the form 5204 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 5205 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 5206 Expr *UpdateExpr; 5207 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is 5208 /// important for non-associative operations. 5209 bool IsXLHSInRHSPart; 5210 BinaryOperatorKind Op; 5211 SourceLocation OpLoc; 5212 /// \brief true if the source expression is a postfix unary operation, false 5213 /// if it is a prefix unary operation. 5214 bool IsPostfixUpdate; 5215 5216 public: 5217 OpenMPAtomicUpdateChecker(Sema &SemaRef) 5218 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 5219 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 5220 /// \brief Check specified statement that it is suitable for 'atomic update' 5221 /// constructs and extract 'x', 'expr' and Operation from the original 5222 /// expression. If DiagId and NoteId == 0, then only check is performed 5223 /// without error notification. 5224 /// \param DiagId Diagnostic which should be emitted if error is found. 5225 /// \param NoteId Diagnostic note for the main error message. 5226 /// \return true if statement is not an update expression, false otherwise. 5227 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 5228 /// \brief Return the 'x' lvalue part of the source atomic expression. 5229 Expr *getX() const { return X; } 5230 /// \brief Return the 'expr' rvalue part of the source atomic expression. 5231 Expr *getExpr() const { return E; } 5232 /// \brief Return the update expression used in calculation of the updated 5233 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 5234 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 5235 Expr *getUpdateExpr() const { return UpdateExpr; } 5236 /// \brief Return true if 'x' is LHS in RHS part of full update expression, 5237 /// false otherwise. 5238 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 5239 5240 /// \brief true if the source expression is a postfix unary operation, false 5241 /// if it is a prefix unary operation. 5242 bool isPostfixUpdate() const { return IsPostfixUpdate; } 5243 5244 private: 5245 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 5246 unsigned NoteId = 0); 5247 }; 5248 } // namespace 5249 5250 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 5251 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 5252 ExprAnalysisErrorCode ErrorFound = NoError; 5253 SourceLocation ErrorLoc, NoteLoc; 5254 SourceRange ErrorRange, NoteRange; 5255 // Allowed constructs are: 5256 // x = x binop expr; 5257 // x = expr binop x; 5258 if (AtomicBinOp->getOpcode() == BO_Assign) { 5259 X = AtomicBinOp->getLHS(); 5260 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 5261 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 5262 if (AtomicInnerBinOp->isMultiplicativeOp() || 5263 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 5264 AtomicInnerBinOp->isBitwiseOp()) { 5265 Op = AtomicInnerBinOp->getOpcode(); 5266 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 5267 auto *LHS = AtomicInnerBinOp->getLHS(); 5268 auto *RHS = AtomicInnerBinOp->getRHS(); 5269 llvm::FoldingSetNodeID XId, LHSId, RHSId; 5270 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 5271 /*Canonical=*/true); 5272 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 5273 /*Canonical=*/true); 5274 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 5275 /*Canonical=*/true); 5276 if (XId == LHSId) { 5277 E = RHS; 5278 IsXLHSInRHSPart = true; 5279 } else if (XId == RHSId) { 5280 E = LHS; 5281 IsXLHSInRHSPart = false; 5282 } else { 5283 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 5284 ErrorRange = AtomicInnerBinOp->getSourceRange(); 5285 NoteLoc = X->getExprLoc(); 5286 NoteRange = X->getSourceRange(); 5287 ErrorFound = NotAnUpdateExpression; 5288 } 5289 } else { 5290 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 5291 ErrorRange = AtomicInnerBinOp->getSourceRange(); 5292 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 5293 NoteRange = SourceRange(NoteLoc, NoteLoc); 5294 ErrorFound = NotABinaryOperator; 5295 } 5296 } else { 5297 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 5298 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 5299 ErrorFound = NotABinaryExpression; 5300 } 5301 } else { 5302 ErrorLoc = AtomicBinOp->getExprLoc(); 5303 ErrorRange = AtomicBinOp->getSourceRange(); 5304 NoteLoc = AtomicBinOp->getOperatorLoc(); 5305 NoteRange = SourceRange(NoteLoc, NoteLoc); 5306 ErrorFound = NotAnAssignmentOp; 5307 } 5308 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5309 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5310 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5311 return true; 5312 } else if (SemaRef.CurContext->isDependentContext()) 5313 E = X = UpdateExpr = nullptr; 5314 return ErrorFound != NoError; 5315 } 5316 5317 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 5318 unsigned NoteId) { 5319 ExprAnalysisErrorCode ErrorFound = NoError; 5320 SourceLocation ErrorLoc, NoteLoc; 5321 SourceRange ErrorRange, NoteRange; 5322 // Allowed constructs are: 5323 // x++; 5324 // x--; 5325 // ++x; 5326 // --x; 5327 // x binop= expr; 5328 // x = x binop expr; 5329 // x = expr binop x; 5330 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 5331 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 5332 if (AtomicBody->getType()->isScalarType() || 5333 AtomicBody->isInstantiationDependent()) { 5334 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 5335 AtomicBody->IgnoreParenImpCasts())) { 5336 // Check for Compound Assignment Operation 5337 Op = BinaryOperator::getOpForCompoundAssignment( 5338 AtomicCompAssignOp->getOpcode()); 5339 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 5340 E = AtomicCompAssignOp->getRHS(); 5341 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 5342 IsXLHSInRHSPart = true; 5343 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 5344 AtomicBody->IgnoreParenImpCasts())) { 5345 // Check for Binary Operation 5346 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 5347 return true; 5348 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 5349 AtomicBody->IgnoreParenImpCasts())) { 5350 // Check for Unary Operation 5351 if (AtomicUnaryOp->isIncrementDecrementOp()) { 5352 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 5353 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 5354 OpLoc = AtomicUnaryOp->getOperatorLoc(); 5355 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 5356 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 5357 IsXLHSInRHSPart = true; 5358 } else { 5359 ErrorFound = NotAnUnaryIncDecExpression; 5360 ErrorLoc = AtomicUnaryOp->getExprLoc(); 5361 ErrorRange = AtomicUnaryOp->getSourceRange(); 5362 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 5363 NoteRange = SourceRange(NoteLoc, NoteLoc); 5364 } 5365 } else if (!AtomicBody->isInstantiationDependent()) { 5366 ErrorFound = NotABinaryOrUnaryExpression; 5367 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 5368 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 5369 } 5370 } else { 5371 ErrorFound = NotAScalarType; 5372 NoteLoc = ErrorLoc = AtomicBody->getLocStart(); 5373 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5374 } 5375 } else { 5376 ErrorFound = NotAnExpression; 5377 NoteLoc = ErrorLoc = S->getLocStart(); 5378 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5379 } 5380 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5381 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5382 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5383 return true; 5384 } else if (SemaRef.CurContext->isDependentContext()) 5385 E = X = UpdateExpr = nullptr; 5386 if (ErrorFound == NoError && E && X) { 5387 // Build an update expression of form 'OpaqueValueExpr(x) binop 5388 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 5389 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 5390 auto *OVEX = new (SemaRef.getASTContext()) 5391 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 5392 auto *OVEExpr = new (SemaRef.getASTContext()) 5393 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 5394 auto Update = 5395 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 5396 IsXLHSInRHSPart ? OVEExpr : OVEX); 5397 if (Update.isInvalid()) 5398 return true; 5399 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 5400 Sema::AA_Casting); 5401 if (Update.isInvalid()) 5402 return true; 5403 UpdateExpr = Update.get(); 5404 } 5405 return ErrorFound != NoError; 5406 } 5407 5408 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 5409 Stmt *AStmt, 5410 SourceLocation StartLoc, 5411 SourceLocation EndLoc) { 5412 if (!AStmt) 5413 return StmtError(); 5414 5415 auto *CS = cast<CapturedStmt>(AStmt); 5416 // 1.2.2 OpenMP Language Terminology 5417 // Structured block - An executable statement with a single entry at the 5418 // top and a single exit at the bottom. 5419 // The point of exit cannot be a branch out of the structured block. 5420 // longjmp() and throw() must not violate the entry/exit criteria. 5421 OpenMPClauseKind AtomicKind = OMPC_unknown; 5422 SourceLocation AtomicKindLoc; 5423 for (auto *C : Clauses) { 5424 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 5425 C->getClauseKind() == OMPC_update || 5426 C->getClauseKind() == OMPC_capture) { 5427 if (AtomicKind != OMPC_unknown) { 5428 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses) 5429 << SourceRange(C->getLocStart(), C->getLocEnd()); 5430 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 5431 << getOpenMPClauseName(AtomicKind); 5432 } else { 5433 AtomicKind = C->getClauseKind(); 5434 AtomicKindLoc = C->getLocStart(); 5435 } 5436 } 5437 } 5438 5439 auto Body = CS->getCapturedStmt(); 5440 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 5441 Body = EWC->getSubExpr(); 5442 5443 Expr *X = nullptr; 5444 Expr *V = nullptr; 5445 Expr *E = nullptr; 5446 Expr *UE = nullptr; 5447 bool IsXLHSInRHSPart = false; 5448 bool IsPostfixUpdate = false; 5449 // OpenMP [2.12.6, atomic Construct] 5450 // In the next expressions: 5451 // * x and v (as applicable) are both l-value expressions with scalar type. 5452 // * During the execution of an atomic region, multiple syntactic 5453 // occurrences of x must designate the same storage location. 5454 // * Neither of v and expr (as applicable) may access the storage location 5455 // designated by x. 5456 // * Neither of x and expr (as applicable) may access the storage location 5457 // designated by v. 5458 // * expr is an expression with scalar type. 5459 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 5460 // * binop, binop=, ++, and -- are not overloaded operators. 5461 // * The expression x binop expr must be numerically equivalent to x binop 5462 // (expr). This requirement is satisfied if the operators in expr have 5463 // precedence greater than binop, or by using parentheses around expr or 5464 // subexpressions of expr. 5465 // * The expression expr binop x must be numerically equivalent to (expr) 5466 // binop x. This requirement is satisfied if the operators in expr have 5467 // precedence equal to or greater than binop, or by using parentheses around 5468 // expr or subexpressions of expr. 5469 // * For forms that allow multiple occurrences of x, the number of times 5470 // that x is evaluated is unspecified. 5471 if (AtomicKind == OMPC_read) { 5472 enum { 5473 NotAnExpression, 5474 NotAnAssignmentOp, 5475 NotAScalarType, 5476 NotAnLValue, 5477 NoError 5478 } ErrorFound = NoError; 5479 SourceLocation ErrorLoc, NoteLoc; 5480 SourceRange ErrorRange, NoteRange; 5481 // If clause is read: 5482 // v = x; 5483 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5484 auto *AtomicBinOp = 5485 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5486 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5487 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 5488 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 5489 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 5490 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 5491 if (!X->isLValue() || !V->isLValue()) { 5492 auto NotLValueExpr = X->isLValue() ? V : X; 5493 ErrorFound = NotAnLValue; 5494 ErrorLoc = AtomicBinOp->getExprLoc(); 5495 ErrorRange = AtomicBinOp->getSourceRange(); 5496 NoteLoc = NotLValueExpr->getExprLoc(); 5497 NoteRange = NotLValueExpr->getSourceRange(); 5498 } 5499 } else if (!X->isInstantiationDependent() || 5500 !V->isInstantiationDependent()) { 5501 auto NotScalarExpr = 5502 (X->isInstantiationDependent() || X->getType()->isScalarType()) 5503 ? V 5504 : X; 5505 ErrorFound = NotAScalarType; 5506 ErrorLoc = AtomicBinOp->getExprLoc(); 5507 ErrorRange = AtomicBinOp->getSourceRange(); 5508 NoteLoc = NotScalarExpr->getExprLoc(); 5509 NoteRange = NotScalarExpr->getSourceRange(); 5510 } 5511 } else if (!AtomicBody->isInstantiationDependent()) { 5512 ErrorFound = NotAnAssignmentOp; 5513 ErrorLoc = AtomicBody->getExprLoc(); 5514 ErrorRange = AtomicBody->getSourceRange(); 5515 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5516 : AtomicBody->getExprLoc(); 5517 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5518 : AtomicBody->getSourceRange(); 5519 } 5520 } else { 5521 ErrorFound = NotAnExpression; 5522 NoteLoc = ErrorLoc = Body->getLocStart(); 5523 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5524 } 5525 if (ErrorFound != NoError) { 5526 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 5527 << ErrorRange; 5528 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 5529 << NoteRange; 5530 return StmtError(); 5531 } else if (CurContext->isDependentContext()) 5532 V = X = nullptr; 5533 } else if (AtomicKind == OMPC_write) { 5534 enum { 5535 NotAnExpression, 5536 NotAnAssignmentOp, 5537 NotAScalarType, 5538 NotAnLValue, 5539 NoError 5540 } ErrorFound = NoError; 5541 SourceLocation ErrorLoc, NoteLoc; 5542 SourceRange ErrorRange, NoteRange; 5543 // If clause is write: 5544 // x = expr; 5545 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5546 auto *AtomicBinOp = 5547 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5548 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5549 X = AtomicBinOp->getLHS(); 5550 E = AtomicBinOp->getRHS(); 5551 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 5552 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 5553 if (!X->isLValue()) { 5554 ErrorFound = NotAnLValue; 5555 ErrorLoc = AtomicBinOp->getExprLoc(); 5556 ErrorRange = AtomicBinOp->getSourceRange(); 5557 NoteLoc = X->getExprLoc(); 5558 NoteRange = X->getSourceRange(); 5559 } 5560 } else if (!X->isInstantiationDependent() || 5561 !E->isInstantiationDependent()) { 5562 auto NotScalarExpr = 5563 (X->isInstantiationDependent() || X->getType()->isScalarType()) 5564 ? E 5565 : X; 5566 ErrorFound = NotAScalarType; 5567 ErrorLoc = AtomicBinOp->getExprLoc(); 5568 ErrorRange = AtomicBinOp->getSourceRange(); 5569 NoteLoc = NotScalarExpr->getExprLoc(); 5570 NoteRange = NotScalarExpr->getSourceRange(); 5571 } 5572 } else if (!AtomicBody->isInstantiationDependent()) { 5573 ErrorFound = NotAnAssignmentOp; 5574 ErrorLoc = AtomicBody->getExprLoc(); 5575 ErrorRange = AtomicBody->getSourceRange(); 5576 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5577 : AtomicBody->getExprLoc(); 5578 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5579 : AtomicBody->getSourceRange(); 5580 } 5581 } else { 5582 ErrorFound = NotAnExpression; 5583 NoteLoc = ErrorLoc = Body->getLocStart(); 5584 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5585 } 5586 if (ErrorFound != NoError) { 5587 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 5588 << ErrorRange; 5589 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 5590 << NoteRange; 5591 return StmtError(); 5592 } else if (CurContext->isDependentContext()) 5593 E = X = nullptr; 5594 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 5595 // If clause is update: 5596 // x++; 5597 // x--; 5598 // ++x; 5599 // --x; 5600 // x binop= expr; 5601 // x = x binop expr; 5602 // x = expr binop x; 5603 OpenMPAtomicUpdateChecker Checker(*this); 5604 if (Checker.checkStatement( 5605 Body, (AtomicKind == OMPC_update) 5606 ? diag::err_omp_atomic_update_not_expression_statement 5607 : diag::err_omp_atomic_not_expression_statement, 5608 diag::note_omp_atomic_update)) 5609 return StmtError(); 5610 if (!CurContext->isDependentContext()) { 5611 E = Checker.getExpr(); 5612 X = Checker.getX(); 5613 UE = Checker.getUpdateExpr(); 5614 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5615 } 5616 } else if (AtomicKind == OMPC_capture) { 5617 enum { 5618 NotAnAssignmentOp, 5619 NotACompoundStatement, 5620 NotTwoSubstatements, 5621 NotASpecificExpression, 5622 NoError 5623 } ErrorFound = NoError; 5624 SourceLocation ErrorLoc, NoteLoc; 5625 SourceRange ErrorRange, NoteRange; 5626 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5627 // If clause is a capture: 5628 // v = x++; 5629 // v = x--; 5630 // v = ++x; 5631 // v = --x; 5632 // v = x binop= expr; 5633 // v = x = x binop expr; 5634 // v = x = expr binop x; 5635 auto *AtomicBinOp = 5636 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5637 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5638 V = AtomicBinOp->getLHS(); 5639 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 5640 OpenMPAtomicUpdateChecker Checker(*this); 5641 if (Checker.checkStatement( 5642 Body, diag::err_omp_atomic_capture_not_expression_statement, 5643 diag::note_omp_atomic_update)) 5644 return StmtError(); 5645 E = Checker.getExpr(); 5646 X = Checker.getX(); 5647 UE = Checker.getUpdateExpr(); 5648 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5649 IsPostfixUpdate = Checker.isPostfixUpdate(); 5650 } else if (!AtomicBody->isInstantiationDependent()) { 5651 ErrorLoc = AtomicBody->getExprLoc(); 5652 ErrorRange = AtomicBody->getSourceRange(); 5653 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5654 : AtomicBody->getExprLoc(); 5655 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5656 : AtomicBody->getSourceRange(); 5657 ErrorFound = NotAnAssignmentOp; 5658 } 5659 if (ErrorFound != NoError) { 5660 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 5661 << ErrorRange; 5662 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 5663 return StmtError(); 5664 } else if (CurContext->isDependentContext()) { 5665 UE = V = E = X = nullptr; 5666 } 5667 } else { 5668 // If clause is a capture: 5669 // { v = x; x = expr; } 5670 // { v = x; x++; } 5671 // { v = x; x--; } 5672 // { v = x; ++x; } 5673 // { v = x; --x; } 5674 // { v = x; x binop= expr; } 5675 // { v = x; x = x binop expr; } 5676 // { v = x; x = expr binop x; } 5677 // { x++; v = x; } 5678 // { x--; v = x; } 5679 // { ++x; v = x; } 5680 // { --x; v = x; } 5681 // { x binop= expr; v = x; } 5682 // { x = x binop expr; v = x; } 5683 // { x = expr binop x; v = x; } 5684 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 5685 // Check that this is { expr1; expr2; } 5686 if (CS->size() == 2) { 5687 auto *First = CS->body_front(); 5688 auto *Second = CS->body_back(); 5689 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 5690 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 5691 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 5692 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 5693 // Need to find what subexpression is 'v' and what is 'x'. 5694 OpenMPAtomicUpdateChecker Checker(*this); 5695 bool IsUpdateExprFound = !Checker.checkStatement(Second); 5696 BinaryOperator *BinOp = nullptr; 5697 if (IsUpdateExprFound) { 5698 BinOp = dyn_cast<BinaryOperator>(First); 5699 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 5700 } 5701 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 5702 // { v = x; x++; } 5703 // { v = x; x--; } 5704 // { v = x; ++x; } 5705 // { v = x; --x; } 5706 // { v = x; x binop= expr; } 5707 // { v = x; x = x binop expr; } 5708 // { v = x; x = expr binop x; } 5709 // Check that the first expression has form v = x. 5710 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 5711 llvm::FoldingSetNodeID XId, PossibleXId; 5712 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 5713 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 5714 IsUpdateExprFound = XId == PossibleXId; 5715 if (IsUpdateExprFound) { 5716 V = BinOp->getLHS(); 5717 X = Checker.getX(); 5718 E = Checker.getExpr(); 5719 UE = Checker.getUpdateExpr(); 5720 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5721 IsPostfixUpdate = true; 5722 } 5723 } 5724 if (!IsUpdateExprFound) { 5725 IsUpdateExprFound = !Checker.checkStatement(First); 5726 BinOp = nullptr; 5727 if (IsUpdateExprFound) { 5728 BinOp = dyn_cast<BinaryOperator>(Second); 5729 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 5730 } 5731 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 5732 // { x++; v = x; } 5733 // { x--; v = x; } 5734 // { ++x; v = x; } 5735 // { --x; v = x; } 5736 // { x binop= expr; v = x; } 5737 // { x = x binop expr; v = x; } 5738 // { x = expr binop x; v = x; } 5739 // Check that the second expression has form v = x. 5740 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 5741 llvm::FoldingSetNodeID XId, PossibleXId; 5742 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 5743 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 5744 IsUpdateExprFound = XId == PossibleXId; 5745 if (IsUpdateExprFound) { 5746 V = BinOp->getLHS(); 5747 X = Checker.getX(); 5748 E = Checker.getExpr(); 5749 UE = Checker.getUpdateExpr(); 5750 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5751 IsPostfixUpdate = false; 5752 } 5753 } 5754 } 5755 if (!IsUpdateExprFound) { 5756 // { v = x; x = expr; } 5757 auto *FirstExpr = dyn_cast<Expr>(First); 5758 auto *SecondExpr = dyn_cast<Expr>(Second); 5759 if (!FirstExpr || !SecondExpr || 5760 !(FirstExpr->isInstantiationDependent() || 5761 SecondExpr->isInstantiationDependent())) { 5762 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 5763 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 5764 ErrorFound = NotAnAssignmentOp; 5765 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 5766 : First->getLocStart(); 5767 NoteRange = ErrorRange = FirstBinOp 5768 ? FirstBinOp->getSourceRange() 5769 : SourceRange(ErrorLoc, ErrorLoc); 5770 } else { 5771 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 5772 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 5773 ErrorFound = NotAnAssignmentOp; 5774 NoteLoc = ErrorLoc = SecondBinOp 5775 ? SecondBinOp->getOperatorLoc() 5776 : Second->getLocStart(); 5777 NoteRange = ErrorRange = 5778 SecondBinOp ? SecondBinOp->getSourceRange() 5779 : SourceRange(ErrorLoc, ErrorLoc); 5780 } else { 5781 auto *PossibleXRHSInFirst = 5782 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 5783 auto *PossibleXLHSInSecond = 5784 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 5785 llvm::FoldingSetNodeID X1Id, X2Id; 5786 PossibleXRHSInFirst->Profile(X1Id, Context, 5787 /*Canonical=*/true); 5788 PossibleXLHSInSecond->Profile(X2Id, Context, 5789 /*Canonical=*/true); 5790 IsUpdateExprFound = X1Id == X2Id; 5791 if (IsUpdateExprFound) { 5792 V = FirstBinOp->getLHS(); 5793 X = SecondBinOp->getLHS(); 5794 E = SecondBinOp->getRHS(); 5795 UE = nullptr; 5796 IsXLHSInRHSPart = false; 5797 IsPostfixUpdate = true; 5798 } else { 5799 ErrorFound = NotASpecificExpression; 5800 ErrorLoc = FirstBinOp->getExprLoc(); 5801 ErrorRange = FirstBinOp->getSourceRange(); 5802 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 5803 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 5804 } 5805 } 5806 } 5807 } 5808 } 5809 } else { 5810 NoteLoc = ErrorLoc = Body->getLocStart(); 5811 NoteRange = ErrorRange = 5812 SourceRange(Body->getLocStart(), Body->getLocStart()); 5813 ErrorFound = NotTwoSubstatements; 5814 } 5815 } else { 5816 NoteLoc = ErrorLoc = Body->getLocStart(); 5817 NoteRange = ErrorRange = 5818 SourceRange(Body->getLocStart(), Body->getLocStart()); 5819 ErrorFound = NotACompoundStatement; 5820 } 5821 if (ErrorFound != NoError) { 5822 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 5823 << ErrorRange; 5824 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 5825 return StmtError(); 5826 } else if (CurContext->isDependentContext()) { 5827 UE = V = E = X = nullptr; 5828 } 5829 } 5830 } 5831 5832 getCurFunction()->setHasBranchProtectedScope(); 5833 5834 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5835 X, V, E, UE, IsXLHSInRHSPart, 5836 IsPostfixUpdate); 5837 } 5838 5839 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 5840 Stmt *AStmt, 5841 SourceLocation StartLoc, 5842 SourceLocation EndLoc) { 5843 if (!AStmt) 5844 return StmtError(); 5845 5846 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5847 // 1.2.2 OpenMP Language Terminology 5848 // Structured block - An executable statement with a single entry at the 5849 // top and a single exit at the bottom. 5850 // The point of exit cannot be a branch out of the structured block. 5851 // longjmp() and throw() must not violate the entry/exit criteria. 5852 CS->getCapturedDecl()->setNothrow(); 5853 5854 // OpenMP [2.16, Nesting of Regions] 5855 // If specified, a teams construct must be contained within a target 5856 // construct. That target construct must contain no statements or directives 5857 // outside of the teams construct. 5858 if (DSAStack->hasInnerTeamsRegion()) { 5859 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true); 5860 bool OMPTeamsFound = true; 5861 if (auto *CS = dyn_cast<CompoundStmt>(S)) { 5862 auto I = CS->body_begin(); 5863 while (I != CS->body_end()) { 5864 auto *OED = dyn_cast<OMPExecutableDirective>(*I); 5865 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) { 5866 OMPTeamsFound = false; 5867 break; 5868 } 5869 ++I; 5870 } 5871 assert(I != CS->body_end() && "Not found statement"); 5872 S = *I; 5873 } else { 5874 auto *OED = dyn_cast<OMPExecutableDirective>(S); 5875 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 5876 } 5877 if (!OMPTeamsFound) { 5878 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 5879 Diag(DSAStack->getInnerTeamsRegionLoc(), 5880 diag::note_omp_nested_teams_construct_here); 5881 Diag(S->getLocStart(), diag::note_omp_nested_statement_here) 5882 << isa<OMPExecutableDirective>(S); 5883 return StmtError(); 5884 } 5885 } 5886 5887 getCurFunction()->setHasBranchProtectedScope(); 5888 5889 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5890 } 5891 5892 StmtResult 5893 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 5894 Stmt *AStmt, SourceLocation StartLoc, 5895 SourceLocation EndLoc) { 5896 if (!AStmt) 5897 return StmtError(); 5898 5899 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5900 // 1.2.2 OpenMP Language Terminology 5901 // Structured block - An executable statement with a single entry at the 5902 // top and a single exit at the bottom. 5903 // The point of exit cannot be a branch out of the structured block. 5904 // longjmp() and throw() must not violate the entry/exit criteria. 5905 CS->getCapturedDecl()->setNothrow(); 5906 5907 getCurFunction()->setHasBranchProtectedScope(); 5908 5909 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 5910 AStmt); 5911 } 5912 5913 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 5914 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5915 SourceLocation EndLoc, 5916 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5917 if (!AStmt) 5918 return StmtError(); 5919 5920 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5921 // 1.2.2 OpenMP Language Terminology 5922 // Structured block - An executable statement with a single entry at the 5923 // top and a single exit at the bottom. 5924 // The point of exit cannot be a branch out of the structured block. 5925 // longjmp() and throw() must not violate the entry/exit criteria. 5926 CS->getCapturedDecl()->setNothrow(); 5927 5928 OMPLoopDirective::HelperExprs B; 5929 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5930 // define the nested loops number. 5931 unsigned NestedLoopCount = 5932 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 5933 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5934 VarsWithImplicitDSA, B); 5935 if (NestedLoopCount == 0) 5936 return StmtError(); 5937 5938 assert((CurContext->isDependentContext() || B.builtAll()) && 5939 "omp target parallel for loop exprs were not built"); 5940 5941 if (!CurContext->isDependentContext()) { 5942 // Finalize the clauses that need pre-built expressions for CodeGen. 5943 for (auto C : Clauses) { 5944 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5945 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5946 B.NumIterations, *this, CurScope, 5947 DSAStack)) 5948 return StmtError(); 5949 } 5950 } 5951 5952 getCurFunction()->setHasBranchProtectedScope(); 5953 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc, 5954 NestedLoopCount, Clauses, AStmt, 5955 B, DSAStack->isCancelRegion()); 5956 } 5957 5958 /// Check for existence of a map clause in the list of clauses. 5959 static bool hasClauses(ArrayRef<OMPClause *> Clauses, 5960 const OpenMPClauseKind K) { 5961 return llvm::any_of( 5962 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); 5963 } 5964 5965 template <typename... Params> 5966 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, 5967 const Params... ClauseTypes) { 5968 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); 5969 } 5970 5971 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 5972 Stmt *AStmt, 5973 SourceLocation StartLoc, 5974 SourceLocation EndLoc) { 5975 if (!AStmt) 5976 return StmtError(); 5977 5978 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5979 5980 // OpenMP [2.10.1, Restrictions, p. 97] 5981 // At least one map clause must appear on the directive. 5982 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) { 5983 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 5984 << "'map' or 'use_device_ptr'" 5985 << getOpenMPDirectiveName(OMPD_target_data); 5986 return StmtError(); 5987 } 5988 5989 getCurFunction()->setHasBranchProtectedScope(); 5990 5991 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 5992 AStmt); 5993 } 5994 5995 StmtResult 5996 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 5997 SourceLocation StartLoc, 5998 SourceLocation EndLoc) { 5999 // OpenMP [2.10.2, Restrictions, p. 99] 6000 // At least one map clause must appear on the directive. 6001 if (!hasClauses(Clauses, OMPC_map)) { 6002 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 6003 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); 6004 return StmtError(); 6005 } 6006 6007 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, 6008 Clauses); 6009 } 6010 6011 StmtResult 6012 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 6013 SourceLocation StartLoc, 6014 SourceLocation EndLoc) { 6015 // OpenMP [2.10.3, Restrictions, p. 102] 6016 // At least one map clause must appear on the directive. 6017 if (!hasClauses(Clauses, OMPC_map)) { 6018 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 6019 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data); 6020 return StmtError(); 6021 } 6022 6023 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses); 6024 } 6025 6026 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 6027 SourceLocation StartLoc, 6028 SourceLocation EndLoc) { 6029 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { 6030 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 6031 return StmtError(); 6032 } 6033 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses); 6034 } 6035 6036 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 6037 Stmt *AStmt, SourceLocation StartLoc, 6038 SourceLocation EndLoc) { 6039 if (!AStmt) 6040 return StmtError(); 6041 6042 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6043 // 1.2.2 OpenMP Language Terminology 6044 // Structured block - An executable statement with a single entry at the 6045 // top and a single exit at the bottom. 6046 // The point of exit cannot be a branch out of the structured block. 6047 // longjmp() and throw() must not violate the entry/exit criteria. 6048 CS->getCapturedDecl()->setNothrow(); 6049 6050 getCurFunction()->setHasBranchProtectedScope(); 6051 6052 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6053 } 6054 6055 StmtResult 6056 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 6057 SourceLocation EndLoc, 6058 OpenMPDirectiveKind CancelRegion) { 6059 if (DSAStack->isParentNowaitRegion()) { 6060 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 6061 return StmtError(); 6062 } 6063 if (DSAStack->isParentOrderedRegion()) { 6064 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 6065 return StmtError(); 6066 } 6067 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 6068 CancelRegion); 6069 } 6070 6071 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 6072 SourceLocation StartLoc, 6073 SourceLocation EndLoc, 6074 OpenMPDirectiveKind CancelRegion) { 6075 if (DSAStack->isParentNowaitRegion()) { 6076 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 6077 return StmtError(); 6078 } 6079 if (DSAStack->isParentOrderedRegion()) { 6080 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 6081 return StmtError(); 6082 } 6083 DSAStack->setParentCancelRegion(/*Cancel=*/true); 6084 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 6085 CancelRegion); 6086 } 6087 6088 static bool checkGrainsizeNumTasksClauses(Sema &S, 6089 ArrayRef<OMPClause *> Clauses) { 6090 OMPClause *PrevClause = nullptr; 6091 bool ErrorFound = false; 6092 for (auto *C : Clauses) { 6093 if (C->getClauseKind() == OMPC_grainsize || 6094 C->getClauseKind() == OMPC_num_tasks) { 6095 if (!PrevClause) 6096 PrevClause = C; 6097 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 6098 S.Diag(C->getLocStart(), 6099 diag::err_omp_grainsize_num_tasks_mutually_exclusive) 6100 << getOpenMPClauseName(C->getClauseKind()) 6101 << getOpenMPClauseName(PrevClause->getClauseKind()); 6102 S.Diag(PrevClause->getLocStart(), 6103 diag::note_omp_previous_grainsize_num_tasks) 6104 << getOpenMPClauseName(PrevClause->getClauseKind()); 6105 ErrorFound = true; 6106 } 6107 } 6108 } 6109 return ErrorFound; 6110 } 6111 6112 static bool checkReductionClauseWithNogroup(Sema &S, 6113 ArrayRef<OMPClause *> Clauses) { 6114 OMPClause *ReductionClause = nullptr; 6115 OMPClause *NogroupClause = nullptr; 6116 for (auto *C : Clauses) { 6117 if (C->getClauseKind() == OMPC_reduction) { 6118 ReductionClause = C; 6119 if (NogroupClause) 6120 break; 6121 continue; 6122 } 6123 if (C->getClauseKind() == OMPC_nogroup) { 6124 NogroupClause = C; 6125 if (ReductionClause) 6126 break; 6127 continue; 6128 } 6129 } 6130 if (ReductionClause && NogroupClause) { 6131 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup) 6132 << SourceRange(NogroupClause->getLocStart(), 6133 NogroupClause->getLocEnd()); 6134 return true; 6135 } 6136 return false; 6137 } 6138 6139 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 6140 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6141 SourceLocation EndLoc, 6142 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6143 if (!AStmt) 6144 return StmtError(); 6145 6146 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6147 OMPLoopDirective::HelperExprs B; 6148 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6149 // define the nested loops number. 6150 unsigned NestedLoopCount = 6151 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 6152 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 6153 VarsWithImplicitDSA, B); 6154 if (NestedLoopCount == 0) 6155 return StmtError(); 6156 6157 assert((CurContext->isDependentContext() || B.builtAll()) && 6158 "omp for loop exprs were not built"); 6159 6160 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6161 // The grainsize clause and num_tasks clause are mutually exclusive and may 6162 // not appear on the same taskloop directive. 6163 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 6164 return StmtError(); 6165 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6166 // If a reduction clause is present on the taskloop directive, the nogroup 6167 // clause must not be specified. 6168 if (checkReductionClauseWithNogroup(*this, Clauses)) 6169 return StmtError(); 6170 6171 getCurFunction()->setHasBranchProtectedScope(); 6172 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 6173 NestedLoopCount, Clauses, AStmt, B); 6174 } 6175 6176 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 6177 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6178 SourceLocation EndLoc, 6179 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6180 if (!AStmt) 6181 return StmtError(); 6182 6183 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6184 OMPLoopDirective::HelperExprs B; 6185 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6186 // define the nested loops number. 6187 unsigned NestedLoopCount = 6188 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 6189 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 6190 VarsWithImplicitDSA, B); 6191 if (NestedLoopCount == 0) 6192 return StmtError(); 6193 6194 assert((CurContext->isDependentContext() || B.builtAll()) && 6195 "omp for loop exprs were not built"); 6196 6197 if (!CurContext->isDependentContext()) { 6198 // Finalize the clauses that need pre-built expressions for CodeGen. 6199 for (auto C : Clauses) { 6200 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6201 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6202 B.NumIterations, *this, CurScope, 6203 DSAStack)) 6204 return StmtError(); 6205 } 6206 } 6207 6208 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6209 // The grainsize clause and num_tasks clause are mutually exclusive and may 6210 // not appear on the same taskloop directive. 6211 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 6212 return StmtError(); 6213 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6214 // If a reduction clause is present on the taskloop directive, the nogroup 6215 // clause must not be specified. 6216 if (checkReductionClauseWithNogroup(*this, Clauses)) 6217 return StmtError(); 6218 6219 getCurFunction()->setHasBranchProtectedScope(); 6220 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 6221 NestedLoopCount, Clauses, AStmt, B); 6222 } 6223 6224 StmtResult Sema::ActOnOpenMPDistributeDirective( 6225 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6226 SourceLocation EndLoc, 6227 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6228 if (!AStmt) 6229 return StmtError(); 6230 6231 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6232 OMPLoopDirective::HelperExprs B; 6233 // In presence of clause 'collapse' with number of loops, it will 6234 // define the nested loops number. 6235 unsigned NestedLoopCount = 6236 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 6237 nullptr /*ordered not a clause on distribute*/, AStmt, 6238 *this, *DSAStack, VarsWithImplicitDSA, B); 6239 if (NestedLoopCount == 0) 6240 return StmtError(); 6241 6242 assert((CurContext->isDependentContext() || B.builtAll()) && 6243 "omp for loop exprs were not built"); 6244 6245 getCurFunction()->setHasBranchProtectedScope(); 6246 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 6247 NestedLoopCount, Clauses, AStmt, B); 6248 } 6249 6250 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 6251 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6252 SourceLocation EndLoc, 6253 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6254 if (!AStmt) 6255 return StmtError(); 6256 6257 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6258 // 1.2.2 OpenMP Language Terminology 6259 // Structured block - An executable statement with a single entry at the 6260 // top and a single exit at the bottom. 6261 // The point of exit cannot be a branch out of the structured block. 6262 // longjmp() and throw() must not violate the entry/exit criteria. 6263 CS->getCapturedDecl()->setNothrow(); 6264 6265 OMPLoopDirective::HelperExprs B; 6266 // In presence of clause 'collapse' with number of loops, it will 6267 // define the nested loops number. 6268 unsigned NestedLoopCount = CheckOpenMPLoop( 6269 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 6270 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6271 VarsWithImplicitDSA, B); 6272 if (NestedLoopCount == 0) 6273 return StmtError(); 6274 6275 assert((CurContext->isDependentContext() || B.builtAll()) && 6276 "omp for loop exprs were not built"); 6277 6278 getCurFunction()->setHasBranchProtectedScope(); 6279 return OMPDistributeParallelForDirective::Create( 6280 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6281 } 6282 6283 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 6284 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6285 SourceLocation EndLoc, 6286 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6287 if (!AStmt) 6288 return StmtError(); 6289 6290 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6291 // 1.2.2 OpenMP Language Terminology 6292 // Structured block - An executable statement with a single entry at the 6293 // top and a single exit at the bottom. 6294 // The point of exit cannot be a branch out of the structured block. 6295 // longjmp() and throw() must not violate the entry/exit criteria. 6296 CS->getCapturedDecl()->setNothrow(); 6297 6298 OMPLoopDirective::HelperExprs B; 6299 // In presence of clause 'collapse' with number of loops, it will 6300 // define the nested loops number. 6301 unsigned NestedLoopCount = CheckOpenMPLoop( 6302 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 6303 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6304 VarsWithImplicitDSA, B); 6305 if (NestedLoopCount == 0) 6306 return StmtError(); 6307 6308 assert((CurContext->isDependentContext() || B.builtAll()) && 6309 "omp for loop exprs were not built"); 6310 6311 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6312 return StmtError(); 6313 6314 getCurFunction()->setHasBranchProtectedScope(); 6315 return OMPDistributeParallelForSimdDirective::Create( 6316 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6317 } 6318 6319 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 6320 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6321 SourceLocation EndLoc, 6322 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6323 if (!AStmt) 6324 return StmtError(); 6325 6326 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6327 // 1.2.2 OpenMP Language Terminology 6328 // Structured block - An executable statement with a single entry at the 6329 // top and a single exit at the bottom. 6330 // The point of exit cannot be a branch out of the structured block. 6331 // longjmp() and throw() must not violate the entry/exit criteria. 6332 CS->getCapturedDecl()->setNothrow(); 6333 6334 OMPLoopDirective::HelperExprs B; 6335 // In presence of clause 'collapse' with number of loops, it will 6336 // define the nested loops number. 6337 unsigned NestedLoopCount = 6338 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 6339 nullptr /*ordered not a clause on distribute*/, AStmt, 6340 *this, *DSAStack, VarsWithImplicitDSA, B); 6341 if (NestedLoopCount == 0) 6342 return StmtError(); 6343 6344 assert((CurContext->isDependentContext() || B.builtAll()) && 6345 "omp for loop exprs were not built"); 6346 6347 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6348 return StmtError(); 6349 6350 getCurFunction()->setHasBranchProtectedScope(); 6351 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 6352 NestedLoopCount, Clauses, AStmt, B); 6353 } 6354 6355 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 6356 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6357 SourceLocation EndLoc, 6358 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6359 if (!AStmt) 6360 return StmtError(); 6361 6362 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6363 // 1.2.2 OpenMP Language Terminology 6364 // Structured block - An executable statement with a single entry at the 6365 // top and a single exit at the bottom. 6366 // The point of exit cannot be a branch out of the structured block. 6367 // longjmp() and throw() must not violate the entry/exit criteria. 6368 CS->getCapturedDecl()->setNothrow(); 6369 6370 OMPLoopDirective::HelperExprs B; 6371 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6372 // define the nested loops number. 6373 unsigned NestedLoopCount = CheckOpenMPLoop( 6374 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 6375 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6376 VarsWithImplicitDSA, B); 6377 if (NestedLoopCount == 0) 6378 return StmtError(); 6379 6380 assert((CurContext->isDependentContext() || B.builtAll()) && 6381 "omp target parallel for simd loop exprs were not built"); 6382 6383 if (!CurContext->isDependentContext()) { 6384 // Finalize the clauses that need pre-built expressions for CodeGen. 6385 for (auto C : Clauses) { 6386 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6387 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6388 B.NumIterations, *this, CurScope, 6389 DSAStack)) 6390 return StmtError(); 6391 } 6392 } 6393 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6394 return StmtError(); 6395 6396 getCurFunction()->setHasBranchProtectedScope(); 6397 return OMPTargetParallelForSimdDirective::Create( 6398 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6399 } 6400 6401 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 6402 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6403 SourceLocation EndLoc, 6404 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6405 if (!AStmt) 6406 return StmtError(); 6407 6408 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6409 // 1.2.2 OpenMP Language Terminology 6410 // Structured block - An executable statement with a single entry at the 6411 // top and a single exit at the bottom. 6412 // The point of exit cannot be a branch out of the structured block. 6413 // longjmp() and throw() must not violate the entry/exit criteria. 6414 CS->getCapturedDecl()->setNothrow(); 6415 6416 OMPLoopDirective::HelperExprs B; 6417 // In presence of clause 'collapse' with number of loops, it will define the 6418 // nested loops number. 6419 unsigned NestedLoopCount = 6420 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 6421 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6422 VarsWithImplicitDSA, B); 6423 if (NestedLoopCount == 0) 6424 return StmtError(); 6425 6426 assert((CurContext->isDependentContext() || B.builtAll()) && 6427 "omp target simd loop exprs were not built"); 6428 6429 if (!CurContext->isDependentContext()) { 6430 // Finalize the clauses that need pre-built expressions for CodeGen. 6431 for (auto C : Clauses) { 6432 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6433 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6434 B.NumIterations, *this, CurScope, 6435 DSAStack)) 6436 return StmtError(); 6437 } 6438 } 6439 6440 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6441 return StmtError(); 6442 6443 getCurFunction()->setHasBranchProtectedScope(); 6444 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 6445 NestedLoopCount, Clauses, AStmt, B); 6446 } 6447 6448 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 6449 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6450 SourceLocation EndLoc, 6451 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6452 if (!AStmt) 6453 return StmtError(); 6454 6455 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6456 // 1.2.2 OpenMP Language Terminology 6457 // Structured block - An executable statement with a single entry at the 6458 // top and a single exit at the bottom. 6459 // The point of exit cannot be a branch out of the structured block. 6460 // longjmp() and throw() must not violate the entry/exit criteria. 6461 CS->getCapturedDecl()->setNothrow(); 6462 6463 OMPLoopDirective::HelperExprs B; 6464 // In presence of clause 'collapse' with number of loops, it will 6465 // define the nested loops number. 6466 unsigned NestedLoopCount = 6467 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 6468 nullptr /*ordered not a clause on distribute*/, AStmt, 6469 *this, *DSAStack, VarsWithImplicitDSA, B); 6470 if (NestedLoopCount == 0) 6471 return StmtError(); 6472 6473 assert((CurContext->isDependentContext() || B.builtAll()) && 6474 "omp teams distribute loop exprs were not built"); 6475 6476 getCurFunction()->setHasBranchProtectedScope(); 6477 return OMPTeamsDistributeDirective::Create( 6478 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6479 } 6480 6481 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 6482 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6483 SourceLocation EndLoc, 6484 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6485 if (!AStmt) 6486 return StmtError(); 6487 6488 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6489 // 1.2.2 OpenMP Language Terminology 6490 // Structured block - An executable statement with a single entry at the 6491 // top and a single exit at the bottom. 6492 // The point of exit cannot be a branch out of the structured block. 6493 // longjmp() and throw() must not violate the entry/exit criteria. 6494 CS->getCapturedDecl()->setNothrow(); 6495 6496 OMPLoopDirective::HelperExprs B; 6497 // In presence of clause 'collapse' with number of loops, it will 6498 // define the nested loops number. 6499 unsigned NestedLoopCount = CheckOpenMPLoop( 6500 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 6501 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6502 VarsWithImplicitDSA, B); 6503 6504 if (NestedLoopCount == 0) 6505 return StmtError(); 6506 6507 assert((CurContext->isDependentContext() || B.builtAll()) && 6508 "omp teams distribute simd loop exprs were not built"); 6509 6510 if (!CurContext->isDependentContext()) { 6511 // Finalize the clauses that need pre-built expressions for CodeGen. 6512 for (auto C : Clauses) { 6513 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6514 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6515 B.NumIterations, *this, CurScope, 6516 DSAStack)) 6517 return StmtError(); 6518 } 6519 } 6520 6521 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6522 return StmtError(); 6523 6524 getCurFunction()->setHasBranchProtectedScope(); 6525 return OMPTeamsDistributeSimdDirective::Create( 6526 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6527 } 6528 6529 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 6530 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6531 SourceLocation EndLoc, 6532 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6533 if (!AStmt) 6534 return StmtError(); 6535 6536 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6537 // 1.2.2 OpenMP Language Terminology 6538 // Structured block - An executable statement with a single entry at the 6539 // top and a single exit at the bottom. 6540 // The point of exit cannot be a branch out of the structured block. 6541 // longjmp() and throw() must not violate the entry/exit criteria. 6542 CS->getCapturedDecl()->setNothrow(); 6543 6544 OMPLoopDirective::HelperExprs B; 6545 // In presence of clause 'collapse' with number of loops, it will 6546 // define the nested loops number. 6547 auto NestedLoopCount = CheckOpenMPLoop( 6548 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 6549 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6550 VarsWithImplicitDSA, B); 6551 6552 if (NestedLoopCount == 0) 6553 return StmtError(); 6554 6555 assert((CurContext->isDependentContext() || B.builtAll()) && 6556 "omp for loop exprs were not built"); 6557 6558 if (!CurContext->isDependentContext()) { 6559 // Finalize the clauses that need pre-built expressions for CodeGen. 6560 for (auto C : Clauses) { 6561 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6562 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6563 B.NumIterations, *this, CurScope, 6564 DSAStack)) 6565 return StmtError(); 6566 } 6567 } 6568 6569 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6570 return StmtError(); 6571 6572 getCurFunction()->setHasBranchProtectedScope(); 6573 return OMPTeamsDistributeParallelForSimdDirective::Create( 6574 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6575 } 6576 6577 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 6578 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6579 SourceLocation EndLoc, 6580 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6581 if (!AStmt) 6582 return StmtError(); 6583 6584 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6585 // 1.2.2 OpenMP Language Terminology 6586 // Structured block - An executable statement with a single entry at the 6587 // top and a single exit at the bottom. 6588 // The point of exit cannot be a branch out of the structured block. 6589 // longjmp() and throw() must not violate the entry/exit criteria. 6590 CS->getCapturedDecl()->setNothrow(); 6591 6592 OMPLoopDirective::HelperExprs B; 6593 // In presence of clause 'collapse' with number of loops, it will 6594 // define the nested loops number. 6595 unsigned NestedLoopCount = CheckOpenMPLoop( 6596 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 6597 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6598 VarsWithImplicitDSA, B); 6599 6600 if (NestedLoopCount == 0) 6601 return StmtError(); 6602 6603 assert((CurContext->isDependentContext() || B.builtAll()) && 6604 "omp for loop exprs were not built"); 6605 6606 if (!CurContext->isDependentContext()) { 6607 // Finalize the clauses that need pre-built expressions for CodeGen. 6608 for (auto C : Clauses) { 6609 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6610 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6611 B.NumIterations, *this, CurScope, 6612 DSAStack)) 6613 return StmtError(); 6614 } 6615 } 6616 6617 getCurFunction()->setHasBranchProtectedScope(); 6618 return OMPTeamsDistributeParallelForDirective::Create( 6619 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6620 } 6621 6622 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 6623 Stmt *AStmt, 6624 SourceLocation StartLoc, 6625 SourceLocation EndLoc) { 6626 if (!AStmt) 6627 return StmtError(); 6628 6629 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6630 // 1.2.2 OpenMP Language Terminology 6631 // Structured block - An executable statement with a single entry at the 6632 // top and a single exit at the bottom. 6633 // The point of exit cannot be a branch out of the structured block. 6634 // longjmp() and throw() must not violate the entry/exit criteria. 6635 CS->getCapturedDecl()->setNothrow(); 6636 6637 getCurFunction()->setHasBranchProtectedScope(); 6638 6639 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 6640 AStmt); 6641 } 6642 6643 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 6644 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6645 SourceLocation EndLoc, 6646 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6647 if (!AStmt) 6648 return StmtError(); 6649 6650 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6651 // 1.2.2 OpenMP Language Terminology 6652 // Structured block - An executable statement with a single entry at the 6653 // top and a single exit at the bottom. 6654 // The point of exit cannot be a branch out of the structured block. 6655 // longjmp() and throw() must not violate the entry/exit criteria. 6656 CS->getCapturedDecl()->setNothrow(); 6657 6658 OMPLoopDirective::HelperExprs B; 6659 // In presence of clause 'collapse' with number of loops, it will 6660 // define the nested loops number. 6661 auto NestedLoopCount = CheckOpenMPLoop( 6662 OMPD_target_teams_distribute, 6663 getCollapseNumberExpr(Clauses), 6664 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6665 VarsWithImplicitDSA, B); 6666 if (NestedLoopCount == 0) 6667 return StmtError(); 6668 6669 assert((CurContext->isDependentContext() || B.builtAll()) && 6670 "omp target teams distribute loop exprs were not built"); 6671 6672 getCurFunction()->setHasBranchProtectedScope(); 6673 return OMPTargetTeamsDistributeDirective::Create( 6674 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6675 } 6676 6677 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 6678 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6679 SourceLocation EndLoc, 6680 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6681 if (!AStmt) 6682 return StmtError(); 6683 6684 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6685 // 1.2.2 OpenMP Language Terminology 6686 // Structured block - An executable statement with a single entry at the 6687 // top and a single exit at the bottom. 6688 // The point of exit cannot be a branch out of the structured block. 6689 // longjmp() and throw() must not violate the entry/exit criteria. 6690 CS->getCapturedDecl()->setNothrow(); 6691 6692 OMPLoopDirective::HelperExprs B; 6693 // In presence of clause 'collapse' with number of loops, it will 6694 // define the nested loops number. 6695 auto NestedLoopCount = CheckOpenMPLoop( 6696 OMPD_target_teams_distribute_parallel_for, 6697 getCollapseNumberExpr(Clauses), 6698 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6699 VarsWithImplicitDSA, B); 6700 if (NestedLoopCount == 0) 6701 return StmtError(); 6702 6703 assert((CurContext->isDependentContext() || B.builtAll()) && 6704 "omp target teams distribute parallel for loop exprs were not built"); 6705 6706 if (!CurContext->isDependentContext()) { 6707 // Finalize the clauses that need pre-built expressions for CodeGen. 6708 for (auto C : Clauses) { 6709 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6710 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6711 B.NumIterations, *this, CurScope, 6712 DSAStack)) 6713 return StmtError(); 6714 } 6715 } 6716 6717 getCurFunction()->setHasBranchProtectedScope(); 6718 return OMPTargetTeamsDistributeParallelForDirective::Create( 6719 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6720 } 6721 6722 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 6723 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6724 SourceLocation EndLoc, 6725 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6726 if (!AStmt) 6727 return StmtError(); 6728 6729 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6730 // 1.2.2 OpenMP Language Terminology 6731 // Structured block - An executable statement with a single entry at the 6732 // top and a single exit at the bottom. 6733 // The point of exit cannot be a branch out of the structured block. 6734 // longjmp() and throw() must not violate the entry/exit criteria. 6735 CS->getCapturedDecl()->setNothrow(); 6736 6737 OMPLoopDirective::HelperExprs B; 6738 // In presence of clause 'collapse' with number of loops, it will 6739 // define the nested loops number. 6740 auto NestedLoopCount = CheckOpenMPLoop( 6741 OMPD_target_teams_distribute_parallel_for_simd, 6742 getCollapseNumberExpr(Clauses), 6743 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6744 VarsWithImplicitDSA, B); 6745 if (NestedLoopCount == 0) 6746 return StmtError(); 6747 6748 assert((CurContext->isDependentContext() || B.builtAll()) && 6749 "omp target teams distribute parallel for simd loop exprs were not " 6750 "built"); 6751 6752 if (!CurContext->isDependentContext()) { 6753 // Finalize the clauses that need pre-built expressions for CodeGen. 6754 for (auto C : Clauses) { 6755 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6756 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6757 B.NumIterations, *this, CurScope, 6758 DSAStack)) 6759 return StmtError(); 6760 } 6761 } 6762 6763 getCurFunction()->setHasBranchProtectedScope(); 6764 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 6765 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6766 } 6767 6768 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 6769 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6770 SourceLocation EndLoc, 6771 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6772 if (!AStmt) 6773 return StmtError(); 6774 6775 auto *CS = cast<CapturedStmt>(AStmt); 6776 // 1.2.2 OpenMP Language Terminology 6777 // Structured block - An executable statement with a single entry at the 6778 // top and a single exit at the bottom. 6779 // The point of exit cannot be a branch out of the structured block. 6780 // longjmp() and throw() must not violate the entry/exit criteria. 6781 CS->getCapturedDecl()->setNothrow(); 6782 6783 OMPLoopDirective::HelperExprs B; 6784 // In presence of clause 'collapse' with number of loops, it will 6785 // define the nested loops number. 6786 auto NestedLoopCount = CheckOpenMPLoop( 6787 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 6788 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6789 VarsWithImplicitDSA, B); 6790 if (NestedLoopCount == 0) 6791 return StmtError(); 6792 6793 assert((CurContext->isDependentContext() || B.builtAll()) && 6794 "omp target teams distribute simd loop exprs were not built"); 6795 6796 getCurFunction()->setHasBranchProtectedScope(); 6797 return OMPTargetTeamsDistributeSimdDirective::Create( 6798 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6799 } 6800 6801 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 6802 SourceLocation StartLoc, 6803 SourceLocation LParenLoc, 6804 SourceLocation EndLoc) { 6805 OMPClause *Res = nullptr; 6806 switch (Kind) { 6807 case OMPC_final: 6808 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 6809 break; 6810 case OMPC_num_threads: 6811 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 6812 break; 6813 case OMPC_safelen: 6814 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 6815 break; 6816 case OMPC_simdlen: 6817 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 6818 break; 6819 case OMPC_collapse: 6820 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 6821 break; 6822 case OMPC_ordered: 6823 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 6824 break; 6825 case OMPC_device: 6826 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc); 6827 break; 6828 case OMPC_num_teams: 6829 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 6830 break; 6831 case OMPC_thread_limit: 6832 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 6833 break; 6834 case OMPC_priority: 6835 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 6836 break; 6837 case OMPC_grainsize: 6838 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 6839 break; 6840 case OMPC_num_tasks: 6841 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 6842 break; 6843 case OMPC_hint: 6844 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 6845 break; 6846 case OMPC_if: 6847 case OMPC_default: 6848 case OMPC_proc_bind: 6849 case OMPC_schedule: 6850 case OMPC_private: 6851 case OMPC_firstprivate: 6852 case OMPC_lastprivate: 6853 case OMPC_shared: 6854 case OMPC_reduction: 6855 case OMPC_task_reduction: 6856 case OMPC_linear: 6857 case OMPC_aligned: 6858 case OMPC_copyin: 6859 case OMPC_copyprivate: 6860 case OMPC_nowait: 6861 case OMPC_untied: 6862 case OMPC_mergeable: 6863 case OMPC_threadprivate: 6864 case OMPC_flush: 6865 case OMPC_read: 6866 case OMPC_write: 6867 case OMPC_update: 6868 case OMPC_capture: 6869 case OMPC_seq_cst: 6870 case OMPC_depend: 6871 case OMPC_threads: 6872 case OMPC_simd: 6873 case OMPC_map: 6874 case OMPC_nogroup: 6875 case OMPC_dist_schedule: 6876 case OMPC_defaultmap: 6877 case OMPC_unknown: 6878 case OMPC_uniform: 6879 case OMPC_to: 6880 case OMPC_from: 6881 case OMPC_use_device_ptr: 6882 case OMPC_is_device_ptr: 6883 llvm_unreachable("Clause is not allowed."); 6884 } 6885 return Res; 6886 } 6887 6888 // An OpenMP directive such as 'target parallel' has two captured regions: 6889 // for the 'target' and 'parallel' respectively. This function returns 6890 // the region in which to capture expressions associated with a clause. 6891 // A return value of OMPD_unknown signifies that the expression should not 6892 // be captured. 6893 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 6894 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 6895 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 6896 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 6897 6898 switch (CKind) { 6899 case OMPC_if: 6900 switch (DKind) { 6901 case OMPD_target_parallel: 6902 // If this clause applies to the nested 'parallel' region, capture within 6903 // the 'target' region, otherwise do not capture. 6904 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 6905 CaptureRegion = OMPD_target; 6906 break; 6907 case OMPD_cancel: 6908 case OMPD_parallel: 6909 case OMPD_parallel_sections: 6910 case OMPD_parallel_for: 6911 case OMPD_parallel_for_simd: 6912 case OMPD_target: 6913 case OMPD_target_simd: 6914 case OMPD_target_parallel_for: 6915 case OMPD_target_parallel_for_simd: 6916 case OMPD_target_teams: 6917 case OMPD_target_teams_distribute: 6918 case OMPD_target_teams_distribute_simd: 6919 case OMPD_target_teams_distribute_parallel_for: 6920 case OMPD_target_teams_distribute_parallel_for_simd: 6921 case OMPD_teams_distribute_parallel_for: 6922 case OMPD_teams_distribute_parallel_for_simd: 6923 case OMPD_distribute_parallel_for: 6924 case OMPD_distribute_parallel_for_simd: 6925 case OMPD_task: 6926 case OMPD_taskloop: 6927 case OMPD_taskloop_simd: 6928 case OMPD_target_data: 6929 case OMPD_target_enter_data: 6930 case OMPD_target_exit_data: 6931 case OMPD_target_update: 6932 // Do not capture if-clause expressions. 6933 break; 6934 case OMPD_threadprivate: 6935 case OMPD_taskyield: 6936 case OMPD_barrier: 6937 case OMPD_taskwait: 6938 case OMPD_cancellation_point: 6939 case OMPD_flush: 6940 case OMPD_declare_reduction: 6941 case OMPD_declare_simd: 6942 case OMPD_declare_target: 6943 case OMPD_end_declare_target: 6944 case OMPD_teams: 6945 case OMPD_simd: 6946 case OMPD_for: 6947 case OMPD_for_simd: 6948 case OMPD_sections: 6949 case OMPD_section: 6950 case OMPD_single: 6951 case OMPD_master: 6952 case OMPD_critical: 6953 case OMPD_taskgroup: 6954 case OMPD_distribute: 6955 case OMPD_ordered: 6956 case OMPD_atomic: 6957 case OMPD_distribute_simd: 6958 case OMPD_teams_distribute: 6959 case OMPD_teams_distribute_simd: 6960 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 6961 case OMPD_unknown: 6962 llvm_unreachable("Unknown OpenMP directive"); 6963 } 6964 break; 6965 case OMPC_num_threads: 6966 switch (DKind) { 6967 case OMPD_target_parallel: 6968 CaptureRegion = OMPD_target; 6969 break; 6970 case OMPD_cancel: 6971 case OMPD_parallel: 6972 case OMPD_parallel_sections: 6973 case OMPD_parallel_for: 6974 case OMPD_parallel_for_simd: 6975 case OMPD_target: 6976 case OMPD_target_simd: 6977 case OMPD_target_parallel_for: 6978 case OMPD_target_parallel_for_simd: 6979 case OMPD_target_teams: 6980 case OMPD_target_teams_distribute: 6981 case OMPD_target_teams_distribute_simd: 6982 case OMPD_target_teams_distribute_parallel_for: 6983 case OMPD_target_teams_distribute_parallel_for_simd: 6984 case OMPD_teams_distribute_parallel_for: 6985 case OMPD_teams_distribute_parallel_for_simd: 6986 case OMPD_distribute_parallel_for: 6987 case OMPD_distribute_parallel_for_simd: 6988 case OMPD_task: 6989 case OMPD_taskloop: 6990 case OMPD_taskloop_simd: 6991 case OMPD_target_data: 6992 case OMPD_target_enter_data: 6993 case OMPD_target_exit_data: 6994 case OMPD_target_update: 6995 // Do not capture num_threads-clause expressions. 6996 break; 6997 case OMPD_threadprivate: 6998 case OMPD_taskyield: 6999 case OMPD_barrier: 7000 case OMPD_taskwait: 7001 case OMPD_cancellation_point: 7002 case OMPD_flush: 7003 case OMPD_declare_reduction: 7004 case OMPD_declare_simd: 7005 case OMPD_declare_target: 7006 case OMPD_end_declare_target: 7007 case OMPD_teams: 7008 case OMPD_simd: 7009 case OMPD_for: 7010 case OMPD_for_simd: 7011 case OMPD_sections: 7012 case OMPD_section: 7013 case OMPD_single: 7014 case OMPD_master: 7015 case OMPD_critical: 7016 case OMPD_taskgroup: 7017 case OMPD_distribute: 7018 case OMPD_ordered: 7019 case OMPD_atomic: 7020 case OMPD_distribute_simd: 7021 case OMPD_teams_distribute: 7022 case OMPD_teams_distribute_simd: 7023 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 7024 case OMPD_unknown: 7025 llvm_unreachable("Unknown OpenMP directive"); 7026 } 7027 break; 7028 case OMPC_num_teams: 7029 switch (DKind) { 7030 case OMPD_target_teams: 7031 CaptureRegion = OMPD_target; 7032 break; 7033 case OMPD_cancel: 7034 case OMPD_parallel: 7035 case OMPD_parallel_sections: 7036 case OMPD_parallel_for: 7037 case OMPD_parallel_for_simd: 7038 case OMPD_target: 7039 case OMPD_target_simd: 7040 case OMPD_target_parallel: 7041 case OMPD_target_parallel_for: 7042 case OMPD_target_parallel_for_simd: 7043 case OMPD_target_teams_distribute: 7044 case OMPD_target_teams_distribute_simd: 7045 case OMPD_target_teams_distribute_parallel_for: 7046 case OMPD_target_teams_distribute_parallel_for_simd: 7047 case OMPD_teams_distribute_parallel_for: 7048 case OMPD_teams_distribute_parallel_for_simd: 7049 case OMPD_distribute_parallel_for: 7050 case OMPD_distribute_parallel_for_simd: 7051 case OMPD_task: 7052 case OMPD_taskloop: 7053 case OMPD_taskloop_simd: 7054 case OMPD_target_data: 7055 case OMPD_target_enter_data: 7056 case OMPD_target_exit_data: 7057 case OMPD_target_update: 7058 case OMPD_teams: 7059 case OMPD_teams_distribute: 7060 case OMPD_teams_distribute_simd: 7061 // Do not capture num_teams-clause expressions. 7062 break; 7063 case OMPD_threadprivate: 7064 case OMPD_taskyield: 7065 case OMPD_barrier: 7066 case OMPD_taskwait: 7067 case OMPD_cancellation_point: 7068 case OMPD_flush: 7069 case OMPD_declare_reduction: 7070 case OMPD_declare_simd: 7071 case OMPD_declare_target: 7072 case OMPD_end_declare_target: 7073 case OMPD_simd: 7074 case OMPD_for: 7075 case OMPD_for_simd: 7076 case OMPD_sections: 7077 case OMPD_section: 7078 case OMPD_single: 7079 case OMPD_master: 7080 case OMPD_critical: 7081 case OMPD_taskgroup: 7082 case OMPD_distribute: 7083 case OMPD_ordered: 7084 case OMPD_atomic: 7085 case OMPD_distribute_simd: 7086 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 7087 case OMPD_unknown: 7088 llvm_unreachable("Unknown OpenMP directive"); 7089 } 7090 break; 7091 case OMPC_thread_limit: 7092 switch (DKind) { 7093 case OMPD_target_teams: 7094 CaptureRegion = OMPD_target; 7095 break; 7096 case OMPD_cancel: 7097 case OMPD_parallel: 7098 case OMPD_parallel_sections: 7099 case OMPD_parallel_for: 7100 case OMPD_parallel_for_simd: 7101 case OMPD_target: 7102 case OMPD_target_simd: 7103 case OMPD_target_parallel: 7104 case OMPD_target_parallel_for: 7105 case OMPD_target_parallel_for_simd: 7106 case OMPD_target_teams_distribute: 7107 case OMPD_target_teams_distribute_simd: 7108 case OMPD_target_teams_distribute_parallel_for: 7109 case OMPD_target_teams_distribute_parallel_for_simd: 7110 case OMPD_teams_distribute_parallel_for: 7111 case OMPD_teams_distribute_parallel_for_simd: 7112 case OMPD_distribute_parallel_for: 7113 case OMPD_distribute_parallel_for_simd: 7114 case OMPD_task: 7115 case OMPD_taskloop: 7116 case OMPD_taskloop_simd: 7117 case OMPD_target_data: 7118 case OMPD_target_enter_data: 7119 case OMPD_target_exit_data: 7120 case OMPD_target_update: 7121 case OMPD_teams: 7122 case OMPD_teams_distribute: 7123 case OMPD_teams_distribute_simd: 7124 // Do not capture thread_limit-clause expressions. 7125 break; 7126 case OMPD_threadprivate: 7127 case OMPD_taskyield: 7128 case OMPD_barrier: 7129 case OMPD_taskwait: 7130 case OMPD_cancellation_point: 7131 case OMPD_flush: 7132 case OMPD_declare_reduction: 7133 case OMPD_declare_simd: 7134 case OMPD_declare_target: 7135 case OMPD_end_declare_target: 7136 case OMPD_simd: 7137 case OMPD_for: 7138 case OMPD_for_simd: 7139 case OMPD_sections: 7140 case OMPD_section: 7141 case OMPD_single: 7142 case OMPD_master: 7143 case OMPD_critical: 7144 case OMPD_taskgroup: 7145 case OMPD_distribute: 7146 case OMPD_ordered: 7147 case OMPD_atomic: 7148 case OMPD_distribute_simd: 7149 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 7150 case OMPD_unknown: 7151 llvm_unreachable("Unknown OpenMP directive"); 7152 } 7153 break; 7154 case OMPC_schedule: 7155 case OMPC_dist_schedule: 7156 case OMPC_firstprivate: 7157 case OMPC_lastprivate: 7158 case OMPC_reduction: 7159 case OMPC_task_reduction: 7160 case OMPC_linear: 7161 case OMPC_default: 7162 case OMPC_proc_bind: 7163 case OMPC_final: 7164 case OMPC_safelen: 7165 case OMPC_simdlen: 7166 case OMPC_collapse: 7167 case OMPC_private: 7168 case OMPC_shared: 7169 case OMPC_aligned: 7170 case OMPC_copyin: 7171 case OMPC_copyprivate: 7172 case OMPC_ordered: 7173 case OMPC_nowait: 7174 case OMPC_untied: 7175 case OMPC_mergeable: 7176 case OMPC_threadprivate: 7177 case OMPC_flush: 7178 case OMPC_read: 7179 case OMPC_write: 7180 case OMPC_update: 7181 case OMPC_capture: 7182 case OMPC_seq_cst: 7183 case OMPC_depend: 7184 case OMPC_device: 7185 case OMPC_threads: 7186 case OMPC_simd: 7187 case OMPC_map: 7188 case OMPC_priority: 7189 case OMPC_grainsize: 7190 case OMPC_nogroup: 7191 case OMPC_num_tasks: 7192 case OMPC_hint: 7193 case OMPC_defaultmap: 7194 case OMPC_unknown: 7195 case OMPC_uniform: 7196 case OMPC_to: 7197 case OMPC_from: 7198 case OMPC_use_device_ptr: 7199 case OMPC_is_device_ptr: 7200 llvm_unreachable("Unexpected OpenMP clause."); 7201 } 7202 return CaptureRegion; 7203 } 7204 7205 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 7206 Expr *Condition, SourceLocation StartLoc, 7207 SourceLocation LParenLoc, 7208 SourceLocation NameModifierLoc, 7209 SourceLocation ColonLoc, 7210 SourceLocation EndLoc) { 7211 Expr *ValExpr = Condition; 7212 Stmt *HelperValStmt = nullptr; 7213 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 7214 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 7215 !Condition->isInstantiationDependent() && 7216 !Condition->containsUnexpandedParameterPack()) { 7217 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 7218 if (Val.isInvalid()) 7219 return nullptr; 7220 7221 ValExpr = MakeFullExpr(Val.get()).get(); 7222 7223 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 7224 CaptureRegion = 7225 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier); 7226 if (CaptureRegion != OMPD_unknown) { 7227 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7228 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7229 HelperValStmt = buildPreInits(Context, Captures); 7230 } 7231 } 7232 7233 return new (Context) 7234 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 7235 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 7236 } 7237 7238 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 7239 SourceLocation StartLoc, 7240 SourceLocation LParenLoc, 7241 SourceLocation EndLoc) { 7242 Expr *ValExpr = Condition; 7243 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 7244 !Condition->isInstantiationDependent() && 7245 !Condition->containsUnexpandedParameterPack()) { 7246 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 7247 if (Val.isInvalid()) 7248 return nullptr; 7249 7250 ValExpr = MakeFullExpr(Val.get()).get(); 7251 } 7252 7253 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 7254 } 7255 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 7256 Expr *Op) { 7257 if (!Op) 7258 return ExprError(); 7259 7260 class IntConvertDiagnoser : public ICEConvertDiagnoser { 7261 public: 7262 IntConvertDiagnoser() 7263 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 7264 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 7265 QualType T) override { 7266 return S.Diag(Loc, diag::err_omp_not_integral) << T; 7267 } 7268 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 7269 QualType T) override { 7270 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 7271 } 7272 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 7273 QualType T, 7274 QualType ConvTy) override { 7275 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 7276 } 7277 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 7278 QualType ConvTy) override { 7279 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 7280 << ConvTy->isEnumeralType() << ConvTy; 7281 } 7282 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 7283 QualType T) override { 7284 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 7285 } 7286 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 7287 QualType ConvTy) override { 7288 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 7289 << ConvTy->isEnumeralType() << ConvTy; 7290 } 7291 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 7292 QualType) override { 7293 llvm_unreachable("conversion functions are permitted"); 7294 } 7295 } ConvertDiagnoser; 7296 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 7297 } 7298 7299 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, 7300 OpenMPClauseKind CKind, 7301 bool StrictlyPositive) { 7302 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 7303 !ValExpr->isInstantiationDependent()) { 7304 SourceLocation Loc = ValExpr->getExprLoc(); 7305 ExprResult Value = 7306 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 7307 if (Value.isInvalid()) 7308 return false; 7309 7310 ValExpr = Value.get(); 7311 // The expression must evaluate to a non-negative integer value. 7312 llvm::APSInt Result; 7313 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && 7314 Result.isSigned() && 7315 !((!StrictlyPositive && Result.isNonNegative()) || 7316 (StrictlyPositive && Result.isStrictlyPositive()))) { 7317 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 7318 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 7319 << ValExpr->getSourceRange(); 7320 return false; 7321 } 7322 } 7323 return true; 7324 } 7325 7326 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 7327 SourceLocation StartLoc, 7328 SourceLocation LParenLoc, 7329 SourceLocation EndLoc) { 7330 Expr *ValExpr = NumThreads; 7331 Stmt *HelperValStmt = nullptr; 7332 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 7333 7334 // OpenMP [2.5, Restrictions] 7335 // The num_threads expression must evaluate to a positive integer value. 7336 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 7337 /*StrictlyPositive=*/true)) 7338 return nullptr; 7339 7340 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 7341 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads); 7342 if (CaptureRegion != OMPD_unknown) { 7343 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7344 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7345 HelperValStmt = buildPreInits(Context, Captures); 7346 } 7347 7348 return new (Context) OMPNumThreadsClause( 7349 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 7350 } 7351 7352 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 7353 OpenMPClauseKind CKind, 7354 bool StrictlyPositive) { 7355 if (!E) 7356 return ExprError(); 7357 if (E->isValueDependent() || E->isTypeDependent() || 7358 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 7359 return E; 7360 llvm::APSInt Result; 7361 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 7362 if (ICE.isInvalid()) 7363 return ExprError(); 7364 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 7365 (!StrictlyPositive && !Result.isNonNegative())) { 7366 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 7367 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 7368 << E->getSourceRange(); 7369 return ExprError(); 7370 } 7371 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 7372 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 7373 << E->getSourceRange(); 7374 return ExprError(); 7375 } 7376 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 7377 DSAStack->setAssociatedLoops(Result.getExtValue()); 7378 else if (CKind == OMPC_ordered) 7379 DSAStack->setAssociatedLoops(Result.getExtValue()); 7380 return ICE; 7381 } 7382 7383 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 7384 SourceLocation LParenLoc, 7385 SourceLocation EndLoc) { 7386 // OpenMP [2.8.1, simd construct, Description] 7387 // The parameter of the safelen clause must be a constant 7388 // positive integer expression. 7389 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 7390 if (Safelen.isInvalid()) 7391 return nullptr; 7392 return new (Context) 7393 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 7394 } 7395 7396 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 7397 SourceLocation LParenLoc, 7398 SourceLocation EndLoc) { 7399 // OpenMP [2.8.1, simd construct, Description] 7400 // The parameter of the simdlen clause must be a constant 7401 // positive integer expression. 7402 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 7403 if (Simdlen.isInvalid()) 7404 return nullptr; 7405 return new (Context) 7406 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 7407 } 7408 7409 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 7410 SourceLocation StartLoc, 7411 SourceLocation LParenLoc, 7412 SourceLocation EndLoc) { 7413 // OpenMP [2.7.1, loop construct, Description] 7414 // OpenMP [2.8.1, simd construct, Description] 7415 // OpenMP [2.9.6, distribute construct, Description] 7416 // The parameter of the collapse clause must be a constant 7417 // positive integer expression. 7418 ExprResult NumForLoopsResult = 7419 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 7420 if (NumForLoopsResult.isInvalid()) 7421 return nullptr; 7422 return new (Context) 7423 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 7424 } 7425 7426 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 7427 SourceLocation EndLoc, 7428 SourceLocation LParenLoc, 7429 Expr *NumForLoops) { 7430 // OpenMP [2.7.1, loop construct, Description] 7431 // OpenMP [2.8.1, simd construct, Description] 7432 // OpenMP [2.9.6, distribute construct, Description] 7433 // The parameter of the ordered clause must be a constant 7434 // positive integer expression if any. 7435 if (NumForLoops && LParenLoc.isValid()) { 7436 ExprResult NumForLoopsResult = 7437 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 7438 if (NumForLoopsResult.isInvalid()) 7439 return nullptr; 7440 NumForLoops = NumForLoopsResult.get(); 7441 } else 7442 NumForLoops = nullptr; 7443 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops); 7444 return new (Context) 7445 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc); 7446 } 7447 7448 OMPClause *Sema::ActOnOpenMPSimpleClause( 7449 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 7450 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 7451 OMPClause *Res = nullptr; 7452 switch (Kind) { 7453 case OMPC_default: 7454 Res = 7455 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 7456 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 7457 break; 7458 case OMPC_proc_bind: 7459 Res = ActOnOpenMPProcBindClause( 7460 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 7461 LParenLoc, EndLoc); 7462 break; 7463 case OMPC_if: 7464 case OMPC_final: 7465 case OMPC_num_threads: 7466 case OMPC_safelen: 7467 case OMPC_simdlen: 7468 case OMPC_collapse: 7469 case OMPC_schedule: 7470 case OMPC_private: 7471 case OMPC_firstprivate: 7472 case OMPC_lastprivate: 7473 case OMPC_shared: 7474 case OMPC_reduction: 7475 case OMPC_task_reduction: 7476 case OMPC_linear: 7477 case OMPC_aligned: 7478 case OMPC_copyin: 7479 case OMPC_copyprivate: 7480 case OMPC_ordered: 7481 case OMPC_nowait: 7482 case OMPC_untied: 7483 case OMPC_mergeable: 7484 case OMPC_threadprivate: 7485 case OMPC_flush: 7486 case OMPC_read: 7487 case OMPC_write: 7488 case OMPC_update: 7489 case OMPC_capture: 7490 case OMPC_seq_cst: 7491 case OMPC_depend: 7492 case OMPC_device: 7493 case OMPC_threads: 7494 case OMPC_simd: 7495 case OMPC_map: 7496 case OMPC_num_teams: 7497 case OMPC_thread_limit: 7498 case OMPC_priority: 7499 case OMPC_grainsize: 7500 case OMPC_nogroup: 7501 case OMPC_num_tasks: 7502 case OMPC_hint: 7503 case OMPC_dist_schedule: 7504 case OMPC_defaultmap: 7505 case OMPC_unknown: 7506 case OMPC_uniform: 7507 case OMPC_to: 7508 case OMPC_from: 7509 case OMPC_use_device_ptr: 7510 case OMPC_is_device_ptr: 7511 llvm_unreachable("Clause is not allowed."); 7512 } 7513 return Res; 7514 } 7515 7516 static std::string 7517 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 7518 ArrayRef<unsigned> Exclude = llvm::None) { 7519 std::string Values; 7520 unsigned Bound = Last >= 2 ? Last - 2 : 0; 7521 unsigned Skipped = Exclude.size(); 7522 auto S = Exclude.begin(), E = Exclude.end(); 7523 for (unsigned i = First; i < Last; ++i) { 7524 if (std::find(S, E, i) != E) { 7525 --Skipped; 7526 continue; 7527 } 7528 Values += "'"; 7529 Values += getOpenMPSimpleClauseTypeName(K, i); 7530 Values += "'"; 7531 if (i == Bound - Skipped) 7532 Values += " or "; 7533 else if (i != Bound + 1 - Skipped) 7534 Values += ", "; 7535 } 7536 return Values; 7537 } 7538 7539 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 7540 SourceLocation KindKwLoc, 7541 SourceLocation StartLoc, 7542 SourceLocation LParenLoc, 7543 SourceLocation EndLoc) { 7544 if (Kind == OMPC_DEFAULT_unknown) { 7545 static_assert(OMPC_DEFAULT_unknown > 0, 7546 "OMPC_DEFAULT_unknown not greater than 0"); 7547 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 7548 << getListOfPossibleValues(OMPC_default, /*First=*/0, 7549 /*Last=*/OMPC_DEFAULT_unknown) 7550 << getOpenMPClauseName(OMPC_default); 7551 return nullptr; 7552 } 7553 switch (Kind) { 7554 case OMPC_DEFAULT_none: 7555 DSAStack->setDefaultDSANone(KindKwLoc); 7556 break; 7557 case OMPC_DEFAULT_shared: 7558 DSAStack->setDefaultDSAShared(KindKwLoc); 7559 break; 7560 case OMPC_DEFAULT_unknown: 7561 llvm_unreachable("Clause kind is not allowed."); 7562 break; 7563 } 7564 return new (Context) 7565 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 7566 } 7567 7568 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 7569 SourceLocation KindKwLoc, 7570 SourceLocation StartLoc, 7571 SourceLocation LParenLoc, 7572 SourceLocation EndLoc) { 7573 if (Kind == OMPC_PROC_BIND_unknown) { 7574 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 7575 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0, 7576 /*Last=*/OMPC_PROC_BIND_unknown) 7577 << getOpenMPClauseName(OMPC_proc_bind); 7578 return nullptr; 7579 } 7580 return new (Context) 7581 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 7582 } 7583 7584 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 7585 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 7586 SourceLocation StartLoc, SourceLocation LParenLoc, 7587 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 7588 SourceLocation EndLoc) { 7589 OMPClause *Res = nullptr; 7590 switch (Kind) { 7591 case OMPC_schedule: 7592 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 7593 assert(Argument.size() == NumberOfElements && 7594 ArgumentLoc.size() == NumberOfElements); 7595 Res = ActOnOpenMPScheduleClause( 7596 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 7597 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 7598 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 7599 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 7600 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 7601 break; 7602 case OMPC_if: 7603 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 7604 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 7605 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 7606 DelimLoc, EndLoc); 7607 break; 7608 case OMPC_dist_schedule: 7609 Res = ActOnOpenMPDistScheduleClause( 7610 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 7611 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 7612 break; 7613 case OMPC_defaultmap: 7614 enum { Modifier, DefaultmapKind }; 7615 Res = ActOnOpenMPDefaultmapClause( 7616 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 7617 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 7618 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 7619 EndLoc); 7620 break; 7621 case OMPC_final: 7622 case OMPC_num_threads: 7623 case OMPC_safelen: 7624 case OMPC_simdlen: 7625 case OMPC_collapse: 7626 case OMPC_default: 7627 case OMPC_proc_bind: 7628 case OMPC_private: 7629 case OMPC_firstprivate: 7630 case OMPC_lastprivate: 7631 case OMPC_shared: 7632 case OMPC_reduction: 7633 case OMPC_task_reduction: 7634 case OMPC_linear: 7635 case OMPC_aligned: 7636 case OMPC_copyin: 7637 case OMPC_copyprivate: 7638 case OMPC_ordered: 7639 case OMPC_nowait: 7640 case OMPC_untied: 7641 case OMPC_mergeable: 7642 case OMPC_threadprivate: 7643 case OMPC_flush: 7644 case OMPC_read: 7645 case OMPC_write: 7646 case OMPC_update: 7647 case OMPC_capture: 7648 case OMPC_seq_cst: 7649 case OMPC_depend: 7650 case OMPC_device: 7651 case OMPC_threads: 7652 case OMPC_simd: 7653 case OMPC_map: 7654 case OMPC_num_teams: 7655 case OMPC_thread_limit: 7656 case OMPC_priority: 7657 case OMPC_grainsize: 7658 case OMPC_nogroup: 7659 case OMPC_num_tasks: 7660 case OMPC_hint: 7661 case OMPC_unknown: 7662 case OMPC_uniform: 7663 case OMPC_to: 7664 case OMPC_from: 7665 case OMPC_use_device_ptr: 7666 case OMPC_is_device_ptr: 7667 llvm_unreachable("Clause is not allowed."); 7668 } 7669 return Res; 7670 } 7671 7672 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 7673 OpenMPScheduleClauseModifier M2, 7674 SourceLocation M1Loc, SourceLocation M2Loc) { 7675 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 7676 SmallVector<unsigned, 2> Excluded; 7677 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 7678 Excluded.push_back(M2); 7679 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 7680 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 7681 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 7682 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 7683 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 7684 << getListOfPossibleValues(OMPC_schedule, 7685 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 7686 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 7687 Excluded) 7688 << getOpenMPClauseName(OMPC_schedule); 7689 return true; 7690 } 7691 return false; 7692 } 7693 7694 OMPClause *Sema::ActOnOpenMPScheduleClause( 7695 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 7696 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 7697 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 7698 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 7699 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 7700 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 7701 return nullptr; 7702 // OpenMP, 2.7.1, Loop Construct, Restrictions 7703 // Either the monotonic modifier or the nonmonotonic modifier can be specified 7704 // but not both. 7705 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 7706 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 7707 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 7708 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 7709 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 7710 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 7711 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 7712 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 7713 return nullptr; 7714 } 7715 if (Kind == OMPC_SCHEDULE_unknown) { 7716 std::string Values; 7717 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 7718 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 7719 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 7720 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 7721 Exclude); 7722 } else { 7723 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 7724 /*Last=*/OMPC_SCHEDULE_unknown); 7725 } 7726 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 7727 << Values << getOpenMPClauseName(OMPC_schedule); 7728 return nullptr; 7729 } 7730 // OpenMP, 2.7.1, Loop Construct, Restrictions 7731 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 7732 // schedule(guided). 7733 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 7734 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 7735 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 7736 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 7737 diag::err_omp_schedule_nonmonotonic_static); 7738 return nullptr; 7739 } 7740 Expr *ValExpr = ChunkSize; 7741 Stmt *HelperValStmt = nullptr; 7742 if (ChunkSize) { 7743 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 7744 !ChunkSize->isInstantiationDependent() && 7745 !ChunkSize->containsUnexpandedParameterPack()) { 7746 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 7747 ExprResult Val = 7748 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 7749 if (Val.isInvalid()) 7750 return nullptr; 7751 7752 ValExpr = Val.get(); 7753 7754 // OpenMP [2.7.1, Restrictions] 7755 // chunk_size must be a loop invariant integer expression with a positive 7756 // value. 7757 llvm::APSInt Result; 7758 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 7759 if (Result.isSigned() && !Result.isStrictlyPositive()) { 7760 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 7761 << "schedule" << 1 << ChunkSize->getSourceRange(); 7762 return nullptr; 7763 } 7764 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 7765 !CurContext->isDependentContext()) { 7766 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7767 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7768 HelperValStmt = buildPreInits(Context, Captures); 7769 } 7770 } 7771 } 7772 7773 return new (Context) 7774 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 7775 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 7776 } 7777 7778 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 7779 SourceLocation StartLoc, 7780 SourceLocation EndLoc) { 7781 OMPClause *Res = nullptr; 7782 switch (Kind) { 7783 case OMPC_ordered: 7784 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 7785 break; 7786 case OMPC_nowait: 7787 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 7788 break; 7789 case OMPC_untied: 7790 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 7791 break; 7792 case OMPC_mergeable: 7793 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 7794 break; 7795 case OMPC_read: 7796 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 7797 break; 7798 case OMPC_write: 7799 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 7800 break; 7801 case OMPC_update: 7802 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 7803 break; 7804 case OMPC_capture: 7805 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 7806 break; 7807 case OMPC_seq_cst: 7808 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 7809 break; 7810 case OMPC_threads: 7811 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 7812 break; 7813 case OMPC_simd: 7814 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 7815 break; 7816 case OMPC_nogroup: 7817 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 7818 break; 7819 case OMPC_if: 7820 case OMPC_final: 7821 case OMPC_num_threads: 7822 case OMPC_safelen: 7823 case OMPC_simdlen: 7824 case OMPC_collapse: 7825 case OMPC_schedule: 7826 case OMPC_private: 7827 case OMPC_firstprivate: 7828 case OMPC_lastprivate: 7829 case OMPC_shared: 7830 case OMPC_reduction: 7831 case OMPC_task_reduction: 7832 case OMPC_linear: 7833 case OMPC_aligned: 7834 case OMPC_copyin: 7835 case OMPC_copyprivate: 7836 case OMPC_default: 7837 case OMPC_proc_bind: 7838 case OMPC_threadprivate: 7839 case OMPC_flush: 7840 case OMPC_depend: 7841 case OMPC_device: 7842 case OMPC_map: 7843 case OMPC_num_teams: 7844 case OMPC_thread_limit: 7845 case OMPC_priority: 7846 case OMPC_grainsize: 7847 case OMPC_num_tasks: 7848 case OMPC_hint: 7849 case OMPC_dist_schedule: 7850 case OMPC_defaultmap: 7851 case OMPC_unknown: 7852 case OMPC_uniform: 7853 case OMPC_to: 7854 case OMPC_from: 7855 case OMPC_use_device_ptr: 7856 case OMPC_is_device_ptr: 7857 llvm_unreachable("Clause is not allowed."); 7858 } 7859 return Res; 7860 } 7861 7862 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 7863 SourceLocation EndLoc) { 7864 DSAStack->setNowaitRegion(); 7865 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 7866 } 7867 7868 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 7869 SourceLocation EndLoc) { 7870 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 7871 } 7872 7873 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 7874 SourceLocation EndLoc) { 7875 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 7876 } 7877 7878 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 7879 SourceLocation EndLoc) { 7880 return new (Context) OMPReadClause(StartLoc, EndLoc); 7881 } 7882 7883 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 7884 SourceLocation EndLoc) { 7885 return new (Context) OMPWriteClause(StartLoc, EndLoc); 7886 } 7887 7888 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 7889 SourceLocation EndLoc) { 7890 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 7891 } 7892 7893 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 7894 SourceLocation EndLoc) { 7895 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 7896 } 7897 7898 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 7899 SourceLocation EndLoc) { 7900 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 7901 } 7902 7903 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 7904 SourceLocation EndLoc) { 7905 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 7906 } 7907 7908 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 7909 SourceLocation EndLoc) { 7910 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 7911 } 7912 7913 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 7914 SourceLocation EndLoc) { 7915 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 7916 } 7917 7918 OMPClause *Sema::ActOnOpenMPVarListClause( 7919 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 7920 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 7921 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 7922 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind, 7923 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier, 7924 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 7925 SourceLocation DepLinMapLoc) { 7926 OMPClause *Res = nullptr; 7927 switch (Kind) { 7928 case OMPC_private: 7929 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7930 break; 7931 case OMPC_firstprivate: 7932 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7933 break; 7934 case OMPC_lastprivate: 7935 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7936 break; 7937 case OMPC_shared: 7938 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 7939 break; 7940 case OMPC_reduction: 7941 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 7942 EndLoc, ReductionIdScopeSpec, ReductionId); 7943 break; 7944 case OMPC_task_reduction: 7945 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 7946 EndLoc, ReductionIdScopeSpec, 7947 ReductionId); 7948 break; 7949 case OMPC_linear: 7950 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 7951 LinKind, DepLinMapLoc, ColonLoc, EndLoc); 7952 break; 7953 case OMPC_aligned: 7954 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 7955 ColonLoc, EndLoc); 7956 break; 7957 case OMPC_copyin: 7958 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 7959 break; 7960 case OMPC_copyprivate: 7961 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7962 break; 7963 case OMPC_flush: 7964 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 7965 break; 7966 case OMPC_depend: 7967 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, 7968 StartLoc, LParenLoc, EndLoc); 7969 break; 7970 case OMPC_map: 7971 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit, 7972 DepLinMapLoc, ColonLoc, VarList, StartLoc, 7973 LParenLoc, EndLoc); 7974 break; 7975 case OMPC_to: 7976 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc); 7977 break; 7978 case OMPC_from: 7979 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc); 7980 break; 7981 case OMPC_use_device_ptr: 7982 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 7983 break; 7984 case OMPC_is_device_ptr: 7985 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 7986 break; 7987 case OMPC_if: 7988 case OMPC_final: 7989 case OMPC_num_threads: 7990 case OMPC_safelen: 7991 case OMPC_simdlen: 7992 case OMPC_collapse: 7993 case OMPC_default: 7994 case OMPC_proc_bind: 7995 case OMPC_schedule: 7996 case OMPC_ordered: 7997 case OMPC_nowait: 7998 case OMPC_untied: 7999 case OMPC_mergeable: 8000 case OMPC_threadprivate: 8001 case OMPC_read: 8002 case OMPC_write: 8003 case OMPC_update: 8004 case OMPC_capture: 8005 case OMPC_seq_cst: 8006 case OMPC_device: 8007 case OMPC_threads: 8008 case OMPC_simd: 8009 case OMPC_num_teams: 8010 case OMPC_thread_limit: 8011 case OMPC_priority: 8012 case OMPC_grainsize: 8013 case OMPC_nogroup: 8014 case OMPC_num_tasks: 8015 case OMPC_hint: 8016 case OMPC_dist_schedule: 8017 case OMPC_defaultmap: 8018 case OMPC_unknown: 8019 case OMPC_uniform: 8020 llvm_unreachable("Clause is not allowed."); 8021 } 8022 return Res; 8023 } 8024 8025 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 8026 ExprObjectKind OK, SourceLocation Loc) { 8027 ExprResult Res = BuildDeclRefExpr( 8028 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 8029 if (!Res.isUsable()) 8030 return ExprError(); 8031 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 8032 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 8033 if (!Res.isUsable()) 8034 return ExprError(); 8035 } 8036 if (VK != VK_LValue && Res.get()->isGLValue()) { 8037 Res = DefaultLvalueConversion(Res.get()); 8038 if (!Res.isUsable()) 8039 return ExprError(); 8040 } 8041 return Res; 8042 } 8043 8044 static std::pair<ValueDecl *, bool> 8045 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 8046 SourceRange &ERange, bool AllowArraySection = false) { 8047 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 8048 RefExpr->containsUnexpandedParameterPack()) 8049 return std::make_pair(nullptr, true); 8050 8051 // OpenMP [3.1, C/C++] 8052 // A list item is a variable name. 8053 // OpenMP [2.9.3.3, Restrictions, p.1] 8054 // A variable that is part of another variable (as an array or 8055 // structure element) cannot appear in a private clause. 8056 RefExpr = RefExpr->IgnoreParens(); 8057 enum { 8058 NoArrayExpr = -1, 8059 ArraySubscript = 0, 8060 OMPArraySection = 1 8061 } IsArrayExpr = NoArrayExpr; 8062 if (AllowArraySection) { 8063 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 8064 auto *Base = ASE->getBase()->IgnoreParenImpCasts(); 8065 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 8066 Base = TempASE->getBase()->IgnoreParenImpCasts(); 8067 RefExpr = Base; 8068 IsArrayExpr = ArraySubscript; 8069 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 8070 auto *Base = OASE->getBase()->IgnoreParenImpCasts(); 8071 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 8072 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 8073 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 8074 Base = TempASE->getBase()->IgnoreParenImpCasts(); 8075 RefExpr = Base; 8076 IsArrayExpr = OMPArraySection; 8077 } 8078 } 8079 ELoc = RefExpr->getExprLoc(); 8080 ERange = RefExpr->getSourceRange(); 8081 RefExpr = RefExpr->IgnoreParenImpCasts(); 8082 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 8083 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 8084 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 8085 (S.getCurrentThisType().isNull() || !ME || 8086 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 8087 !isa<FieldDecl>(ME->getMemberDecl()))) { 8088 if (IsArrayExpr != NoArrayExpr) 8089 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 8090 << ERange; 8091 else { 8092 S.Diag(ELoc, 8093 AllowArraySection 8094 ? diag::err_omp_expected_var_name_member_expr_or_array_item 8095 : diag::err_omp_expected_var_name_member_expr) 8096 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 8097 } 8098 return std::make_pair(nullptr, false); 8099 } 8100 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false); 8101 } 8102 8103 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 8104 SourceLocation StartLoc, 8105 SourceLocation LParenLoc, 8106 SourceLocation EndLoc) { 8107 SmallVector<Expr *, 8> Vars; 8108 SmallVector<Expr *, 8> PrivateCopies; 8109 for (auto &RefExpr : VarList) { 8110 assert(RefExpr && "NULL expr in OpenMP private clause."); 8111 SourceLocation ELoc; 8112 SourceRange ERange; 8113 Expr *SimpleRefExpr = RefExpr; 8114 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8115 if (Res.second) { 8116 // It will be analyzed later. 8117 Vars.push_back(RefExpr); 8118 PrivateCopies.push_back(nullptr); 8119 } 8120 ValueDecl *D = Res.first; 8121 if (!D) 8122 continue; 8123 8124 QualType Type = D->getType(); 8125 auto *VD = dyn_cast<VarDecl>(D); 8126 8127 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8128 // A variable that appears in a private clause must not have an incomplete 8129 // type or a reference type. 8130 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 8131 continue; 8132 Type = Type.getNonReferenceType(); 8133 8134 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8135 // in a Construct] 8136 // Variables with the predetermined data-sharing attributes may not be 8137 // listed in data-sharing attributes clauses, except for the cases 8138 // listed below. For these exceptions only, listing a predetermined 8139 // variable in a data-sharing attribute clause is allowed and overrides 8140 // the variable's predetermined data-sharing attributes. 8141 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8142 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 8143 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 8144 << getOpenMPClauseName(OMPC_private); 8145 ReportOriginalDSA(*this, DSAStack, D, DVar); 8146 continue; 8147 } 8148 8149 auto CurrDir = DSAStack->getCurrentDirective(); 8150 // Variably modified types are not supported for tasks. 8151 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 8152 isOpenMPTaskingDirective(CurrDir)) { 8153 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 8154 << getOpenMPClauseName(OMPC_private) << Type 8155 << getOpenMPDirectiveName(CurrDir); 8156 bool IsDecl = 8157 !VD || 8158 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8159 Diag(D->getLocation(), 8160 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8161 << D; 8162 continue; 8163 } 8164 8165 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 8166 // A list item cannot appear in both a map clause and a data-sharing 8167 // attribute clause on the same construct 8168 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || 8169 CurrDir == OMPD_target_teams || 8170 CurrDir == OMPD_target_teams_distribute || 8171 CurrDir == OMPD_target_teams_distribute_parallel_for || 8172 CurrDir == OMPD_target_teams_distribute_parallel_for_simd || 8173 CurrDir == OMPD_target_teams_distribute_simd || 8174 CurrDir == OMPD_target_parallel_for_simd || 8175 CurrDir == OMPD_target_parallel_for) { 8176 OpenMPClauseKind ConflictKind; 8177 if (DSAStack->checkMappableExprComponentListsForDecl( 8178 VD, /*CurrentRegionOnly=*/true, 8179 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 8180 OpenMPClauseKind WhereFoundClauseKind) -> bool { 8181 ConflictKind = WhereFoundClauseKind; 8182 return true; 8183 })) { 8184 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 8185 << getOpenMPClauseName(OMPC_private) 8186 << getOpenMPClauseName(ConflictKind) 8187 << getOpenMPDirectiveName(CurrDir); 8188 ReportOriginalDSA(*this, DSAStack, D, DVar); 8189 continue; 8190 } 8191 } 8192 8193 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 8194 // A variable of class type (or array thereof) that appears in a private 8195 // clause requires an accessible, unambiguous default constructor for the 8196 // class type. 8197 // Generate helper private variable and initialize it with the default 8198 // value. The address of the original variable is replaced by the address of 8199 // the new private variable in CodeGen. This new variable is not added to 8200 // IdResolver, so the code in the OpenMP region uses original variable for 8201 // proper diagnostics. 8202 Type = Type.getUnqualifiedType(); 8203 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 8204 D->hasAttrs() ? &D->getAttrs() : nullptr); 8205 ActOnUninitializedDecl(VDPrivate); 8206 if (VDPrivate->isInvalidDecl()) 8207 continue; 8208 auto VDPrivateRefExpr = buildDeclRefExpr( 8209 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 8210 8211 DeclRefExpr *Ref = nullptr; 8212 if (!VD && !CurContext->isDependentContext()) 8213 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 8214 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 8215 Vars.push_back((VD || CurContext->isDependentContext()) 8216 ? RefExpr->IgnoreParens() 8217 : Ref); 8218 PrivateCopies.push_back(VDPrivateRefExpr); 8219 } 8220 8221 if (Vars.empty()) 8222 return nullptr; 8223 8224 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 8225 PrivateCopies); 8226 } 8227 8228 namespace { 8229 class DiagsUninitializedSeveretyRAII { 8230 private: 8231 DiagnosticsEngine &Diags; 8232 SourceLocation SavedLoc; 8233 bool IsIgnored; 8234 8235 public: 8236 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 8237 bool IsIgnored) 8238 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 8239 if (!IsIgnored) { 8240 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 8241 /*Map*/ diag::Severity::Ignored, Loc); 8242 } 8243 } 8244 ~DiagsUninitializedSeveretyRAII() { 8245 if (!IsIgnored) 8246 Diags.popMappings(SavedLoc); 8247 } 8248 }; 8249 } 8250 8251 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 8252 SourceLocation StartLoc, 8253 SourceLocation LParenLoc, 8254 SourceLocation EndLoc) { 8255 SmallVector<Expr *, 8> Vars; 8256 SmallVector<Expr *, 8> PrivateCopies; 8257 SmallVector<Expr *, 8> Inits; 8258 SmallVector<Decl *, 4> ExprCaptures; 8259 bool IsImplicitClause = 8260 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 8261 auto ImplicitClauseLoc = DSAStack->getConstructLoc(); 8262 8263 for (auto &RefExpr : VarList) { 8264 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 8265 SourceLocation ELoc; 8266 SourceRange ERange; 8267 Expr *SimpleRefExpr = RefExpr; 8268 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8269 if (Res.second) { 8270 // It will be analyzed later. 8271 Vars.push_back(RefExpr); 8272 PrivateCopies.push_back(nullptr); 8273 Inits.push_back(nullptr); 8274 } 8275 ValueDecl *D = Res.first; 8276 if (!D) 8277 continue; 8278 8279 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 8280 QualType Type = D->getType(); 8281 auto *VD = dyn_cast<VarDecl>(D); 8282 8283 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8284 // A variable that appears in a private clause must not have an incomplete 8285 // type or a reference type. 8286 if (RequireCompleteType(ELoc, Type, 8287 diag::err_omp_firstprivate_incomplete_type)) 8288 continue; 8289 Type = Type.getNonReferenceType(); 8290 8291 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 8292 // A variable of class type (or array thereof) that appears in a private 8293 // clause requires an accessible, unambiguous copy constructor for the 8294 // class type. 8295 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 8296 8297 // If an implicit firstprivate variable found it was checked already. 8298 DSAStackTy::DSAVarData TopDVar; 8299 if (!IsImplicitClause) { 8300 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8301 TopDVar = DVar; 8302 bool IsConstant = ElemType.isConstant(Context); 8303 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 8304 // A list item that specifies a given variable may not appear in more 8305 // than one clause on the same directive, except that a variable may be 8306 // specified in both firstprivate and lastprivate clauses. 8307 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 8308 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) { 8309 Diag(ELoc, diag::err_omp_wrong_dsa) 8310 << getOpenMPClauseName(DVar.CKind) 8311 << getOpenMPClauseName(OMPC_firstprivate); 8312 ReportOriginalDSA(*this, DSAStack, D, DVar); 8313 continue; 8314 } 8315 8316 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8317 // in a Construct] 8318 // Variables with the predetermined data-sharing attributes may not be 8319 // listed in data-sharing attributes clauses, except for the cases 8320 // listed below. For these exceptions only, listing a predetermined 8321 // variable in a data-sharing attribute clause is allowed and overrides 8322 // the variable's predetermined data-sharing attributes. 8323 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8324 // in a Construct, C/C++, p.2] 8325 // Variables with const-qualified type having no mutable member may be 8326 // listed in a firstprivate clause, even if they are static data members. 8327 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 8328 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 8329 Diag(ELoc, diag::err_omp_wrong_dsa) 8330 << getOpenMPClauseName(DVar.CKind) 8331 << getOpenMPClauseName(OMPC_firstprivate); 8332 ReportOriginalDSA(*this, DSAStack, D, DVar); 8333 continue; 8334 } 8335 8336 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8337 // OpenMP [2.9.3.4, Restrictions, p.2] 8338 // A list item that is private within a parallel region must not appear 8339 // in a firstprivate clause on a worksharing construct if any of the 8340 // worksharing regions arising from the worksharing construct ever bind 8341 // to any of the parallel regions arising from the parallel construct. 8342 if (isOpenMPWorksharingDirective(CurrDir) && 8343 !isOpenMPParallelDirective(CurrDir) && 8344 !isOpenMPTeamsDirective(CurrDir)) { 8345 DVar = DSAStack->getImplicitDSA(D, true); 8346 if (DVar.CKind != OMPC_shared && 8347 (isOpenMPParallelDirective(DVar.DKind) || 8348 DVar.DKind == OMPD_unknown)) { 8349 Diag(ELoc, diag::err_omp_required_access) 8350 << getOpenMPClauseName(OMPC_firstprivate) 8351 << getOpenMPClauseName(OMPC_shared); 8352 ReportOriginalDSA(*this, DSAStack, D, DVar); 8353 continue; 8354 } 8355 } 8356 // OpenMP [2.9.3.4, Restrictions, p.3] 8357 // A list item that appears in a reduction clause of a parallel construct 8358 // must not appear in a firstprivate clause on a worksharing or task 8359 // construct if any of the worksharing or task regions arising from the 8360 // worksharing or task construct ever bind to any of the parallel regions 8361 // arising from the parallel construct. 8362 // OpenMP [2.9.3.4, Restrictions, p.4] 8363 // A list item that appears in a reduction clause in worksharing 8364 // construct must not appear in a firstprivate clause in a task construct 8365 // encountered during execution of any of the worksharing regions arising 8366 // from the worksharing construct. 8367 if (isOpenMPTaskingDirective(CurrDir)) { 8368 DVar = DSAStack->hasInnermostDSA( 8369 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 8370 [](OpenMPDirectiveKind K) -> bool { 8371 return isOpenMPParallelDirective(K) || 8372 isOpenMPWorksharingDirective(K); 8373 }, 8374 false); 8375 if (DVar.CKind == OMPC_reduction && 8376 (isOpenMPParallelDirective(DVar.DKind) || 8377 isOpenMPWorksharingDirective(DVar.DKind))) { 8378 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 8379 << getOpenMPDirectiveName(DVar.DKind); 8380 ReportOriginalDSA(*this, DSAStack, D, DVar); 8381 continue; 8382 } 8383 } 8384 8385 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 8386 // A list item that is private within a teams region must not appear in a 8387 // firstprivate clause on a distribute construct if any of the distribute 8388 // regions arising from the distribute construct ever bind to any of the 8389 // teams regions arising from the teams construct. 8390 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 8391 // A list item that appears in a reduction clause of a teams construct 8392 // must not appear in a firstprivate clause on a distribute construct if 8393 // any of the distribute regions arising from the distribute construct 8394 // ever bind to any of the teams regions arising from the teams construct. 8395 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 8396 // A list item may appear in a firstprivate or lastprivate clause but not 8397 // both. 8398 if (CurrDir == OMPD_distribute) { 8399 DVar = DSAStack->hasInnermostDSA( 8400 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; }, 8401 [](OpenMPDirectiveKind K) -> bool { 8402 return isOpenMPTeamsDirective(K); 8403 }, 8404 false); 8405 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) { 8406 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams); 8407 ReportOriginalDSA(*this, DSAStack, D, DVar); 8408 continue; 8409 } 8410 DVar = DSAStack->hasInnermostDSA( 8411 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 8412 [](OpenMPDirectiveKind K) -> bool { 8413 return isOpenMPTeamsDirective(K); 8414 }, 8415 false); 8416 if (DVar.CKind == OMPC_reduction && 8417 isOpenMPTeamsDirective(DVar.DKind)) { 8418 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction); 8419 ReportOriginalDSA(*this, DSAStack, D, DVar); 8420 continue; 8421 } 8422 DVar = DSAStack->getTopDSA(D, false); 8423 if (DVar.CKind == OMPC_lastprivate) { 8424 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute); 8425 ReportOriginalDSA(*this, DSAStack, D, DVar); 8426 continue; 8427 } 8428 } 8429 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 8430 // A list item cannot appear in both a map clause and a data-sharing 8431 // attribute clause on the same construct 8432 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || 8433 CurrDir == OMPD_target_teams || 8434 CurrDir == OMPD_target_teams_distribute || 8435 CurrDir == OMPD_target_teams_distribute_parallel_for || 8436 CurrDir == OMPD_target_teams_distribute_parallel_for_simd || 8437 CurrDir == OMPD_target_teams_distribute_simd || 8438 CurrDir == OMPD_target_parallel_for_simd || 8439 CurrDir == OMPD_target_parallel_for) { 8440 OpenMPClauseKind ConflictKind; 8441 if (DSAStack->checkMappableExprComponentListsForDecl( 8442 VD, /*CurrentRegionOnly=*/true, 8443 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 8444 OpenMPClauseKind WhereFoundClauseKind) -> bool { 8445 ConflictKind = WhereFoundClauseKind; 8446 return true; 8447 })) { 8448 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 8449 << getOpenMPClauseName(OMPC_firstprivate) 8450 << getOpenMPClauseName(ConflictKind) 8451 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8452 ReportOriginalDSA(*this, DSAStack, D, DVar); 8453 continue; 8454 } 8455 } 8456 } 8457 8458 // Variably modified types are not supported for tasks. 8459 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 8460 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 8461 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 8462 << getOpenMPClauseName(OMPC_firstprivate) << Type 8463 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8464 bool IsDecl = 8465 !VD || 8466 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8467 Diag(D->getLocation(), 8468 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8469 << D; 8470 continue; 8471 } 8472 8473 Type = Type.getUnqualifiedType(); 8474 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 8475 D->hasAttrs() ? &D->getAttrs() : nullptr); 8476 // Generate helper private variable and initialize it with the value of the 8477 // original variable. The address of the original variable is replaced by 8478 // the address of the new private variable in the CodeGen. This new variable 8479 // is not added to IdResolver, so the code in the OpenMP region uses 8480 // original variable for proper diagnostics and variable capturing. 8481 Expr *VDInitRefExpr = nullptr; 8482 // For arrays generate initializer for single element and replace it by the 8483 // original array element in CodeGen. 8484 if (Type->isArrayType()) { 8485 auto VDInit = 8486 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 8487 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 8488 auto Init = DefaultLvalueConversion(VDInitRefExpr).get(); 8489 ElemType = ElemType.getUnqualifiedType(); 8490 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 8491 ".firstprivate.temp"); 8492 InitializedEntity Entity = 8493 InitializedEntity::InitializeVariable(VDInitTemp); 8494 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 8495 8496 InitializationSequence InitSeq(*this, Entity, Kind, Init); 8497 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 8498 if (Result.isInvalid()) 8499 VDPrivate->setInvalidDecl(); 8500 else 8501 VDPrivate->setInit(Result.getAs<Expr>()); 8502 // Remove temp variable declaration. 8503 Context.Deallocate(VDInitTemp); 8504 } else { 8505 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 8506 ".firstprivate.temp"); 8507 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 8508 RefExpr->getExprLoc()); 8509 AddInitializerToDecl(VDPrivate, 8510 DefaultLvalueConversion(VDInitRefExpr).get(), 8511 /*DirectInit=*/false); 8512 } 8513 if (VDPrivate->isInvalidDecl()) { 8514 if (IsImplicitClause) { 8515 Diag(RefExpr->getExprLoc(), 8516 diag::note_omp_task_predetermined_firstprivate_here); 8517 } 8518 continue; 8519 } 8520 CurContext->addDecl(VDPrivate); 8521 auto VDPrivateRefExpr = buildDeclRefExpr( 8522 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 8523 RefExpr->getExprLoc()); 8524 DeclRefExpr *Ref = nullptr; 8525 if (!VD && !CurContext->isDependentContext()) { 8526 if (TopDVar.CKind == OMPC_lastprivate) 8527 Ref = TopDVar.PrivateCopy; 8528 else { 8529 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 8530 if (!IsOpenMPCapturedDecl(D)) 8531 ExprCaptures.push_back(Ref->getDecl()); 8532 } 8533 } 8534 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 8535 Vars.push_back((VD || CurContext->isDependentContext()) 8536 ? RefExpr->IgnoreParens() 8537 : Ref); 8538 PrivateCopies.push_back(VDPrivateRefExpr); 8539 Inits.push_back(VDInitRefExpr); 8540 } 8541 8542 if (Vars.empty()) 8543 return nullptr; 8544 8545 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 8546 Vars, PrivateCopies, Inits, 8547 buildPreInits(Context, ExprCaptures)); 8548 } 8549 8550 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 8551 SourceLocation StartLoc, 8552 SourceLocation LParenLoc, 8553 SourceLocation EndLoc) { 8554 SmallVector<Expr *, 8> Vars; 8555 SmallVector<Expr *, 8> SrcExprs; 8556 SmallVector<Expr *, 8> DstExprs; 8557 SmallVector<Expr *, 8> AssignmentOps; 8558 SmallVector<Decl *, 4> ExprCaptures; 8559 SmallVector<Expr *, 4> ExprPostUpdates; 8560 for (auto &RefExpr : VarList) { 8561 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 8562 SourceLocation ELoc; 8563 SourceRange ERange; 8564 Expr *SimpleRefExpr = RefExpr; 8565 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8566 if (Res.second) { 8567 // It will be analyzed later. 8568 Vars.push_back(RefExpr); 8569 SrcExprs.push_back(nullptr); 8570 DstExprs.push_back(nullptr); 8571 AssignmentOps.push_back(nullptr); 8572 } 8573 ValueDecl *D = Res.first; 8574 if (!D) 8575 continue; 8576 8577 QualType Type = D->getType(); 8578 auto *VD = dyn_cast<VarDecl>(D); 8579 8580 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 8581 // A variable that appears in a lastprivate clause must not have an 8582 // incomplete type or a reference type. 8583 if (RequireCompleteType(ELoc, Type, 8584 diag::err_omp_lastprivate_incomplete_type)) 8585 continue; 8586 Type = Type.getNonReferenceType(); 8587 8588 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 8589 // in a Construct] 8590 // Variables with the predetermined data-sharing attributes may not be 8591 // listed in data-sharing attributes clauses, except for the cases 8592 // listed below. 8593 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8594 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 8595 DVar.CKind != OMPC_firstprivate && 8596 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 8597 Diag(ELoc, diag::err_omp_wrong_dsa) 8598 << getOpenMPClauseName(DVar.CKind) 8599 << getOpenMPClauseName(OMPC_lastprivate); 8600 ReportOriginalDSA(*this, DSAStack, D, DVar); 8601 continue; 8602 } 8603 8604 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8605 // OpenMP [2.14.3.5, Restrictions, p.2] 8606 // A list item that is private within a parallel region, or that appears in 8607 // the reduction clause of a parallel construct, must not appear in a 8608 // lastprivate clause on a worksharing construct if any of the corresponding 8609 // worksharing regions ever binds to any of the corresponding parallel 8610 // regions. 8611 DSAStackTy::DSAVarData TopDVar = DVar; 8612 if (isOpenMPWorksharingDirective(CurrDir) && 8613 !isOpenMPParallelDirective(CurrDir) && 8614 !isOpenMPTeamsDirective(CurrDir)) { 8615 DVar = DSAStack->getImplicitDSA(D, true); 8616 if (DVar.CKind != OMPC_shared) { 8617 Diag(ELoc, diag::err_omp_required_access) 8618 << getOpenMPClauseName(OMPC_lastprivate) 8619 << getOpenMPClauseName(OMPC_shared); 8620 ReportOriginalDSA(*this, DSAStack, D, DVar); 8621 continue; 8622 } 8623 } 8624 8625 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 8626 // A list item may appear in a firstprivate or lastprivate clause but not 8627 // both. 8628 if (CurrDir == OMPD_distribute) { 8629 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8630 if (DVar.CKind == OMPC_firstprivate) { 8631 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute); 8632 ReportOriginalDSA(*this, DSAStack, D, DVar); 8633 continue; 8634 } 8635 } 8636 8637 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 8638 // A variable of class type (or array thereof) that appears in a 8639 // lastprivate clause requires an accessible, unambiguous default 8640 // constructor for the class type, unless the list item is also specified 8641 // in a firstprivate clause. 8642 // A variable of class type (or array thereof) that appears in a 8643 // lastprivate clause requires an accessible, unambiguous copy assignment 8644 // operator for the class type. 8645 Type = Context.getBaseElementType(Type).getNonReferenceType(); 8646 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(), 8647 Type.getUnqualifiedType(), ".lastprivate.src", 8648 D->hasAttrs() ? &D->getAttrs() : nullptr); 8649 auto *PseudoSrcExpr = 8650 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 8651 auto *DstVD = 8652 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 8653 D->hasAttrs() ? &D->getAttrs() : nullptr); 8654 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 8655 // For arrays generate assignment operation for single element and replace 8656 // it by the original array element in CodeGen. 8657 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 8658 PseudoDstExpr, PseudoSrcExpr); 8659 if (AssignmentOp.isInvalid()) 8660 continue; 8661 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 8662 /*DiscardedValue=*/true); 8663 if (AssignmentOp.isInvalid()) 8664 continue; 8665 8666 DeclRefExpr *Ref = nullptr; 8667 if (!VD && !CurContext->isDependentContext()) { 8668 if (TopDVar.CKind == OMPC_firstprivate) 8669 Ref = TopDVar.PrivateCopy; 8670 else { 8671 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 8672 if (!IsOpenMPCapturedDecl(D)) 8673 ExprCaptures.push_back(Ref->getDecl()); 8674 } 8675 if (TopDVar.CKind == OMPC_firstprivate || 8676 (!IsOpenMPCapturedDecl(D) && 8677 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 8678 ExprResult RefRes = DefaultLvalueConversion(Ref); 8679 if (!RefRes.isUsable()) 8680 continue; 8681 ExprResult PostUpdateRes = 8682 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 8683 RefRes.get()); 8684 if (!PostUpdateRes.isUsable()) 8685 continue; 8686 ExprPostUpdates.push_back( 8687 IgnoredValueConversions(PostUpdateRes.get()).get()); 8688 } 8689 } 8690 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 8691 Vars.push_back((VD || CurContext->isDependentContext()) 8692 ? RefExpr->IgnoreParens() 8693 : Ref); 8694 SrcExprs.push_back(PseudoSrcExpr); 8695 DstExprs.push_back(PseudoDstExpr); 8696 AssignmentOps.push_back(AssignmentOp.get()); 8697 } 8698 8699 if (Vars.empty()) 8700 return nullptr; 8701 8702 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 8703 Vars, SrcExprs, DstExprs, AssignmentOps, 8704 buildPreInits(Context, ExprCaptures), 8705 buildPostUpdate(*this, ExprPostUpdates)); 8706 } 8707 8708 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 8709 SourceLocation StartLoc, 8710 SourceLocation LParenLoc, 8711 SourceLocation EndLoc) { 8712 SmallVector<Expr *, 8> Vars; 8713 for (auto &RefExpr : VarList) { 8714 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 8715 SourceLocation ELoc; 8716 SourceRange ERange; 8717 Expr *SimpleRefExpr = RefExpr; 8718 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8719 if (Res.second) { 8720 // It will be analyzed later. 8721 Vars.push_back(RefExpr); 8722 } 8723 ValueDecl *D = Res.first; 8724 if (!D) 8725 continue; 8726 8727 auto *VD = dyn_cast<VarDecl>(D); 8728 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8729 // in a Construct] 8730 // Variables with the predetermined data-sharing attributes may not be 8731 // listed in data-sharing attributes clauses, except for the cases 8732 // listed below. For these exceptions only, listing a predetermined 8733 // variable in a data-sharing attribute clause is allowed and overrides 8734 // the variable's predetermined data-sharing attributes. 8735 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8736 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 8737 DVar.RefExpr) { 8738 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 8739 << getOpenMPClauseName(OMPC_shared); 8740 ReportOriginalDSA(*this, DSAStack, D, DVar); 8741 continue; 8742 } 8743 8744 DeclRefExpr *Ref = nullptr; 8745 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 8746 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 8747 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 8748 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 8749 ? RefExpr->IgnoreParens() 8750 : Ref); 8751 } 8752 8753 if (Vars.empty()) 8754 return nullptr; 8755 8756 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 8757 } 8758 8759 namespace { 8760 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 8761 DSAStackTy *Stack; 8762 8763 public: 8764 bool VisitDeclRefExpr(DeclRefExpr *E) { 8765 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { 8766 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false); 8767 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 8768 return false; 8769 if (DVar.CKind != OMPC_unknown) 8770 return true; 8771 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 8772 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 8773 false); 8774 if (DVarPrivate.CKind != OMPC_unknown) 8775 return true; 8776 return false; 8777 } 8778 return false; 8779 } 8780 bool VisitStmt(Stmt *S) { 8781 for (auto Child : S->children()) { 8782 if (Child && Visit(Child)) 8783 return true; 8784 } 8785 return false; 8786 } 8787 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 8788 }; 8789 } // namespace 8790 8791 namespace { 8792 // Transform MemberExpression for specified FieldDecl of current class to 8793 // DeclRefExpr to specified OMPCapturedExprDecl. 8794 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 8795 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 8796 ValueDecl *Field; 8797 DeclRefExpr *CapturedExpr; 8798 8799 public: 8800 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 8801 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 8802 8803 ExprResult TransformMemberExpr(MemberExpr *E) { 8804 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 8805 E->getMemberDecl() == Field) { 8806 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 8807 return CapturedExpr; 8808 } 8809 return BaseTransform::TransformMemberExpr(E); 8810 } 8811 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 8812 }; 8813 } // namespace 8814 8815 template <typename T> 8816 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups, 8817 const llvm::function_ref<T(ValueDecl *)> &Gen) { 8818 for (auto &Set : Lookups) { 8819 for (auto *D : Set) { 8820 if (auto Res = Gen(cast<ValueDecl>(D))) 8821 return Res; 8822 } 8823 } 8824 return T(); 8825 } 8826 8827 static ExprResult 8828 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 8829 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 8830 const DeclarationNameInfo &ReductionId, QualType Ty, 8831 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 8832 if (ReductionIdScopeSpec.isInvalid()) 8833 return ExprError(); 8834 SmallVector<UnresolvedSet<8>, 4> Lookups; 8835 if (S) { 8836 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 8837 Lookup.suppressDiagnostics(); 8838 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 8839 auto *D = Lookup.getRepresentativeDecl(); 8840 do { 8841 S = S->getParent(); 8842 } while (S && !S->isDeclScope(D)); 8843 if (S) 8844 S = S->getParent(); 8845 Lookups.push_back(UnresolvedSet<8>()); 8846 Lookups.back().append(Lookup.begin(), Lookup.end()); 8847 Lookup.clear(); 8848 } 8849 } else if (auto *ULE = 8850 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 8851 Lookups.push_back(UnresolvedSet<8>()); 8852 Decl *PrevD = nullptr; 8853 for (auto *D : ULE->decls()) { 8854 if (D == PrevD) 8855 Lookups.push_back(UnresolvedSet<8>()); 8856 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D)) 8857 Lookups.back().addDecl(DRD); 8858 PrevD = D; 8859 } 8860 } 8861 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || 8862 Ty->isInstantiationDependentType() || 8863 Ty->containsUnexpandedParameterPack() || 8864 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool { 8865 return !D->isInvalidDecl() && 8866 (D->getType()->isDependentType() || 8867 D->getType()->isInstantiationDependentType() || 8868 D->getType()->containsUnexpandedParameterPack()); 8869 })) { 8870 UnresolvedSet<8> ResSet; 8871 for (auto &Set : Lookups) { 8872 ResSet.append(Set.begin(), Set.end()); 8873 // The last item marks the end of all declarations at the specified scope. 8874 ResSet.addDecl(Set[Set.size() - 1]); 8875 } 8876 return UnresolvedLookupExpr::Create( 8877 SemaRef.Context, /*NamingClass=*/nullptr, 8878 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 8879 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 8880 } 8881 if (auto *VD = filterLookupForUDR<ValueDecl *>( 8882 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 8883 if (!D->isInvalidDecl() && 8884 SemaRef.Context.hasSameType(D->getType(), Ty)) 8885 return D; 8886 return nullptr; 8887 })) 8888 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 8889 if (auto *VD = filterLookupForUDR<ValueDecl *>( 8890 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 8891 if (!D->isInvalidDecl() && 8892 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 8893 !Ty.isMoreQualifiedThan(D->getType())) 8894 return D; 8895 return nullptr; 8896 })) { 8897 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 8898 /*DetectVirtual=*/false); 8899 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 8900 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 8901 VD->getType().getUnqualifiedType()))) { 8902 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(), 8903 /*DiagID=*/0) != 8904 Sema::AR_inaccessible) { 8905 SemaRef.BuildBasePathArray(Paths, BasePath); 8906 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 8907 } 8908 } 8909 } 8910 } 8911 if (ReductionIdScopeSpec.isSet()) { 8912 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range; 8913 return ExprError(); 8914 } 8915 return ExprEmpty(); 8916 } 8917 8918 namespace { 8919 /// Data for the reduction-based clauses. 8920 struct ReductionData { 8921 /// List of original reduction items. 8922 SmallVector<Expr *, 8> Vars; 8923 /// List of private copies of the reduction items. 8924 SmallVector<Expr *, 8> Privates; 8925 /// LHS expressions for the reduction_op expressions. 8926 SmallVector<Expr *, 8> LHSs; 8927 /// RHS expressions for the reduction_op expressions. 8928 SmallVector<Expr *, 8> RHSs; 8929 /// Reduction operation expression. 8930 SmallVector<Expr *, 8> ReductionOps; 8931 /// List of captures for clause. 8932 SmallVector<Decl *, 4> ExprCaptures; 8933 /// List of postupdate expressions. 8934 SmallVector<Expr *, 4> ExprPostUpdates; 8935 ReductionData() = delete; 8936 /// Reserves required memory for the reduction data. 8937 ReductionData(unsigned Size) { 8938 Vars.reserve(Size); 8939 Privates.reserve(Size); 8940 LHSs.reserve(Size); 8941 RHSs.reserve(Size); 8942 ReductionOps.reserve(Size); 8943 ExprCaptures.reserve(Size); 8944 ExprPostUpdates.reserve(Size); 8945 } 8946 /// Stores reduction item and reduction operation only (required for dependent 8947 /// reduction item). 8948 void push(Expr *Item, Expr *ReductionOp) { 8949 Vars.emplace_back(Item); 8950 Privates.emplace_back(nullptr); 8951 LHSs.emplace_back(nullptr); 8952 RHSs.emplace_back(nullptr); 8953 ReductionOps.emplace_back(ReductionOp); 8954 } 8955 /// Stores reduction data. 8956 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, 8957 Expr *ReductionOp) { 8958 Vars.emplace_back(Item); 8959 Privates.emplace_back(Private); 8960 LHSs.emplace_back(LHS); 8961 RHSs.emplace_back(RHS); 8962 ReductionOps.emplace_back(ReductionOp); 8963 } 8964 }; 8965 } // namespace 8966 8967 static bool ActOnOMPReductionKindClause( 8968 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, 8969 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 8970 SourceLocation ColonLoc, SourceLocation EndLoc, 8971 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 8972 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { 8973 auto DN = ReductionId.getName(); 8974 auto OOK = DN.getCXXOverloadedOperator(); 8975 BinaryOperatorKind BOK = BO_Comma; 8976 8977 ASTContext &Context = S.Context; 8978 // OpenMP [2.14.3.6, reduction clause] 8979 // C 8980 // reduction-identifier is either an identifier or one of the following 8981 // operators: +, -, *, &, |, ^, && and || 8982 // C++ 8983 // reduction-identifier is either an id-expression or one of the following 8984 // operators: +, -, *, &, |, ^, && and || 8985 // FIXME: Only 'min' and 'max' identifiers are supported for now. 8986 switch (OOK) { 8987 case OO_Plus: 8988 case OO_Minus: 8989 BOK = BO_Add; 8990 break; 8991 case OO_Star: 8992 BOK = BO_Mul; 8993 break; 8994 case OO_Amp: 8995 BOK = BO_And; 8996 break; 8997 case OO_Pipe: 8998 BOK = BO_Or; 8999 break; 9000 case OO_Caret: 9001 BOK = BO_Xor; 9002 break; 9003 case OO_AmpAmp: 9004 BOK = BO_LAnd; 9005 break; 9006 case OO_PipePipe: 9007 BOK = BO_LOr; 9008 break; 9009 case OO_New: 9010 case OO_Delete: 9011 case OO_Array_New: 9012 case OO_Array_Delete: 9013 case OO_Slash: 9014 case OO_Percent: 9015 case OO_Tilde: 9016 case OO_Exclaim: 9017 case OO_Equal: 9018 case OO_Less: 9019 case OO_Greater: 9020 case OO_LessEqual: 9021 case OO_GreaterEqual: 9022 case OO_PlusEqual: 9023 case OO_MinusEqual: 9024 case OO_StarEqual: 9025 case OO_SlashEqual: 9026 case OO_PercentEqual: 9027 case OO_CaretEqual: 9028 case OO_AmpEqual: 9029 case OO_PipeEqual: 9030 case OO_LessLess: 9031 case OO_GreaterGreater: 9032 case OO_LessLessEqual: 9033 case OO_GreaterGreaterEqual: 9034 case OO_EqualEqual: 9035 case OO_ExclaimEqual: 9036 case OO_PlusPlus: 9037 case OO_MinusMinus: 9038 case OO_Comma: 9039 case OO_ArrowStar: 9040 case OO_Arrow: 9041 case OO_Call: 9042 case OO_Subscript: 9043 case OO_Conditional: 9044 case OO_Coawait: 9045 case NUM_OVERLOADED_OPERATORS: 9046 llvm_unreachable("Unexpected reduction identifier"); 9047 case OO_None: 9048 if (auto II = DN.getAsIdentifierInfo()) { 9049 if (II->isStr("max")) 9050 BOK = BO_GT; 9051 else if (II->isStr("min")) 9052 BOK = BO_LT; 9053 } 9054 break; 9055 } 9056 SourceRange ReductionIdRange; 9057 if (ReductionIdScopeSpec.isValid()) 9058 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 9059 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 9060 9061 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 9062 bool FirstIter = true; 9063 for (auto RefExpr : VarList) { 9064 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 9065 // OpenMP [2.1, C/C++] 9066 // A list item is a variable or array section, subject to the restrictions 9067 // specified in Section 2.4 on page 42 and in each of the sections 9068 // describing clauses and directives for which a list appears. 9069 // OpenMP [2.14.3.3, Restrictions, p.1] 9070 // A variable that is part of another variable (as an array or 9071 // structure element) cannot appear in a private clause. 9072 if (!FirstIter && IR != ER) 9073 ++IR; 9074 FirstIter = false; 9075 SourceLocation ELoc; 9076 SourceRange ERange; 9077 Expr *SimpleRefExpr = RefExpr; 9078 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 9079 /*AllowArraySection=*/true); 9080 if (Res.second) { 9081 // Try to find 'declare reduction' corresponding construct before using 9082 // builtin/overloaded operators. 9083 QualType Type = Context.DependentTy; 9084 CXXCastPath BasePath; 9085 ExprResult DeclareReductionRef = buildDeclareReductionRef( 9086 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 9087 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 9088 Expr *ReductionOp = nullptr; 9089 if (S.CurContext->isDependentContext() && 9090 (DeclareReductionRef.isUnset() || 9091 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 9092 ReductionOp = DeclareReductionRef.get(); 9093 // It will be analyzed later. 9094 RD.push(RefExpr, ReductionOp); 9095 } 9096 ValueDecl *D = Res.first; 9097 if (!D) 9098 continue; 9099 9100 QualType Type; 9101 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 9102 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 9103 if (ASE) 9104 Type = ASE->getType().getNonReferenceType(); 9105 else if (OASE) { 9106 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 9107 if (auto *ATy = BaseType->getAsArrayTypeUnsafe()) 9108 Type = ATy->getElementType(); 9109 else 9110 Type = BaseType->getPointeeType(); 9111 Type = Type.getNonReferenceType(); 9112 } else 9113 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 9114 auto *VD = dyn_cast<VarDecl>(D); 9115 9116 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 9117 // A variable that appears in a private clause must not have an incomplete 9118 // type or a reference type. 9119 if (S.RequireCompleteType(ELoc, Type, 9120 diag::err_omp_reduction_incomplete_type)) 9121 continue; 9122 // OpenMP [2.14.3.6, reduction clause, Restrictions] 9123 // A list item that appears in a reduction clause must not be 9124 // const-qualified. 9125 if (Type.getNonReferenceType().isConstant(Context)) { 9126 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange; 9127 if (!ASE && !OASE) { 9128 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 9129 VarDecl::DeclarationOnly; 9130 S.Diag(D->getLocation(), 9131 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9132 << D; 9133 } 9134 continue; 9135 } 9136 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 9137 // If a list-item is a reference type then it must bind to the same object 9138 // for all threads of the team. 9139 if (!ASE && !OASE && VD) { 9140 VarDecl *VDDef = VD->getDefinition(); 9141 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 9142 DSARefChecker Check(Stack); 9143 if (Check.Visit(VDDef->getInit())) { 9144 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) 9145 << getOpenMPClauseName(ClauseKind) << ERange; 9146 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 9147 continue; 9148 } 9149 } 9150 } 9151 9152 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 9153 // in a Construct] 9154 // Variables with the predetermined data-sharing attributes may not be 9155 // listed in data-sharing attributes clauses, except for the cases 9156 // listed below. For these exceptions only, listing a predetermined 9157 // variable in a data-sharing attribute clause is allowed and overrides 9158 // the variable's predetermined data-sharing attributes. 9159 // OpenMP [2.14.3.6, Restrictions, p.3] 9160 // Any number of reduction clauses can be specified on the directive, 9161 // but a list item can appear only once in the reduction clauses for that 9162 // directive. 9163 DSAStackTy::DSAVarData DVar; 9164 DVar = Stack->getTopDSA(D, false); 9165 if (DVar.CKind == OMPC_reduction) { 9166 S.Diag(ELoc, diag::err_omp_once_referenced) 9167 << getOpenMPClauseName(ClauseKind); 9168 if (DVar.RefExpr) 9169 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 9170 } else if (DVar.CKind != OMPC_unknown) { 9171 S.Diag(ELoc, diag::err_omp_wrong_dsa) 9172 << getOpenMPClauseName(DVar.CKind) 9173 << getOpenMPClauseName(OMPC_reduction); 9174 ReportOriginalDSA(S, Stack, D, DVar); 9175 continue; 9176 } 9177 9178 // OpenMP [2.14.3.6, Restrictions, p.1] 9179 // A list item that appears in a reduction clause of a worksharing 9180 // construct must be shared in the parallel regions to which any of the 9181 // worksharing regions arising from the worksharing construct bind. 9182 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); 9183 if (isOpenMPWorksharingDirective(CurrDir) && 9184 !isOpenMPParallelDirective(CurrDir) && 9185 !isOpenMPTeamsDirective(CurrDir)) { 9186 DVar = Stack->getImplicitDSA(D, true); 9187 if (DVar.CKind != OMPC_shared) { 9188 S.Diag(ELoc, diag::err_omp_required_access) 9189 << getOpenMPClauseName(OMPC_reduction) 9190 << getOpenMPClauseName(OMPC_shared); 9191 ReportOriginalDSA(S, Stack, D, DVar); 9192 continue; 9193 } 9194 } 9195 9196 // Try to find 'declare reduction' corresponding construct before using 9197 // builtin/overloaded operators. 9198 CXXCastPath BasePath; 9199 ExprResult DeclareReductionRef = buildDeclareReductionRef( 9200 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 9201 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 9202 if (DeclareReductionRef.isInvalid()) 9203 continue; 9204 if (S.CurContext->isDependentContext() && 9205 (DeclareReductionRef.isUnset() || 9206 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 9207 RD.push(RefExpr, DeclareReductionRef.get()); 9208 continue; 9209 } 9210 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 9211 // Not allowed reduction identifier is found. 9212 S.Diag(ReductionId.getLocStart(), 9213 diag::err_omp_unknown_reduction_identifier) 9214 << Type << ReductionIdRange; 9215 continue; 9216 } 9217 9218 // OpenMP [2.14.3.6, reduction clause, Restrictions] 9219 // The type of a list item that appears in a reduction clause must be valid 9220 // for the reduction-identifier. For a max or min reduction in C, the type 9221 // of the list item must be an allowed arithmetic data type: char, int, 9222 // float, double, or _Bool, possibly modified with long, short, signed, or 9223 // unsigned. For a max or min reduction in C++, the type of the list item 9224 // must be an allowed arithmetic data type: char, wchar_t, int, float, 9225 // double, or bool, possibly modified with long, short, signed, or unsigned. 9226 if (DeclareReductionRef.isUnset()) { 9227 if ((BOK == BO_GT || BOK == BO_LT) && 9228 !(Type->isScalarType() || 9229 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 9230 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 9231 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; 9232 if (!ASE && !OASE) { 9233 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 9234 VarDecl::DeclarationOnly; 9235 S.Diag(D->getLocation(), 9236 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9237 << D; 9238 } 9239 continue; 9240 } 9241 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 9242 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { 9243 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) 9244 << getOpenMPClauseName(ClauseKind); 9245 if (!ASE && !OASE) { 9246 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 9247 VarDecl::DeclarationOnly; 9248 S.Diag(D->getLocation(), 9249 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9250 << D; 9251 } 9252 continue; 9253 } 9254 } 9255 9256 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 9257 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", 9258 D->hasAttrs() ? &D->getAttrs() : nullptr); 9259 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), 9260 D->hasAttrs() ? &D->getAttrs() : nullptr); 9261 auto PrivateTy = Type; 9262 if (OASE || 9263 (!ASE && 9264 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 9265 // For arrays/array sections only: 9266 // Create pseudo array type for private copy. The size for this array will 9267 // be generated during codegen. 9268 // For array subscripts or single variables Private Ty is the same as Type 9269 // (type of the variable or single array element). 9270 PrivateTy = Context.getVariableArrayType( 9271 Type, 9272 new (Context) OpaqueValueExpr(SourceLocation(), Context.getSizeType(), 9273 VK_RValue), 9274 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 9275 } else if (!ASE && !OASE && 9276 Context.getAsArrayType(D->getType().getNonReferenceType())) 9277 PrivateTy = D->getType().getNonReferenceType(); 9278 // Private copy. 9279 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(), 9280 D->hasAttrs() ? &D->getAttrs() : nullptr); 9281 // Add initializer for private variable. 9282 Expr *Init = nullptr; 9283 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); 9284 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); 9285 if (DeclareReductionRef.isUsable()) { 9286 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 9287 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 9288 if (DRD->getInitializer()) { 9289 Init = DRDRef; 9290 RHSVD->setInit(DRDRef); 9291 RHSVD->setInitStyle(VarDecl::CallInit); 9292 } 9293 } else { 9294 switch (BOK) { 9295 case BO_Add: 9296 case BO_Xor: 9297 case BO_Or: 9298 case BO_LOr: 9299 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 9300 if (Type->isScalarType() || Type->isAnyComplexType()) 9301 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 9302 break; 9303 case BO_Mul: 9304 case BO_LAnd: 9305 if (Type->isScalarType() || Type->isAnyComplexType()) { 9306 // '*' and '&&' reduction ops - initializer is '1'. 9307 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 9308 } 9309 break; 9310 case BO_And: { 9311 // '&' reduction op - initializer is '~0'. 9312 QualType OrigType = Type; 9313 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 9314 Type = ComplexTy->getElementType(); 9315 if (Type->isRealFloatingType()) { 9316 llvm::APFloat InitValue = 9317 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), 9318 /*isIEEE=*/true); 9319 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 9320 Type, ELoc); 9321 } else if (Type->isScalarType()) { 9322 auto Size = Context.getTypeSize(Type); 9323 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 9324 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 9325 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 9326 } 9327 if (Init && OrigType->isAnyComplexType()) { 9328 // Init = 0xFFFF + 0xFFFFi; 9329 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 9330 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 9331 } 9332 Type = OrigType; 9333 break; 9334 } 9335 case BO_LT: 9336 case BO_GT: { 9337 // 'min' reduction op - initializer is 'Largest representable number in 9338 // the reduction list item type'. 9339 // 'max' reduction op - initializer is 'Least representable number in 9340 // the reduction list item type'. 9341 if (Type->isIntegerType() || Type->isPointerType()) { 9342 bool IsSigned = Type->hasSignedIntegerRepresentation(); 9343 auto Size = Context.getTypeSize(Type); 9344 QualType IntTy = 9345 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 9346 llvm::APInt InitValue = 9347 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 9348 : llvm::APInt::getMinValue(Size) 9349 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 9350 : llvm::APInt::getMaxValue(Size); 9351 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 9352 if (Type->isPointerType()) { 9353 // Cast to pointer type. 9354 auto CastExpr = S.BuildCStyleCastExpr( 9355 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc), 9356 SourceLocation(), Init); 9357 if (CastExpr.isInvalid()) 9358 continue; 9359 Init = CastExpr.get(); 9360 } 9361 } else if (Type->isRealFloatingType()) { 9362 llvm::APFloat InitValue = llvm::APFloat::getLargest( 9363 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 9364 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 9365 Type, ELoc); 9366 } 9367 break; 9368 } 9369 case BO_PtrMemD: 9370 case BO_PtrMemI: 9371 case BO_MulAssign: 9372 case BO_Div: 9373 case BO_Rem: 9374 case BO_Sub: 9375 case BO_Shl: 9376 case BO_Shr: 9377 case BO_LE: 9378 case BO_GE: 9379 case BO_EQ: 9380 case BO_NE: 9381 case BO_AndAssign: 9382 case BO_XorAssign: 9383 case BO_OrAssign: 9384 case BO_Assign: 9385 case BO_AddAssign: 9386 case BO_SubAssign: 9387 case BO_DivAssign: 9388 case BO_RemAssign: 9389 case BO_ShlAssign: 9390 case BO_ShrAssign: 9391 case BO_Comma: 9392 llvm_unreachable("Unexpected reduction operation"); 9393 } 9394 } 9395 if (Init && DeclareReductionRef.isUnset()) 9396 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 9397 else if (!Init) 9398 S.ActOnUninitializedDecl(RHSVD); 9399 if (RHSVD->isInvalidDecl()) 9400 continue; 9401 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 9402 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) 9403 << Type << ReductionIdRange; 9404 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 9405 VarDecl::DeclarationOnly; 9406 S.Diag(D->getLocation(), 9407 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9408 << D; 9409 continue; 9410 } 9411 // Store initializer for single element in private copy. Will be used during 9412 // codegen. 9413 PrivateVD->setInit(RHSVD->getInit()); 9414 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 9415 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); 9416 ExprResult ReductionOp; 9417 if (DeclareReductionRef.isUsable()) { 9418 QualType RedTy = DeclareReductionRef.get()->getType(); 9419 QualType PtrRedTy = Context.getPointerType(RedTy); 9420 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 9421 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 9422 if (!BasePath.empty()) { 9423 LHS = S.DefaultLvalueConversion(LHS.get()); 9424 RHS = S.DefaultLvalueConversion(RHS.get()); 9425 LHS = ImplicitCastExpr::Create(Context, PtrRedTy, 9426 CK_UncheckedDerivedToBase, LHS.get(), 9427 &BasePath, LHS.get()->getValueKind()); 9428 RHS = ImplicitCastExpr::Create(Context, PtrRedTy, 9429 CK_UncheckedDerivedToBase, RHS.get(), 9430 &BasePath, RHS.get()->getValueKind()); 9431 } 9432 FunctionProtoType::ExtProtoInfo EPI; 9433 QualType Params[] = {PtrRedTy, PtrRedTy}; 9434 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 9435 auto *OVE = new (Context) OpaqueValueExpr( 9436 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 9437 S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); 9438 Expr *Args[] = {LHS.get(), RHS.get()}; 9439 ReductionOp = new (Context) 9440 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); 9441 } else { 9442 ReductionOp = S.BuildBinOp( 9443 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE); 9444 if (ReductionOp.isUsable()) { 9445 if (BOK != BO_LT && BOK != BO_GT) { 9446 ReductionOp = 9447 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(), 9448 BO_Assign, LHSDRE, ReductionOp.get()); 9449 } else { 9450 auto *ConditionalOp = new (Context) ConditionalOperator( 9451 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(), 9452 RHSDRE, Type, VK_LValue, OK_Ordinary); 9453 ReductionOp = 9454 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(), 9455 BO_Assign, LHSDRE, ConditionalOp); 9456 } 9457 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get()); 9458 } 9459 if (ReductionOp.isInvalid()) 9460 continue; 9461 } 9462 9463 DeclRefExpr *Ref = nullptr; 9464 Expr *VarsExpr = RefExpr->IgnoreParens(); 9465 if (!VD && !S.CurContext->isDependentContext()) { 9466 if (ASE || OASE) { 9467 TransformExprToCaptures RebuildToCapture(S, D); 9468 VarsExpr = 9469 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 9470 Ref = RebuildToCapture.getCapturedExpr(); 9471 } else { 9472 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); 9473 } 9474 if (!S.IsOpenMPCapturedDecl(D)) { 9475 RD.ExprCaptures.emplace_back(Ref->getDecl()); 9476 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 9477 ExprResult RefRes = S.DefaultLvalueConversion(Ref); 9478 if (!RefRes.isUsable()) 9479 continue; 9480 ExprResult PostUpdateRes = 9481 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 9482 RefRes.get()); 9483 if (!PostUpdateRes.isUsable()) 9484 continue; 9485 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 9486 Stack->getCurrentDirective() == OMPD_taskgroup) { 9487 S.Diag(RefExpr->getExprLoc(), 9488 diag::err_omp_reduction_non_addressable_expression) 9489 << RefExpr->getSourceRange(); 9490 continue; 9491 } 9492 RD.ExprPostUpdates.emplace_back( 9493 S.IgnoredValueConversions(PostUpdateRes.get()).get()); 9494 } 9495 } 9496 } 9497 // All reduction items are still marked as reduction (to do not increase 9498 // code base size). 9499 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref); 9500 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get()); 9501 } 9502 return RD.Vars.empty(); 9503 } 9504 9505 OMPClause *Sema::ActOnOpenMPReductionClause( 9506 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 9507 SourceLocation ColonLoc, SourceLocation EndLoc, 9508 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 9509 ArrayRef<Expr *> UnresolvedReductions) { 9510 ReductionData RD(VarList.size()); 9511 9512 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, 9513 StartLoc, LParenLoc, ColonLoc, EndLoc, 9514 ReductionIdScopeSpec, ReductionId, 9515 UnresolvedReductions, RD)) 9516 return nullptr; 9517 9518 return OMPReductionClause::Create( 9519 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 9520 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 9521 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 9522 buildPreInits(Context, RD.ExprCaptures), 9523 buildPostUpdate(*this, RD.ExprPostUpdates)); 9524 } 9525 9526 OMPClause *Sema::ActOnOpenMPTaskReductionClause( 9527 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 9528 SourceLocation ColonLoc, SourceLocation EndLoc, 9529 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 9530 ArrayRef<Expr *> UnresolvedReductions) { 9531 ReductionData RD(VarList.size()); 9532 9533 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, 9534 VarList, StartLoc, LParenLoc, ColonLoc, 9535 EndLoc, ReductionIdScopeSpec, ReductionId, 9536 UnresolvedReductions, RD)) 9537 return nullptr; 9538 9539 return OMPTaskReductionClause::Create( 9540 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 9541 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 9542 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 9543 buildPreInits(Context, RD.ExprCaptures), 9544 buildPostUpdate(*this, RD.ExprPostUpdates)); 9545 } 9546 9547 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 9548 SourceLocation LinLoc) { 9549 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 9550 LinKind == OMPC_LINEAR_unknown) { 9551 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 9552 return true; 9553 } 9554 return false; 9555 } 9556 9557 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc, 9558 OpenMPLinearClauseKind LinKind, 9559 QualType Type) { 9560 auto *VD = dyn_cast_or_null<VarDecl>(D); 9561 // A variable must not have an incomplete type or a reference type. 9562 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 9563 return true; 9564 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 9565 !Type->isReferenceType()) { 9566 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 9567 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 9568 return true; 9569 } 9570 Type = Type.getNonReferenceType(); 9571 9572 // A list item must not be const-qualified. 9573 if (Type.isConstant(Context)) { 9574 Diag(ELoc, diag::err_omp_const_variable) 9575 << getOpenMPClauseName(OMPC_linear); 9576 if (D) { 9577 bool IsDecl = 9578 !VD || 9579 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9580 Diag(D->getLocation(), 9581 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9582 << D; 9583 } 9584 return true; 9585 } 9586 9587 // A list item must be of integral or pointer type. 9588 Type = Type.getUnqualifiedType().getCanonicalType(); 9589 const auto *Ty = Type.getTypePtrOrNull(); 9590 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 9591 !Ty->isPointerType())) { 9592 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 9593 if (D) { 9594 bool IsDecl = 9595 !VD || 9596 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9597 Diag(D->getLocation(), 9598 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9599 << D; 9600 } 9601 return true; 9602 } 9603 return false; 9604 } 9605 9606 OMPClause *Sema::ActOnOpenMPLinearClause( 9607 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 9608 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 9609 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 9610 SmallVector<Expr *, 8> Vars; 9611 SmallVector<Expr *, 8> Privates; 9612 SmallVector<Expr *, 8> Inits; 9613 SmallVector<Decl *, 4> ExprCaptures; 9614 SmallVector<Expr *, 4> ExprPostUpdates; 9615 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 9616 LinKind = OMPC_LINEAR_val; 9617 for (auto &RefExpr : VarList) { 9618 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9619 SourceLocation ELoc; 9620 SourceRange ERange; 9621 Expr *SimpleRefExpr = RefExpr; 9622 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9623 /*AllowArraySection=*/false); 9624 if (Res.second) { 9625 // It will be analyzed later. 9626 Vars.push_back(RefExpr); 9627 Privates.push_back(nullptr); 9628 Inits.push_back(nullptr); 9629 } 9630 ValueDecl *D = Res.first; 9631 if (!D) 9632 continue; 9633 9634 QualType Type = D->getType(); 9635 auto *VD = dyn_cast<VarDecl>(D); 9636 9637 // OpenMP [2.14.3.7, linear clause] 9638 // A list-item cannot appear in more than one linear clause. 9639 // A list-item that appears in a linear clause cannot appear in any 9640 // other data-sharing attribute clause. 9641 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 9642 if (DVar.RefExpr) { 9643 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 9644 << getOpenMPClauseName(OMPC_linear); 9645 ReportOriginalDSA(*this, DSAStack, D, DVar); 9646 continue; 9647 } 9648 9649 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 9650 continue; 9651 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 9652 9653 // Build private copy of original var. 9654 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(), 9655 D->hasAttrs() ? &D->getAttrs() : nullptr); 9656 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 9657 // Build var to save initial value. 9658 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 9659 Expr *InitExpr; 9660 DeclRefExpr *Ref = nullptr; 9661 if (!VD && !CurContext->isDependentContext()) { 9662 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 9663 if (!IsOpenMPCapturedDecl(D)) { 9664 ExprCaptures.push_back(Ref->getDecl()); 9665 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 9666 ExprResult RefRes = DefaultLvalueConversion(Ref); 9667 if (!RefRes.isUsable()) 9668 continue; 9669 ExprResult PostUpdateRes = 9670 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 9671 SimpleRefExpr, RefRes.get()); 9672 if (!PostUpdateRes.isUsable()) 9673 continue; 9674 ExprPostUpdates.push_back( 9675 IgnoredValueConversions(PostUpdateRes.get()).get()); 9676 } 9677 } 9678 } 9679 if (LinKind == OMPC_LINEAR_uval) 9680 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 9681 else 9682 InitExpr = VD ? SimpleRefExpr : Ref; 9683 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 9684 /*DirectInit=*/false); 9685 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 9686 9687 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 9688 Vars.push_back((VD || CurContext->isDependentContext()) 9689 ? RefExpr->IgnoreParens() 9690 : Ref); 9691 Privates.push_back(PrivateRef); 9692 Inits.push_back(InitRef); 9693 } 9694 9695 if (Vars.empty()) 9696 return nullptr; 9697 9698 Expr *StepExpr = Step; 9699 Expr *CalcStepExpr = nullptr; 9700 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 9701 !Step->isInstantiationDependent() && 9702 !Step->containsUnexpandedParameterPack()) { 9703 SourceLocation StepLoc = Step->getLocStart(); 9704 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 9705 if (Val.isInvalid()) 9706 return nullptr; 9707 StepExpr = Val.get(); 9708 9709 // Build var to save the step value. 9710 VarDecl *SaveVar = 9711 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 9712 ExprResult SaveRef = 9713 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 9714 ExprResult CalcStep = 9715 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 9716 CalcStep = ActOnFinishFullExpr(CalcStep.get()); 9717 9718 // Warn about zero linear step (it would be probably better specified as 9719 // making corresponding variables 'const'). 9720 llvm::APSInt Result; 9721 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); 9722 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) 9723 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 9724 << (Vars.size() > 1); 9725 if (!IsConstant && CalcStep.isUsable()) { 9726 // Calculate the step beforehand instead of doing this on each iteration. 9727 // (This is not used if the number of iterations may be kfold-ed). 9728 CalcStepExpr = CalcStep.get(); 9729 } 9730 } 9731 9732 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 9733 ColonLoc, EndLoc, Vars, Privates, Inits, 9734 StepExpr, CalcStepExpr, 9735 buildPreInits(Context, ExprCaptures), 9736 buildPostUpdate(*this, ExprPostUpdates)); 9737 } 9738 9739 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 9740 Expr *NumIterations, Sema &SemaRef, 9741 Scope *S, DSAStackTy *Stack) { 9742 // Walk the vars and build update/final expressions for the CodeGen. 9743 SmallVector<Expr *, 8> Updates; 9744 SmallVector<Expr *, 8> Finals; 9745 Expr *Step = Clause.getStep(); 9746 Expr *CalcStep = Clause.getCalcStep(); 9747 // OpenMP [2.14.3.7, linear clause] 9748 // If linear-step is not specified it is assumed to be 1. 9749 if (Step == nullptr) 9750 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 9751 else if (CalcStep) { 9752 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 9753 } 9754 bool HasErrors = false; 9755 auto CurInit = Clause.inits().begin(); 9756 auto CurPrivate = Clause.privates().begin(); 9757 auto LinKind = Clause.getModifier(); 9758 for (auto &RefExpr : Clause.varlists()) { 9759 SourceLocation ELoc; 9760 SourceRange ERange; 9761 Expr *SimpleRefExpr = RefExpr; 9762 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange, 9763 /*AllowArraySection=*/false); 9764 ValueDecl *D = Res.first; 9765 if (Res.second || !D) { 9766 Updates.push_back(nullptr); 9767 Finals.push_back(nullptr); 9768 HasErrors = true; 9769 continue; 9770 } 9771 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) { 9772 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts()) 9773 ->getMemberDecl(); 9774 } 9775 auto &&Info = Stack->isLoopControlVariable(D); 9776 Expr *InitExpr = *CurInit; 9777 9778 // Build privatized reference to the current linear var. 9779 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 9780 Expr *CapturedRef; 9781 if (LinKind == OMPC_LINEAR_uval) 9782 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 9783 else 9784 CapturedRef = 9785 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 9786 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 9787 /*RefersToCapture=*/true); 9788 9789 // Build update: Var = InitExpr + IV * Step 9790 ExprResult Update; 9791 if (!Info.first) { 9792 Update = 9793 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, 9794 InitExpr, IV, Step, /* Subtract */ false); 9795 } else 9796 Update = *CurPrivate; 9797 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(), 9798 /*DiscardedValue=*/true); 9799 9800 // Build final: Var = InitExpr + NumIterations * Step 9801 ExprResult Final; 9802 if (!Info.first) { 9803 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 9804 InitExpr, NumIterations, Step, 9805 /* Subtract */ false); 9806 } else 9807 Final = *CurPrivate; 9808 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(), 9809 /*DiscardedValue=*/true); 9810 9811 if (!Update.isUsable() || !Final.isUsable()) { 9812 Updates.push_back(nullptr); 9813 Finals.push_back(nullptr); 9814 HasErrors = true; 9815 } else { 9816 Updates.push_back(Update.get()); 9817 Finals.push_back(Final.get()); 9818 } 9819 ++CurInit; 9820 ++CurPrivate; 9821 } 9822 Clause.setUpdates(Updates); 9823 Clause.setFinals(Finals); 9824 return HasErrors; 9825 } 9826 9827 OMPClause *Sema::ActOnOpenMPAlignedClause( 9828 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 9829 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 9830 9831 SmallVector<Expr *, 8> Vars; 9832 for (auto &RefExpr : VarList) { 9833 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9834 SourceLocation ELoc; 9835 SourceRange ERange; 9836 Expr *SimpleRefExpr = RefExpr; 9837 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9838 /*AllowArraySection=*/false); 9839 if (Res.second) { 9840 // It will be analyzed later. 9841 Vars.push_back(RefExpr); 9842 } 9843 ValueDecl *D = Res.first; 9844 if (!D) 9845 continue; 9846 9847 QualType QType = D->getType(); 9848 auto *VD = dyn_cast<VarDecl>(D); 9849 9850 // OpenMP [2.8.1, simd construct, Restrictions] 9851 // The type of list items appearing in the aligned clause must be 9852 // array, pointer, reference to array, or reference to pointer. 9853 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 9854 const Type *Ty = QType.getTypePtrOrNull(); 9855 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 9856 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 9857 << QType << getLangOpts().CPlusPlus << ERange; 9858 bool IsDecl = 9859 !VD || 9860 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9861 Diag(D->getLocation(), 9862 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9863 << D; 9864 continue; 9865 } 9866 9867 // OpenMP [2.8.1, simd construct, Restrictions] 9868 // A list-item cannot appear in more than one aligned clause. 9869 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 9870 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange; 9871 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 9872 << getOpenMPClauseName(OMPC_aligned); 9873 continue; 9874 } 9875 9876 DeclRefExpr *Ref = nullptr; 9877 if (!VD && IsOpenMPCapturedDecl(D)) 9878 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 9879 Vars.push_back(DefaultFunctionArrayConversion( 9880 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 9881 .get()); 9882 } 9883 9884 // OpenMP [2.8.1, simd construct, Description] 9885 // The parameter of the aligned clause, alignment, must be a constant 9886 // positive integer expression. 9887 // If no optional parameter is specified, implementation-defined default 9888 // alignments for SIMD instructions on the target platforms are assumed. 9889 if (Alignment != nullptr) { 9890 ExprResult AlignResult = 9891 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 9892 if (AlignResult.isInvalid()) 9893 return nullptr; 9894 Alignment = AlignResult.get(); 9895 } 9896 if (Vars.empty()) 9897 return nullptr; 9898 9899 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 9900 EndLoc, Vars, Alignment); 9901 } 9902 9903 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 9904 SourceLocation StartLoc, 9905 SourceLocation LParenLoc, 9906 SourceLocation EndLoc) { 9907 SmallVector<Expr *, 8> Vars; 9908 SmallVector<Expr *, 8> SrcExprs; 9909 SmallVector<Expr *, 8> DstExprs; 9910 SmallVector<Expr *, 8> AssignmentOps; 9911 for (auto &RefExpr : VarList) { 9912 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 9913 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 9914 // It will be analyzed later. 9915 Vars.push_back(RefExpr); 9916 SrcExprs.push_back(nullptr); 9917 DstExprs.push_back(nullptr); 9918 AssignmentOps.push_back(nullptr); 9919 continue; 9920 } 9921 9922 SourceLocation ELoc = RefExpr->getExprLoc(); 9923 // OpenMP [2.1, C/C++] 9924 // A list item is a variable name. 9925 // OpenMP [2.14.4.1, Restrictions, p.1] 9926 // A list item that appears in a copyin clause must be threadprivate. 9927 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 9928 if (!DE || !isa<VarDecl>(DE->getDecl())) { 9929 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 9930 << 0 << RefExpr->getSourceRange(); 9931 continue; 9932 } 9933 9934 Decl *D = DE->getDecl(); 9935 VarDecl *VD = cast<VarDecl>(D); 9936 9937 QualType Type = VD->getType(); 9938 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 9939 // It will be analyzed later. 9940 Vars.push_back(DE); 9941 SrcExprs.push_back(nullptr); 9942 DstExprs.push_back(nullptr); 9943 AssignmentOps.push_back(nullptr); 9944 continue; 9945 } 9946 9947 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 9948 // A list item that appears in a copyin clause must be threadprivate. 9949 if (!DSAStack->isThreadPrivate(VD)) { 9950 Diag(ELoc, diag::err_omp_required_access) 9951 << getOpenMPClauseName(OMPC_copyin) 9952 << getOpenMPDirectiveName(OMPD_threadprivate); 9953 continue; 9954 } 9955 9956 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 9957 // A variable of class type (or array thereof) that appears in a 9958 // copyin clause requires an accessible, unambiguous copy assignment 9959 // operator for the class type. 9960 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 9961 auto *SrcVD = 9962 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(), 9963 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 9964 auto *PseudoSrcExpr = buildDeclRefExpr( 9965 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 9966 auto *DstVD = 9967 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst", 9968 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 9969 auto *PseudoDstExpr = 9970 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 9971 // For arrays generate assignment operation for single element and replace 9972 // it by the original array element in CodeGen. 9973 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, 9974 PseudoDstExpr, PseudoSrcExpr); 9975 if (AssignmentOp.isInvalid()) 9976 continue; 9977 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 9978 /*DiscardedValue=*/true); 9979 if (AssignmentOp.isInvalid()) 9980 continue; 9981 9982 DSAStack->addDSA(VD, DE, OMPC_copyin); 9983 Vars.push_back(DE); 9984 SrcExprs.push_back(PseudoSrcExpr); 9985 DstExprs.push_back(PseudoDstExpr); 9986 AssignmentOps.push_back(AssignmentOp.get()); 9987 } 9988 9989 if (Vars.empty()) 9990 return nullptr; 9991 9992 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 9993 SrcExprs, DstExprs, AssignmentOps); 9994 } 9995 9996 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 9997 SourceLocation StartLoc, 9998 SourceLocation LParenLoc, 9999 SourceLocation EndLoc) { 10000 SmallVector<Expr *, 8> Vars; 10001 SmallVector<Expr *, 8> SrcExprs; 10002 SmallVector<Expr *, 8> DstExprs; 10003 SmallVector<Expr *, 8> AssignmentOps; 10004 for (auto &RefExpr : VarList) { 10005 assert(RefExpr && "NULL expr in OpenMP linear clause."); 10006 SourceLocation ELoc; 10007 SourceRange ERange; 10008 Expr *SimpleRefExpr = RefExpr; 10009 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 10010 /*AllowArraySection=*/false); 10011 if (Res.second) { 10012 // It will be analyzed later. 10013 Vars.push_back(RefExpr); 10014 SrcExprs.push_back(nullptr); 10015 DstExprs.push_back(nullptr); 10016 AssignmentOps.push_back(nullptr); 10017 } 10018 ValueDecl *D = Res.first; 10019 if (!D) 10020 continue; 10021 10022 QualType Type = D->getType(); 10023 auto *VD = dyn_cast<VarDecl>(D); 10024 10025 // OpenMP [2.14.4.2, Restrictions, p.2] 10026 // A list item that appears in a copyprivate clause may not appear in a 10027 // private or firstprivate clause on the single construct. 10028 if (!VD || !DSAStack->isThreadPrivate(VD)) { 10029 auto DVar = DSAStack->getTopDSA(D, false); 10030 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 10031 DVar.RefExpr) { 10032 Diag(ELoc, diag::err_omp_wrong_dsa) 10033 << getOpenMPClauseName(DVar.CKind) 10034 << getOpenMPClauseName(OMPC_copyprivate); 10035 ReportOriginalDSA(*this, DSAStack, D, DVar); 10036 continue; 10037 } 10038 10039 // OpenMP [2.11.4.2, Restrictions, p.1] 10040 // All list items that appear in a copyprivate clause must be either 10041 // threadprivate or private in the enclosing context. 10042 if (DVar.CKind == OMPC_unknown) { 10043 DVar = DSAStack->getImplicitDSA(D, false); 10044 if (DVar.CKind == OMPC_shared) { 10045 Diag(ELoc, diag::err_omp_required_access) 10046 << getOpenMPClauseName(OMPC_copyprivate) 10047 << "threadprivate or private in the enclosing context"; 10048 ReportOriginalDSA(*this, DSAStack, D, DVar); 10049 continue; 10050 } 10051 } 10052 } 10053 10054 // Variably modified types are not supported. 10055 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 10056 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 10057 << getOpenMPClauseName(OMPC_copyprivate) << Type 10058 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 10059 bool IsDecl = 10060 !VD || 10061 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10062 Diag(D->getLocation(), 10063 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10064 << D; 10065 continue; 10066 } 10067 10068 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 10069 // A variable of class type (or array thereof) that appears in a 10070 // copyin clause requires an accessible, unambiguous copy assignment 10071 // operator for the class type. 10072 Type = Context.getBaseElementType(Type.getNonReferenceType()) 10073 .getUnqualifiedType(); 10074 auto *SrcVD = 10075 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src", 10076 D->hasAttrs() ? &D->getAttrs() : nullptr); 10077 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 10078 auto *DstVD = 10079 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst", 10080 D->hasAttrs() ? &D->getAttrs() : nullptr); 10081 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 10082 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 10083 PseudoDstExpr, PseudoSrcExpr); 10084 if (AssignmentOp.isInvalid()) 10085 continue; 10086 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 10087 /*DiscardedValue=*/true); 10088 if (AssignmentOp.isInvalid()) 10089 continue; 10090 10091 // No need to mark vars as copyprivate, they are already threadprivate or 10092 // implicitly private. 10093 assert(VD || IsOpenMPCapturedDecl(D)); 10094 Vars.push_back( 10095 VD ? RefExpr->IgnoreParens() 10096 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 10097 SrcExprs.push_back(PseudoSrcExpr); 10098 DstExprs.push_back(PseudoDstExpr); 10099 AssignmentOps.push_back(AssignmentOp.get()); 10100 } 10101 10102 if (Vars.empty()) 10103 return nullptr; 10104 10105 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10106 Vars, SrcExprs, DstExprs, AssignmentOps); 10107 } 10108 10109 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 10110 SourceLocation StartLoc, 10111 SourceLocation LParenLoc, 10112 SourceLocation EndLoc) { 10113 if (VarList.empty()) 10114 return nullptr; 10115 10116 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 10117 } 10118 10119 OMPClause * 10120 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, 10121 SourceLocation DepLoc, SourceLocation ColonLoc, 10122 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 10123 SourceLocation LParenLoc, SourceLocation EndLoc) { 10124 if (DSAStack->getCurrentDirective() == OMPD_ordered && 10125 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 10126 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 10127 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 10128 return nullptr; 10129 } 10130 if (DSAStack->getCurrentDirective() != OMPD_ordered && 10131 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 10132 DepKind == OMPC_DEPEND_sink)) { 10133 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink}; 10134 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 10135 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 10136 /*Last=*/OMPC_DEPEND_unknown, Except) 10137 << getOpenMPClauseName(OMPC_depend); 10138 return nullptr; 10139 } 10140 SmallVector<Expr *, 8> Vars; 10141 DSAStackTy::OperatorOffsetTy OpsOffs; 10142 llvm::APSInt DepCounter(/*BitWidth=*/32); 10143 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 10144 if (DepKind == OMPC_DEPEND_sink) { 10145 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) { 10146 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 10147 TotalDepCount.setIsUnsigned(/*Val=*/true); 10148 } 10149 } 10150 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) || 10151 DSAStack->getParentOrderedRegionParam()) { 10152 for (auto &RefExpr : VarList) { 10153 assert(RefExpr && "NULL expr in OpenMP shared clause."); 10154 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 10155 // It will be analyzed later. 10156 Vars.push_back(RefExpr); 10157 continue; 10158 } 10159 10160 SourceLocation ELoc = RefExpr->getExprLoc(); 10161 auto *SimpleExpr = RefExpr->IgnoreParenCasts(); 10162 if (DepKind == OMPC_DEPEND_sink) { 10163 if (DepCounter >= TotalDepCount) { 10164 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 10165 continue; 10166 } 10167 ++DepCounter; 10168 // OpenMP [2.13.9, Summary] 10169 // depend(dependence-type : vec), where dependence-type is: 10170 // 'sink' and where vec is the iteration vector, which has the form: 10171 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 10172 // where n is the value specified by the ordered clause in the loop 10173 // directive, xi denotes the loop iteration variable of the i-th nested 10174 // loop associated with the loop directive, and di is a constant 10175 // non-negative integer. 10176 if (CurContext->isDependentContext()) { 10177 // It will be analyzed later. 10178 Vars.push_back(RefExpr); 10179 continue; 10180 } 10181 SimpleExpr = SimpleExpr->IgnoreImplicit(); 10182 OverloadedOperatorKind OOK = OO_None; 10183 SourceLocation OOLoc; 10184 Expr *LHS = SimpleExpr; 10185 Expr *RHS = nullptr; 10186 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 10187 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 10188 OOLoc = BO->getOperatorLoc(); 10189 LHS = BO->getLHS()->IgnoreParenImpCasts(); 10190 RHS = BO->getRHS()->IgnoreParenImpCasts(); 10191 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 10192 OOK = OCE->getOperator(); 10193 OOLoc = OCE->getOperatorLoc(); 10194 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 10195 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 10196 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 10197 OOK = MCE->getMethodDecl() 10198 ->getNameInfo() 10199 .getName() 10200 .getCXXOverloadedOperator(); 10201 OOLoc = MCE->getCallee()->getExprLoc(); 10202 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 10203 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 10204 } 10205 SourceLocation ELoc; 10206 SourceRange ERange; 10207 auto Res = getPrivateItem(*this, LHS, ELoc, ERange, 10208 /*AllowArraySection=*/false); 10209 if (Res.second) { 10210 // It will be analyzed later. 10211 Vars.push_back(RefExpr); 10212 } 10213 ValueDecl *D = Res.first; 10214 if (!D) 10215 continue; 10216 10217 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 10218 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 10219 continue; 10220 } 10221 if (RHS) { 10222 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 10223 RHS, OMPC_depend, /*StrictlyPositive=*/false); 10224 if (RHSRes.isInvalid()) 10225 continue; 10226 } 10227 if (!CurContext->isDependentContext() && 10228 DSAStack->getParentOrderedRegionParam() && 10229 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 10230 ValueDecl* VD = DSAStack->getParentLoopControlVariable( 10231 DepCounter.getZExtValue()); 10232 if (VD) { 10233 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 10234 << 1 << VD; 10235 } else { 10236 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; 10237 } 10238 continue; 10239 } 10240 OpsOffs.push_back({RHS, OOK}); 10241 } else { 10242 // OpenMP [2.11.1.1, Restrictions, p.3] 10243 // A variable that is part of another variable (such as a field of a 10244 // structure) but is not an array element or an array section cannot 10245 // appear in a depend clause. 10246 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr); 10247 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 10248 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr); 10249 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 10250 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) || 10251 (ASE && 10252 !ASE->getBase() 10253 ->getType() 10254 .getNonReferenceType() 10255 ->isPointerType() && 10256 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 10257 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item) 10258 << 0 << RefExpr->getSourceRange(); 10259 continue; 10260 } 10261 } 10262 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 10263 } 10264 10265 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 10266 TotalDepCount > VarList.size() && 10267 DSAStack->getParentOrderedRegionParam() && 10268 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { 10269 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1 10270 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 10271 } 10272 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 10273 Vars.empty()) 10274 return nullptr; 10275 } 10276 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10277 DepKind, DepLoc, ColonLoc, Vars); 10278 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) 10279 DSAStack->addDoacrossDependClause(C, OpsOffs); 10280 return C; 10281 } 10282 10283 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, 10284 SourceLocation LParenLoc, 10285 SourceLocation EndLoc) { 10286 Expr *ValExpr = Device; 10287 10288 // OpenMP [2.9.1, Restrictions] 10289 // The device expression must evaluate to a non-negative integer value. 10290 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 10291 /*StrictlyPositive=*/false)) 10292 return nullptr; 10293 10294 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc); 10295 } 10296 10297 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc, 10298 DSAStackTy *Stack, CXXRecordDecl *RD) { 10299 if (!RD || RD->isInvalidDecl()) 10300 return true; 10301 10302 auto QTy = SemaRef.Context.getRecordType(RD); 10303 if (RD->isDynamicClass()) { 10304 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 10305 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target); 10306 return false; 10307 } 10308 auto *DC = RD; 10309 bool IsCorrect = true; 10310 for (auto *I : DC->decls()) { 10311 if (I) { 10312 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) { 10313 if (MD->isStatic()) { 10314 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 10315 SemaRef.Diag(MD->getLocation(), 10316 diag::note_omp_static_member_in_target); 10317 IsCorrect = false; 10318 } 10319 } else if (auto *VD = dyn_cast<VarDecl>(I)) { 10320 if (VD->isStaticDataMember()) { 10321 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 10322 SemaRef.Diag(VD->getLocation(), 10323 diag::note_omp_static_member_in_target); 10324 IsCorrect = false; 10325 } 10326 } 10327 } 10328 } 10329 10330 for (auto &I : RD->bases()) { 10331 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack, 10332 I.getType()->getAsCXXRecordDecl())) 10333 IsCorrect = false; 10334 } 10335 return IsCorrect; 10336 } 10337 10338 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 10339 DSAStackTy *Stack, QualType QTy) { 10340 NamedDecl *ND; 10341 if (QTy->isIncompleteType(&ND)) { 10342 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 10343 return false; 10344 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) { 10345 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD)) 10346 return false; 10347 } 10348 return true; 10349 } 10350 10351 /// \brief Return true if it can be proven that the provided array expression 10352 /// (array section or array subscript) does NOT specify the whole size of the 10353 /// array whose base type is \a BaseQTy. 10354 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 10355 const Expr *E, 10356 QualType BaseQTy) { 10357 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 10358 10359 // If this is an array subscript, it refers to the whole size if the size of 10360 // the dimension is constant and equals 1. Also, an array section assumes the 10361 // format of an array subscript if no colon is used. 10362 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) { 10363 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 10364 return ATy->getSize().getSExtValue() != 1; 10365 // Size can't be evaluated statically. 10366 return false; 10367 } 10368 10369 assert(OASE && "Expecting array section if not an array subscript."); 10370 auto *LowerBound = OASE->getLowerBound(); 10371 auto *Length = OASE->getLength(); 10372 10373 // If there is a lower bound that does not evaluates to zero, we are not 10374 // covering the whole dimension. 10375 if (LowerBound) { 10376 llvm::APSInt ConstLowerBound; 10377 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext())) 10378 return false; // Can't get the integer value as a constant. 10379 if (ConstLowerBound.getSExtValue()) 10380 return true; 10381 } 10382 10383 // If we don't have a length we covering the whole dimension. 10384 if (!Length) 10385 return false; 10386 10387 // If the base is a pointer, we don't have a way to get the size of the 10388 // pointee. 10389 if (BaseQTy->isPointerType()) 10390 return false; 10391 10392 // We can only check if the length is the same as the size of the dimension 10393 // if we have a constant array. 10394 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 10395 if (!CATy) 10396 return false; 10397 10398 llvm::APSInt ConstLength; 10399 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 10400 return false; // Can't get the integer value as a constant. 10401 10402 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 10403 } 10404 10405 // Return true if it can be proven that the provided array expression (array 10406 // section or array subscript) does NOT specify a single element of the array 10407 // whose base type is \a BaseQTy. 10408 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 10409 const Expr *E, 10410 QualType BaseQTy) { 10411 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 10412 10413 // An array subscript always refer to a single element. Also, an array section 10414 // assumes the format of an array subscript if no colon is used. 10415 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) 10416 return false; 10417 10418 assert(OASE && "Expecting array section if not an array subscript."); 10419 auto *Length = OASE->getLength(); 10420 10421 // If we don't have a length we have to check if the array has unitary size 10422 // for this dimension. Also, we should always expect a length if the base type 10423 // is pointer. 10424 if (!Length) { 10425 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 10426 return ATy->getSize().getSExtValue() != 1; 10427 // We cannot assume anything. 10428 return false; 10429 } 10430 10431 // Check if the length evaluates to 1. 10432 llvm::APSInt ConstLength; 10433 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 10434 return false; // Can't get the integer value as a constant. 10435 10436 return ConstLength.getSExtValue() != 1; 10437 } 10438 10439 // Return the expression of the base of the mappable expression or null if it 10440 // cannot be determined and do all the necessary checks to see if the expression 10441 // is valid as a standalone mappable expression. In the process, record all the 10442 // components of the expression. 10443 static Expr *CheckMapClauseExpressionBase( 10444 Sema &SemaRef, Expr *E, 10445 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 10446 OpenMPClauseKind CKind) { 10447 SourceLocation ELoc = E->getExprLoc(); 10448 SourceRange ERange = E->getSourceRange(); 10449 10450 // The base of elements of list in a map clause have to be either: 10451 // - a reference to variable or field. 10452 // - a member expression. 10453 // - an array expression. 10454 // 10455 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 10456 // reference to 'r'. 10457 // 10458 // If we have: 10459 // 10460 // struct SS { 10461 // Bla S; 10462 // foo() { 10463 // #pragma omp target map (S.Arr[:12]); 10464 // } 10465 // } 10466 // 10467 // We want to retrieve the member expression 'this->S'; 10468 10469 Expr *RelevantExpr = nullptr; 10470 10471 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2] 10472 // If a list item is an array section, it must specify contiguous storage. 10473 // 10474 // For this restriction it is sufficient that we make sure only references 10475 // to variables or fields and array expressions, and that no array sections 10476 // exist except in the rightmost expression (unless they cover the whole 10477 // dimension of the array). E.g. these would be invalid: 10478 // 10479 // r.ArrS[3:5].Arr[6:7] 10480 // 10481 // r.ArrS[3:5].x 10482 // 10483 // but these would be valid: 10484 // r.ArrS[3].Arr[6:7] 10485 // 10486 // r.ArrS[3].x 10487 10488 bool AllowUnitySizeArraySection = true; 10489 bool AllowWholeSizeArraySection = true; 10490 10491 while (!RelevantExpr) { 10492 E = E->IgnoreParenImpCasts(); 10493 10494 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) { 10495 if (!isa<VarDecl>(CurE->getDecl())) 10496 break; 10497 10498 RelevantExpr = CurE; 10499 10500 // If we got a reference to a declaration, we should not expect any array 10501 // section before that. 10502 AllowUnitySizeArraySection = false; 10503 AllowWholeSizeArraySection = false; 10504 10505 // Record the component. 10506 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent( 10507 CurE, CurE->getDecl())); 10508 continue; 10509 } 10510 10511 if (auto *CurE = dyn_cast<MemberExpr>(E)) { 10512 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts(); 10513 10514 if (isa<CXXThisExpr>(BaseE)) 10515 // We found a base expression: this->Val. 10516 RelevantExpr = CurE; 10517 else 10518 E = BaseE; 10519 10520 if (!isa<FieldDecl>(CurE->getMemberDecl())) { 10521 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 10522 << CurE->getSourceRange(); 10523 break; 10524 } 10525 10526 auto *FD = cast<FieldDecl>(CurE->getMemberDecl()); 10527 10528 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 10529 // A bit-field cannot appear in a map clause. 10530 // 10531 if (FD->isBitField()) { 10532 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 10533 << CurE->getSourceRange() << getOpenMPClauseName(CKind); 10534 break; 10535 } 10536 10537 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10538 // If the type of a list item is a reference to a type T then the type 10539 // will be considered to be T for all purposes of this clause. 10540 QualType CurType = BaseE->getType().getNonReferenceType(); 10541 10542 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 10543 // A list item cannot be a variable that is a member of a structure with 10544 // a union type. 10545 // 10546 if (auto *RT = CurType->getAs<RecordType>()) 10547 if (RT->isUnionType()) { 10548 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 10549 << CurE->getSourceRange(); 10550 break; 10551 } 10552 10553 // If we got a member expression, we should not expect any array section 10554 // before that: 10555 // 10556 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 10557 // If a list item is an element of a structure, only the rightmost symbol 10558 // of the variable reference can be an array section. 10559 // 10560 AllowUnitySizeArraySection = false; 10561 AllowWholeSizeArraySection = false; 10562 10563 // Record the component. 10564 CurComponents.push_back( 10565 OMPClauseMappableExprCommon::MappableComponent(CurE, FD)); 10566 continue; 10567 } 10568 10569 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) { 10570 E = CurE->getBase()->IgnoreParenImpCasts(); 10571 10572 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 10573 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 10574 << 0 << CurE->getSourceRange(); 10575 break; 10576 } 10577 10578 // If we got an array subscript that express the whole dimension we 10579 // can have any array expressions before. If it only expressing part of 10580 // the dimension, we can only have unitary-size array expressions. 10581 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, 10582 E->getType())) 10583 AllowWholeSizeArraySection = false; 10584 10585 // Record the component - we don't have any declaration associated. 10586 CurComponents.push_back( 10587 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 10588 continue; 10589 } 10590 10591 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) { 10592 E = CurE->getBase()->IgnoreParenImpCasts(); 10593 10594 auto CurType = 10595 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 10596 10597 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10598 // If the type of a list item is a reference to a type T then the type 10599 // will be considered to be T for all purposes of this clause. 10600 if (CurType->isReferenceType()) 10601 CurType = CurType->getPointeeType(); 10602 10603 bool IsPointer = CurType->isAnyPointerType(); 10604 10605 if (!IsPointer && !CurType->isArrayType()) { 10606 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 10607 << 0 << CurE->getSourceRange(); 10608 break; 10609 } 10610 10611 bool NotWhole = 10612 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType); 10613 bool NotUnity = 10614 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType); 10615 10616 if (AllowWholeSizeArraySection) { 10617 // Any array section is currently allowed. Allowing a whole size array 10618 // section implies allowing a unity array section as well. 10619 // 10620 // If this array section refers to the whole dimension we can still 10621 // accept other array sections before this one, except if the base is a 10622 // pointer. Otherwise, only unitary sections are accepted. 10623 if (NotWhole || IsPointer) 10624 AllowWholeSizeArraySection = false; 10625 } else if (AllowUnitySizeArraySection && NotUnity) { 10626 // A unity or whole array section is not allowed and that is not 10627 // compatible with the properties of the current array section. 10628 SemaRef.Diag( 10629 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 10630 << CurE->getSourceRange(); 10631 break; 10632 } 10633 10634 // Record the component - we don't have any declaration associated. 10635 CurComponents.push_back( 10636 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 10637 continue; 10638 } 10639 10640 // If nothing else worked, this is not a valid map clause expression. 10641 SemaRef.Diag(ELoc, 10642 diag::err_omp_expected_named_var_member_or_array_expression) 10643 << ERange; 10644 break; 10645 } 10646 10647 return RelevantExpr; 10648 } 10649 10650 // Return true if expression E associated with value VD has conflicts with other 10651 // map information. 10652 static bool CheckMapConflicts( 10653 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E, 10654 bool CurrentRegionOnly, 10655 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 10656 OpenMPClauseKind CKind) { 10657 assert(VD && E); 10658 SourceLocation ELoc = E->getExprLoc(); 10659 SourceRange ERange = E->getSourceRange(); 10660 10661 // In order to easily check the conflicts we need to match each component of 10662 // the expression under test with the components of the expressions that are 10663 // already in the stack. 10664 10665 assert(!CurComponents.empty() && "Map clause expression with no components!"); 10666 assert(CurComponents.back().getAssociatedDeclaration() == VD && 10667 "Map clause expression with unexpected base!"); 10668 10669 // Variables to help detecting enclosing problems in data environment nests. 10670 bool IsEnclosedByDataEnvironmentExpr = false; 10671 const Expr *EnclosingExpr = nullptr; 10672 10673 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 10674 VD, CurrentRegionOnly, 10675 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 10676 StackComponents, 10677 OpenMPClauseKind) -> bool { 10678 10679 assert(!StackComponents.empty() && 10680 "Map clause expression with no components!"); 10681 assert(StackComponents.back().getAssociatedDeclaration() == VD && 10682 "Map clause expression with unexpected base!"); 10683 10684 // The whole expression in the stack. 10685 auto *RE = StackComponents.front().getAssociatedExpression(); 10686 10687 // Expressions must start from the same base. Here we detect at which 10688 // point both expressions diverge from each other and see if we can 10689 // detect if the memory referred to both expressions is contiguous and 10690 // do not overlap. 10691 auto CI = CurComponents.rbegin(); 10692 auto CE = CurComponents.rend(); 10693 auto SI = StackComponents.rbegin(); 10694 auto SE = StackComponents.rend(); 10695 for (; CI != CE && SI != SE; ++CI, ++SI) { 10696 10697 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 10698 // At most one list item can be an array item derived from a given 10699 // variable in map clauses of the same construct. 10700 if (CurrentRegionOnly && 10701 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 10702 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) && 10703 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 10704 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) { 10705 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 10706 diag::err_omp_multiple_array_items_in_map_clause) 10707 << CI->getAssociatedExpression()->getSourceRange(); 10708 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 10709 diag::note_used_here) 10710 << SI->getAssociatedExpression()->getSourceRange(); 10711 return true; 10712 } 10713 10714 // Do both expressions have the same kind? 10715 if (CI->getAssociatedExpression()->getStmtClass() != 10716 SI->getAssociatedExpression()->getStmtClass()) 10717 break; 10718 10719 // Are we dealing with different variables/fields? 10720 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 10721 break; 10722 } 10723 // Check if the extra components of the expressions in the enclosing 10724 // data environment are redundant for the current base declaration. 10725 // If they are, the maps completely overlap, which is legal. 10726 for (; SI != SE; ++SI) { 10727 QualType Type; 10728 if (auto *ASE = 10729 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 10730 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 10731 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>( 10732 SI->getAssociatedExpression())) { 10733 auto *E = OASE->getBase()->IgnoreParenImpCasts(); 10734 Type = 10735 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 10736 } 10737 if (Type.isNull() || Type->isAnyPointerType() || 10738 CheckArrayExpressionDoesNotReferToWholeSize( 10739 SemaRef, SI->getAssociatedExpression(), Type)) 10740 break; 10741 } 10742 10743 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 10744 // List items of map clauses in the same construct must not share 10745 // original storage. 10746 // 10747 // If the expressions are exactly the same or one is a subset of the 10748 // other, it means they are sharing storage. 10749 if (CI == CE && SI == SE) { 10750 if (CurrentRegionOnly) { 10751 if (CKind == OMPC_map) 10752 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 10753 else { 10754 assert(CKind == OMPC_to || CKind == OMPC_from); 10755 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 10756 << ERange; 10757 } 10758 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10759 << RE->getSourceRange(); 10760 return true; 10761 } else { 10762 // If we find the same expression in the enclosing data environment, 10763 // that is legal. 10764 IsEnclosedByDataEnvironmentExpr = true; 10765 return false; 10766 } 10767 } 10768 10769 QualType DerivedType = 10770 std::prev(CI)->getAssociatedDeclaration()->getType(); 10771 SourceLocation DerivedLoc = 10772 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 10773 10774 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10775 // If the type of a list item is a reference to a type T then the type 10776 // will be considered to be T for all purposes of this clause. 10777 DerivedType = DerivedType.getNonReferenceType(); 10778 10779 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 10780 // A variable for which the type is pointer and an array section 10781 // derived from that variable must not appear as list items of map 10782 // clauses of the same construct. 10783 // 10784 // Also, cover one of the cases in: 10785 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 10786 // If any part of the original storage of a list item has corresponding 10787 // storage in the device data environment, all of the original storage 10788 // must have corresponding storage in the device data environment. 10789 // 10790 if (DerivedType->isAnyPointerType()) { 10791 if (CI == CE || SI == SE) { 10792 SemaRef.Diag( 10793 DerivedLoc, 10794 diag::err_omp_pointer_mapped_along_with_derived_section) 10795 << DerivedLoc; 10796 } else { 10797 assert(CI != CE && SI != SE); 10798 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced) 10799 << DerivedLoc; 10800 } 10801 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10802 << RE->getSourceRange(); 10803 return true; 10804 } 10805 10806 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 10807 // List items of map clauses in the same construct must not share 10808 // original storage. 10809 // 10810 // An expression is a subset of the other. 10811 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 10812 if (CKind == OMPC_map) 10813 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 10814 else { 10815 assert(CKind == OMPC_to || CKind == OMPC_from); 10816 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 10817 << ERange; 10818 } 10819 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10820 << RE->getSourceRange(); 10821 return true; 10822 } 10823 10824 // The current expression uses the same base as other expression in the 10825 // data environment but does not contain it completely. 10826 if (!CurrentRegionOnly && SI != SE) 10827 EnclosingExpr = RE; 10828 10829 // The current expression is a subset of the expression in the data 10830 // environment. 10831 IsEnclosedByDataEnvironmentExpr |= 10832 (!CurrentRegionOnly && CI != CE && SI == SE); 10833 10834 return false; 10835 }); 10836 10837 if (CurrentRegionOnly) 10838 return FoundError; 10839 10840 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 10841 // If any part of the original storage of a list item has corresponding 10842 // storage in the device data environment, all of the original storage must 10843 // have corresponding storage in the device data environment. 10844 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 10845 // If a list item is an element of a structure, and a different element of 10846 // the structure has a corresponding list item in the device data environment 10847 // prior to a task encountering the construct associated with the map clause, 10848 // then the list item must also have a corresponding list item in the device 10849 // data environment prior to the task encountering the construct. 10850 // 10851 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 10852 SemaRef.Diag(ELoc, 10853 diag::err_omp_original_storage_is_shared_and_does_not_contain) 10854 << ERange; 10855 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 10856 << EnclosingExpr->getSourceRange(); 10857 return true; 10858 } 10859 10860 return FoundError; 10861 } 10862 10863 namespace { 10864 // Utility struct that gathers all the related lists associated with a mappable 10865 // expression. 10866 struct MappableVarListInfo final { 10867 // The list of expressions. 10868 ArrayRef<Expr *> VarList; 10869 // The list of processed expressions. 10870 SmallVector<Expr *, 16> ProcessedVarList; 10871 // The mappble components for each expression. 10872 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 10873 // The base declaration of the variable. 10874 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 10875 10876 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 10877 // We have a list of components and base declarations for each entry in the 10878 // variable list. 10879 VarComponents.reserve(VarList.size()); 10880 VarBaseDeclarations.reserve(VarList.size()); 10881 } 10882 }; 10883 } 10884 10885 // Check the validity of the provided variable list for the provided clause kind 10886 // \a CKind. In the check process the valid expressions, and mappable expression 10887 // components and variables are extracted and used to fill \a Vars, 10888 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and 10889 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'. 10890 static void 10891 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS, 10892 OpenMPClauseKind CKind, MappableVarListInfo &MVLI, 10893 SourceLocation StartLoc, 10894 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 10895 bool IsMapTypeImplicit = false) { 10896 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 10897 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 10898 "Unexpected clause kind with mappable expressions!"); 10899 10900 // Keep track of the mappable components and base declarations in this clause. 10901 // Each entry in the list is going to have a list of components associated. We 10902 // record each set of the components so that we can build the clause later on. 10903 // In the end we should have the same amount of declarations and component 10904 // lists. 10905 10906 for (auto &RE : MVLI.VarList) { 10907 assert(RE && "Null expr in omp to/from/map clause"); 10908 SourceLocation ELoc = RE->getExprLoc(); 10909 10910 auto *VE = RE->IgnoreParenLValueCasts(); 10911 10912 if (VE->isValueDependent() || VE->isTypeDependent() || 10913 VE->isInstantiationDependent() || 10914 VE->containsUnexpandedParameterPack()) { 10915 // We can only analyze this information once the missing information is 10916 // resolved. 10917 MVLI.ProcessedVarList.push_back(RE); 10918 continue; 10919 } 10920 10921 auto *SimpleExpr = RE->IgnoreParenCasts(); 10922 10923 if (!RE->IgnoreParenImpCasts()->isLValue()) { 10924 SemaRef.Diag(ELoc, 10925 diag::err_omp_expected_named_var_member_or_array_expression) 10926 << RE->getSourceRange(); 10927 continue; 10928 } 10929 10930 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 10931 ValueDecl *CurDeclaration = nullptr; 10932 10933 // Obtain the array or member expression bases if required. Also, fill the 10934 // components array with all the components identified in the process. 10935 auto *BE = 10936 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind); 10937 if (!BE) 10938 continue; 10939 10940 assert(!CurComponents.empty() && 10941 "Invalid mappable expression information."); 10942 10943 // For the following checks, we rely on the base declaration which is 10944 // expected to be associated with the last component. The declaration is 10945 // expected to be a variable or a field (if 'this' is being mapped). 10946 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 10947 assert(CurDeclaration && "Null decl on map clause."); 10948 assert( 10949 CurDeclaration->isCanonicalDecl() && 10950 "Expecting components to have associated only canonical declarations."); 10951 10952 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 10953 auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 10954 10955 assert((VD || FD) && "Only variables or fields are expected here!"); 10956 (void)FD; 10957 10958 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 10959 // threadprivate variables cannot appear in a map clause. 10960 // OpenMP 4.5 [2.10.5, target update Construct] 10961 // threadprivate variables cannot appear in a from clause. 10962 if (VD && DSAS->isThreadPrivate(VD)) { 10963 auto DVar = DSAS->getTopDSA(VD, false); 10964 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 10965 << getOpenMPClauseName(CKind); 10966 ReportOriginalDSA(SemaRef, DSAS, VD, DVar); 10967 continue; 10968 } 10969 10970 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 10971 // A list item cannot appear in both a map clause and a data-sharing 10972 // attribute clause on the same construct. 10973 10974 // Check conflicts with other map clause expressions. We check the conflicts 10975 // with the current construct separately from the enclosing data 10976 // environment, because the restrictions are different. We only have to 10977 // check conflicts across regions for the map clauses. 10978 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 10979 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 10980 break; 10981 if (CKind == OMPC_map && 10982 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 10983 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 10984 break; 10985 10986 // OpenMP 4.5 [2.10.5, target update Construct] 10987 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10988 // If the type of a list item is a reference to a type T then the type will 10989 // be considered to be T for all purposes of this clause. 10990 QualType Type = CurDeclaration->getType().getNonReferenceType(); 10991 10992 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 10993 // A list item in a to or from clause must have a mappable type. 10994 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 10995 // A list item must have a mappable type. 10996 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 10997 DSAS, Type)) 10998 continue; 10999 11000 if (CKind == OMPC_map) { 11001 // target enter data 11002 // OpenMP [2.10.2, Restrictions, p. 99] 11003 // A map-type must be specified in all map clauses and must be either 11004 // to or alloc. 11005 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 11006 if (DKind == OMPD_target_enter_data && 11007 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 11008 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 11009 << (IsMapTypeImplicit ? 1 : 0) 11010 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 11011 << getOpenMPDirectiveName(DKind); 11012 continue; 11013 } 11014 11015 // target exit_data 11016 // OpenMP [2.10.3, Restrictions, p. 102] 11017 // A map-type must be specified in all map clauses and must be either 11018 // from, release, or delete. 11019 if (DKind == OMPD_target_exit_data && 11020 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 11021 MapType == OMPC_MAP_delete)) { 11022 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 11023 << (IsMapTypeImplicit ? 1 : 0) 11024 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 11025 << getOpenMPDirectiveName(DKind); 11026 continue; 11027 } 11028 11029 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 11030 // A list item cannot appear in both a map clause and a data-sharing 11031 // attribute clause on the same construct 11032 if ((DKind == OMPD_target || DKind == OMPD_target_teams || 11033 DKind == OMPD_target_teams_distribute || 11034 DKind == OMPD_target_teams_distribute_parallel_for || 11035 DKind == OMPD_target_teams_distribute_parallel_for_simd || 11036 DKind == OMPD_target_teams_distribute_simd) && VD) { 11037 auto DVar = DSAS->getTopDSA(VD, false); 11038 if (isOpenMPPrivate(DVar.CKind)) { 11039 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 11040 << getOpenMPClauseName(DVar.CKind) 11041 << getOpenMPClauseName(OMPC_map) 11042 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 11043 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar); 11044 continue; 11045 } 11046 } 11047 } 11048 11049 // Save the current expression. 11050 MVLI.ProcessedVarList.push_back(RE); 11051 11052 // Store the components in the stack so that they can be used to check 11053 // against other clauses later on. 11054 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 11055 /*WhereFoundClauseKind=*/OMPC_map); 11056 11057 // Save the components and declaration to create the clause. For purposes of 11058 // the clause creation, any component list that has has base 'this' uses 11059 // null as base declaration. 11060 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 11061 MVLI.VarComponents.back().append(CurComponents.begin(), 11062 CurComponents.end()); 11063 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 11064 : CurDeclaration); 11065 } 11066 } 11067 11068 OMPClause * 11069 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier, 11070 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 11071 SourceLocation MapLoc, SourceLocation ColonLoc, 11072 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 11073 SourceLocation LParenLoc, SourceLocation EndLoc) { 11074 MappableVarListInfo MVLI(VarList); 11075 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc, 11076 MapType, IsMapTypeImplicit); 11077 11078 // We need to produce a map clause even if we don't have variables so that 11079 // other diagnostics related with non-existing map clauses are accurate. 11080 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11081 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11082 MVLI.VarComponents, MapTypeModifier, MapType, 11083 IsMapTypeImplicit, MapLoc); 11084 } 11085 11086 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 11087 TypeResult ParsedType) { 11088 assert(ParsedType.isUsable()); 11089 11090 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 11091 if (ReductionType.isNull()) 11092 return QualType(); 11093 11094 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 11095 // A type name in a declare reduction directive cannot be a function type, an 11096 // array type, a reference type, or a type qualified with const, volatile or 11097 // restrict. 11098 if (ReductionType.hasQualifiers()) { 11099 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 11100 return QualType(); 11101 } 11102 11103 if (ReductionType->isFunctionType()) { 11104 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 11105 return QualType(); 11106 } 11107 if (ReductionType->isReferenceType()) { 11108 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 11109 return QualType(); 11110 } 11111 if (ReductionType->isArrayType()) { 11112 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 11113 return QualType(); 11114 } 11115 return ReductionType; 11116 } 11117 11118 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 11119 Scope *S, DeclContext *DC, DeclarationName Name, 11120 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 11121 AccessSpecifier AS, Decl *PrevDeclInScope) { 11122 SmallVector<Decl *, 8> Decls; 11123 Decls.reserve(ReductionTypes.size()); 11124 11125 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 11126 ForRedeclaration); 11127 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 11128 // A reduction-identifier may not be re-declared in the current scope for the 11129 // same type or for a type that is compatible according to the base language 11130 // rules. 11131 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 11132 OMPDeclareReductionDecl *PrevDRD = nullptr; 11133 bool InCompoundScope = true; 11134 if (S != nullptr) { 11135 // Find previous declaration with the same name not referenced in other 11136 // declarations. 11137 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 11138 InCompoundScope = 11139 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 11140 LookupName(Lookup, S); 11141 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 11142 /*AllowInlineNamespace=*/false); 11143 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 11144 auto Filter = Lookup.makeFilter(); 11145 while (Filter.hasNext()) { 11146 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 11147 if (InCompoundScope) { 11148 auto I = UsedAsPrevious.find(PrevDecl); 11149 if (I == UsedAsPrevious.end()) 11150 UsedAsPrevious[PrevDecl] = false; 11151 if (auto *D = PrevDecl->getPrevDeclInScope()) 11152 UsedAsPrevious[D] = true; 11153 } 11154 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 11155 PrevDecl->getLocation(); 11156 } 11157 Filter.done(); 11158 if (InCompoundScope) { 11159 for (auto &PrevData : UsedAsPrevious) { 11160 if (!PrevData.second) { 11161 PrevDRD = PrevData.first; 11162 break; 11163 } 11164 } 11165 } 11166 } else if (PrevDeclInScope != nullptr) { 11167 auto *PrevDRDInScope = PrevDRD = 11168 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 11169 do { 11170 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 11171 PrevDRDInScope->getLocation(); 11172 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 11173 } while (PrevDRDInScope != nullptr); 11174 } 11175 for (auto &TyData : ReductionTypes) { 11176 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 11177 bool Invalid = false; 11178 if (I != PreviousRedeclTypes.end()) { 11179 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 11180 << TyData.first; 11181 Diag(I->second, diag::note_previous_definition); 11182 Invalid = true; 11183 } 11184 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 11185 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 11186 Name, TyData.first, PrevDRD); 11187 DC->addDecl(DRD); 11188 DRD->setAccess(AS); 11189 Decls.push_back(DRD); 11190 if (Invalid) 11191 DRD->setInvalidDecl(); 11192 else 11193 PrevDRD = DRD; 11194 } 11195 11196 return DeclGroupPtrTy::make( 11197 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 11198 } 11199 11200 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 11201 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11202 11203 // Enter new function scope. 11204 PushFunctionScope(); 11205 getCurFunction()->setHasBranchProtectedScope(); 11206 getCurFunction()->setHasOMPDeclareReductionCombiner(); 11207 11208 if (S != nullptr) 11209 PushDeclContext(S, DRD); 11210 else 11211 CurContext = DRD; 11212 11213 PushExpressionEvaluationContext( 11214 ExpressionEvaluationContext::PotentiallyEvaluated); 11215 11216 QualType ReductionType = DRD->getType(); 11217 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 11218 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 11219 // uses semantics of argument handles by value, but it should be passed by 11220 // reference. C lang does not support references, so pass all parameters as 11221 // pointers. 11222 // Create 'T omp_in;' variable. 11223 auto *OmpInParm = 11224 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 11225 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 11226 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 11227 // uses semantics of argument handles by value, but it should be passed by 11228 // reference. C lang does not support references, so pass all parameters as 11229 // pointers. 11230 // Create 'T omp_out;' variable. 11231 auto *OmpOutParm = 11232 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 11233 if (S != nullptr) { 11234 PushOnScopeChains(OmpInParm, S); 11235 PushOnScopeChains(OmpOutParm, S); 11236 } else { 11237 DRD->addDecl(OmpInParm); 11238 DRD->addDecl(OmpOutParm); 11239 } 11240 } 11241 11242 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 11243 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11244 DiscardCleanupsInEvaluationContext(); 11245 PopExpressionEvaluationContext(); 11246 11247 PopDeclContext(); 11248 PopFunctionScopeInfo(); 11249 11250 if (Combiner != nullptr) 11251 DRD->setCombiner(Combiner); 11252 else 11253 DRD->setInvalidDecl(); 11254 } 11255 11256 void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 11257 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11258 11259 // Enter new function scope. 11260 PushFunctionScope(); 11261 getCurFunction()->setHasBranchProtectedScope(); 11262 11263 if (S != nullptr) 11264 PushDeclContext(S, DRD); 11265 else 11266 CurContext = DRD; 11267 11268 PushExpressionEvaluationContext( 11269 ExpressionEvaluationContext::PotentiallyEvaluated); 11270 11271 QualType ReductionType = DRD->getType(); 11272 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 11273 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 11274 // uses semantics of argument handles by value, but it should be passed by 11275 // reference. C lang does not support references, so pass all parameters as 11276 // pointers. 11277 // Create 'T omp_priv;' variable. 11278 auto *OmpPrivParm = 11279 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 11280 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 11281 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 11282 // uses semantics of argument handles by value, but it should be passed by 11283 // reference. C lang does not support references, so pass all parameters as 11284 // pointers. 11285 // Create 'T omp_orig;' variable. 11286 auto *OmpOrigParm = 11287 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 11288 if (S != nullptr) { 11289 PushOnScopeChains(OmpPrivParm, S); 11290 PushOnScopeChains(OmpOrigParm, S); 11291 } else { 11292 DRD->addDecl(OmpPrivParm); 11293 DRD->addDecl(OmpOrigParm); 11294 } 11295 } 11296 11297 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, 11298 Expr *Initializer) { 11299 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11300 DiscardCleanupsInEvaluationContext(); 11301 PopExpressionEvaluationContext(); 11302 11303 PopDeclContext(); 11304 PopFunctionScopeInfo(); 11305 11306 if (Initializer != nullptr) 11307 DRD->setInitializer(Initializer); 11308 else 11309 DRD->setInvalidDecl(); 11310 } 11311 11312 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 11313 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 11314 for (auto *D : DeclReductions.get()) { 11315 if (IsValid) { 11316 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11317 if (S != nullptr) 11318 PushOnScopeChains(DRD, S, /*AddToContext=*/false); 11319 } else 11320 D->setInvalidDecl(); 11321 } 11322 return DeclReductions; 11323 } 11324 11325 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 11326 SourceLocation StartLoc, 11327 SourceLocation LParenLoc, 11328 SourceLocation EndLoc) { 11329 Expr *ValExpr = NumTeams; 11330 Stmt *HelperValStmt = nullptr; 11331 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 11332 11333 // OpenMP [teams Constrcut, Restrictions] 11334 // The num_teams expression must evaluate to a positive integer value. 11335 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 11336 /*StrictlyPositive=*/true)) 11337 return nullptr; 11338 11339 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 11340 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams); 11341 if (CaptureRegion != OMPD_unknown) { 11342 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11343 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11344 HelperValStmt = buildPreInits(Context, Captures); 11345 } 11346 11347 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 11348 StartLoc, LParenLoc, EndLoc); 11349 } 11350 11351 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 11352 SourceLocation StartLoc, 11353 SourceLocation LParenLoc, 11354 SourceLocation EndLoc) { 11355 Expr *ValExpr = ThreadLimit; 11356 Stmt *HelperValStmt = nullptr; 11357 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 11358 11359 // OpenMP [teams Constrcut, Restrictions] 11360 // The thread_limit expression must evaluate to a positive integer value. 11361 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 11362 /*StrictlyPositive=*/true)) 11363 return nullptr; 11364 11365 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 11366 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit); 11367 if (CaptureRegion != OMPD_unknown) { 11368 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11369 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11370 HelperValStmt = buildPreInits(Context, Captures); 11371 } 11372 11373 return new (Context) OMPThreadLimitClause( 11374 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 11375 } 11376 11377 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 11378 SourceLocation StartLoc, 11379 SourceLocation LParenLoc, 11380 SourceLocation EndLoc) { 11381 Expr *ValExpr = Priority; 11382 11383 // OpenMP [2.9.1, task Constrcut] 11384 // The priority-value is a non-negative numerical scalar expression. 11385 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority, 11386 /*StrictlyPositive=*/false)) 11387 return nullptr; 11388 11389 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11390 } 11391 11392 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 11393 SourceLocation StartLoc, 11394 SourceLocation LParenLoc, 11395 SourceLocation EndLoc) { 11396 Expr *ValExpr = Grainsize; 11397 11398 // OpenMP [2.9.2, taskloop Constrcut] 11399 // The parameter of the grainsize clause must be a positive integer 11400 // expression. 11401 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize, 11402 /*StrictlyPositive=*/true)) 11403 return nullptr; 11404 11405 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11406 } 11407 11408 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 11409 SourceLocation StartLoc, 11410 SourceLocation LParenLoc, 11411 SourceLocation EndLoc) { 11412 Expr *ValExpr = NumTasks; 11413 11414 // OpenMP [2.9.2, taskloop Constrcut] 11415 // The parameter of the num_tasks clause must be a positive integer 11416 // expression. 11417 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks, 11418 /*StrictlyPositive=*/true)) 11419 return nullptr; 11420 11421 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11422 } 11423 11424 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 11425 SourceLocation LParenLoc, 11426 SourceLocation EndLoc) { 11427 // OpenMP [2.13.2, critical construct, Description] 11428 // ... where hint-expression is an integer constant expression that evaluates 11429 // to a valid lock hint. 11430 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 11431 if (HintExpr.isInvalid()) 11432 return nullptr; 11433 return new (Context) 11434 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 11435 } 11436 11437 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 11438 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 11439 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 11440 SourceLocation EndLoc) { 11441 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 11442 std::string Values; 11443 Values += "'"; 11444 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 11445 Values += "'"; 11446 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 11447 << Values << getOpenMPClauseName(OMPC_dist_schedule); 11448 return nullptr; 11449 } 11450 Expr *ValExpr = ChunkSize; 11451 Stmt *HelperValStmt = nullptr; 11452 if (ChunkSize) { 11453 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 11454 !ChunkSize->isInstantiationDependent() && 11455 !ChunkSize->containsUnexpandedParameterPack()) { 11456 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 11457 ExprResult Val = 11458 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 11459 if (Val.isInvalid()) 11460 return nullptr; 11461 11462 ValExpr = Val.get(); 11463 11464 // OpenMP [2.7.1, Restrictions] 11465 // chunk_size must be a loop invariant integer expression with a positive 11466 // value. 11467 llvm::APSInt Result; 11468 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 11469 if (Result.isSigned() && !Result.isStrictlyPositive()) { 11470 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 11471 << "dist_schedule" << ChunkSize->getSourceRange(); 11472 return nullptr; 11473 } 11474 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 11475 !CurContext->isDependentContext()) { 11476 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11477 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11478 HelperValStmt = buildPreInits(Context, Captures); 11479 } 11480 } 11481 } 11482 11483 return new (Context) 11484 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 11485 Kind, ValExpr, HelperValStmt); 11486 } 11487 11488 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 11489 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 11490 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 11491 SourceLocation KindLoc, SourceLocation EndLoc) { 11492 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)' 11493 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) { 11494 std::string Value; 11495 SourceLocation Loc; 11496 Value += "'"; 11497 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 11498 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 11499 OMPC_DEFAULTMAP_MODIFIER_tofrom); 11500 Loc = MLoc; 11501 } else { 11502 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 11503 OMPC_DEFAULTMAP_scalar); 11504 Loc = KindLoc; 11505 } 11506 Value += "'"; 11507 Diag(Loc, diag::err_omp_unexpected_clause_value) 11508 << Value << getOpenMPClauseName(OMPC_defaultmap); 11509 return nullptr; 11510 } 11511 11512 return new (Context) 11513 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 11514 } 11515 11516 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 11517 DeclContext *CurLexicalContext = getCurLexicalContext(); 11518 if (!CurLexicalContext->isFileContext() && 11519 !CurLexicalContext->isExternCContext() && 11520 !CurLexicalContext->isExternCXXContext()) { 11521 Diag(Loc, diag::err_omp_region_not_file_context); 11522 return false; 11523 } 11524 if (IsInOpenMPDeclareTargetContext) { 11525 Diag(Loc, diag::err_omp_enclosed_declare_target); 11526 return false; 11527 } 11528 11529 IsInOpenMPDeclareTargetContext = true; 11530 return true; 11531 } 11532 11533 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 11534 assert(IsInOpenMPDeclareTargetContext && 11535 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 11536 11537 IsInOpenMPDeclareTargetContext = false; 11538 } 11539 11540 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, 11541 CXXScopeSpec &ScopeSpec, 11542 const DeclarationNameInfo &Id, 11543 OMPDeclareTargetDeclAttr::MapTypeTy MT, 11544 NamedDeclSetType &SameDirectiveDecls) { 11545 LookupResult Lookup(*this, Id, LookupOrdinaryName); 11546 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 11547 11548 if (Lookup.isAmbiguous()) 11549 return; 11550 Lookup.suppressDiagnostics(); 11551 11552 if (!Lookup.isSingleResult()) { 11553 if (TypoCorrection Corrected = 11554 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, 11555 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this), 11556 CTK_ErrorRecovery)) { 11557 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 11558 << Id.getName()); 11559 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 11560 return; 11561 } 11562 11563 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 11564 return; 11565 } 11566 11567 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 11568 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 11569 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 11570 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 11571 11572 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) { 11573 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT); 11574 ND->addAttr(A); 11575 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11576 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 11577 checkDeclIsAllowedInOpenMPTarget(nullptr, ND); 11578 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) { 11579 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link) 11580 << Id.getName(); 11581 } 11582 } else 11583 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 11584 } 11585 11586 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 11587 Sema &SemaRef, Decl *D) { 11588 if (!D) 11589 return; 11590 Decl *LD = nullptr; 11591 if (isa<TagDecl>(D)) { 11592 LD = cast<TagDecl>(D)->getDefinition(); 11593 } else if (isa<VarDecl>(D)) { 11594 LD = cast<VarDecl>(D)->getDefinition(); 11595 11596 // If this is an implicit variable that is legal and we do not need to do 11597 // anything. 11598 if (cast<VarDecl>(D)->isImplicit()) { 11599 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11600 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11601 D->addAttr(A); 11602 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11603 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11604 return; 11605 } 11606 11607 } else if (isa<FunctionDecl>(D)) { 11608 const FunctionDecl *FD = nullptr; 11609 if (cast<FunctionDecl>(D)->hasBody(FD)) 11610 LD = const_cast<FunctionDecl *>(FD); 11611 11612 // If the definition is associated with the current declaration in the 11613 // target region (it can be e.g. a lambda) that is legal and we do not need 11614 // to do anything else. 11615 if (LD == D) { 11616 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11617 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11618 D->addAttr(A); 11619 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11620 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11621 return; 11622 } 11623 } 11624 if (!LD) 11625 LD = D; 11626 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() && 11627 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) { 11628 // Outlined declaration is not declared target. 11629 if (LD->isOutOfLine()) { 11630 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 11631 SemaRef.Diag(SL, diag::note_used_here) << SR; 11632 } else { 11633 DeclContext *DC = LD->getDeclContext(); 11634 while (DC) { 11635 if (isa<FunctionDecl>(DC) && 11636 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>()) 11637 break; 11638 DC = DC->getParent(); 11639 } 11640 if (DC) 11641 return; 11642 11643 // Is not declared in target context. 11644 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 11645 SemaRef.Diag(SL, diag::note_used_here) << SR; 11646 } 11647 // Mark decl as declared target to prevent further diagnostic. 11648 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11649 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11650 D->addAttr(A); 11651 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11652 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11653 } 11654 } 11655 11656 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 11657 Sema &SemaRef, DSAStackTy *Stack, 11658 ValueDecl *VD) { 11659 if (VD->hasAttr<OMPDeclareTargetDeclAttr>()) 11660 return true; 11661 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType())) 11662 return false; 11663 return true; 11664 } 11665 11666 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) { 11667 if (!D || D->isInvalidDecl()) 11668 return; 11669 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 11670 SourceLocation SL = E ? E->getLocStart() : D->getLocation(); 11671 // 2.10.6: threadprivate variable cannot appear in a declare target directive. 11672 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 11673 if (DSAStack->isThreadPrivate(VD)) { 11674 Diag(SL, diag::err_omp_threadprivate_in_target); 11675 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 11676 return; 11677 } 11678 } 11679 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 11680 // Problem if any with var declared with incomplete type will be reported 11681 // as normal, so no need to check it here. 11682 if ((E || !VD->getType()->isIncompleteType()) && 11683 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) { 11684 // Mark decl as declared target to prevent further diagnostic. 11685 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) { 11686 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11687 Context, OMPDeclareTargetDeclAttr::MT_To); 11688 VD->addAttr(A); 11689 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11690 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A); 11691 } 11692 return; 11693 } 11694 } 11695 if (!E) { 11696 // Checking declaration inside declare target region. 11697 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() && 11698 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) { 11699 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11700 Context, OMPDeclareTargetDeclAttr::MT_To); 11701 D->addAttr(A); 11702 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11703 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11704 } 11705 return; 11706 } 11707 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 11708 } 11709 11710 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, 11711 SourceLocation StartLoc, 11712 SourceLocation LParenLoc, 11713 SourceLocation EndLoc) { 11714 MappableVarListInfo MVLI(VarList); 11715 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc); 11716 if (MVLI.ProcessedVarList.empty()) 11717 return nullptr; 11718 11719 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11720 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11721 MVLI.VarComponents); 11722 } 11723 11724 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, 11725 SourceLocation StartLoc, 11726 SourceLocation LParenLoc, 11727 SourceLocation EndLoc) { 11728 MappableVarListInfo MVLI(VarList); 11729 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc); 11730 if (MVLI.ProcessedVarList.empty()) 11731 return nullptr; 11732 11733 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11734 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11735 MVLI.VarComponents); 11736 } 11737 11738 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 11739 SourceLocation StartLoc, 11740 SourceLocation LParenLoc, 11741 SourceLocation EndLoc) { 11742 MappableVarListInfo MVLI(VarList); 11743 SmallVector<Expr *, 8> PrivateCopies; 11744 SmallVector<Expr *, 8> Inits; 11745 11746 for (auto &RefExpr : VarList) { 11747 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 11748 SourceLocation ELoc; 11749 SourceRange ERange; 11750 Expr *SimpleRefExpr = RefExpr; 11751 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11752 if (Res.second) { 11753 // It will be analyzed later. 11754 MVLI.ProcessedVarList.push_back(RefExpr); 11755 PrivateCopies.push_back(nullptr); 11756 Inits.push_back(nullptr); 11757 } 11758 ValueDecl *D = Res.first; 11759 if (!D) 11760 continue; 11761 11762 QualType Type = D->getType(); 11763 Type = Type.getNonReferenceType().getUnqualifiedType(); 11764 11765 auto *VD = dyn_cast<VarDecl>(D); 11766 11767 // Item should be a pointer or reference to pointer. 11768 if (!Type->isPointerType()) { 11769 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 11770 << 0 << RefExpr->getSourceRange(); 11771 continue; 11772 } 11773 11774 // Build the private variable and the expression that refers to it. 11775 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 11776 D->hasAttrs() ? &D->getAttrs() : nullptr); 11777 if (VDPrivate->isInvalidDecl()) 11778 continue; 11779 11780 CurContext->addDecl(VDPrivate); 11781 auto VDPrivateRefExpr = buildDeclRefExpr( 11782 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 11783 11784 // Add temporary variable to initialize the private copy of the pointer. 11785 auto *VDInit = 11786 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 11787 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 11788 RefExpr->getExprLoc()); 11789 AddInitializerToDecl(VDPrivate, 11790 DefaultLvalueConversion(VDInitRefExpr).get(), 11791 /*DirectInit=*/false); 11792 11793 // If required, build a capture to implement the privatization initialized 11794 // with the current list item value. 11795 DeclRefExpr *Ref = nullptr; 11796 if (!VD) 11797 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 11798 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 11799 PrivateCopies.push_back(VDPrivateRefExpr); 11800 Inits.push_back(VDInitRefExpr); 11801 11802 // We need to add a data sharing attribute for this variable to make sure it 11803 // is correctly captured. A variable that shows up in a use_device_ptr has 11804 // similar properties of a first private variable. 11805 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 11806 11807 // Create a mappable component for the list item. List items in this clause 11808 // only need a component. 11809 MVLI.VarBaseDeclarations.push_back(D); 11810 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 11811 MVLI.VarComponents.back().push_back( 11812 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D)); 11813 } 11814 11815 if (MVLI.ProcessedVarList.empty()) 11816 return nullptr; 11817 11818 return OMPUseDevicePtrClause::Create( 11819 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 11820 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents); 11821 } 11822 11823 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 11824 SourceLocation StartLoc, 11825 SourceLocation LParenLoc, 11826 SourceLocation EndLoc) { 11827 MappableVarListInfo MVLI(VarList); 11828 for (auto &RefExpr : VarList) { 11829 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 11830 SourceLocation ELoc; 11831 SourceRange ERange; 11832 Expr *SimpleRefExpr = RefExpr; 11833 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11834 if (Res.second) { 11835 // It will be analyzed later. 11836 MVLI.ProcessedVarList.push_back(RefExpr); 11837 } 11838 ValueDecl *D = Res.first; 11839 if (!D) 11840 continue; 11841 11842 QualType Type = D->getType(); 11843 // item should be a pointer or array or reference to pointer or array 11844 if (!Type.getNonReferenceType()->isPointerType() && 11845 !Type.getNonReferenceType()->isArrayType()) { 11846 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 11847 << 0 << RefExpr->getSourceRange(); 11848 continue; 11849 } 11850 11851 // Check if the declaration in the clause does not show up in any data 11852 // sharing attribute. 11853 auto DVar = DSAStack->getTopDSA(D, false); 11854 if (isOpenMPPrivate(DVar.CKind)) { 11855 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 11856 << getOpenMPClauseName(DVar.CKind) 11857 << getOpenMPClauseName(OMPC_is_device_ptr) 11858 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 11859 ReportOriginalDSA(*this, DSAStack, D, DVar); 11860 continue; 11861 } 11862 11863 Expr *ConflictExpr; 11864 if (DSAStack->checkMappableExprComponentListsForDecl( 11865 D, /*CurrentRegionOnly=*/true, 11866 [&ConflictExpr]( 11867 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 11868 OpenMPClauseKind) -> bool { 11869 ConflictExpr = R.front().getAssociatedExpression(); 11870 return true; 11871 })) { 11872 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 11873 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 11874 << ConflictExpr->getSourceRange(); 11875 continue; 11876 } 11877 11878 // Store the components in the stack so that they can be used to check 11879 // against other clauses later on. 11880 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D); 11881 DSAStack->addMappableExpressionComponents( 11882 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 11883 11884 // Record the expression we've just processed. 11885 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 11886 11887 // Create a mappable component for the list item. List items in this clause 11888 // only need a component. We use a null declaration to signal fields in 11889 // 'this'. 11890 assert((isa<DeclRefExpr>(SimpleRefExpr) || 11891 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 11892 "Unexpected device pointer expression!"); 11893 MVLI.VarBaseDeclarations.push_back( 11894 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 11895 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 11896 MVLI.VarComponents.back().push_back(MC); 11897 } 11898 11899 if (MVLI.ProcessedVarList.empty()) 11900 return nullptr; 11901 11902 return OMPIsDevicePtrClause::Create( 11903 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 11904 MVLI.VarBaseDeclarations, MVLI.VarComponents); 11905 } 11906