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 /// Create a new mappable expression component list associated with a given 416 /// declaration and initialize it with the provided list of components. 417 void addMappableExpressionComponents( 418 ValueDecl *VD, 419 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 420 OpenMPClauseKind WhereFoundClauseKind) { 421 assert(!isStackEmpty() && 422 "Not expecting to retrieve components from a empty stack!"); 423 auto &MEC = Stack.back().first.back().MappedExprComponents[VD]; 424 // Create new entry and append the new components there. 425 MEC.Components.resize(MEC.Components.size() + 1); 426 MEC.Components.back().append(Components.begin(), Components.end()); 427 MEC.Kind = WhereFoundClauseKind; 428 } 429 430 unsigned getNestingLevel() const { 431 assert(!isStackEmpty()); 432 return Stack.back().first.size() - 1; 433 } 434 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) { 435 assert(!isStackEmpty() && Stack.back().first.size() > 1); 436 auto &StackElem = *std::next(Stack.back().first.rbegin()); 437 assert(isOpenMPWorksharingDirective(StackElem.Directive)); 438 StackElem.DoacrossDepends.insert({C, OpsOffs}); 439 } 440 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 441 getDoacrossDependClauses() const { 442 assert(!isStackEmpty()); 443 auto &StackElem = Stack.back().first.back(); 444 if (isOpenMPWorksharingDirective(StackElem.Directive)) { 445 auto &Ref = StackElem.DoacrossDepends; 446 return llvm::make_range(Ref.begin(), Ref.end()); 447 } 448 return llvm::make_range(StackElem.DoacrossDepends.end(), 449 StackElem.DoacrossDepends.end()); 450 } 451 }; 452 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) { 453 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) || 454 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown; 455 } 456 } // namespace 457 458 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 459 auto *VD = dyn_cast<VarDecl>(D); 460 auto *FD = dyn_cast<FieldDecl>(D); 461 if (VD != nullptr) { 462 VD = VD->getCanonicalDecl(); 463 D = VD; 464 } else { 465 assert(FD); 466 FD = FD->getCanonicalDecl(); 467 D = FD; 468 } 469 return D; 470 } 471 472 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter, 473 ValueDecl *D) { 474 D = getCanonicalDecl(D); 475 auto *VD = dyn_cast<VarDecl>(D); 476 auto *FD = dyn_cast<FieldDecl>(D); 477 DSAVarData DVar; 478 if (isStackEmpty() || Iter == Stack.back().first.rend()) { 479 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 480 // in a region but not in construct] 481 // File-scope or namespace-scope variables referenced in called routines 482 // in the region are shared unless they appear in a threadprivate 483 // directive. 484 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D)) 485 DVar.CKind = OMPC_shared; 486 487 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 488 // in a region but not in construct] 489 // Variables with static storage duration that are declared in called 490 // routines in the region are shared. 491 if (VD && VD->hasGlobalStorage()) 492 DVar.CKind = OMPC_shared; 493 494 // Non-static data members are shared by default. 495 if (FD) 496 DVar.CKind = OMPC_shared; 497 498 return DVar; 499 } 500 501 DVar.DKind = Iter->Directive; 502 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 503 // in a Construct, C/C++, predetermined, p.1] 504 // Variables with automatic storage duration that are declared in a scope 505 // inside the construct are private. 506 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 507 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 508 DVar.CKind = OMPC_private; 509 return DVar; 510 } 511 512 // Explicitly specified attributes and local variables with predetermined 513 // attributes. 514 if (Iter->SharingMap.count(D)) { 515 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer(); 516 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy; 517 DVar.CKind = Iter->SharingMap[D].Attributes; 518 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 519 return DVar; 520 } 521 522 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 523 // in a Construct, C/C++, implicitly determined, p.1] 524 // In a parallel or task construct, the data-sharing attributes of these 525 // variables are determined by the default clause, if present. 526 switch (Iter->DefaultAttr) { 527 case DSA_shared: 528 DVar.CKind = OMPC_shared; 529 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 530 return DVar; 531 case DSA_none: 532 return DVar; 533 case DSA_unspecified: 534 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 535 // in a Construct, implicitly determined, p.2] 536 // In a parallel construct, if no default clause is present, these 537 // variables are shared. 538 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 539 if (isOpenMPParallelDirective(DVar.DKind) || 540 isOpenMPTeamsDirective(DVar.DKind)) { 541 DVar.CKind = OMPC_shared; 542 return DVar; 543 } 544 545 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 546 // in a Construct, implicitly determined, p.4] 547 // In a task construct, if no default clause is present, a variable that in 548 // the enclosing context is determined to be shared by all implicit tasks 549 // bound to the current team is shared. 550 if (isOpenMPTaskingDirective(DVar.DKind)) { 551 DSAVarData DVarTemp; 552 auto I = Iter, E = Stack.back().first.rend(); 553 do { 554 ++I; 555 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 556 // Referenced in a Construct, implicitly determined, p.6] 557 // In a task construct, if no default clause is present, a variable 558 // whose data-sharing attribute is not determined by the rules above is 559 // firstprivate. 560 DVarTemp = getDSA(I, D); 561 if (DVarTemp.CKind != OMPC_shared) { 562 DVar.RefExpr = nullptr; 563 DVar.CKind = OMPC_firstprivate; 564 return DVar; 565 } 566 } while (I != E && !isParallelOrTaskRegion(I->Directive)); 567 DVar.CKind = 568 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 569 return DVar; 570 } 571 } 572 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 573 // in a Construct, implicitly determined, p.3] 574 // For constructs other than task, if no default clause is present, these 575 // variables inherit their data-sharing attributes from the enclosing 576 // context. 577 return getDSA(++Iter, D); 578 } 579 580 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) { 581 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 582 D = getCanonicalDecl(D); 583 auto &StackElem = Stack.back().first.back(); 584 auto It = StackElem.AlignedMap.find(D); 585 if (It == StackElem.AlignedMap.end()) { 586 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 587 StackElem.AlignedMap[D] = NewDE; 588 return nullptr; 589 } else { 590 assert(It->second && "Unexpected nullptr expr in the aligned map"); 591 return It->second; 592 } 593 return nullptr; 594 } 595 596 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) { 597 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 598 D = getCanonicalDecl(D); 599 auto &StackElem = Stack.back().first.back(); 600 StackElem.LCVMap.insert( 601 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)}); 602 } 603 604 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) { 605 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 606 D = getCanonicalDecl(D); 607 auto &StackElem = Stack.back().first.back(); 608 auto It = StackElem.LCVMap.find(D); 609 if (It != StackElem.LCVMap.end()) 610 return It->second; 611 return {0, nullptr}; 612 } 613 614 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) { 615 assert(!isStackEmpty() && Stack.back().first.size() > 1 && 616 "Data-sharing attributes stack is empty"); 617 D = getCanonicalDecl(D); 618 auto &StackElem = *std::next(Stack.back().first.rbegin()); 619 auto It = StackElem.LCVMap.find(D); 620 if (It != StackElem.LCVMap.end()) 621 return It->second; 622 return {0, nullptr}; 623 } 624 625 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) { 626 assert(!isStackEmpty() && Stack.back().first.size() > 1 && 627 "Data-sharing attributes stack is empty"); 628 auto &StackElem = *std::next(Stack.back().first.rbegin()); 629 if (StackElem.LCVMap.size() < I) 630 return nullptr; 631 for (auto &Pair : StackElem.LCVMap) 632 if (Pair.second.first == I) 633 return Pair.first; 634 return nullptr; 635 } 636 637 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, 638 DeclRefExpr *PrivateCopy) { 639 D = getCanonicalDecl(D); 640 if (A == OMPC_threadprivate) { 641 auto &Data = Threadprivates[D]; 642 Data.Attributes = A; 643 Data.RefExpr.setPointer(E); 644 Data.PrivateCopy = nullptr; 645 } else { 646 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 647 auto &Data = Stack.back().first.back().SharingMap[D]; 648 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 649 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 650 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 651 (isLoopControlVariable(D).first && A == OMPC_private)); 652 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 653 Data.RefExpr.setInt(/*IntVal=*/true); 654 return; 655 } 656 const bool IsLastprivate = 657 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 658 Data.Attributes = A; 659 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 660 Data.PrivateCopy = PrivateCopy; 661 if (PrivateCopy) { 662 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()]; 663 Data.Attributes = A; 664 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 665 Data.PrivateCopy = nullptr; 666 } 667 } 668 } 669 670 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) { 671 D = D->getCanonicalDecl(); 672 if (!isStackEmpty() && Stack.back().first.size() > 1) { 673 reverse_iterator I = Iter, E = Stack.back().first.rend(); 674 Scope *TopScope = nullptr; 675 while (I != E && !isParallelOrTaskRegion(I->Directive)) 676 ++I; 677 if (I == E) 678 return false; 679 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; 680 Scope *CurScope = getCurScope(); 681 while (CurScope != TopScope && !CurScope->isDeclScope(D)) 682 CurScope = CurScope->getParent(); 683 return CurScope != TopScope; 684 } 685 return false; 686 } 687 688 /// \brief Build a variable declaration for OpenMP loop iteration variable. 689 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 690 StringRef Name, const AttrVec *Attrs = nullptr) { 691 DeclContext *DC = SemaRef.CurContext; 692 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 693 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 694 VarDecl *Decl = 695 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 696 if (Attrs) { 697 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 698 I != E; ++I) 699 Decl->addAttr(*I); 700 } 701 Decl->setImplicit(); 702 return Decl; 703 } 704 705 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 706 SourceLocation Loc, 707 bool RefersToCapture = false) { 708 D->setReferenced(); 709 D->markUsed(S.Context); 710 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 711 SourceLocation(), D, RefersToCapture, Loc, Ty, 712 VK_LValue); 713 } 714 715 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) { 716 D = getCanonicalDecl(D); 717 DSAVarData DVar; 718 719 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 720 // in a Construct, C/C++, predetermined, p.1] 721 // Variables appearing in threadprivate directives are threadprivate. 722 auto *VD = dyn_cast<VarDecl>(D); 723 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 724 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 725 SemaRef.getLangOpts().OpenMPUseTLS && 726 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 727 (VD && VD->getStorageClass() == SC_Register && 728 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 729 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 730 D->getLocation()), 731 OMPC_threadprivate); 732 } 733 auto TI = Threadprivates.find(D); 734 if (TI != Threadprivates.end()) { 735 DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); 736 DVar.CKind = OMPC_threadprivate; 737 return DVar; 738 } 739 740 if (isStackEmpty()) 741 // Not in OpenMP execution region and top scope was already checked. 742 return DVar; 743 744 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 745 // in a Construct, C/C++, predetermined, p.4] 746 // Static data members are shared. 747 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 748 // in a Construct, C/C++, predetermined, p.7] 749 // Variables with static storage duration that are declared in a scope 750 // inside the construct are shared. 751 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; }; 752 if (VD && VD->isStaticDataMember()) { 753 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent); 754 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 755 return DVar; 756 757 DVar.CKind = OMPC_shared; 758 return DVar; 759 } 760 761 QualType Type = D->getType().getNonReferenceType().getCanonicalType(); 762 bool IsConstant = Type.isConstant(SemaRef.getASTContext()); 763 Type = SemaRef.getASTContext().getBaseElementType(Type); 764 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 765 // in a Construct, C/C++, predetermined, p.6] 766 // Variables with const qualified type having no mutable member are 767 // shared. 768 CXXRecordDecl *RD = 769 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 770 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 771 if (auto *CTD = CTSD->getSpecializedTemplate()) 772 RD = CTD->getTemplatedDecl(); 773 if (IsConstant && 774 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() && 775 RD->hasMutableFields())) { 776 // Variables with const-qualified type having no mutable member may be 777 // listed in a firstprivate clause, even if they are static data members. 778 DSAVarData DVarTemp = hasDSA( 779 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; }, 780 MatchesAlways, FromParent); 781 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr) 782 return DVar; 783 784 DVar.CKind = OMPC_shared; 785 return DVar; 786 } 787 788 // Explicitly specified attributes and local variables with predetermined 789 // attributes. 790 auto StartI = std::next(Stack.back().first.rbegin()); 791 auto EndI = Stack.back().first.rend(); 792 if (FromParent && StartI != EndI) 793 StartI = std::next(StartI); 794 auto I = std::prev(StartI); 795 if (I->SharingMap.count(D)) { 796 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer(); 797 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy; 798 DVar.CKind = I->SharingMap[D].Attributes; 799 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 800 } 801 802 return DVar; 803 } 804 805 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 806 bool FromParent) { 807 if (isStackEmpty()) { 808 StackTy::reverse_iterator I; 809 return getDSA(I, D); 810 } 811 D = getCanonicalDecl(D); 812 auto StartI = Stack.back().first.rbegin(); 813 auto EndI = Stack.back().first.rend(); 814 if (FromParent && StartI != EndI) 815 StartI = std::next(StartI); 816 return getDSA(StartI, D); 817 } 818 819 DSAStackTy::DSAVarData 820 DSAStackTy::hasDSA(ValueDecl *D, 821 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 822 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 823 bool FromParent) { 824 if (isStackEmpty()) 825 return {}; 826 D = getCanonicalDecl(D); 827 auto StartI = std::next(Stack.back().first.rbegin()); 828 auto EndI = Stack.back().first.rend(); 829 if (FromParent && StartI != EndI) 830 StartI = std::next(StartI); 831 if (StartI == EndI) 832 return {}; 833 auto I = std::prev(StartI); 834 do { 835 ++I; 836 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive)) 837 continue; 838 DSAVarData DVar = getDSA(I, D); 839 if (CPred(DVar.CKind)) 840 return DVar; 841 } while (I != EndI); 842 return {}; 843 } 844 845 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 846 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 847 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 848 bool FromParent) { 849 if (isStackEmpty()) 850 return {}; 851 D = getCanonicalDecl(D); 852 auto StartI = std::next(Stack.back().first.rbegin()); 853 auto EndI = Stack.back().first.rend(); 854 if (FromParent && StartI != EndI) 855 StartI = std::next(StartI); 856 if (StartI == EndI || !DPred(StartI->Directive)) 857 return {}; 858 DSAVarData DVar = getDSA(StartI, D); 859 return CPred(DVar.CKind) ? DVar : DSAVarData(); 860 } 861 862 bool DSAStackTy::hasExplicitDSA( 863 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 864 unsigned Level, bool NotLastprivate) { 865 if (CPred(ClauseKindMode)) 866 return true; 867 if (isStackEmpty()) 868 return false; 869 D = getCanonicalDecl(D); 870 auto StartI = Stack.back().first.begin(); 871 auto EndI = Stack.back().first.end(); 872 if (std::distance(StartI, EndI) <= (int)Level) 873 return false; 874 std::advance(StartI, Level); 875 return (StartI->SharingMap.count(D) > 0) && 876 StartI->SharingMap[D].RefExpr.getPointer() && 877 CPred(StartI->SharingMap[D].Attributes) && 878 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt()); 879 } 880 881 bool DSAStackTy::hasExplicitDirective( 882 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 883 unsigned Level) { 884 if (isStackEmpty()) 885 return false; 886 auto StartI = Stack.back().first.begin(); 887 auto EndI = Stack.back().first.end(); 888 if (std::distance(StartI, EndI) <= (int)Level) 889 return false; 890 std::advance(StartI, Level); 891 return DPred(StartI->Directive); 892 } 893 894 bool DSAStackTy::hasDirective( 895 const llvm::function_ref<bool(OpenMPDirectiveKind, 896 const DeclarationNameInfo &, SourceLocation)> 897 &DPred, 898 bool FromParent) { 899 // We look only in the enclosing region. 900 if (isStackEmpty()) 901 return false; 902 auto StartI = std::next(Stack.back().first.rbegin()); 903 auto EndI = Stack.back().first.rend(); 904 if (FromParent && StartI != EndI) 905 StartI = std::next(StartI); 906 for (auto I = StartI, EE = EndI; I != EE; ++I) { 907 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 908 return true; 909 } 910 return false; 911 } 912 913 void Sema::InitDataSharingAttributesStack() { 914 VarDataSharingAttributesStack = new DSAStackTy(*this); 915 } 916 917 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 918 919 void Sema::pushOpenMPFunctionRegion() { 920 DSAStack->pushFunction(); 921 } 922 923 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 924 DSAStack->popFunction(OldFSI); 925 } 926 927 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) { 928 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 929 930 auto &Ctx = getASTContext(); 931 bool IsByRef = true; 932 933 // Find the directive that is associated with the provided scope. 934 auto Ty = D->getType(); 935 936 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 937 // This table summarizes how a given variable should be passed to the device 938 // given its type and the clauses where it appears. This table is based on 939 // the description in OpenMP 4.5 [2.10.4, target Construct] and 940 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 941 // 942 // ========================================================================= 943 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 944 // | |(tofrom:scalar)| | pvt | | | | 945 // ========================================================================= 946 // | scl | | | | - | | bycopy| 947 // | scl | | - | x | - | - | bycopy| 948 // | scl | | x | - | - | - | null | 949 // | scl | x | | | - | | byref | 950 // | scl | x | - | x | - | - | bycopy| 951 // | scl | x | x | - | - | - | null | 952 // | scl | | - | - | - | x | byref | 953 // | scl | x | - | - | - | x | byref | 954 // 955 // | agg | n.a. | | | - | | byref | 956 // | agg | n.a. | - | x | - | - | byref | 957 // | agg | n.a. | x | - | - | - | null | 958 // | agg | n.a. | - | - | - | x | byref | 959 // | agg | n.a. | - | - | - | x[] | byref | 960 // 961 // | ptr | n.a. | | | - | | bycopy| 962 // | ptr | n.a. | - | x | - | - | bycopy| 963 // | ptr | n.a. | x | - | - | - | null | 964 // | ptr | n.a. | - | - | - | x | byref | 965 // | ptr | n.a. | - | - | - | x[] | bycopy| 966 // | ptr | n.a. | - | - | x | | bycopy| 967 // | ptr | n.a. | - | - | x | x | bycopy| 968 // | ptr | n.a. | - | - | x | x[] | bycopy| 969 // ========================================================================= 970 // Legend: 971 // scl - scalar 972 // ptr - pointer 973 // agg - aggregate 974 // x - applies 975 // - - invalid in this combination 976 // [] - mapped with an array section 977 // byref - should be mapped by reference 978 // byval - should be mapped by value 979 // null - initialize a local variable to null on the device 980 // 981 // Observations: 982 // - All scalar declarations that show up in a map clause have to be passed 983 // by reference, because they may have been mapped in the enclosing data 984 // environment. 985 // - If the scalar value does not fit the size of uintptr, it has to be 986 // passed by reference, regardless the result in the table above. 987 // - For pointers mapped by value that have either an implicit map or an 988 // array section, the runtime library may pass the NULL value to the 989 // device instead of the value passed to it by the compiler. 990 991 if (Ty->isReferenceType()) 992 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 993 994 // Locate map clauses and see if the variable being captured is referred to 995 // in any of those clauses. Here we only care about variables, not fields, 996 // because fields are part of aggregates. 997 bool IsVariableUsedInMapClause = false; 998 bool IsVariableAssociatedWithSection = false; 999 1000 DSAStack->checkMappableExprComponentListsForDecl( 1001 D, /*CurrentRegionOnly=*/true, 1002 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 1003 MapExprComponents, 1004 OpenMPClauseKind WhereFoundClauseKind) { 1005 // Only the map clause information influences how a variable is 1006 // captured. E.g. is_device_ptr does not require changing the default 1007 // behavior. 1008 if (WhereFoundClauseKind != OMPC_map) 1009 return false; 1010 1011 auto EI = MapExprComponents.rbegin(); 1012 auto EE = MapExprComponents.rend(); 1013 1014 assert(EI != EE && "Invalid map expression!"); 1015 1016 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 1017 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 1018 1019 ++EI; 1020 if (EI == EE) 1021 return false; 1022 1023 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 1024 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 1025 isa<MemberExpr>(EI->getAssociatedExpression())) { 1026 IsVariableAssociatedWithSection = true; 1027 // There is nothing more we need to know about this variable. 1028 return true; 1029 } 1030 1031 // Keep looking for more map info. 1032 return false; 1033 }); 1034 1035 if (IsVariableUsedInMapClause) { 1036 // If variable is identified in a map clause it is always captured by 1037 // reference except if it is a pointer that is dereferenced somehow. 1038 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 1039 } else { 1040 // By default, all the data that has a scalar type is mapped by copy. 1041 IsByRef = !Ty->isScalarType(); 1042 } 1043 } 1044 1045 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 1046 IsByRef = !DSAStack->hasExplicitDSA( 1047 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; }, 1048 Level, /*NotLastprivate=*/true); 1049 } 1050 1051 // When passing data by copy, we need to make sure it fits the uintptr size 1052 // and alignment, because the runtime library only deals with uintptr types. 1053 // If it does not fit the uintptr size, we need to pass the data by reference 1054 // instead. 1055 if (!IsByRef && 1056 (Ctx.getTypeSizeInChars(Ty) > 1057 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 1058 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 1059 IsByRef = true; 1060 } 1061 1062 return IsByRef; 1063 } 1064 1065 unsigned Sema::getOpenMPNestingLevel() const { 1066 assert(getLangOpts().OpenMP); 1067 return DSAStack->getNestingLevel(); 1068 } 1069 1070 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) { 1071 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1072 D = getCanonicalDecl(D); 1073 1074 // If we are attempting to capture a global variable in a directive with 1075 // 'target' we return true so that this global is also mapped to the device. 1076 // 1077 // FIXME: If the declaration is enclosed in a 'declare target' directive, 1078 // then it should not be captured. Therefore, an extra check has to be 1079 // inserted here once support for 'declare target' is added. 1080 // 1081 auto *VD = dyn_cast<VarDecl>(D); 1082 if (VD && !VD->hasLocalStorage()) { 1083 if (DSAStack->getCurrentDirective() == OMPD_target && 1084 !DSAStack->isClauseParsingMode()) 1085 return VD; 1086 if (DSAStack->hasDirective( 1087 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 1088 SourceLocation) -> bool { 1089 return isOpenMPTargetExecutionDirective(K); 1090 }, 1091 false)) 1092 return VD; 1093 } 1094 1095 if (DSAStack->getCurrentDirective() != OMPD_unknown && 1096 (!DSAStack->isClauseParsingMode() || 1097 DSAStack->getParentDirective() != OMPD_unknown)) { 1098 auto &&Info = DSAStack->isLoopControlVariable(D); 1099 if (Info.first || 1100 (VD && VD->hasLocalStorage() && 1101 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) || 1102 (VD && DSAStack->isForceVarCapturing())) 1103 return VD ? VD : Info.second; 1104 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 1105 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind)) 1106 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1107 DVarPrivate = DSAStack->hasDSA( 1108 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 1109 DSAStack->isClauseParsingMode()); 1110 if (DVarPrivate.CKind != OMPC_unknown) 1111 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1112 } 1113 return nullptr; 1114 } 1115 1116 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) { 1117 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1118 return DSAStack->hasExplicitDSA( 1119 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, Level); 1120 } 1121 1122 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) { 1123 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1124 // Return true if the current level is no longer enclosed in a target region. 1125 1126 auto *VD = dyn_cast<VarDecl>(D); 1127 return VD && !VD->hasLocalStorage() && 1128 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1129 Level); 1130 } 1131 1132 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 1133 1134 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 1135 const DeclarationNameInfo &DirName, 1136 Scope *CurScope, SourceLocation Loc) { 1137 DSAStack->push(DKind, DirName, CurScope, Loc); 1138 PushExpressionEvaluationContext( 1139 ExpressionEvaluationContext::PotentiallyEvaluated); 1140 } 1141 1142 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 1143 DSAStack->setClauseParsingMode(K); 1144 } 1145 1146 void Sema::EndOpenMPClause() { 1147 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 1148 } 1149 1150 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 1151 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 1152 // A variable of class type (or array thereof) that appears in a lastprivate 1153 // clause requires an accessible, unambiguous default constructor for the 1154 // class type, unless the list item is also specified in a firstprivate 1155 // clause. 1156 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 1157 for (auto *C : D->clauses()) { 1158 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 1159 SmallVector<Expr *, 8> PrivateCopies; 1160 for (auto *DE : Clause->varlists()) { 1161 if (DE->isValueDependent() || DE->isTypeDependent()) { 1162 PrivateCopies.push_back(nullptr); 1163 continue; 1164 } 1165 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 1166 VarDecl *VD = cast<VarDecl>(DRE->getDecl()); 1167 QualType Type = VD->getType().getNonReferenceType(); 1168 auto DVar = DSAStack->getTopDSA(VD, false); 1169 if (DVar.CKind == OMPC_lastprivate) { 1170 // Generate helper private variable and initialize it with the 1171 // default value. The address of the original variable is replaced 1172 // by the address of the new private variable in CodeGen. This new 1173 // variable is not added to IdResolver, so the code in the OpenMP 1174 // region uses original variable for proper diagnostics. 1175 auto *VDPrivate = buildVarDecl( 1176 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 1177 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr); 1178 ActOnUninitializedDecl(VDPrivate); 1179 if (VDPrivate->isInvalidDecl()) 1180 continue; 1181 PrivateCopies.push_back(buildDeclRefExpr( 1182 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 1183 } else { 1184 // The variable is also a firstprivate, so initialization sequence 1185 // for private copy is generated already. 1186 PrivateCopies.push_back(nullptr); 1187 } 1188 } 1189 // Set initializers to private copies if no errors were found. 1190 if (PrivateCopies.size() == Clause->varlist_size()) 1191 Clause->setPrivateCopies(PrivateCopies); 1192 } 1193 } 1194 } 1195 1196 DSAStack->pop(); 1197 DiscardCleanupsInEvaluationContext(); 1198 PopExpressionEvaluationContext(); 1199 } 1200 1201 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 1202 Expr *NumIterations, Sema &SemaRef, 1203 Scope *S, DSAStackTy *Stack); 1204 1205 namespace { 1206 1207 class VarDeclFilterCCC : public CorrectionCandidateCallback { 1208 private: 1209 Sema &SemaRef; 1210 1211 public: 1212 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 1213 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1214 NamedDecl *ND = Candidate.getCorrectionDecl(); 1215 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 1216 return VD->hasGlobalStorage() && 1217 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1218 SemaRef.getCurScope()); 1219 } 1220 return false; 1221 } 1222 }; 1223 1224 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback { 1225 private: 1226 Sema &SemaRef; 1227 1228 public: 1229 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 1230 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1231 NamedDecl *ND = Candidate.getCorrectionDecl(); 1232 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 1233 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1234 SemaRef.getCurScope()); 1235 } 1236 return false; 1237 } 1238 }; 1239 1240 } // namespace 1241 1242 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 1243 CXXScopeSpec &ScopeSpec, 1244 const DeclarationNameInfo &Id) { 1245 LookupResult Lookup(*this, Id, LookupOrdinaryName); 1246 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 1247 1248 if (Lookup.isAmbiguous()) 1249 return ExprError(); 1250 1251 VarDecl *VD; 1252 if (!Lookup.isSingleResult()) { 1253 if (TypoCorrection Corrected = CorrectTypo( 1254 Id, LookupOrdinaryName, CurScope, nullptr, 1255 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) { 1256 diagnoseTypo(Corrected, 1257 PDiag(Lookup.empty() 1258 ? diag::err_undeclared_var_use_suggest 1259 : diag::err_omp_expected_var_arg_suggest) 1260 << Id.getName()); 1261 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 1262 } else { 1263 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 1264 : diag::err_omp_expected_var_arg) 1265 << Id.getName(); 1266 return ExprError(); 1267 } 1268 } else { 1269 if (!(VD = Lookup.getAsSingle<VarDecl>())) { 1270 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 1271 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 1272 return ExprError(); 1273 } 1274 } 1275 Lookup.suppressDiagnostics(); 1276 1277 // OpenMP [2.9.2, Syntax, C/C++] 1278 // Variables must be file-scope, namespace-scope, or static block-scope. 1279 if (!VD->hasGlobalStorage()) { 1280 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 1281 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal(); 1282 bool IsDecl = 1283 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1284 Diag(VD->getLocation(), 1285 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1286 << VD; 1287 return ExprError(); 1288 } 1289 1290 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 1291 NamedDecl *ND = cast<NamedDecl>(CanonicalVD); 1292 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 1293 // A threadprivate directive for file-scope variables must appear outside 1294 // any definition or declaration. 1295 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 1296 !getCurLexicalContext()->isTranslationUnit()) { 1297 Diag(Id.getLoc(), diag::err_omp_var_scope) 1298 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1299 bool IsDecl = 1300 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1301 Diag(VD->getLocation(), 1302 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1303 << VD; 1304 return ExprError(); 1305 } 1306 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 1307 // A threadprivate directive for static class member variables must appear 1308 // in the class definition, in the same scope in which the member 1309 // variables are declared. 1310 if (CanonicalVD->isStaticDataMember() && 1311 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 1312 Diag(Id.getLoc(), diag::err_omp_var_scope) 1313 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1314 bool IsDecl = 1315 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1316 Diag(VD->getLocation(), 1317 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1318 << VD; 1319 return ExprError(); 1320 } 1321 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 1322 // A threadprivate directive for namespace-scope variables must appear 1323 // outside any definition or declaration other than the namespace 1324 // definition itself. 1325 if (CanonicalVD->getDeclContext()->isNamespace() && 1326 (!getCurLexicalContext()->isFileContext() || 1327 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 1328 Diag(Id.getLoc(), diag::err_omp_var_scope) 1329 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1330 bool IsDecl = 1331 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1332 Diag(VD->getLocation(), 1333 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1334 << VD; 1335 return ExprError(); 1336 } 1337 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 1338 // A threadprivate directive for static block-scope variables must appear 1339 // in the scope of the variable and not in a nested scope. 1340 if (CanonicalVD->isStaticLocal() && CurScope && 1341 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 1342 Diag(Id.getLoc(), diag::err_omp_var_scope) 1343 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1344 bool IsDecl = 1345 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1346 Diag(VD->getLocation(), 1347 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1348 << VD; 1349 return ExprError(); 1350 } 1351 1352 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 1353 // A threadprivate directive must lexically precede all references to any 1354 // of the variables in its list. 1355 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) { 1356 Diag(Id.getLoc(), diag::err_omp_var_used) 1357 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1358 return ExprError(); 1359 } 1360 1361 QualType ExprType = VD->getType().getNonReferenceType(); 1362 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 1363 SourceLocation(), VD, 1364 /*RefersToEnclosingVariableOrCapture=*/false, 1365 Id.getLoc(), ExprType, VK_LValue); 1366 } 1367 1368 Sema::DeclGroupPtrTy 1369 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 1370 ArrayRef<Expr *> VarList) { 1371 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 1372 CurContext->addDecl(D); 1373 return DeclGroupPtrTy::make(DeclGroupRef(D)); 1374 } 1375 return nullptr; 1376 } 1377 1378 namespace { 1379 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> { 1380 Sema &SemaRef; 1381 1382 public: 1383 bool VisitDeclRefExpr(const DeclRefExpr *E) { 1384 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1385 if (VD->hasLocalStorage()) { 1386 SemaRef.Diag(E->getLocStart(), 1387 diag::err_omp_local_var_in_threadprivate_init) 1388 << E->getSourceRange(); 1389 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 1390 << VD << VD->getSourceRange(); 1391 return true; 1392 } 1393 } 1394 return false; 1395 } 1396 bool VisitStmt(const Stmt *S) { 1397 for (auto Child : S->children()) { 1398 if (Child && Visit(Child)) 1399 return true; 1400 } 1401 return false; 1402 } 1403 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 1404 }; 1405 } // namespace 1406 1407 OMPThreadPrivateDecl * 1408 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 1409 SmallVector<Expr *, 8> Vars; 1410 for (auto &RefExpr : VarList) { 1411 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr); 1412 VarDecl *VD = cast<VarDecl>(DE->getDecl()); 1413 SourceLocation ILoc = DE->getExprLoc(); 1414 1415 // Mark variable as used. 1416 VD->setReferenced(); 1417 VD->markUsed(Context); 1418 1419 QualType QType = VD->getType(); 1420 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 1421 // It will be analyzed later. 1422 Vars.push_back(DE); 1423 continue; 1424 } 1425 1426 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1427 // A threadprivate variable must not have an incomplete type. 1428 if (RequireCompleteType(ILoc, VD->getType(), 1429 diag::err_omp_threadprivate_incomplete_type)) { 1430 continue; 1431 } 1432 1433 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1434 // A threadprivate variable must not have a reference type. 1435 if (VD->getType()->isReferenceType()) { 1436 Diag(ILoc, diag::err_omp_ref_type_arg) 1437 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 1438 bool IsDecl = 1439 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1440 Diag(VD->getLocation(), 1441 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1442 << VD; 1443 continue; 1444 } 1445 1446 // Check if this is a TLS variable. If TLS is not being supported, produce 1447 // the corresponding diagnostic. 1448 if ((VD->getTLSKind() != VarDecl::TLS_None && 1449 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1450 getLangOpts().OpenMPUseTLS && 1451 getASTContext().getTargetInfo().isTLSSupported())) || 1452 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 1453 !VD->isLocalVarDecl())) { 1454 Diag(ILoc, diag::err_omp_var_thread_local) 1455 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 1456 bool IsDecl = 1457 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1458 Diag(VD->getLocation(), 1459 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1460 << VD; 1461 continue; 1462 } 1463 1464 // Check if initial value of threadprivate variable reference variable with 1465 // local storage (it is not supported by runtime). 1466 if (auto Init = VD->getAnyInitializer()) { 1467 LocalVarRefChecker Checker(*this); 1468 if (Checker.Visit(Init)) 1469 continue; 1470 } 1471 1472 Vars.push_back(RefExpr); 1473 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 1474 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 1475 Context, SourceRange(Loc, Loc))); 1476 if (auto *ML = Context.getASTMutationListener()) 1477 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 1478 } 1479 OMPThreadPrivateDecl *D = nullptr; 1480 if (!Vars.empty()) { 1481 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 1482 Vars); 1483 D->setAccess(AS_public); 1484 } 1485 return D; 1486 } 1487 1488 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack, 1489 const ValueDecl *D, DSAStackTy::DSAVarData DVar, 1490 bool IsLoopIterVar = false) { 1491 if (DVar.RefExpr) { 1492 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 1493 << getOpenMPClauseName(DVar.CKind); 1494 return; 1495 } 1496 enum { 1497 PDSA_StaticMemberShared, 1498 PDSA_StaticLocalVarShared, 1499 PDSA_LoopIterVarPrivate, 1500 PDSA_LoopIterVarLinear, 1501 PDSA_LoopIterVarLastprivate, 1502 PDSA_ConstVarShared, 1503 PDSA_GlobalVarShared, 1504 PDSA_TaskVarFirstprivate, 1505 PDSA_LocalVarPrivate, 1506 PDSA_Implicit 1507 } Reason = PDSA_Implicit; 1508 bool ReportHint = false; 1509 auto ReportLoc = D->getLocation(); 1510 auto *VD = dyn_cast<VarDecl>(D); 1511 if (IsLoopIterVar) { 1512 if (DVar.CKind == OMPC_private) 1513 Reason = PDSA_LoopIterVarPrivate; 1514 else if (DVar.CKind == OMPC_lastprivate) 1515 Reason = PDSA_LoopIterVarLastprivate; 1516 else 1517 Reason = PDSA_LoopIterVarLinear; 1518 } else if (isOpenMPTaskingDirective(DVar.DKind) && 1519 DVar.CKind == OMPC_firstprivate) { 1520 Reason = PDSA_TaskVarFirstprivate; 1521 ReportLoc = DVar.ImplicitDSALoc; 1522 } else if (VD && VD->isStaticLocal()) 1523 Reason = PDSA_StaticLocalVarShared; 1524 else if (VD && VD->isStaticDataMember()) 1525 Reason = PDSA_StaticMemberShared; 1526 else if (VD && VD->isFileVarDecl()) 1527 Reason = PDSA_GlobalVarShared; 1528 else if (D->getType().isConstant(SemaRef.getASTContext())) 1529 Reason = PDSA_ConstVarShared; 1530 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 1531 ReportHint = true; 1532 Reason = PDSA_LocalVarPrivate; 1533 } 1534 if (Reason != PDSA_Implicit) { 1535 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 1536 << Reason << ReportHint 1537 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 1538 } else if (DVar.ImplicitDSALoc.isValid()) { 1539 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 1540 << getOpenMPClauseName(DVar.CKind); 1541 } 1542 } 1543 1544 namespace { 1545 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> { 1546 DSAStackTy *Stack; 1547 Sema &SemaRef; 1548 bool ErrorFound; 1549 CapturedStmt *CS; 1550 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate; 1551 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 1552 1553 public: 1554 void VisitDeclRefExpr(DeclRefExpr *E) { 1555 if (E->isTypeDependent() || E->isValueDependent() || 1556 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1557 return; 1558 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1559 // Skip internally declared variables. 1560 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD)) 1561 return; 1562 1563 auto DVar = Stack->getTopDSA(VD, false); 1564 // Check if the variable has explicit DSA set and stop analysis if it so. 1565 if (DVar.RefExpr) 1566 return; 1567 1568 auto ELoc = E->getExprLoc(); 1569 auto DKind = Stack->getCurrentDirective(); 1570 // The default(none) clause requires that each variable that is referenced 1571 // in the construct, and does not have a predetermined data-sharing 1572 // attribute, must have its data-sharing attribute explicitly determined 1573 // by being listed in a data-sharing attribute clause. 1574 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && 1575 isParallelOrTaskRegion(DKind) && 1576 VarsWithInheritedDSA.count(VD) == 0) { 1577 VarsWithInheritedDSA[VD] = E; 1578 return; 1579 } 1580 1581 // OpenMP [2.9.3.6, Restrictions, p.2] 1582 // A list item that appears in a reduction clause of the innermost 1583 // enclosing worksharing or parallel construct may not be accessed in an 1584 // explicit task. 1585 DVar = Stack->hasInnermostDSA( 1586 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 1587 [](OpenMPDirectiveKind K) -> bool { 1588 return isOpenMPParallelDirective(K) || 1589 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 1590 }, 1591 false); 1592 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 1593 ErrorFound = true; 1594 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1595 ReportOriginalDSA(SemaRef, Stack, VD, DVar); 1596 return; 1597 } 1598 1599 // Define implicit data-sharing attributes for task. 1600 DVar = Stack->getImplicitDSA(VD, false); 1601 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 1602 !Stack->isLoopControlVariable(VD).first) 1603 ImplicitFirstprivate.push_back(E); 1604 } 1605 } 1606 void VisitMemberExpr(MemberExpr *E) { 1607 if (E->isTypeDependent() || E->isValueDependent() || 1608 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1609 return; 1610 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 1611 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 1612 auto DVar = Stack->getTopDSA(FD, false); 1613 // Check if the variable has explicit DSA set and stop analysis if it 1614 // so. 1615 if (DVar.RefExpr) 1616 return; 1617 1618 auto ELoc = E->getExprLoc(); 1619 auto DKind = Stack->getCurrentDirective(); 1620 // OpenMP [2.9.3.6, Restrictions, p.2] 1621 // A list item that appears in a reduction clause of the innermost 1622 // enclosing worksharing or parallel construct may not be accessed in 1623 // an explicit task. 1624 DVar = Stack->hasInnermostDSA( 1625 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 1626 [](OpenMPDirectiveKind K) -> bool { 1627 return isOpenMPParallelDirective(K) || 1628 isOpenMPWorksharingDirective(K) || 1629 isOpenMPTeamsDirective(K); 1630 }, 1631 false); 1632 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 1633 ErrorFound = true; 1634 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1635 ReportOriginalDSA(SemaRef, Stack, FD, DVar); 1636 return; 1637 } 1638 1639 // Define implicit data-sharing attributes for task. 1640 DVar = Stack->getImplicitDSA(FD, false); 1641 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 1642 !Stack->isLoopControlVariable(FD).first) 1643 ImplicitFirstprivate.push_back(E); 1644 } 1645 } else 1646 Visit(E->getBase()); 1647 } 1648 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 1649 for (auto *C : S->clauses()) { 1650 // Skip analysis of arguments of implicitly defined firstprivate clause 1651 // for task directives. 1652 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid())) 1653 for (auto *CC : C->children()) { 1654 if (CC) 1655 Visit(CC); 1656 } 1657 } 1658 } 1659 void VisitStmt(Stmt *S) { 1660 for (auto *C : S->children()) { 1661 if (C && !isa<OMPExecutableDirective>(C)) 1662 Visit(C); 1663 } 1664 } 1665 1666 bool isErrorFound() { return ErrorFound; } 1667 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; } 1668 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() { 1669 return VarsWithInheritedDSA; 1670 } 1671 1672 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 1673 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {} 1674 }; 1675 } // namespace 1676 1677 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 1678 switch (DKind) { 1679 case OMPD_parallel: 1680 case OMPD_parallel_for: 1681 case OMPD_parallel_for_simd: 1682 case OMPD_parallel_sections: 1683 case OMPD_teams: { 1684 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1685 QualType KmpInt32PtrTy = 1686 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1687 Sema::CapturedParamNameType Params[] = { 1688 std::make_pair(".global_tid.", KmpInt32PtrTy), 1689 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1690 std::make_pair(StringRef(), QualType()) // __context with shared vars 1691 }; 1692 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1693 Params); 1694 break; 1695 } 1696 case OMPD_target_teams: 1697 case OMPD_target_parallel: { 1698 Sema::CapturedParamNameType ParamsTarget[] = { 1699 std::make_pair(StringRef(), QualType()) // __context with shared vars 1700 }; 1701 // Start a captured region for 'target' with no implicit parameters. 1702 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1703 ParamsTarget); 1704 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1705 QualType KmpInt32PtrTy = 1706 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1707 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 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 // Start a captured region for 'teams' or 'parallel'. Both regions have 1713 // the same implicit parameters. 1714 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1715 ParamsTeamsOrParallel); 1716 break; 1717 } 1718 case OMPD_simd: 1719 case OMPD_for: 1720 case OMPD_for_simd: 1721 case OMPD_sections: 1722 case OMPD_section: 1723 case OMPD_single: 1724 case OMPD_master: 1725 case OMPD_critical: 1726 case OMPD_taskgroup: 1727 case OMPD_distribute: 1728 case OMPD_ordered: 1729 case OMPD_atomic: 1730 case OMPD_target_data: 1731 case OMPD_target: 1732 case OMPD_target_parallel_for: 1733 case OMPD_target_parallel_for_simd: 1734 case OMPD_target_simd: { 1735 Sema::CapturedParamNameType Params[] = { 1736 std::make_pair(StringRef(), QualType()) // __context with shared vars 1737 }; 1738 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1739 Params); 1740 break; 1741 } 1742 case OMPD_task: { 1743 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1744 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 1745 FunctionProtoType::ExtProtoInfo EPI; 1746 EPI.Variadic = true; 1747 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 1748 Sema::CapturedParamNameType Params[] = { 1749 std::make_pair(".global_tid.", KmpInt32Ty), 1750 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 1751 std::make_pair(".privates.", Context.VoidPtrTy.withConst()), 1752 std::make_pair(".copy_fn.", 1753 Context.getPointerType(CopyFnType).withConst()), 1754 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 1755 std::make_pair(StringRef(), QualType()) // __context with shared vars 1756 }; 1757 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1758 Params); 1759 // Mark this captured region as inlined, because we don't use outlined 1760 // function directly. 1761 getCurCapturedRegion()->TheCapturedDecl->addAttr( 1762 AlwaysInlineAttr::CreateImplicit( 1763 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 1764 break; 1765 } 1766 case OMPD_taskloop: 1767 case OMPD_taskloop_simd: { 1768 QualType KmpInt32Ty = 1769 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 1770 QualType KmpUInt64Ty = 1771 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 1772 QualType KmpInt64Ty = 1773 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 1774 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 1775 FunctionProtoType::ExtProtoInfo EPI; 1776 EPI.Variadic = true; 1777 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 1778 Sema::CapturedParamNameType Params[] = { 1779 std::make_pair(".global_tid.", KmpInt32Ty), 1780 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 1781 std::make_pair(".privates.", 1782 Context.VoidPtrTy.withConst().withRestrict()), 1783 std::make_pair( 1784 ".copy_fn.", 1785 Context.getPointerType(CopyFnType).withConst().withRestrict()), 1786 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 1787 std::make_pair(".lb.", KmpUInt64Ty), 1788 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty), 1789 std::make_pair(".liter.", KmpInt32Ty), 1790 std::make_pair(StringRef(), QualType()) // __context with shared vars 1791 }; 1792 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1793 Params); 1794 // Mark this captured region as inlined, because we don't use outlined 1795 // function directly. 1796 getCurCapturedRegion()->TheCapturedDecl->addAttr( 1797 AlwaysInlineAttr::CreateImplicit( 1798 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 1799 break; 1800 } 1801 case OMPD_distribute_parallel_for_simd: 1802 case OMPD_distribute_simd: 1803 case OMPD_distribute_parallel_for: 1804 case OMPD_teams_distribute: 1805 case OMPD_teams_distribute_simd: 1806 case OMPD_teams_distribute_parallel_for_simd: 1807 case OMPD_teams_distribute_parallel_for: 1808 case OMPD_target_teams_distribute: 1809 case OMPD_target_teams_distribute_parallel_for: 1810 case OMPD_target_teams_distribute_parallel_for_simd: 1811 case OMPD_target_teams_distribute_simd: { 1812 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1813 QualType KmpInt32PtrTy = 1814 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1815 Sema::CapturedParamNameType Params[] = { 1816 std::make_pair(".global_tid.", KmpInt32PtrTy), 1817 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1818 std::make_pair(".previous.lb.", Context.getSizeType()), 1819 std::make_pair(".previous.ub.", Context.getSizeType()), 1820 std::make_pair(StringRef(), QualType()) // __context with shared vars 1821 }; 1822 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1823 Params); 1824 break; 1825 } 1826 case OMPD_threadprivate: 1827 case OMPD_taskyield: 1828 case OMPD_barrier: 1829 case OMPD_taskwait: 1830 case OMPD_cancellation_point: 1831 case OMPD_cancel: 1832 case OMPD_flush: 1833 case OMPD_target_enter_data: 1834 case OMPD_target_exit_data: 1835 case OMPD_declare_reduction: 1836 case OMPD_declare_simd: 1837 case OMPD_declare_target: 1838 case OMPD_end_declare_target: 1839 case OMPD_target_update: 1840 llvm_unreachable("OpenMP Directive is not allowed"); 1841 case OMPD_unknown: 1842 llvm_unreachable("Unknown OpenMP directive"); 1843 } 1844 } 1845 1846 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 1847 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 1848 getOpenMPCaptureRegions(CaptureRegions, DKind); 1849 return CaptureRegions.size(); 1850 } 1851 1852 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 1853 Expr *CaptureExpr, bool WithInit, 1854 bool AsExpression) { 1855 assert(CaptureExpr); 1856 ASTContext &C = S.getASTContext(); 1857 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 1858 QualType Ty = Init->getType(); 1859 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 1860 if (S.getLangOpts().CPlusPlus) 1861 Ty = C.getLValueReferenceType(Ty); 1862 else { 1863 Ty = C.getPointerType(Ty); 1864 ExprResult Res = 1865 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 1866 if (!Res.isUsable()) 1867 return nullptr; 1868 Init = Res.get(); 1869 } 1870 WithInit = true; 1871 } 1872 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 1873 CaptureExpr->getLocStart()); 1874 if (!WithInit) 1875 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange())); 1876 S.CurContext->addHiddenDecl(CED); 1877 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 1878 return CED; 1879 } 1880 1881 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 1882 bool WithInit) { 1883 OMPCapturedExprDecl *CD; 1884 if (auto *VD = S.IsOpenMPCapturedDecl(D)) 1885 CD = cast<OMPCapturedExprDecl>(VD); 1886 else 1887 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 1888 /*AsExpression=*/false); 1889 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 1890 CaptureExpr->getExprLoc()); 1891 } 1892 1893 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 1894 if (!Ref) { 1895 auto *CD = 1896 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."), 1897 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true); 1898 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 1899 CaptureExpr->getExprLoc()); 1900 } 1901 ExprResult Res = Ref; 1902 if (!S.getLangOpts().CPlusPlus && 1903 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 1904 Ref->getType()->isPointerType()) 1905 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 1906 if (!Res.isUsable()) 1907 return ExprError(); 1908 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get()); 1909 } 1910 1911 namespace { 1912 // OpenMP directives parsed in this section are represented as a 1913 // CapturedStatement with an associated statement. If a syntax error 1914 // is detected during the parsing of the associated statement, the 1915 // compiler must abort processing and close the CapturedStatement. 1916 // 1917 // Combined directives such as 'target parallel' have more than one 1918 // nested CapturedStatements. This RAII ensures that we unwind out 1919 // of all the nested CapturedStatements when an error is found. 1920 class CaptureRegionUnwinderRAII { 1921 private: 1922 Sema &S; 1923 bool &ErrorFound; 1924 OpenMPDirectiveKind DKind; 1925 1926 public: 1927 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 1928 OpenMPDirectiveKind DKind) 1929 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 1930 ~CaptureRegionUnwinderRAII() { 1931 if (ErrorFound) { 1932 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 1933 while (--ThisCaptureLevel >= 0) 1934 S.ActOnCapturedRegionError(); 1935 } 1936 } 1937 }; 1938 } // namespace 1939 1940 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 1941 ArrayRef<OMPClause *> Clauses) { 1942 bool ErrorFound = false; 1943 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 1944 *this, ErrorFound, DSAStack->getCurrentDirective()); 1945 if (!S.isUsable()) { 1946 ErrorFound = true; 1947 return StmtError(); 1948 } 1949 1950 OMPOrderedClause *OC = nullptr; 1951 OMPScheduleClause *SC = nullptr; 1952 SmallVector<OMPLinearClause *, 4> LCs; 1953 SmallVector<OMPClauseWithPreInit *, 8> PICs; 1954 // This is required for proper codegen. 1955 for (auto *Clause : Clauses) { 1956 if (isOpenMPPrivate(Clause->getClauseKind()) || 1957 Clause->getClauseKind() == OMPC_copyprivate || 1958 (getLangOpts().OpenMPUseTLS && 1959 getASTContext().getTargetInfo().isTLSSupported() && 1960 Clause->getClauseKind() == OMPC_copyin)) { 1961 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 1962 // Mark all variables in private list clauses as used in inner region. 1963 for (auto *VarRef : Clause->children()) { 1964 if (auto *E = cast_or_null<Expr>(VarRef)) { 1965 MarkDeclarationsReferencedInExpr(E); 1966 } 1967 } 1968 DSAStack->setForceVarCapturing(/*V=*/false); 1969 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { 1970 if (auto *C = OMPClauseWithPreInit::get(Clause)) 1971 PICs.push_back(C); 1972 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 1973 if (auto *E = C->getPostUpdateExpr()) 1974 MarkDeclarationsReferencedInExpr(E); 1975 } 1976 } 1977 if (Clause->getClauseKind() == OMPC_schedule) 1978 SC = cast<OMPScheduleClause>(Clause); 1979 else if (Clause->getClauseKind() == OMPC_ordered) 1980 OC = cast<OMPOrderedClause>(Clause); 1981 else if (Clause->getClauseKind() == OMPC_linear) 1982 LCs.push_back(cast<OMPLinearClause>(Clause)); 1983 } 1984 // OpenMP, 2.7.1 Loop Construct, Restrictions 1985 // The nonmonotonic modifier cannot be specified if an ordered clause is 1986 // specified. 1987 if (SC && 1988 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 1989 SC->getSecondScheduleModifier() == 1990 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 1991 OC) { 1992 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 1993 ? SC->getFirstScheduleModifierLoc() 1994 : SC->getSecondScheduleModifierLoc(), 1995 diag::err_omp_schedule_nonmonotonic_ordered) 1996 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 1997 ErrorFound = true; 1998 } 1999 if (!LCs.empty() && OC && OC->getNumForLoops()) { 2000 for (auto *C : LCs) { 2001 Diag(C->getLocStart(), diag::err_omp_linear_ordered) 2002 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 2003 } 2004 ErrorFound = true; 2005 } 2006 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 2007 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 2008 OC->getNumForLoops()) { 2009 Diag(OC->getLocStart(), diag::err_omp_ordered_simd) 2010 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 2011 ErrorFound = true; 2012 } 2013 if (ErrorFound) { 2014 return StmtError(); 2015 } 2016 StmtResult SR = S; 2017 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2018 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 2019 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 2020 // Mark all variables in private list clauses as used in inner region. 2021 // Required for proper codegen of combined directives. 2022 // TODO: add processing for other clauses. 2023 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { 2024 for (auto *C : PICs) { 2025 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 2026 // Find the particular capture region for the clause if the 2027 // directive is a combined one with multiple capture regions. 2028 // If the directive is not a combined one, the capture region 2029 // associated with the clause is OMPD_unknown and is generated 2030 // only once. 2031 if (CaptureRegion == ThisCaptureRegion || 2032 CaptureRegion == OMPD_unknown) { 2033 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 2034 for (auto *D : DS->decls()) 2035 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 2036 } 2037 } 2038 } 2039 } 2040 SR = ActOnCapturedRegionEnd(SR.get()); 2041 } 2042 return SR; 2043 } 2044 2045 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 2046 OpenMPDirectiveKind CancelRegion, 2047 SourceLocation StartLoc) { 2048 // CancelRegion is only needed for cancel and cancellation_point. 2049 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 2050 return false; 2051 2052 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 2053 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 2054 return false; 2055 2056 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 2057 << getOpenMPDirectiveName(CancelRegion); 2058 return true; 2059 } 2060 2061 static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack, 2062 OpenMPDirectiveKind CurrentRegion, 2063 const DeclarationNameInfo &CurrentName, 2064 OpenMPDirectiveKind CancelRegion, 2065 SourceLocation StartLoc) { 2066 if (Stack->getCurScope()) { 2067 auto ParentRegion = Stack->getParentDirective(); 2068 auto OffendingRegion = ParentRegion; 2069 bool NestingProhibited = false; 2070 bool CloseNesting = true; 2071 bool OrphanSeen = false; 2072 enum { 2073 NoRecommend, 2074 ShouldBeInParallelRegion, 2075 ShouldBeInOrderedRegion, 2076 ShouldBeInTargetRegion, 2077 ShouldBeInTeamsRegion 2078 } Recommend = NoRecommend; 2079 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { 2080 // OpenMP [2.16, Nesting of Regions] 2081 // OpenMP constructs may not be nested inside a simd region. 2082 // OpenMP [2.8.1,simd Construct, Restrictions] 2083 // An ordered construct with the simd clause is the only OpenMP 2084 // construct that can appear in the simd region. 2085 // Allowing a SIMD construct nested in another SIMD construct is an 2086 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 2087 // message. 2088 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 2089 ? diag::err_omp_prohibited_region_simd 2090 : diag::warn_omp_nesting_simd); 2091 return CurrentRegion != OMPD_simd; 2092 } 2093 if (ParentRegion == OMPD_atomic) { 2094 // OpenMP [2.16, Nesting of Regions] 2095 // OpenMP constructs may not be nested inside an atomic region. 2096 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 2097 return true; 2098 } 2099 if (CurrentRegion == OMPD_section) { 2100 // OpenMP [2.7.2, sections Construct, Restrictions] 2101 // Orphaned section directives are prohibited. That is, the section 2102 // directives must appear within the sections construct and must not be 2103 // encountered elsewhere in the sections region. 2104 if (ParentRegion != OMPD_sections && 2105 ParentRegion != OMPD_parallel_sections) { 2106 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 2107 << (ParentRegion != OMPD_unknown) 2108 << getOpenMPDirectiveName(ParentRegion); 2109 return true; 2110 } 2111 return false; 2112 } 2113 // Allow some constructs (except teams) to be orphaned (they could be 2114 // used in functions, called from OpenMP regions with the required 2115 // preconditions). 2116 if (ParentRegion == OMPD_unknown && 2117 !isOpenMPNestingTeamsDirective(CurrentRegion)) 2118 return false; 2119 if (CurrentRegion == OMPD_cancellation_point || 2120 CurrentRegion == OMPD_cancel) { 2121 // OpenMP [2.16, Nesting of Regions] 2122 // A cancellation point construct for which construct-type-clause is 2123 // taskgroup must be nested inside a task construct. A cancellation 2124 // point construct for which construct-type-clause is not taskgroup must 2125 // be closely nested inside an OpenMP construct that matches the type 2126 // specified in construct-type-clause. 2127 // A cancel construct for which construct-type-clause is taskgroup must be 2128 // nested inside a task construct. A cancel construct for which 2129 // construct-type-clause is not taskgroup must be closely nested inside an 2130 // OpenMP construct that matches the type specified in 2131 // construct-type-clause. 2132 NestingProhibited = 2133 !((CancelRegion == OMPD_parallel && 2134 (ParentRegion == OMPD_parallel || 2135 ParentRegion == OMPD_target_parallel)) || 2136 (CancelRegion == OMPD_for && 2137 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 2138 ParentRegion == OMPD_target_parallel_for)) || 2139 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || 2140 (CancelRegion == OMPD_sections && 2141 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 2142 ParentRegion == OMPD_parallel_sections))); 2143 } else if (CurrentRegion == OMPD_master) { 2144 // OpenMP [2.16, Nesting of Regions] 2145 // A master region may not be closely nested inside a worksharing, 2146 // atomic, or explicit task region. 2147 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2148 isOpenMPTaskingDirective(ParentRegion); 2149 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 2150 // OpenMP [2.16, Nesting of Regions] 2151 // A critical region may not be nested (closely or otherwise) inside a 2152 // critical region with the same name. Note that this restriction is not 2153 // sufficient to prevent deadlock. 2154 SourceLocation PreviousCriticalLoc; 2155 bool DeadLock = Stack->hasDirective( 2156 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 2157 const DeclarationNameInfo &DNI, 2158 SourceLocation Loc) -> bool { 2159 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 2160 PreviousCriticalLoc = Loc; 2161 return true; 2162 } else 2163 return false; 2164 }, 2165 false /* skip top directive */); 2166 if (DeadLock) { 2167 SemaRef.Diag(StartLoc, 2168 diag::err_omp_prohibited_region_critical_same_name) 2169 << CurrentName.getName(); 2170 if (PreviousCriticalLoc.isValid()) 2171 SemaRef.Diag(PreviousCriticalLoc, 2172 diag::note_omp_previous_critical_region); 2173 return true; 2174 } 2175 } else if (CurrentRegion == OMPD_barrier) { 2176 // OpenMP [2.16, Nesting of Regions] 2177 // A barrier region may not be closely nested inside a worksharing, 2178 // explicit task, critical, ordered, atomic, or master region. 2179 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2180 isOpenMPTaskingDirective(ParentRegion) || 2181 ParentRegion == OMPD_master || 2182 ParentRegion == OMPD_critical || 2183 ParentRegion == OMPD_ordered; 2184 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 2185 !isOpenMPParallelDirective(CurrentRegion) && 2186 !isOpenMPTeamsDirective(CurrentRegion)) { 2187 // OpenMP [2.16, Nesting of Regions] 2188 // A worksharing region may not be closely nested inside a worksharing, 2189 // explicit task, critical, ordered, atomic, or master region. 2190 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2191 isOpenMPTaskingDirective(ParentRegion) || 2192 ParentRegion == OMPD_master || 2193 ParentRegion == OMPD_critical || 2194 ParentRegion == OMPD_ordered; 2195 Recommend = ShouldBeInParallelRegion; 2196 } else if (CurrentRegion == OMPD_ordered) { 2197 // OpenMP [2.16, Nesting of Regions] 2198 // An ordered region may not be closely nested inside a critical, 2199 // atomic, or explicit task region. 2200 // An ordered region must be closely nested inside a loop region (or 2201 // parallel loop region) with an ordered clause. 2202 // OpenMP [2.8.1,simd Construct, Restrictions] 2203 // An ordered construct with the simd clause is the only OpenMP construct 2204 // that can appear in the simd region. 2205 NestingProhibited = ParentRegion == OMPD_critical || 2206 isOpenMPTaskingDirective(ParentRegion) || 2207 !(isOpenMPSimdDirective(ParentRegion) || 2208 Stack->isParentOrderedRegion()); 2209 Recommend = ShouldBeInOrderedRegion; 2210 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 2211 // OpenMP [2.16, Nesting of Regions] 2212 // If specified, a teams construct must be contained within a target 2213 // construct. 2214 NestingProhibited = ParentRegion != OMPD_target; 2215 OrphanSeen = ParentRegion == OMPD_unknown; 2216 Recommend = ShouldBeInTargetRegion; 2217 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc()); 2218 } 2219 if (!NestingProhibited && 2220 !isOpenMPTargetExecutionDirective(CurrentRegion) && 2221 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 2222 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 2223 // OpenMP [2.16, Nesting of Regions] 2224 // distribute, parallel, parallel sections, parallel workshare, and the 2225 // parallel loop and parallel loop SIMD constructs are the only OpenMP 2226 // constructs that can be closely nested in the teams region. 2227 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 2228 !isOpenMPDistributeDirective(CurrentRegion); 2229 Recommend = ShouldBeInParallelRegion; 2230 } 2231 if (!NestingProhibited && 2232 isOpenMPNestingDistributeDirective(CurrentRegion)) { 2233 // OpenMP 4.5 [2.17 Nesting of Regions] 2234 // The region associated with the distribute construct must be strictly 2235 // nested inside a teams region 2236 NestingProhibited = 2237 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 2238 Recommend = ShouldBeInTeamsRegion; 2239 } 2240 if (!NestingProhibited && 2241 (isOpenMPTargetExecutionDirective(CurrentRegion) || 2242 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 2243 // OpenMP 4.5 [2.17 Nesting of Regions] 2244 // If a target, target update, target data, target enter data, or 2245 // target exit data construct is encountered during execution of a 2246 // target region, the behavior is unspecified. 2247 NestingProhibited = Stack->hasDirective( 2248 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 2249 SourceLocation) -> bool { 2250 if (isOpenMPTargetExecutionDirective(K)) { 2251 OffendingRegion = K; 2252 return true; 2253 } else 2254 return false; 2255 }, 2256 false /* don't skip top directive */); 2257 CloseNesting = false; 2258 } 2259 if (NestingProhibited) { 2260 if (OrphanSeen) { 2261 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 2262 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 2263 } else { 2264 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 2265 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 2266 << Recommend << getOpenMPDirectiveName(CurrentRegion); 2267 } 2268 return true; 2269 } 2270 } 2271 return false; 2272 } 2273 2274 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 2275 ArrayRef<OMPClause *> Clauses, 2276 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 2277 bool ErrorFound = false; 2278 unsigned NamedModifiersNumber = 0; 2279 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers( 2280 OMPD_unknown + 1); 2281 SmallVector<SourceLocation, 4> NameModifierLoc; 2282 for (const auto *C : Clauses) { 2283 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 2284 // At most one if clause without a directive-name-modifier can appear on 2285 // the directive. 2286 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 2287 if (FoundNameModifiers[CurNM]) { 2288 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause) 2289 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 2290 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 2291 ErrorFound = true; 2292 } else if (CurNM != OMPD_unknown) { 2293 NameModifierLoc.push_back(IC->getNameModifierLoc()); 2294 ++NamedModifiersNumber; 2295 } 2296 FoundNameModifiers[CurNM] = IC; 2297 if (CurNM == OMPD_unknown) 2298 continue; 2299 // Check if the specified name modifier is allowed for the current 2300 // directive. 2301 // At most one if clause with the particular directive-name-modifier can 2302 // appear on the directive. 2303 bool MatchFound = false; 2304 for (auto NM : AllowedNameModifiers) { 2305 if (CurNM == NM) { 2306 MatchFound = true; 2307 break; 2308 } 2309 } 2310 if (!MatchFound) { 2311 S.Diag(IC->getNameModifierLoc(), 2312 diag::err_omp_wrong_if_directive_name_modifier) 2313 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 2314 ErrorFound = true; 2315 } 2316 } 2317 } 2318 // If any if clause on the directive includes a directive-name-modifier then 2319 // all if clauses on the directive must include a directive-name-modifier. 2320 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 2321 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 2322 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(), 2323 diag::err_omp_no_more_if_clause); 2324 } else { 2325 std::string Values; 2326 std::string Sep(", "); 2327 unsigned AllowedCnt = 0; 2328 unsigned TotalAllowedNum = 2329 AllowedNameModifiers.size() - NamedModifiersNumber; 2330 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 2331 ++Cnt) { 2332 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 2333 if (!FoundNameModifiers[NM]) { 2334 Values += "'"; 2335 Values += getOpenMPDirectiveName(NM); 2336 Values += "'"; 2337 if (AllowedCnt + 2 == TotalAllowedNum) 2338 Values += " or "; 2339 else if (AllowedCnt + 1 != TotalAllowedNum) 2340 Values += Sep; 2341 ++AllowedCnt; 2342 } 2343 } 2344 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(), 2345 diag::err_omp_unnamed_if_clause) 2346 << (TotalAllowedNum > 1) << Values; 2347 } 2348 for (auto Loc : NameModifierLoc) { 2349 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 2350 } 2351 ErrorFound = true; 2352 } 2353 return ErrorFound; 2354 } 2355 2356 StmtResult Sema::ActOnOpenMPExecutableDirective( 2357 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 2358 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 2359 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 2360 StmtResult Res = StmtError(); 2361 // First check CancelRegion which is then used in checkNestingOfRegions. 2362 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 2363 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 2364 StartLoc)) 2365 return StmtError(); 2366 2367 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 2368 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 2369 bool ErrorFound = false; 2370 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 2371 if (AStmt) { 2372 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 2373 2374 // Check default data sharing attributes for referenced variables. 2375 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 2376 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 2377 Stmt *S = AStmt; 2378 while (--ThisCaptureLevel >= 0) 2379 S = cast<CapturedStmt>(S)->getCapturedStmt(); 2380 DSAChecker.Visit(S); 2381 if (DSAChecker.isErrorFound()) 2382 return StmtError(); 2383 // Generate list of implicitly defined firstprivate variables. 2384 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 2385 2386 if (!DSAChecker.getImplicitFirstprivate().empty()) { 2387 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 2388 DSAChecker.getImplicitFirstprivate(), SourceLocation(), 2389 SourceLocation(), SourceLocation())) { 2390 ClausesWithImplicit.push_back(Implicit); 2391 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 2392 DSAChecker.getImplicitFirstprivate().size(); 2393 } else 2394 ErrorFound = true; 2395 } 2396 } 2397 2398 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 2399 switch (Kind) { 2400 case OMPD_parallel: 2401 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 2402 EndLoc); 2403 AllowedNameModifiers.push_back(OMPD_parallel); 2404 break; 2405 case OMPD_simd: 2406 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2407 VarsWithInheritedDSA); 2408 break; 2409 case OMPD_for: 2410 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2411 VarsWithInheritedDSA); 2412 break; 2413 case OMPD_for_simd: 2414 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2415 EndLoc, VarsWithInheritedDSA); 2416 break; 2417 case OMPD_sections: 2418 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 2419 EndLoc); 2420 break; 2421 case OMPD_section: 2422 assert(ClausesWithImplicit.empty() && 2423 "No clauses are allowed for 'omp section' directive"); 2424 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 2425 break; 2426 case OMPD_single: 2427 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 2428 EndLoc); 2429 break; 2430 case OMPD_master: 2431 assert(ClausesWithImplicit.empty() && 2432 "No clauses are allowed for 'omp master' directive"); 2433 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 2434 break; 2435 case OMPD_critical: 2436 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 2437 StartLoc, EndLoc); 2438 break; 2439 case OMPD_parallel_for: 2440 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 2441 EndLoc, VarsWithInheritedDSA); 2442 AllowedNameModifiers.push_back(OMPD_parallel); 2443 break; 2444 case OMPD_parallel_for_simd: 2445 Res = ActOnOpenMPParallelForSimdDirective( 2446 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2447 AllowedNameModifiers.push_back(OMPD_parallel); 2448 break; 2449 case OMPD_parallel_sections: 2450 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 2451 StartLoc, EndLoc); 2452 AllowedNameModifiers.push_back(OMPD_parallel); 2453 break; 2454 case OMPD_task: 2455 Res = 2456 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 2457 AllowedNameModifiers.push_back(OMPD_task); 2458 break; 2459 case OMPD_taskyield: 2460 assert(ClausesWithImplicit.empty() && 2461 "No clauses are allowed for 'omp taskyield' directive"); 2462 assert(AStmt == nullptr && 2463 "No associated statement allowed for 'omp taskyield' directive"); 2464 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 2465 break; 2466 case OMPD_barrier: 2467 assert(ClausesWithImplicit.empty() && 2468 "No clauses are allowed for 'omp barrier' directive"); 2469 assert(AStmt == nullptr && 2470 "No associated statement allowed for 'omp barrier' directive"); 2471 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 2472 break; 2473 case OMPD_taskwait: 2474 assert(ClausesWithImplicit.empty() && 2475 "No clauses are allowed for 'omp taskwait' directive"); 2476 assert(AStmt == nullptr && 2477 "No associated statement allowed for 'omp taskwait' directive"); 2478 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 2479 break; 2480 case OMPD_taskgroup: 2481 assert(ClausesWithImplicit.empty() && 2482 "No clauses are allowed for 'omp taskgroup' directive"); 2483 Res = ActOnOpenMPTaskgroupDirective(AStmt, StartLoc, EndLoc); 2484 break; 2485 case OMPD_flush: 2486 assert(AStmt == nullptr && 2487 "No associated statement allowed for 'omp flush' directive"); 2488 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 2489 break; 2490 case OMPD_ordered: 2491 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 2492 EndLoc); 2493 break; 2494 case OMPD_atomic: 2495 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 2496 EndLoc); 2497 break; 2498 case OMPD_teams: 2499 Res = 2500 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 2501 break; 2502 case OMPD_target: 2503 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 2504 EndLoc); 2505 AllowedNameModifiers.push_back(OMPD_target); 2506 break; 2507 case OMPD_target_parallel: 2508 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 2509 StartLoc, EndLoc); 2510 AllowedNameModifiers.push_back(OMPD_target); 2511 AllowedNameModifiers.push_back(OMPD_parallel); 2512 break; 2513 case OMPD_target_parallel_for: 2514 Res = ActOnOpenMPTargetParallelForDirective( 2515 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2516 AllowedNameModifiers.push_back(OMPD_target); 2517 AllowedNameModifiers.push_back(OMPD_parallel); 2518 break; 2519 case OMPD_cancellation_point: 2520 assert(ClausesWithImplicit.empty() && 2521 "No clauses are allowed for 'omp cancellation point' directive"); 2522 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 2523 "cancellation point' directive"); 2524 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 2525 break; 2526 case OMPD_cancel: 2527 assert(AStmt == nullptr && 2528 "No associated statement allowed for 'omp cancel' directive"); 2529 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 2530 CancelRegion); 2531 AllowedNameModifiers.push_back(OMPD_cancel); 2532 break; 2533 case OMPD_target_data: 2534 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 2535 EndLoc); 2536 AllowedNameModifiers.push_back(OMPD_target_data); 2537 break; 2538 case OMPD_target_enter_data: 2539 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 2540 EndLoc); 2541 AllowedNameModifiers.push_back(OMPD_target_enter_data); 2542 break; 2543 case OMPD_target_exit_data: 2544 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 2545 EndLoc); 2546 AllowedNameModifiers.push_back(OMPD_target_exit_data); 2547 break; 2548 case OMPD_taskloop: 2549 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 2550 EndLoc, VarsWithInheritedDSA); 2551 AllowedNameModifiers.push_back(OMPD_taskloop); 2552 break; 2553 case OMPD_taskloop_simd: 2554 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2555 EndLoc, VarsWithInheritedDSA); 2556 AllowedNameModifiers.push_back(OMPD_taskloop); 2557 break; 2558 case OMPD_distribute: 2559 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 2560 EndLoc, VarsWithInheritedDSA); 2561 break; 2562 case OMPD_target_update: 2563 assert(!AStmt && "Statement is not allowed for target update"); 2564 Res = 2565 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc); 2566 AllowedNameModifiers.push_back(OMPD_target_update); 2567 break; 2568 case OMPD_distribute_parallel_for: 2569 Res = ActOnOpenMPDistributeParallelForDirective( 2570 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2571 AllowedNameModifiers.push_back(OMPD_parallel); 2572 break; 2573 case OMPD_distribute_parallel_for_simd: 2574 Res = ActOnOpenMPDistributeParallelForSimdDirective( 2575 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2576 AllowedNameModifiers.push_back(OMPD_parallel); 2577 break; 2578 case OMPD_distribute_simd: 2579 Res = ActOnOpenMPDistributeSimdDirective( 2580 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2581 break; 2582 case OMPD_target_parallel_for_simd: 2583 Res = ActOnOpenMPTargetParallelForSimdDirective( 2584 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2585 AllowedNameModifiers.push_back(OMPD_target); 2586 AllowedNameModifiers.push_back(OMPD_parallel); 2587 break; 2588 case OMPD_target_simd: 2589 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2590 EndLoc, VarsWithInheritedDSA); 2591 AllowedNameModifiers.push_back(OMPD_target); 2592 break; 2593 case OMPD_teams_distribute: 2594 Res = ActOnOpenMPTeamsDistributeDirective( 2595 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2596 break; 2597 case OMPD_teams_distribute_simd: 2598 Res = ActOnOpenMPTeamsDistributeSimdDirective( 2599 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2600 break; 2601 case OMPD_teams_distribute_parallel_for_simd: 2602 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 2603 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2604 AllowedNameModifiers.push_back(OMPD_parallel); 2605 break; 2606 case OMPD_teams_distribute_parallel_for: 2607 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 2608 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2609 AllowedNameModifiers.push_back(OMPD_parallel); 2610 break; 2611 case OMPD_target_teams: 2612 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 2613 EndLoc); 2614 AllowedNameModifiers.push_back(OMPD_target); 2615 break; 2616 case OMPD_target_teams_distribute: 2617 Res = ActOnOpenMPTargetTeamsDistributeDirective( 2618 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2619 AllowedNameModifiers.push_back(OMPD_target); 2620 break; 2621 case OMPD_target_teams_distribute_parallel_for: 2622 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 2623 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2624 AllowedNameModifiers.push_back(OMPD_target); 2625 AllowedNameModifiers.push_back(OMPD_parallel); 2626 break; 2627 case OMPD_target_teams_distribute_parallel_for_simd: 2628 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 2629 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2630 AllowedNameModifiers.push_back(OMPD_target); 2631 AllowedNameModifiers.push_back(OMPD_parallel); 2632 break; 2633 case OMPD_target_teams_distribute_simd: 2634 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 2635 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2636 AllowedNameModifiers.push_back(OMPD_target); 2637 break; 2638 case OMPD_declare_target: 2639 case OMPD_end_declare_target: 2640 case OMPD_threadprivate: 2641 case OMPD_declare_reduction: 2642 case OMPD_declare_simd: 2643 llvm_unreachable("OpenMP Directive is not allowed"); 2644 case OMPD_unknown: 2645 llvm_unreachable("Unknown OpenMP directive"); 2646 } 2647 2648 for (auto P : VarsWithInheritedDSA) { 2649 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 2650 << P.first << P.second->getSourceRange(); 2651 } 2652 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound; 2653 2654 if (!AllowedNameModifiers.empty()) 2655 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 2656 ErrorFound; 2657 2658 if (ErrorFound) 2659 return StmtError(); 2660 return Res; 2661 } 2662 2663 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 2664 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 2665 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 2666 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 2667 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 2668 assert(Aligneds.size() == Alignments.size()); 2669 assert(Linears.size() == LinModifiers.size()); 2670 assert(Linears.size() == Steps.size()); 2671 if (!DG || DG.get().isNull()) 2672 return DeclGroupPtrTy(); 2673 2674 if (!DG.get().isSingleDecl()) { 2675 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd); 2676 return DG; 2677 } 2678 auto *ADecl = DG.get().getSingleDecl(); 2679 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 2680 ADecl = FTD->getTemplatedDecl(); 2681 2682 auto *FD = dyn_cast<FunctionDecl>(ADecl); 2683 if (!FD) { 2684 Diag(ADecl->getLocation(), diag::err_omp_function_expected); 2685 return DeclGroupPtrTy(); 2686 } 2687 2688 // OpenMP [2.8.2, declare simd construct, Description] 2689 // The parameter of the simdlen clause must be a constant positive integer 2690 // expression. 2691 ExprResult SL; 2692 if (Simdlen) 2693 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 2694 // OpenMP [2.8.2, declare simd construct, Description] 2695 // The special this pointer can be used as if was one of the arguments to the 2696 // function in any of the linear, aligned, or uniform clauses. 2697 // The uniform clause declares one or more arguments to have an invariant 2698 // value for all concurrent invocations of the function in the execution of a 2699 // single SIMD loop. 2700 llvm::DenseMap<Decl *, Expr *> UniformedArgs; 2701 Expr *UniformedLinearThis = nullptr; 2702 for (auto *E : Uniforms) { 2703 E = E->IgnoreParenImpCasts(); 2704 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 2705 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 2706 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 2707 FD->getParamDecl(PVD->getFunctionScopeIndex()) 2708 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 2709 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E)); 2710 continue; 2711 } 2712 if (isa<CXXThisExpr>(E)) { 2713 UniformedLinearThis = E; 2714 continue; 2715 } 2716 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 2717 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 2718 } 2719 // OpenMP [2.8.2, declare simd construct, Description] 2720 // The aligned clause declares that the object to which each list item points 2721 // is aligned to the number of bytes expressed in the optional parameter of 2722 // the aligned clause. 2723 // The special this pointer can be used as if was one of the arguments to the 2724 // function in any of the linear, aligned, or uniform clauses. 2725 // The type of list items appearing in the aligned clause must be array, 2726 // pointer, reference to array, or reference to pointer. 2727 llvm::DenseMap<Decl *, Expr *> AlignedArgs; 2728 Expr *AlignedThis = nullptr; 2729 for (auto *E : Aligneds) { 2730 E = E->IgnoreParenImpCasts(); 2731 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 2732 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 2733 auto *CanonPVD = PVD->getCanonicalDecl(); 2734 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 2735 FD->getParamDecl(PVD->getFunctionScopeIndex()) 2736 ->getCanonicalDecl() == CanonPVD) { 2737 // OpenMP [2.8.1, simd construct, Restrictions] 2738 // A list-item cannot appear in more than one aligned clause. 2739 if (AlignedArgs.count(CanonPVD) > 0) { 2740 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 2741 << 1 << E->getSourceRange(); 2742 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 2743 diag::note_omp_explicit_dsa) 2744 << getOpenMPClauseName(OMPC_aligned); 2745 continue; 2746 } 2747 AlignedArgs[CanonPVD] = E; 2748 QualType QTy = PVD->getType() 2749 .getNonReferenceType() 2750 .getUnqualifiedType() 2751 .getCanonicalType(); 2752 const Type *Ty = QTy.getTypePtrOrNull(); 2753 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 2754 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 2755 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 2756 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 2757 } 2758 continue; 2759 } 2760 } 2761 if (isa<CXXThisExpr>(E)) { 2762 if (AlignedThis) { 2763 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 2764 << 2 << E->getSourceRange(); 2765 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 2766 << getOpenMPClauseName(OMPC_aligned); 2767 } 2768 AlignedThis = E; 2769 continue; 2770 } 2771 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 2772 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 2773 } 2774 // The optional parameter of the aligned clause, alignment, must be a constant 2775 // positive integer expression. If no optional parameter is specified, 2776 // implementation-defined default alignments for SIMD instructions on the 2777 // target platforms are assumed. 2778 SmallVector<Expr *, 4> NewAligns; 2779 for (auto *E : Alignments) { 2780 ExprResult Align; 2781 if (E) 2782 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 2783 NewAligns.push_back(Align.get()); 2784 } 2785 // OpenMP [2.8.2, declare simd construct, Description] 2786 // The linear clause declares one or more list items to be private to a SIMD 2787 // lane and to have a linear relationship with respect to the iteration space 2788 // of a loop. 2789 // The special this pointer can be used as if was one of the arguments to the 2790 // function in any of the linear, aligned, or uniform clauses. 2791 // When a linear-step expression is specified in a linear clause it must be 2792 // either a constant integer expression or an integer-typed parameter that is 2793 // specified in a uniform clause on the directive. 2794 llvm::DenseMap<Decl *, Expr *> LinearArgs; 2795 const bool IsUniformedThis = UniformedLinearThis != nullptr; 2796 auto MI = LinModifiers.begin(); 2797 for (auto *E : Linears) { 2798 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 2799 ++MI; 2800 E = E->IgnoreParenImpCasts(); 2801 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 2802 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 2803 auto *CanonPVD = PVD->getCanonicalDecl(); 2804 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 2805 FD->getParamDecl(PVD->getFunctionScopeIndex()) 2806 ->getCanonicalDecl() == CanonPVD) { 2807 // OpenMP [2.15.3.7, linear Clause, Restrictions] 2808 // A list-item cannot appear in more than one linear clause. 2809 if (LinearArgs.count(CanonPVD) > 0) { 2810 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 2811 << getOpenMPClauseName(OMPC_linear) 2812 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 2813 Diag(LinearArgs[CanonPVD]->getExprLoc(), 2814 diag::note_omp_explicit_dsa) 2815 << getOpenMPClauseName(OMPC_linear); 2816 continue; 2817 } 2818 // Each argument can appear in at most one uniform or linear clause. 2819 if (UniformedArgs.count(CanonPVD) > 0) { 2820 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 2821 << getOpenMPClauseName(OMPC_linear) 2822 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 2823 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 2824 diag::note_omp_explicit_dsa) 2825 << getOpenMPClauseName(OMPC_uniform); 2826 continue; 2827 } 2828 LinearArgs[CanonPVD] = E; 2829 if (E->isValueDependent() || E->isTypeDependent() || 2830 E->isInstantiationDependent() || 2831 E->containsUnexpandedParameterPack()) 2832 continue; 2833 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 2834 PVD->getOriginalType()); 2835 continue; 2836 } 2837 } 2838 if (isa<CXXThisExpr>(E)) { 2839 if (UniformedLinearThis) { 2840 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 2841 << getOpenMPClauseName(OMPC_linear) 2842 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 2843 << E->getSourceRange(); 2844 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 2845 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 2846 : OMPC_linear); 2847 continue; 2848 } 2849 UniformedLinearThis = E; 2850 if (E->isValueDependent() || E->isTypeDependent() || 2851 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 2852 continue; 2853 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 2854 E->getType()); 2855 continue; 2856 } 2857 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 2858 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 2859 } 2860 Expr *Step = nullptr; 2861 Expr *NewStep = nullptr; 2862 SmallVector<Expr *, 4> NewSteps; 2863 for (auto *E : Steps) { 2864 // Skip the same step expression, it was checked already. 2865 if (Step == E || !E) { 2866 NewSteps.push_back(E ? NewStep : nullptr); 2867 continue; 2868 } 2869 Step = E; 2870 if (auto *DRE = dyn_cast<DeclRefExpr>(Step)) 2871 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 2872 auto *CanonPVD = PVD->getCanonicalDecl(); 2873 if (UniformedArgs.count(CanonPVD) == 0) { 2874 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 2875 << Step->getSourceRange(); 2876 } else if (E->isValueDependent() || E->isTypeDependent() || 2877 E->isInstantiationDependent() || 2878 E->containsUnexpandedParameterPack() || 2879 CanonPVD->getType()->hasIntegerRepresentation()) 2880 NewSteps.push_back(Step); 2881 else { 2882 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 2883 << Step->getSourceRange(); 2884 } 2885 continue; 2886 } 2887 NewStep = Step; 2888 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 2889 !Step->isInstantiationDependent() && 2890 !Step->containsUnexpandedParameterPack()) { 2891 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 2892 .get(); 2893 if (NewStep) 2894 NewStep = VerifyIntegerConstantExpression(NewStep).get(); 2895 } 2896 NewSteps.push_back(NewStep); 2897 } 2898 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 2899 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 2900 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 2901 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 2902 const_cast<Expr **>(Linears.data()), Linears.size(), 2903 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 2904 NewSteps.data(), NewSteps.size(), SR); 2905 ADecl->addAttr(NewAttr); 2906 return ConvertDeclToDeclGroup(ADecl); 2907 } 2908 2909 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 2910 Stmt *AStmt, 2911 SourceLocation StartLoc, 2912 SourceLocation EndLoc) { 2913 if (!AStmt) 2914 return StmtError(); 2915 2916 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 2917 // 1.2.2 OpenMP Language Terminology 2918 // Structured block - An executable statement with a single entry at the 2919 // top and a single exit at the bottom. 2920 // The point of exit cannot be a branch out of the structured block. 2921 // longjmp() and throw() must not violate the entry/exit criteria. 2922 CS->getCapturedDecl()->setNothrow(); 2923 2924 getCurFunction()->setHasBranchProtectedScope(); 2925 2926 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 2927 DSAStack->isCancelRegion()); 2928 } 2929 2930 namespace { 2931 /// \brief Helper class for checking canonical form of the OpenMP loops and 2932 /// extracting iteration space of each loop in the loop nest, that will be used 2933 /// for IR generation. 2934 class OpenMPIterationSpaceChecker { 2935 /// \brief Reference to Sema. 2936 Sema &SemaRef; 2937 /// \brief A location for diagnostics (when there is no some better location). 2938 SourceLocation DefaultLoc; 2939 /// \brief A location for diagnostics (when increment is not compatible). 2940 SourceLocation ConditionLoc; 2941 /// \brief A source location for referring to loop init later. 2942 SourceRange InitSrcRange; 2943 /// \brief A source location for referring to condition later. 2944 SourceRange ConditionSrcRange; 2945 /// \brief A source location for referring to increment later. 2946 SourceRange IncrementSrcRange; 2947 /// \brief Loop variable. 2948 ValueDecl *LCDecl = nullptr; 2949 /// \brief Reference to loop variable. 2950 Expr *LCRef = nullptr; 2951 /// \brief Lower bound (initializer for the var). 2952 Expr *LB = nullptr; 2953 /// \brief Upper bound. 2954 Expr *UB = nullptr; 2955 /// \brief Loop step (increment). 2956 Expr *Step = nullptr; 2957 /// \brief This flag is true when condition is one of: 2958 /// Var < UB 2959 /// Var <= UB 2960 /// UB > Var 2961 /// UB >= Var 2962 bool TestIsLessOp = false; 2963 /// \brief This flag is true when condition is strict ( < or > ). 2964 bool TestIsStrictOp = false; 2965 /// \brief This flag is true when step is subtracted on each iteration. 2966 bool SubtractStep = false; 2967 2968 public: 2969 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) 2970 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 2971 /// \brief Check init-expr for canonical loop form and save loop counter 2972 /// variable - #Var and its initialization value - #LB. 2973 bool CheckInit(Stmt *S, bool EmitDiags = true); 2974 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags 2975 /// for less/greater and for strict/non-strict comparison. 2976 bool CheckCond(Expr *S); 2977 /// \brief Check incr-expr for canonical loop form and return true if it 2978 /// does not conform, otherwise save loop step (#Step). 2979 bool CheckInc(Expr *S); 2980 /// \brief Return the loop counter variable. 2981 ValueDecl *GetLoopDecl() const { return LCDecl; } 2982 /// \brief Return the reference expression to loop counter variable. 2983 Expr *GetLoopDeclRefExpr() const { return LCRef; } 2984 /// \brief Source range of the loop init. 2985 SourceRange GetInitSrcRange() const { return InitSrcRange; } 2986 /// \brief Source range of the loop condition. 2987 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; } 2988 /// \brief Source range of the loop increment. 2989 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; } 2990 /// \brief True if the step should be subtracted. 2991 bool ShouldSubtractStep() const { return SubtractStep; } 2992 /// \brief Build the expression to calculate the number of iterations. 2993 Expr * 2994 BuildNumIterations(Scope *S, const bool LimitedType, 2995 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 2996 /// \brief Build the precondition expression for the loops. 2997 Expr *BuildPreCond(Scope *S, Expr *Cond, 2998 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 2999 /// \brief Build reference expression to the counter be used for codegen. 3000 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures, 3001 DSAStackTy &DSA) const; 3002 /// \brief Build reference expression to the private counter be used for 3003 /// codegen. 3004 Expr *BuildPrivateCounterVar() const; 3005 /// \brief Build initialization of the counter be used for codegen. 3006 Expr *BuildCounterInit() const; 3007 /// \brief Build step of the counter be used for codegen. 3008 Expr *BuildCounterStep() const; 3009 /// \brief Return true if any expression is dependent. 3010 bool Dependent() const; 3011 3012 private: 3013 /// \brief Check the right-hand side of an assignment in the increment 3014 /// expression. 3015 bool CheckIncRHS(Expr *RHS); 3016 /// \brief Helper to set loop counter variable and its initializer. 3017 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB); 3018 /// \brief Helper to set upper bound. 3019 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR, 3020 SourceLocation SL); 3021 /// \brief Helper to set loop increment. 3022 bool SetStep(Expr *NewStep, bool Subtract); 3023 }; 3024 3025 bool OpenMPIterationSpaceChecker::Dependent() const { 3026 if (!LCDecl) { 3027 assert(!LB && !UB && !Step); 3028 return false; 3029 } 3030 return LCDecl->getType()->isDependentType() || 3031 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 3032 (Step && Step->isValueDependent()); 3033 } 3034 3035 static Expr *getExprAsWritten(Expr *E) { 3036 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E)) 3037 E = ExprTemp->getSubExpr(); 3038 3039 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 3040 E = MTE->GetTemporaryExpr(); 3041 3042 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 3043 E = Binder->getSubExpr(); 3044 3045 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 3046 E = ICE->getSubExprAsWritten(); 3047 return E->IgnoreParens(); 3048 } 3049 3050 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl, 3051 Expr *NewLCRefExpr, 3052 Expr *NewLB) { 3053 // State consistency checking to ensure correct usage. 3054 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 3055 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 3056 if (!NewLCDecl || !NewLB) 3057 return true; 3058 LCDecl = getCanonicalDecl(NewLCDecl); 3059 LCRef = NewLCRefExpr; 3060 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 3061 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 3062 if ((Ctor->isCopyOrMoveConstructor() || 3063 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 3064 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 3065 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 3066 LB = NewLB; 3067 return false; 3068 } 3069 3070 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp, 3071 SourceRange SR, SourceLocation SL) { 3072 // State consistency checking to ensure correct usage. 3073 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 3074 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 3075 if (!NewUB) 3076 return true; 3077 UB = NewUB; 3078 TestIsLessOp = LessOp; 3079 TestIsStrictOp = StrictOp; 3080 ConditionSrcRange = SR; 3081 ConditionLoc = SL; 3082 return false; 3083 } 3084 3085 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) { 3086 // State consistency checking to ensure correct usage. 3087 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 3088 if (!NewStep) 3089 return true; 3090 if (!NewStep->isValueDependent()) { 3091 // Check that the step is integer expression. 3092 SourceLocation StepLoc = NewStep->getLocStart(); 3093 ExprResult Val = 3094 SemaRef.PerformOpenMPImplicitIntegerConversion(StepLoc, NewStep); 3095 if (Val.isInvalid()) 3096 return true; 3097 NewStep = Val.get(); 3098 3099 // OpenMP [2.6, Canonical Loop Form, Restrictions] 3100 // If test-expr is of form var relational-op b and relational-op is < or 3101 // <= then incr-expr must cause var to increase on each iteration of the 3102 // loop. If test-expr is of form var relational-op b and relational-op is 3103 // > or >= then incr-expr must cause var to decrease on each iteration of 3104 // the loop. 3105 // If test-expr is of form b relational-op var and relational-op is < or 3106 // <= then incr-expr must cause var to decrease on each iteration of the 3107 // loop. If test-expr is of form b relational-op var and relational-op is 3108 // > or >= then incr-expr must cause var to increase on each iteration of 3109 // the loop. 3110 llvm::APSInt Result; 3111 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 3112 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 3113 bool IsConstNeg = 3114 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 3115 bool IsConstPos = 3116 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 3117 bool IsConstZero = IsConstant && !Result.getBoolValue(); 3118 if (UB && (IsConstZero || 3119 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract)) 3120 : (IsConstPos || (IsUnsigned && !Subtract))))) { 3121 SemaRef.Diag(NewStep->getExprLoc(), 3122 diag::err_omp_loop_incr_not_compatible) 3123 << LCDecl << TestIsLessOp << NewStep->getSourceRange(); 3124 SemaRef.Diag(ConditionLoc, 3125 diag::note_omp_loop_cond_requres_compatible_incr) 3126 << TestIsLessOp << ConditionSrcRange; 3127 return true; 3128 } 3129 if (TestIsLessOp == Subtract) { 3130 NewStep = 3131 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 3132 .get(); 3133 Subtract = !Subtract; 3134 } 3135 } 3136 3137 Step = NewStep; 3138 SubtractStep = Subtract; 3139 return false; 3140 } 3141 3142 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) { 3143 // Check init-expr for canonical loop form and save loop counter 3144 // variable - #Var and its initialization value - #LB. 3145 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 3146 // var = lb 3147 // integer-type var = lb 3148 // random-access-iterator-type var = lb 3149 // pointer-type var = lb 3150 // 3151 if (!S) { 3152 if (EmitDiags) { 3153 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 3154 } 3155 return true; 3156 } 3157 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3158 if (!ExprTemp->cleanupsHaveSideEffects()) 3159 S = ExprTemp->getSubExpr(); 3160 3161 InitSrcRange = S->getSourceRange(); 3162 if (Expr *E = dyn_cast<Expr>(S)) 3163 S = E->IgnoreParens(); 3164 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3165 if (BO->getOpcode() == BO_Assign) { 3166 auto *LHS = BO->getLHS()->IgnoreParens(); 3167 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3168 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3169 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3170 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3171 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS()); 3172 } 3173 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3174 if (ME->isArrow() && 3175 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3176 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3177 } 3178 } 3179 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 3180 if (DS->isSingleDecl()) { 3181 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 3182 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 3183 // Accept non-canonical init form here but emit ext. warning. 3184 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 3185 SemaRef.Diag(S->getLocStart(), 3186 diag::ext_omp_loop_not_canonical_init) 3187 << S->getSourceRange(); 3188 return SetLCDeclAndLB(Var, nullptr, Var->getInit()); 3189 } 3190 } 3191 } 3192 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3193 if (CE->getOperator() == OO_Equal) { 3194 auto *LHS = CE->getArg(0); 3195 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3196 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3197 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3198 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3199 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1)); 3200 } 3201 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3202 if (ME->isArrow() && 3203 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3204 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3205 } 3206 } 3207 } 3208 3209 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3210 return false; 3211 if (EmitDiags) { 3212 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init) 3213 << S->getSourceRange(); 3214 } 3215 return true; 3216 } 3217 3218 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the 3219 /// variable (which may be the loop variable) if possible. 3220 static const ValueDecl *GetInitLCDecl(Expr *E) { 3221 if (!E) 3222 return nullptr; 3223 E = getExprAsWritten(E); 3224 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 3225 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 3226 if ((Ctor->isCopyOrMoveConstructor() || 3227 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 3228 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 3229 E = CE->getArg(0)->IgnoreParenImpCasts(); 3230 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 3231 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 3232 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD)) 3233 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3234 return getCanonicalDecl(ME->getMemberDecl()); 3235 return getCanonicalDecl(VD); 3236 } 3237 } 3238 if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 3239 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3240 return getCanonicalDecl(ME->getMemberDecl()); 3241 return nullptr; 3242 } 3243 3244 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) { 3245 // Check test-expr for canonical form, save upper-bound UB, flags for 3246 // less/greater and for strict/non-strict comparison. 3247 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3248 // var relational-op b 3249 // b relational-op var 3250 // 3251 if (!S) { 3252 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl; 3253 return true; 3254 } 3255 S = getExprAsWritten(S); 3256 SourceLocation CondLoc = S->getLocStart(); 3257 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3258 if (BO->isRelationalOp()) { 3259 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3260 return SetUB(BO->getRHS(), 3261 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 3262 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3263 BO->getSourceRange(), BO->getOperatorLoc()); 3264 if (GetInitLCDecl(BO->getRHS()) == LCDecl) 3265 return SetUB(BO->getLHS(), 3266 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 3267 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3268 BO->getSourceRange(), BO->getOperatorLoc()); 3269 } 3270 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3271 if (CE->getNumArgs() == 2) { 3272 auto Op = CE->getOperator(); 3273 switch (Op) { 3274 case OO_Greater: 3275 case OO_GreaterEqual: 3276 case OO_Less: 3277 case OO_LessEqual: 3278 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3279 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 3280 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3281 CE->getOperatorLoc()); 3282 if (GetInitLCDecl(CE->getArg(1)) == LCDecl) 3283 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 3284 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3285 CE->getOperatorLoc()); 3286 break; 3287 default: 3288 break; 3289 } 3290 } 3291 } 3292 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3293 return false; 3294 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 3295 << S->getSourceRange() << LCDecl; 3296 return true; 3297 } 3298 3299 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) { 3300 // RHS of canonical loop form increment can be: 3301 // var + incr 3302 // incr + var 3303 // var - incr 3304 // 3305 RHS = RHS->IgnoreParenImpCasts(); 3306 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 3307 if (BO->isAdditiveOp()) { 3308 bool IsAdd = BO->getOpcode() == BO_Add; 3309 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3310 return SetStep(BO->getRHS(), !IsAdd); 3311 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl) 3312 return SetStep(BO->getLHS(), false); 3313 } 3314 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 3315 bool IsAdd = CE->getOperator() == OO_Plus; 3316 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 3317 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3318 return SetStep(CE->getArg(1), !IsAdd); 3319 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl) 3320 return SetStep(CE->getArg(0), false); 3321 } 3322 } 3323 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3324 return false; 3325 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3326 << RHS->getSourceRange() << LCDecl; 3327 return true; 3328 } 3329 3330 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) { 3331 // Check incr-expr for canonical loop form and return true if it 3332 // does not conform. 3333 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3334 // ++var 3335 // var++ 3336 // --var 3337 // var-- 3338 // var += incr 3339 // var -= incr 3340 // var = var + incr 3341 // var = incr + var 3342 // var = var - incr 3343 // 3344 if (!S) { 3345 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 3346 return true; 3347 } 3348 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3349 if (!ExprTemp->cleanupsHaveSideEffects()) 3350 S = ExprTemp->getSubExpr(); 3351 3352 IncrementSrcRange = S->getSourceRange(); 3353 S = S->IgnoreParens(); 3354 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 3355 if (UO->isIncrementDecrementOp() && 3356 GetInitLCDecl(UO->getSubExpr()) == LCDecl) 3357 return SetStep(SemaRef 3358 .ActOnIntegerConstant(UO->getLocStart(), 3359 (UO->isDecrementOp() ? -1 : 1)) 3360 .get(), 3361 false); 3362 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3363 switch (BO->getOpcode()) { 3364 case BO_AddAssign: 3365 case BO_SubAssign: 3366 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3367 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 3368 break; 3369 case BO_Assign: 3370 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3371 return CheckIncRHS(BO->getRHS()); 3372 break; 3373 default: 3374 break; 3375 } 3376 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3377 switch (CE->getOperator()) { 3378 case OO_PlusPlus: 3379 case OO_MinusMinus: 3380 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3381 return SetStep(SemaRef 3382 .ActOnIntegerConstant( 3383 CE->getLocStart(), 3384 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 3385 .get(), 3386 false); 3387 break; 3388 case OO_PlusEqual: 3389 case OO_MinusEqual: 3390 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3391 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 3392 break; 3393 case OO_Equal: 3394 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3395 return CheckIncRHS(CE->getArg(1)); 3396 break; 3397 default: 3398 break; 3399 } 3400 } 3401 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3402 return false; 3403 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3404 << S->getSourceRange() << LCDecl; 3405 return true; 3406 } 3407 3408 static ExprResult 3409 tryBuildCapture(Sema &SemaRef, Expr *Capture, 3410 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3411 if (SemaRef.CurContext->isDependentContext()) 3412 return ExprResult(Capture); 3413 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 3414 return SemaRef.PerformImplicitConversion( 3415 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 3416 /*AllowExplicit=*/true); 3417 auto I = Captures.find(Capture); 3418 if (I != Captures.end()) 3419 return buildCapture(SemaRef, Capture, I->second); 3420 DeclRefExpr *Ref = nullptr; 3421 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 3422 Captures[Capture] = Ref; 3423 return Res; 3424 } 3425 3426 /// \brief Build the expression to calculate the number of iterations. 3427 Expr *OpenMPIterationSpaceChecker::BuildNumIterations( 3428 Scope *S, const bool LimitedType, 3429 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 3430 ExprResult Diff; 3431 auto VarType = LCDecl->getType().getNonReferenceType(); 3432 if (VarType->isIntegerType() || VarType->isPointerType() || 3433 SemaRef.getLangOpts().CPlusPlus) { 3434 // Upper - Lower 3435 auto *UBExpr = TestIsLessOp ? UB : LB; 3436 auto *LBExpr = TestIsLessOp ? LB : UB; 3437 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 3438 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 3439 if (!Upper || !Lower) 3440 return nullptr; 3441 3442 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 3443 3444 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 3445 // BuildBinOp already emitted error, this one is to point user to upper 3446 // and lower bound, and to tell what is passed to 'operator-'. 3447 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx) 3448 << Upper->getSourceRange() << Lower->getSourceRange(); 3449 return nullptr; 3450 } 3451 } 3452 3453 if (!Diff.isUsable()) 3454 return nullptr; 3455 3456 // Upper - Lower [- 1] 3457 if (TestIsStrictOp) 3458 Diff = SemaRef.BuildBinOp( 3459 S, DefaultLoc, BO_Sub, Diff.get(), 3460 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 3461 if (!Diff.isUsable()) 3462 return nullptr; 3463 3464 // Upper - Lower [- 1] + Step 3465 auto NewStep = tryBuildCapture(SemaRef, Step, Captures); 3466 if (!NewStep.isUsable()) 3467 return nullptr; 3468 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 3469 if (!Diff.isUsable()) 3470 return nullptr; 3471 3472 // Parentheses (for dumping/debugging purposes only). 3473 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 3474 if (!Diff.isUsable()) 3475 return nullptr; 3476 3477 // (Upper - Lower [- 1] + Step) / Step 3478 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 3479 if (!Diff.isUsable()) 3480 return nullptr; 3481 3482 // OpenMP runtime requires 32-bit or 64-bit loop variables. 3483 QualType Type = Diff.get()->getType(); 3484 auto &C = SemaRef.Context; 3485 bool UseVarType = VarType->hasIntegerRepresentation() && 3486 C.getTypeSize(Type) > C.getTypeSize(VarType); 3487 if (!Type->isIntegerType() || UseVarType) { 3488 unsigned NewSize = 3489 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 3490 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 3491 : Type->hasSignedIntegerRepresentation(); 3492 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 3493 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 3494 Diff = SemaRef.PerformImplicitConversion( 3495 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 3496 if (!Diff.isUsable()) 3497 return nullptr; 3498 } 3499 } 3500 if (LimitedType) { 3501 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 3502 if (NewSize != C.getTypeSize(Type)) { 3503 if (NewSize < C.getTypeSize(Type)) { 3504 assert(NewSize == 64 && "incorrect loop var size"); 3505 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 3506 << InitSrcRange << ConditionSrcRange; 3507 } 3508 QualType NewType = C.getIntTypeForBitwidth( 3509 NewSize, Type->hasSignedIntegerRepresentation() || 3510 C.getTypeSize(Type) < NewSize); 3511 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 3512 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 3513 Sema::AA_Converting, true); 3514 if (!Diff.isUsable()) 3515 return nullptr; 3516 } 3517 } 3518 } 3519 3520 return Diff.get(); 3521 } 3522 3523 Expr *OpenMPIterationSpaceChecker::BuildPreCond( 3524 Scope *S, Expr *Cond, 3525 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 3526 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 3527 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 3528 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 3529 3530 auto NewLB = tryBuildCapture(SemaRef, LB, Captures); 3531 auto NewUB = tryBuildCapture(SemaRef, UB, Captures); 3532 if (!NewLB.isUsable() || !NewUB.isUsable()) 3533 return nullptr; 3534 3535 auto CondExpr = SemaRef.BuildBinOp( 3536 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE) 3537 : (TestIsStrictOp ? BO_GT : BO_GE), 3538 NewLB.get(), NewUB.get()); 3539 if (CondExpr.isUsable()) { 3540 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 3541 SemaRef.Context.BoolTy)) 3542 CondExpr = SemaRef.PerformImplicitConversion( 3543 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 3544 /*AllowExplicit=*/true); 3545 } 3546 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 3547 // Otherwise use original loop conditon and evaluate it in runtime. 3548 return CondExpr.isUsable() ? CondExpr.get() : Cond; 3549 } 3550 3551 /// \brief Build reference expression to the counter be used for codegen. 3552 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar( 3553 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const { 3554 auto *VD = dyn_cast<VarDecl>(LCDecl); 3555 if (!VD) { 3556 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl); 3557 auto *Ref = buildDeclRefExpr( 3558 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 3559 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false); 3560 // If the loop control decl is explicitly marked as private, do not mark it 3561 // as captured again. 3562 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 3563 Captures.insert(std::make_pair(LCRef, Ref)); 3564 return Ref; 3565 } 3566 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(), 3567 DefaultLoc); 3568 } 3569 3570 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const { 3571 if (LCDecl && !LCDecl->isInvalidDecl()) { 3572 auto Type = LCDecl->getType().getNonReferenceType(); 3573 auto *PrivateVar = 3574 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(), 3575 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr); 3576 if (PrivateVar->isInvalidDecl()) 3577 return nullptr; 3578 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 3579 } 3580 return nullptr; 3581 } 3582 3583 /// \brief Build initialization of the counter to be used for codegen. 3584 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; } 3585 3586 /// \brief Build step of the counter be used for codegen. 3587 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; } 3588 3589 /// \brief Iteration space of a single for loop. 3590 struct LoopIterationSpace final { 3591 /// \brief Condition of the loop. 3592 Expr *PreCond = nullptr; 3593 /// \brief This expression calculates the number of iterations in the loop. 3594 /// It is always possible to calculate it before starting the loop. 3595 Expr *NumIterations = nullptr; 3596 /// \brief The loop counter variable. 3597 Expr *CounterVar = nullptr; 3598 /// \brief Private loop counter variable. 3599 Expr *PrivateCounterVar = nullptr; 3600 /// \brief This is initializer for the initial value of #CounterVar. 3601 Expr *CounterInit = nullptr; 3602 /// \brief This is step for the #CounterVar used to generate its update: 3603 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 3604 Expr *CounterStep = nullptr; 3605 /// \brief Should step be subtracted? 3606 bool Subtract = false; 3607 /// \brief Source range of the loop init. 3608 SourceRange InitSrcRange; 3609 /// \brief Source range of the loop condition. 3610 SourceRange CondSrcRange; 3611 /// \brief Source range of the loop increment. 3612 SourceRange IncSrcRange; 3613 }; 3614 3615 } // namespace 3616 3617 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 3618 assert(getLangOpts().OpenMP && "OpenMP is not active."); 3619 assert(Init && "Expected loop in canonical form."); 3620 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 3621 if (AssociatedLoops > 0 && 3622 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 3623 OpenMPIterationSpaceChecker ISC(*this, ForLoc); 3624 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) { 3625 if (auto *D = ISC.GetLoopDecl()) { 3626 auto *VD = dyn_cast<VarDecl>(D); 3627 if (!VD) { 3628 if (auto *Private = IsOpenMPCapturedDecl(D)) 3629 VD = Private; 3630 else { 3631 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(), 3632 /*WithInit=*/false); 3633 VD = cast<VarDecl>(Ref->getDecl()); 3634 } 3635 } 3636 DSAStack->addLoopControlVariable(D, VD); 3637 } 3638 } 3639 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 3640 } 3641 } 3642 3643 /// \brief Called on a for stmt to check and extract its iteration space 3644 /// for further processing (such as collapsing). 3645 static bool CheckOpenMPIterationSpace( 3646 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 3647 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 3648 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr, 3649 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 3650 LoopIterationSpace &ResultIterSpace, 3651 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3652 // OpenMP [2.6, Canonical Loop Form] 3653 // for (init-expr; test-expr; incr-expr) structured-block 3654 auto *For = dyn_cast_or_null<ForStmt>(S); 3655 if (!For) { 3656 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for) 3657 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 3658 << getOpenMPDirectiveName(DKind) << NestedLoopCount 3659 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 3660 if (NestedLoopCount > 1) { 3661 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 3662 SemaRef.Diag(DSA.getConstructLoc(), 3663 diag::note_omp_collapse_ordered_expr) 3664 << 2 << CollapseLoopCountExpr->getSourceRange() 3665 << OrderedLoopCountExpr->getSourceRange(); 3666 else if (CollapseLoopCountExpr) 3667 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 3668 diag::note_omp_collapse_ordered_expr) 3669 << 0 << CollapseLoopCountExpr->getSourceRange(); 3670 else 3671 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 3672 diag::note_omp_collapse_ordered_expr) 3673 << 1 << OrderedLoopCountExpr->getSourceRange(); 3674 } 3675 return true; 3676 } 3677 assert(For->getBody()); 3678 3679 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); 3680 3681 // Check init. 3682 auto Init = For->getInit(); 3683 if (ISC.CheckInit(Init)) 3684 return true; 3685 3686 bool HasErrors = false; 3687 3688 // Check loop variable's type. 3689 if (auto *LCDecl = ISC.GetLoopDecl()) { 3690 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr(); 3691 3692 // OpenMP [2.6, Canonical Loop Form] 3693 // Var is one of the following: 3694 // A variable of signed or unsigned integer type. 3695 // For C++, a variable of a random access iterator type. 3696 // For C, a variable of a pointer type. 3697 auto VarType = LCDecl->getType().getNonReferenceType(); 3698 if (!VarType->isDependentType() && !VarType->isIntegerType() && 3699 !VarType->isPointerType() && 3700 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 3701 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type) 3702 << SemaRef.getLangOpts().CPlusPlus; 3703 HasErrors = true; 3704 } 3705 3706 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 3707 // a Construct 3708 // The loop iteration variable(s) in the associated for-loop(s) of a for or 3709 // parallel for construct is (are) private. 3710 // The loop iteration variable in the associated for-loop of a simd 3711 // construct with just one associated for-loop is linear with a 3712 // constant-linear-step that is the increment of the associated for-loop. 3713 // Exclude loop var from the list of variables with implicitly defined data 3714 // sharing attributes. 3715 VarsWithImplicitDSA.erase(LCDecl); 3716 3717 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 3718 // in a Construct, C/C++]. 3719 // The loop iteration variable in the associated for-loop of a simd 3720 // construct with just one associated for-loop may be listed in a linear 3721 // clause with a constant-linear-step that is the increment of the 3722 // associated for-loop. 3723 // The loop iteration variable(s) in the associated for-loop(s) of a for or 3724 // parallel for construct may be listed in a private or lastprivate clause. 3725 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false); 3726 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 3727 // declared in the loop and it is predetermined as a private. 3728 auto PredeterminedCKind = 3729 isOpenMPSimdDirective(DKind) 3730 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 3731 : OMPC_private; 3732 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 3733 DVar.CKind != PredeterminedCKind) || 3734 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 3735 isOpenMPDistributeDirective(DKind)) && 3736 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 3737 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 3738 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 3739 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa) 3740 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 3741 << getOpenMPClauseName(PredeterminedCKind); 3742 if (DVar.RefExpr == nullptr) 3743 DVar.CKind = PredeterminedCKind; 3744 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true); 3745 HasErrors = true; 3746 } else if (LoopDeclRefExpr != nullptr) { 3747 // Make the loop iteration variable private (for worksharing constructs), 3748 // linear (for simd directives with the only one associated loop) or 3749 // lastprivate (for simd directives with several collapsed or ordered 3750 // loops). 3751 if (DVar.CKind == OMPC_unknown) 3752 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate, 3753 [](OpenMPDirectiveKind) -> bool { return true; }, 3754 /*FromParent=*/false); 3755 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind); 3756 } 3757 3758 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 3759 3760 // Check test-expr. 3761 HasErrors |= ISC.CheckCond(For->getCond()); 3762 3763 // Check incr-expr. 3764 HasErrors |= ISC.CheckInc(For->getInc()); 3765 } 3766 3767 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 3768 return HasErrors; 3769 3770 // Build the loop's iteration space representation. 3771 ResultIterSpace.PreCond = 3772 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures); 3773 ResultIterSpace.NumIterations = ISC.BuildNumIterations( 3774 DSA.getCurScope(), 3775 (isOpenMPWorksharingDirective(DKind) || 3776 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)), 3777 Captures); 3778 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA); 3779 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar(); 3780 ResultIterSpace.CounterInit = ISC.BuildCounterInit(); 3781 ResultIterSpace.CounterStep = ISC.BuildCounterStep(); 3782 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange(); 3783 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange(); 3784 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange(); 3785 ResultIterSpace.Subtract = ISC.ShouldSubtractStep(); 3786 3787 HasErrors |= (ResultIterSpace.PreCond == nullptr || 3788 ResultIterSpace.NumIterations == nullptr || 3789 ResultIterSpace.CounterVar == nullptr || 3790 ResultIterSpace.PrivateCounterVar == nullptr || 3791 ResultIterSpace.CounterInit == nullptr || 3792 ResultIterSpace.CounterStep == nullptr); 3793 3794 return HasErrors; 3795 } 3796 3797 /// \brief Build 'VarRef = Start. 3798 static ExprResult 3799 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 3800 ExprResult Start, 3801 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3802 // Build 'VarRef = Start. 3803 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures); 3804 if (!NewStart.isUsable()) 3805 return ExprError(); 3806 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 3807 VarRef.get()->getType())) { 3808 NewStart = SemaRef.PerformImplicitConversion( 3809 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 3810 /*AllowExplicit=*/true); 3811 if (!NewStart.isUsable()) 3812 return ExprError(); 3813 } 3814 3815 auto Init = 3816 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 3817 return Init; 3818 } 3819 3820 /// \brief Build 'VarRef = Start + Iter * Step'. 3821 static ExprResult 3822 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc, 3823 ExprResult VarRef, ExprResult Start, ExprResult Iter, 3824 ExprResult Step, bool Subtract, 3825 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) { 3826 // Add parentheses (for debugging purposes only). 3827 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 3828 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 3829 !Step.isUsable()) 3830 return ExprError(); 3831 3832 ExprResult NewStep = Step; 3833 if (Captures) 3834 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 3835 if (NewStep.isInvalid()) 3836 return ExprError(); 3837 ExprResult Update = 3838 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 3839 if (!Update.isUsable()) 3840 return ExprError(); 3841 3842 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 3843 // 'VarRef = Start (+|-) Iter * Step'. 3844 ExprResult NewStart = Start; 3845 if (Captures) 3846 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 3847 if (NewStart.isInvalid()) 3848 return ExprError(); 3849 3850 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 3851 ExprResult SavedUpdate = Update; 3852 ExprResult UpdateVal; 3853 if (VarRef.get()->getType()->isOverloadableType() || 3854 NewStart.get()->getType()->isOverloadableType() || 3855 Update.get()->getType()->isOverloadableType()) { 3856 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 3857 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 3858 Update = 3859 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 3860 if (Update.isUsable()) { 3861 UpdateVal = 3862 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 3863 VarRef.get(), SavedUpdate.get()); 3864 if (UpdateVal.isUsable()) { 3865 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 3866 UpdateVal.get()); 3867 } 3868 } 3869 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 3870 } 3871 3872 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 3873 if (!Update.isUsable() || !UpdateVal.isUsable()) { 3874 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 3875 NewStart.get(), SavedUpdate.get()); 3876 if (!Update.isUsable()) 3877 return ExprError(); 3878 3879 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 3880 VarRef.get()->getType())) { 3881 Update = SemaRef.PerformImplicitConversion( 3882 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 3883 if (!Update.isUsable()) 3884 return ExprError(); 3885 } 3886 3887 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 3888 } 3889 return Update; 3890 } 3891 3892 /// \brief Convert integer expression \a E to make it have at least \a Bits 3893 /// bits. 3894 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 3895 if (E == nullptr) 3896 return ExprError(); 3897 auto &C = SemaRef.Context; 3898 QualType OldType = E->getType(); 3899 unsigned HasBits = C.getTypeSize(OldType); 3900 if (HasBits >= Bits) 3901 return ExprResult(E); 3902 // OK to convert to signed, because new type has more bits than old. 3903 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 3904 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 3905 true); 3906 } 3907 3908 /// \brief Check if the given expression \a E is a constant integer that fits 3909 /// into \a Bits bits. 3910 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) { 3911 if (E == nullptr) 3912 return false; 3913 llvm::APSInt Result; 3914 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 3915 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 3916 return false; 3917 } 3918 3919 /// Build preinits statement for the given declarations. 3920 static Stmt *buildPreInits(ASTContext &Context, 3921 SmallVectorImpl<Decl *> &PreInits) { 3922 if (!PreInits.empty()) { 3923 return new (Context) DeclStmt( 3924 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 3925 SourceLocation(), SourceLocation()); 3926 } 3927 return nullptr; 3928 } 3929 3930 /// Build preinits statement for the given declarations. 3931 static Stmt *buildPreInits(ASTContext &Context, 3932 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3933 if (!Captures.empty()) { 3934 SmallVector<Decl *, 16> PreInits; 3935 for (auto &Pair : Captures) 3936 PreInits.push_back(Pair.second->getDecl()); 3937 return buildPreInits(Context, PreInits); 3938 } 3939 return nullptr; 3940 } 3941 3942 /// Build postupdate expression for the given list of postupdates expressions. 3943 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 3944 Expr *PostUpdate = nullptr; 3945 if (!PostUpdates.empty()) { 3946 for (auto *E : PostUpdates) { 3947 Expr *ConvE = S.BuildCStyleCastExpr( 3948 E->getExprLoc(), 3949 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 3950 E->getExprLoc(), E) 3951 .get(); 3952 PostUpdate = PostUpdate 3953 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 3954 PostUpdate, ConvE) 3955 .get() 3956 : ConvE; 3957 } 3958 } 3959 return PostUpdate; 3960 } 3961 3962 /// \brief Called on a for stmt to check itself and nested loops (if any). 3963 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 3964 /// number of collapsed loops otherwise. 3965 static unsigned 3966 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 3967 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 3968 DSAStackTy &DSA, 3969 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 3970 OMPLoopDirective::HelperExprs &Built) { 3971 unsigned NestedLoopCount = 1; 3972 if (CollapseLoopCountExpr) { 3973 // Found 'collapse' clause - calculate collapse number. 3974 llvm::APSInt Result; 3975 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) 3976 NestedLoopCount = Result.getLimitedValue(); 3977 } 3978 if (OrderedLoopCountExpr) { 3979 // Found 'ordered' clause - calculate collapse number. 3980 llvm::APSInt Result; 3981 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 3982 if (Result.getLimitedValue() < NestedLoopCount) { 3983 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 3984 diag::err_omp_wrong_ordered_loop_count) 3985 << OrderedLoopCountExpr->getSourceRange(); 3986 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 3987 diag::note_collapse_loop_count) 3988 << CollapseLoopCountExpr->getSourceRange(); 3989 } 3990 NestedLoopCount = Result.getLimitedValue(); 3991 } 3992 } 3993 // This is helper routine for loop directives (e.g., 'for', 'simd', 3994 // 'for simd', etc.). 3995 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 3996 SmallVector<LoopIterationSpace, 4> IterSpaces; 3997 IterSpaces.resize(NestedLoopCount); 3998 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 3999 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 4000 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt, 4001 NestedLoopCount, CollapseLoopCountExpr, 4002 OrderedLoopCountExpr, VarsWithImplicitDSA, 4003 IterSpaces[Cnt], Captures)) 4004 return 0; 4005 // Move on to the next nested for loop, or to the loop body. 4006 // OpenMP [2.8.1, simd construct, Restrictions] 4007 // All loops associated with the construct must be perfectly nested; that 4008 // is, there must be no intervening code nor any OpenMP directive between 4009 // any two loops. 4010 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 4011 } 4012 4013 Built.clear(/* size */ NestedLoopCount); 4014 4015 if (SemaRef.CurContext->isDependentContext()) 4016 return NestedLoopCount; 4017 4018 // An example of what is generated for the following code: 4019 // 4020 // #pragma omp simd collapse(2) ordered(2) 4021 // for (i = 0; i < NI; ++i) 4022 // for (k = 0; k < NK; ++k) 4023 // for (j = J0; j < NJ; j+=2) { 4024 // <loop body> 4025 // } 4026 // 4027 // We generate the code below. 4028 // Note: the loop body may be outlined in CodeGen. 4029 // Note: some counters may be C++ classes, operator- is used to find number of 4030 // iterations and operator+= to calculate counter value. 4031 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 4032 // or i64 is currently supported). 4033 // 4034 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 4035 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 4036 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 4037 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 4038 // // similar updates for vars in clauses (e.g. 'linear') 4039 // <loop body (using local i and j)> 4040 // } 4041 // i = NI; // assign final values of counters 4042 // j = NJ; 4043 // 4044 4045 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 4046 // the iteration counts of the collapsed for loops. 4047 // Precondition tests if there is at least one iteration (all conditions are 4048 // true). 4049 auto PreCond = ExprResult(IterSpaces[0].PreCond); 4050 auto N0 = IterSpaces[0].NumIterations; 4051 ExprResult LastIteration32 = WidenIterationCount( 4052 32 /* Bits */, SemaRef 4053 .PerformImplicitConversion( 4054 N0->IgnoreImpCasts(), N0->getType(), 4055 Sema::AA_Converting, /*AllowExplicit=*/true) 4056 .get(), 4057 SemaRef); 4058 ExprResult LastIteration64 = WidenIterationCount( 4059 64 /* Bits */, SemaRef 4060 .PerformImplicitConversion( 4061 N0->IgnoreImpCasts(), N0->getType(), 4062 Sema::AA_Converting, /*AllowExplicit=*/true) 4063 .get(), 4064 SemaRef); 4065 4066 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 4067 return NestedLoopCount; 4068 4069 auto &C = SemaRef.Context; 4070 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 4071 4072 Scope *CurScope = DSA.getCurScope(); 4073 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 4074 if (PreCond.isUsable()) { 4075 PreCond = 4076 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 4077 PreCond.get(), IterSpaces[Cnt].PreCond); 4078 } 4079 auto N = IterSpaces[Cnt].NumIterations; 4080 SourceLocation Loc = N->getExprLoc(); 4081 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 4082 if (LastIteration32.isUsable()) 4083 LastIteration32 = SemaRef.BuildBinOp( 4084 CurScope, Loc, BO_Mul, LastIteration32.get(), 4085 SemaRef 4086 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 4087 Sema::AA_Converting, 4088 /*AllowExplicit=*/true) 4089 .get()); 4090 if (LastIteration64.isUsable()) 4091 LastIteration64 = SemaRef.BuildBinOp( 4092 CurScope, Loc, BO_Mul, LastIteration64.get(), 4093 SemaRef 4094 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 4095 Sema::AA_Converting, 4096 /*AllowExplicit=*/true) 4097 .get()); 4098 } 4099 4100 // Choose either the 32-bit or 64-bit version. 4101 ExprResult LastIteration = LastIteration64; 4102 if (LastIteration32.isUsable() && 4103 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 4104 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 4105 FitsInto( 4106 32 /* Bits */, 4107 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 4108 LastIteration64.get(), SemaRef))) 4109 LastIteration = LastIteration32; 4110 QualType VType = LastIteration.get()->getType(); 4111 QualType RealVType = VType; 4112 QualType StrideVType = VType; 4113 if (isOpenMPTaskLoopDirective(DKind)) { 4114 VType = 4115 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 4116 StrideVType = 4117 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 4118 } 4119 4120 if (!LastIteration.isUsable()) 4121 return 0; 4122 4123 // Save the number of iterations. 4124 ExprResult NumIterations = LastIteration; 4125 { 4126 LastIteration = SemaRef.BuildBinOp( 4127 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 4128 LastIteration.get(), 4129 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4130 if (!LastIteration.isUsable()) 4131 return 0; 4132 } 4133 4134 // Calculate the last iteration number beforehand instead of doing this on 4135 // each iteration. Do not do this if the number of iterations may be kfold-ed. 4136 llvm::APSInt Result; 4137 bool IsConstant = 4138 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 4139 ExprResult CalcLastIteration; 4140 if (!IsConstant) { 4141 ExprResult SaveRef = 4142 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 4143 LastIteration = SaveRef; 4144 4145 // Prepare SaveRef + 1. 4146 NumIterations = SemaRef.BuildBinOp( 4147 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 4148 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4149 if (!NumIterations.isUsable()) 4150 return 0; 4151 } 4152 4153 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 4154 4155 // Build variables passed into runtime, necessary for worksharing directives. 4156 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 4157 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4158 isOpenMPDistributeDirective(DKind)) { 4159 // Lower bound variable, initialized with zero. 4160 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 4161 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 4162 SemaRef.AddInitializerToDecl(LBDecl, 4163 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4164 /*DirectInit*/ false); 4165 4166 // Upper bound variable, initialized with last iteration number. 4167 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 4168 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 4169 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 4170 /*DirectInit*/ false); 4171 4172 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 4173 // This will be used to implement clause 'lastprivate'. 4174 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 4175 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 4176 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 4177 SemaRef.AddInitializerToDecl(ILDecl, 4178 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4179 /*DirectInit*/ false); 4180 4181 // Stride variable returned by runtime (we initialize it to 1 by default). 4182 VarDecl *STDecl = 4183 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 4184 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 4185 SemaRef.AddInitializerToDecl(STDecl, 4186 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 4187 /*DirectInit*/ false); 4188 4189 // Build expression: UB = min(UB, LastIteration) 4190 // It is necessary for CodeGen of directives with static scheduling. 4191 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 4192 UB.get(), LastIteration.get()); 4193 ExprResult CondOp = SemaRef.ActOnConditionalOp( 4194 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get()); 4195 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 4196 CondOp.get()); 4197 EUB = SemaRef.ActOnFinishFullExpr(EUB.get()); 4198 4199 // If we have a combined directive that combines 'distribute', 'for' or 4200 // 'simd' we need to be able to access the bounds of the schedule of the 4201 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 4202 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 4203 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4204 4205 // Lower bound variable, initialized with zero. 4206 VarDecl *CombLBDecl = 4207 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 4208 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 4209 SemaRef.AddInitializerToDecl( 4210 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4211 /*DirectInit*/ false); 4212 4213 // Upper bound variable, initialized with last iteration number. 4214 VarDecl *CombUBDecl = 4215 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 4216 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 4217 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 4218 /*DirectInit*/ false); 4219 4220 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 4221 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 4222 ExprResult CombCondOp = 4223 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 4224 LastIteration.get(), CombUB.get()); 4225 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 4226 CombCondOp.get()); 4227 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get()); 4228 4229 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 4230 // We expect to have at least 2 more parameters than the 'parallel' 4231 // directive does - the lower and upper bounds of the previous schedule. 4232 assert(CD->getNumParams() >= 4 && 4233 "Unexpected number of parameters in loop combined directive"); 4234 4235 // Set the proper type for the bounds given what we learned from the 4236 // enclosed loops. 4237 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 4238 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 4239 4240 // Previous lower and upper bounds are obtained from the region 4241 // parameters. 4242 PrevLB = 4243 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 4244 PrevUB = 4245 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 4246 } 4247 } 4248 4249 // Build the iteration variable and its initialization before loop. 4250 ExprResult IV; 4251 ExprResult Init, CombInit; 4252 { 4253 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 4254 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 4255 Expr *RHS = 4256 (isOpenMPWorksharingDirective(DKind) || 4257 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4258 ? LB.get() 4259 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 4260 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 4261 Init = SemaRef.ActOnFinishFullExpr(Init.get()); 4262 4263 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4264 Expr *CombRHS = 4265 (isOpenMPWorksharingDirective(DKind) || 4266 isOpenMPTaskLoopDirective(DKind) || 4267 isOpenMPDistributeDirective(DKind)) 4268 ? CombLB.get() 4269 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 4270 CombInit = 4271 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 4272 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get()); 4273 } 4274 } 4275 4276 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops. 4277 SourceLocation CondLoc; 4278 ExprResult Cond = 4279 (isOpenMPWorksharingDirective(DKind) || 4280 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4281 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()) 4282 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 4283 NumIterations.get()); 4284 ExprResult CombCond; 4285 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4286 CombCond = 4287 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get()); 4288 } 4289 // Loop increment (IV = IV + 1) 4290 SourceLocation IncLoc; 4291 ExprResult Inc = 4292 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 4293 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 4294 if (!Inc.isUsable()) 4295 return 0; 4296 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 4297 Inc = SemaRef.ActOnFinishFullExpr(Inc.get()); 4298 if (!Inc.isUsable()) 4299 return 0; 4300 4301 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 4302 // Used for directives with static scheduling. 4303 // In combined construct, add combined version that use CombLB and CombUB 4304 // base variables for the update 4305 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 4306 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4307 isOpenMPDistributeDirective(DKind)) { 4308 // LB + ST 4309 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 4310 if (!NextLB.isUsable()) 4311 return 0; 4312 // LB = LB + ST 4313 NextLB = 4314 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 4315 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get()); 4316 if (!NextLB.isUsable()) 4317 return 0; 4318 // UB + ST 4319 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 4320 if (!NextUB.isUsable()) 4321 return 0; 4322 // UB = UB + ST 4323 NextUB = 4324 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 4325 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get()); 4326 if (!NextUB.isUsable()) 4327 return 0; 4328 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4329 CombNextLB = 4330 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 4331 if (!NextLB.isUsable()) 4332 return 0; 4333 // LB = LB + ST 4334 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 4335 CombNextLB.get()); 4336 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get()); 4337 if (!CombNextLB.isUsable()) 4338 return 0; 4339 // UB + ST 4340 CombNextUB = 4341 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 4342 if (!CombNextUB.isUsable()) 4343 return 0; 4344 // UB = UB + ST 4345 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 4346 CombNextUB.get()); 4347 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get()); 4348 if (!CombNextUB.isUsable()) 4349 return 0; 4350 } 4351 } 4352 4353 // Create increment expression for distribute loop when combined in a same 4354 // directive with for as IV = IV + ST; ensure upper bound expression based 4355 // on PrevUB instead of NumIterations - used to implement 'for' when found 4356 // in combination with 'distribute', like in 'distribute parallel for' 4357 SourceLocation DistIncLoc; 4358 ExprResult DistCond, DistInc, PrevEUB; 4359 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4360 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()); 4361 assert(DistCond.isUsable() && "distribute cond expr was not built"); 4362 4363 DistInc = 4364 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 4365 assert(DistInc.isUsable() && "distribute inc expr was not built"); 4366 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 4367 DistInc.get()); 4368 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get()); 4369 assert(DistInc.isUsable() && "distribute inc expr was not built"); 4370 4371 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 4372 // construct 4373 SourceLocation DistEUBLoc; 4374 ExprResult IsUBGreater = 4375 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get()); 4376 ExprResult CondOp = SemaRef.ActOnConditionalOp( 4377 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get()); 4378 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 4379 CondOp.get()); 4380 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get()); 4381 } 4382 4383 // Build updates and final values of the loop counters. 4384 bool HasErrors = false; 4385 Built.Counters.resize(NestedLoopCount); 4386 Built.Inits.resize(NestedLoopCount); 4387 Built.Updates.resize(NestedLoopCount); 4388 Built.Finals.resize(NestedLoopCount); 4389 SmallVector<Expr *, 4> LoopMultipliers; 4390 { 4391 ExprResult Div; 4392 // Go from inner nested loop to outer. 4393 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 4394 LoopIterationSpace &IS = IterSpaces[Cnt]; 4395 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 4396 // Build: Iter = (IV / Div) % IS.NumIters 4397 // where Div is product of previous iterations' IS.NumIters. 4398 ExprResult Iter; 4399 if (Div.isUsable()) { 4400 Iter = 4401 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get()); 4402 } else { 4403 Iter = IV; 4404 assert((Cnt == (int)NestedLoopCount - 1) && 4405 "unusable div expected on first iteration only"); 4406 } 4407 4408 if (Cnt != 0 && Iter.isUsable()) 4409 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(), 4410 IS.NumIterations); 4411 if (!Iter.isUsable()) { 4412 HasErrors = true; 4413 break; 4414 } 4415 4416 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 4417 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 4418 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(), 4419 IS.CounterVar->getExprLoc(), 4420 /*RefersToCapture=*/true); 4421 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 4422 IS.CounterInit, Captures); 4423 if (!Init.isUsable()) { 4424 HasErrors = true; 4425 break; 4426 } 4427 ExprResult Update = BuildCounterUpdate( 4428 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 4429 IS.CounterStep, IS.Subtract, &Captures); 4430 if (!Update.isUsable()) { 4431 HasErrors = true; 4432 break; 4433 } 4434 4435 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 4436 ExprResult Final = BuildCounterUpdate( 4437 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, 4438 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures); 4439 if (!Final.isUsable()) { 4440 HasErrors = true; 4441 break; 4442 } 4443 4444 // Build Div for the next iteration: Div <- Div * IS.NumIters 4445 if (Cnt != 0) { 4446 if (Div.isUnset()) 4447 Div = IS.NumIterations; 4448 else 4449 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(), 4450 IS.NumIterations); 4451 4452 // Add parentheses (for debugging purposes only). 4453 if (Div.isUsable()) 4454 Div = tryBuildCapture(SemaRef, Div.get(), Captures); 4455 if (!Div.isUsable()) { 4456 HasErrors = true; 4457 break; 4458 } 4459 LoopMultipliers.push_back(Div.get()); 4460 } 4461 if (!Update.isUsable() || !Final.isUsable()) { 4462 HasErrors = true; 4463 break; 4464 } 4465 // Save results 4466 Built.Counters[Cnt] = IS.CounterVar; 4467 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 4468 Built.Inits[Cnt] = Init.get(); 4469 Built.Updates[Cnt] = Update.get(); 4470 Built.Finals[Cnt] = Final.get(); 4471 } 4472 } 4473 4474 if (HasErrors) 4475 return 0; 4476 4477 // Save results 4478 Built.IterationVarRef = IV.get(); 4479 Built.LastIteration = LastIteration.get(); 4480 Built.NumIterations = NumIterations.get(); 4481 Built.CalcLastIteration = 4482 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get(); 4483 Built.PreCond = PreCond.get(); 4484 Built.PreInits = buildPreInits(C, Captures); 4485 Built.Cond = Cond.get(); 4486 Built.Init = Init.get(); 4487 Built.Inc = Inc.get(); 4488 Built.LB = LB.get(); 4489 Built.UB = UB.get(); 4490 Built.IL = IL.get(); 4491 Built.ST = ST.get(); 4492 Built.EUB = EUB.get(); 4493 Built.NLB = NextLB.get(); 4494 Built.NUB = NextUB.get(); 4495 Built.PrevLB = PrevLB.get(); 4496 Built.PrevUB = PrevUB.get(); 4497 Built.DistInc = DistInc.get(); 4498 Built.PrevEUB = PrevEUB.get(); 4499 Built.DistCombinedFields.LB = CombLB.get(); 4500 Built.DistCombinedFields.UB = CombUB.get(); 4501 Built.DistCombinedFields.EUB = CombEUB.get(); 4502 Built.DistCombinedFields.Init = CombInit.get(); 4503 Built.DistCombinedFields.Cond = CombCond.get(); 4504 Built.DistCombinedFields.NLB = CombNextLB.get(); 4505 Built.DistCombinedFields.NUB = CombNextUB.get(); 4506 4507 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get(); 4508 // Fill data for doacross depend clauses. 4509 for (auto Pair : DSA.getDoacrossDependClauses()) { 4510 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 4511 Pair.first->setCounterValue(CounterVal); 4512 else { 4513 if (NestedLoopCount != Pair.second.size() || 4514 NestedLoopCount != LoopMultipliers.size() + 1) { 4515 // Erroneous case - clause has some problems. 4516 Pair.first->setCounterValue(CounterVal); 4517 continue; 4518 } 4519 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink); 4520 auto I = Pair.second.rbegin(); 4521 auto IS = IterSpaces.rbegin(); 4522 auto ILM = LoopMultipliers.rbegin(); 4523 Expr *UpCounterVal = CounterVal; 4524 Expr *Multiplier = nullptr; 4525 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 4526 if (I->first) { 4527 assert(IS->CounterStep); 4528 Expr *NormalizedOffset = 4529 SemaRef 4530 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div, 4531 I->first, IS->CounterStep) 4532 .get(); 4533 if (Multiplier) { 4534 NormalizedOffset = 4535 SemaRef 4536 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul, 4537 NormalizedOffset, Multiplier) 4538 .get(); 4539 } 4540 assert(I->second == OO_Plus || I->second == OO_Minus); 4541 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub; 4542 UpCounterVal = SemaRef 4543 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK, 4544 UpCounterVal, NormalizedOffset) 4545 .get(); 4546 } 4547 Multiplier = *ILM; 4548 ++I; 4549 ++IS; 4550 ++ILM; 4551 } 4552 Pair.first->setCounterValue(UpCounterVal); 4553 } 4554 } 4555 4556 return NestedLoopCount; 4557 } 4558 4559 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 4560 auto CollapseClauses = 4561 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 4562 if (CollapseClauses.begin() != CollapseClauses.end()) 4563 return (*CollapseClauses.begin())->getNumForLoops(); 4564 return nullptr; 4565 } 4566 4567 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 4568 auto OrderedClauses = 4569 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 4570 if (OrderedClauses.begin() != OrderedClauses.end()) 4571 return (*OrderedClauses.begin())->getNumForLoops(); 4572 return nullptr; 4573 } 4574 4575 static bool checkSimdlenSafelenSpecified(Sema &S, 4576 const ArrayRef<OMPClause *> Clauses) { 4577 OMPSafelenClause *Safelen = nullptr; 4578 OMPSimdlenClause *Simdlen = nullptr; 4579 4580 for (auto *Clause : Clauses) { 4581 if (Clause->getClauseKind() == OMPC_safelen) 4582 Safelen = cast<OMPSafelenClause>(Clause); 4583 else if (Clause->getClauseKind() == OMPC_simdlen) 4584 Simdlen = cast<OMPSimdlenClause>(Clause); 4585 if (Safelen && Simdlen) 4586 break; 4587 } 4588 4589 if (Simdlen && Safelen) { 4590 llvm::APSInt SimdlenRes, SafelenRes; 4591 auto SimdlenLength = Simdlen->getSimdlen(); 4592 auto SafelenLength = Safelen->getSafelen(); 4593 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 4594 SimdlenLength->isInstantiationDependent() || 4595 SimdlenLength->containsUnexpandedParameterPack()) 4596 return false; 4597 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 4598 SafelenLength->isInstantiationDependent() || 4599 SafelenLength->containsUnexpandedParameterPack()) 4600 return false; 4601 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context); 4602 SafelenLength->EvaluateAsInt(SafelenRes, S.Context); 4603 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 4604 // If both simdlen and safelen clauses are specified, the value of the 4605 // simdlen parameter must be less than or equal to the value of the safelen 4606 // parameter. 4607 if (SimdlenRes > SafelenRes) { 4608 S.Diag(SimdlenLength->getExprLoc(), 4609 diag::err_omp_wrong_simdlen_safelen_values) 4610 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 4611 return true; 4612 } 4613 } 4614 return false; 4615 } 4616 4617 StmtResult Sema::ActOnOpenMPSimdDirective( 4618 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4619 SourceLocation EndLoc, 4620 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4621 if (!AStmt) 4622 return StmtError(); 4623 4624 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4625 OMPLoopDirective::HelperExprs B; 4626 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4627 // define the nested loops number. 4628 unsigned NestedLoopCount = CheckOpenMPLoop( 4629 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 4630 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 4631 if (NestedLoopCount == 0) 4632 return StmtError(); 4633 4634 assert((CurContext->isDependentContext() || B.builtAll()) && 4635 "omp simd loop exprs were not built"); 4636 4637 if (!CurContext->isDependentContext()) { 4638 // Finalize the clauses that need pre-built expressions for CodeGen. 4639 for (auto C : Clauses) { 4640 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4641 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4642 B.NumIterations, *this, CurScope, 4643 DSAStack)) 4644 return StmtError(); 4645 } 4646 } 4647 4648 if (checkSimdlenSafelenSpecified(*this, Clauses)) 4649 return StmtError(); 4650 4651 getCurFunction()->setHasBranchProtectedScope(); 4652 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4653 Clauses, AStmt, B); 4654 } 4655 4656 StmtResult Sema::ActOnOpenMPForDirective( 4657 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4658 SourceLocation EndLoc, 4659 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4660 if (!AStmt) 4661 return StmtError(); 4662 4663 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4664 OMPLoopDirective::HelperExprs B; 4665 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4666 // define the nested loops number. 4667 unsigned NestedLoopCount = CheckOpenMPLoop( 4668 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 4669 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 4670 if (NestedLoopCount == 0) 4671 return StmtError(); 4672 4673 assert((CurContext->isDependentContext() || B.builtAll()) && 4674 "omp for loop exprs were not built"); 4675 4676 if (!CurContext->isDependentContext()) { 4677 // Finalize the clauses that need pre-built expressions for CodeGen. 4678 for (auto C : Clauses) { 4679 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4680 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4681 B.NumIterations, *this, CurScope, 4682 DSAStack)) 4683 return StmtError(); 4684 } 4685 } 4686 4687 getCurFunction()->setHasBranchProtectedScope(); 4688 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4689 Clauses, AStmt, B, DSAStack->isCancelRegion()); 4690 } 4691 4692 StmtResult Sema::ActOnOpenMPForSimdDirective( 4693 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4694 SourceLocation EndLoc, 4695 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4696 if (!AStmt) 4697 return StmtError(); 4698 4699 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4700 OMPLoopDirective::HelperExprs B; 4701 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4702 // define the nested loops number. 4703 unsigned NestedLoopCount = 4704 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 4705 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4706 VarsWithImplicitDSA, B); 4707 if (NestedLoopCount == 0) 4708 return StmtError(); 4709 4710 assert((CurContext->isDependentContext() || B.builtAll()) && 4711 "omp for simd loop exprs were not built"); 4712 4713 if (!CurContext->isDependentContext()) { 4714 // Finalize the clauses that need pre-built expressions for CodeGen. 4715 for (auto C : Clauses) { 4716 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4717 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4718 B.NumIterations, *this, CurScope, 4719 DSAStack)) 4720 return StmtError(); 4721 } 4722 } 4723 4724 if (checkSimdlenSafelenSpecified(*this, Clauses)) 4725 return StmtError(); 4726 4727 getCurFunction()->setHasBranchProtectedScope(); 4728 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4729 Clauses, AStmt, B); 4730 } 4731 4732 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 4733 Stmt *AStmt, 4734 SourceLocation StartLoc, 4735 SourceLocation EndLoc) { 4736 if (!AStmt) 4737 return StmtError(); 4738 4739 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4740 auto BaseStmt = AStmt; 4741 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 4742 BaseStmt = CS->getCapturedStmt(); 4743 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 4744 auto S = C->children(); 4745 if (S.begin() == S.end()) 4746 return StmtError(); 4747 // All associated statements must be '#pragma omp section' except for 4748 // the first one. 4749 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 4750 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 4751 if (SectionStmt) 4752 Diag(SectionStmt->getLocStart(), 4753 diag::err_omp_sections_substmt_not_section); 4754 return StmtError(); 4755 } 4756 cast<OMPSectionDirective>(SectionStmt) 4757 ->setHasCancel(DSAStack->isCancelRegion()); 4758 } 4759 } else { 4760 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt); 4761 return StmtError(); 4762 } 4763 4764 getCurFunction()->setHasBranchProtectedScope(); 4765 4766 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 4767 DSAStack->isCancelRegion()); 4768 } 4769 4770 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 4771 SourceLocation StartLoc, 4772 SourceLocation EndLoc) { 4773 if (!AStmt) 4774 return StmtError(); 4775 4776 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4777 4778 getCurFunction()->setHasBranchProtectedScope(); 4779 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 4780 4781 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 4782 DSAStack->isCancelRegion()); 4783 } 4784 4785 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 4786 Stmt *AStmt, 4787 SourceLocation StartLoc, 4788 SourceLocation EndLoc) { 4789 if (!AStmt) 4790 return StmtError(); 4791 4792 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4793 4794 getCurFunction()->setHasBranchProtectedScope(); 4795 4796 // OpenMP [2.7.3, single Construct, Restrictions] 4797 // The copyprivate clause must not be used with the nowait clause. 4798 OMPClause *Nowait = nullptr; 4799 OMPClause *Copyprivate = nullptr; 4800 for (auto *Clause : Clauses) { 4801 if (Clause->getClauseKind() == OMPC_nowait) 4802 Nowait = Clause; 4803 else if (Clause->getClauseKind() == OMPC_copyprivate) 4804 Copyprivate = Clause; 4805 if (Copyprivate && Nowait) { 4806 Diag(Copyprivate->getLocStart(), 4807 diag::err_omp_single_copyprivate_with_nowait); 4808 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here); 4809 return StmtError(); 4810 } 4811 } 4812 4813 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 4814 } 4815 4816 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 4817 SourceLocation StartLoc, 4818 SourceLocation EndLoc) { 4819 if (!AStmt) 4820 return StmtError(); 4821 4822 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4823 4824 getCurFunction()->setHasBranchProtectedScope(); 4825 4826 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 4827 } 4828 4829 StmtResult Sema::ActOnOpenMPCriticalDirective( 4830 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 4831 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 4832 if (!AStmt) 4833 return StmtError(); 4834 4835 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4836 4837 bool ErrorFound = false; 4838 llvm::APSInt Hint; 4839 SourceLocation HintLoc; 4840 bool DependentHint = false; 4841 for (auto *C : Clauses) { 4842 if (C->getClauseKind() == OMPC_hint) { 4843 if (!DirName.getName()) { 4844 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name); 4845 ErrorFound = true; 4846 } 4847 Expr *E = cast<OMPHintClause>(C)->getHint(); 4848 if (E->isTypeDependent() || E->isValueDependent() || 4849 E->isInstantiationDependent()) 4850 DependentHint = true; 4851 else { 4852 Hint = E->EvaluateKnownConstInt(Context); 4853 HintLoc = C->getLocStart(); 4854 } 4855 } 4856 } 4857 if (ErrorFound) 4858 return StmtError(); 4859 auto Pair = DSAStack->getCriticalWithHint(DirName); 4860 if (Pair.first && DirName.getName() && !DependentHint) { 4861 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 4862 Diag(StartLoc, diag::err_omp_critical_with_hint); 4863 if (HintLoc.isValid()) { 4864 Diag(HintLoc, diag::note_omp_critical_hint_here) 4865 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 4866 } else 4867 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 4868 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 4869 Diag(C->getLocStart(), diag::note_omp_critical_hint_here) 4870 << 1 4871 << C->getHint()->EvaluateKnownConstInt(Context).toString( 4872 /*Radix=*/10, /*Signed=*/false); 4873 } else 4874 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1; 4875 } 4876 } 4877 4878 getCurFunction()->setHasBranchProtectedScope(); 4879 4880 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 4881 Clauses, AStmt); 4882 if (!Pair.first && DirName.getName() && !DependentHint) 4883 DSAStack->addCriticalWithHint(Dir, Hint); 4884 return Dir; 4885 } 4886 4887 StmtResult Sema::ActOnOpenMPParallelForDirective( 4888 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4889 SourceLocation EndLoc, 4890 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4891 if (!AStmt) 4892 return StmtError(); 4893 4894 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 4895 // 1.2.2 OpenMP Language Terminology 4896 // Structured block - An executable statement with a single entry at the 4897 // top and a single exit at the bottom. 4898 // The point of exit cannot be a branch out of the structured block. 4899 // longjmp() and throw() must not violate the entry/exit criteria. 4900 CS->getCapturedDecl()->setNothrow(); 4901 4902 OMPLoopDirective::HelperExprs B; 4903 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4904 // define the nested loops number. 4905 unsigned NestedLoopCount = 4906 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 4907 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4908 VarsWithImplicitDSA, B); 4909 if (NestedLoopCount == 0) 4910 return StmtError(); 4911 4912 assert((CurContext->isDependentContext() || B.builtAll()) && 4913 "omp parallel for loop exprs were not built"); 4914 4915 if (!CurContext->isDependentContext()) { 4916 // Finalize the clauses that need pre-built expressions for CodeGen. 4917 for (auto C : Clauses) { 4918 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4919 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4920 B.NumIterations, *this, CurScope, 4921 DSAStack)) 4922 return StmtError(); 4923 } 4924 } 4925 4926 getCurFunction()->setHasBranchProtectedScope(); 4927 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, 4928 NestedLoopCount, Clauses, AStmt, B, 4929 DSAStack->isCancelRegion()); 4930 } 4931 4932 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 4933 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4934 SourceLocation EndLoc, 4935 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4936 if (!AStmt) 4937 return StmtError(); 4938 4939 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 4940 // 1.2.2 OpenMP Language Terminology 4941 // Structured block - An executable statement with a single entry at the 4942 // top and a single exit at the bottom. 4943 // The point of exit cannot be a branch out of the structured block. 4944 // longjmp() and throw() must not violate the entry/exit criteria. 4945 CS->getCapturedDecl()->setNothrow(); 4946 4947 OMPLoopDirective::HelperExprs B; 4948 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4949 // define the nested loops number. 4950 unsigned NestedLoopCount = 4951 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 4952 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4953 VarsWithImplicitDSA, B); 4954 if (NestedLoopCount == 0) 4955 return StmtError(); 4956 4957 if (!CurContext->isDependentContext()) { 4958 // Finalize the clauses that need pre-built expressions for CodeGen. 4959 for (auto C : Clauses) { 4960 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4961 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4962 B.NumIterations, *this, CurScope, 4963 DSAStack)) 4964 return StmtError(); 4965 } 4966 } 4967 4968 if (checkSimdlenSafelenSpecified(*this, Clauses)) 4969 return StmtError(); 4970 4971 getCurFunction()->setHasBranchProtectedScope(); 4972 return OMPParallelForSimdDirective::Create( 4973 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 4974 } 4975 4976 StmtResult 4977 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 4978 Stmt *AStmt, SourceLocation StartLoc, 4979 SourceLocation EndLoc) { 4980 if (!AStmt) 4981 return StmtError(); 4982 4983 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4984 auto BaseStmt = AStmt; 4985 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 4986 BaseStmt = CS->getCapturedStmt(); 4987 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 4988 auto S = C->children(); 4989 if (S.begin() == S.end()) 4990 return StmtError(); 4991 // All associated statements must be '#pragma omp section' except for 4992 // the first one. 4993 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 4994 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 4995 if (SectionStmt) 4996 Diag(SectionStmt->getLocStart(), 4997 diag::err_omp_parallel_sections_substmt_not_section); 4998 return StmtError(); 4999 } 5000 cast<OMPSectionDirective>(SectionStmt) 5001 ->setHasCancel(DSAStack->isCancelRegion()); 5002 } 5003 } else { 5004 Diag(AStmt->getLocStart(), 5005 diag::err_omp_parallel_sections_not_compound_stmt); 5006 return StmtError(); 5007 } 5008 5009 getCurFunction()->setHasBranchProtectedScope(); 5010 5011 return OMPParallelSectionsDirective::Create( 5012 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); 5013 } 5014 5015 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 5016 Stmt *AStmt, SourceLocation StartLoc, 5017 SourceLocation EndLoc) { 5018 if (!AStmt) 5019 return StmtError(); 5020 5021 auto *CS = cast<CapturedStmt>(AStmt); 5022 // 1.2.2 OpenMP Language Terminology 5023 // Structured block - An executable statement with a single entry at the 5024 // top and a single exit at the bottom. 5025 // The point of exit cannot be a branch out of the structured block. 5026 // longjmp() and throw() must not violate the entry/exit criteria. 5027 CS->getCapturedDecl()->setNothrow(); 5028 5029 getCurFunction()->setHasBranchProtectedScope(); 5030 5031 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5032 DSAStack->isCancelRegion()); 5033 } 5034 5035 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 5036 SourceLocation EndLoc) { 5037 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 5038 } 5039 5040 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 5041 SourceLocation EndLoc) { 5042 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 5043 } 5044 5045 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 5046 SourceLocation EndLoc) { 5047 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 5048 } 5049 5050 StmtResult Sema::ActOnOpenMPTaskgroupDirective(Stmt *AStmt, 5051 SourceLocation StartLoc, 5052 SourceLocation EndLoc) { 5053 if (!AStmt) 5054 return StmtError(); 5055 5056 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5057 5058 getCurFunction()->setHasBranchProtectedScope(); 5059 5060 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, AStmt); 5061 } 5062 5063 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 5064 SourceLocation StartLoc, 5065 SourceLocation EndLoc) { 5066 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 5067 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 5068 } 5069 5070 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 5071 Stmt *AStmt, 5072 SourceLocation StartLoc, 5073 SourceLocation EndLoc) { 5074 OMPClause *DependFound = nullptr; 5075 OMPClause *DependSourceClause = nullptr; 5076 OMPClause *DependSinkClause = nullptr; 5077 bool ErrorFound = false; 5078 OMPThreadsClause *TC = nullptr; 5079 OMPSIMDClause *SC = nullptr; 5080 for (auto *C : Clauses) { 5081 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 5082 DependFound = C; 5083 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 5084 if (DependSourceClause) { 5085 Diag(C->getLocStart(), diag::err_omp_more_one_clause) 5086 << getOpenMPDirectiveName(OMPD_ordered) 5087 << getOpenMPClauseName(OMPC_depend) << 2; 5088 ErrorFound = true; 5089 } else 5090 DependSourceClause = C; 5091 if (DependSinkClause) { 5092 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 5093 << 0; 5094 ErrorFound = true; 5095 } 5096 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 5097 if (DependSourceClause) { 5098 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 5099 << 1; 5100 ErrorFound = true; 5101 } 5102 DependSinkClause = C; 5103 } 5104 } else if (C->getClauseKind() == OMPC_threads) 5105 TC = cast<OMPThreadsClause>(C); 5106 else if (C->getClauseKind() == OMPC_simd) 5107 SC = cast<OMPSIMDClause>(C); 5108 } 5109 if (!ErrorFound && !SC && 5110 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 5111 // OpenMP [2.8.1,simd Construct, Restrictions] 5112 // An ordered construct with the simd clause is the only OpenMP construct 5113 // that can appear in the simd region. 5114 Diag(StartLoc, diag::err_omp_prohibited_region_simd); 5115 ErrorFound = true; 5116 } else if (DependFound && (TC || SC)) { 5117 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd) 5118 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 5119 ErrorFound = true; 5120 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) { 5121 Diag(DependFound->getLocStart(), 5122 diag::err_omp_ordered_directive_without_param); 5123 ErrorFound = true; 5124 } else if (TC || Clauses.empty()) { 5125 if (auto *Param = DSAStack->getParentOrderedRegionParam()) { 5126 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc; 5127 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 5128 << (TC != nullptr); 5129 Diag(Param->getLocStart(), diag::note_omp_ordered_param); 5130 ErrorFound = true; 5131 } 5132 } 5133 if ((!AStmt && !DependFound) || ErrorFound) 5134 return StmtError(); 5135 5136 if (AStmt) { 5137 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5138 5139 getCurFunction()->setHasBranchProtectedScope(); 5140 } 5141 5142 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5143 } 5144 5145 namespace { 5146 /// \brief Helper class for checking expression in 'omp atomic [update]' 5147 /// construct. 5148 class OpenMPAtomicUpdateChecker { 5149 /// \brief Error results for atomic update expressions. 5150 enum ExprAnalysisErrorCode { 5151 /// \brief A statement is not an expression statement. 5152 NotAnExpression, 5153 /// \brief Expression is not builtin binary or unary operation. 5154 NotABinaryOrUnaryExpression, 5155 /// \brief Unary operation is not post-/pre- increment/decrement operation. 5156 NotAnUnaryIncDecExpression, 5157 /// \brief An expression is not of scalar type. 5158 NotAScalarType, 5159 /// \brief A binary operation is not an assignment operation. 5160 NotAnAssignmentOp, 5161 /// \brief RHS part of the binary operation is not a binary expression. 5162 NotABinaryExpression, 5163 /// \brief RHS part is not additive/multiplicative/shift/biwise binary 5164 /// expression. 5165 NotABinaryOperator, 5166 /// \brief RHS binary operation does not have reference to the updated LHS 5167 /// part. 5168 NotAnUpdateExpression, 5169 /// \brief No errors is found. 5170 NoError 5171 }; 5172 /// \brief Reference to Sema. 5173 Sema &SemaRef; 5174 /// \brief A location for note diagnostics (when error is found). 5175 SourceLocation NoteLoc; 5176 /// \brief 'x' lvalue part of the source atomic expression. 5177 Expr *X; 5178 /// \brief 'expr' rvalue part of the source atomic expression. 5179 Expr *E; 5180 /// \brief Helper expression of the form 5181 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 5182 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 5183 Expr *UpdateExpr; 5184 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is 5185 /// important for non-associative operations. 5186 bool IsXLHSInRHSPart; 5187 BinaryOperatorKind Op; 5188 SourceLocation OpLoc; 5189 /// \brief true if the source expression is a postfix unary operation, false 5190 /// if it is a prefix unary operation. 5191 bool IsPostfixUpdate; 5192 5193 public: 5194 OpenMPAtomicUpdateChecker(Sema &SemaRef) 5195 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 5196 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 5197 /// \brief Check specified statement that it is suitable for 'atomic update' 5198 /// constructs and extract 'x', 'expr' and Operation from the original 5199 /// expression. If DiagId and NoteId == 0, then only check is performed 5200 /// without error notification. 5201 /// \param DiagId Diagnostic which should be emitted if error is found. 5202 /// \param NoteId Diagnostic note for the main error message. 5203 /// \return true if statement is not an update expression, false otherwise. 5204 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 5205 /// \brief Return the 'x' lvalue part of the source atomic expression. 5206 Expr *getX() const { return X; } 5207 /// \brief Return the 'expr' rvalue part of the source atomic expression. 5208 Expr *getExpr() const { return E; } 5209 /// \brief Return the update expression used in calculation of the updated 5210 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 5211 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 5212 Expr *getUpdateExpr() const { return UpdateExpr; } 5213 /// \brief Return true if 'x' is LHS in RHS part of full update expression, 5214 /// false otherwise. 5215 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 5216 5217 /// \brief true if the source expression is a postfix unary operation, false 5218 /// if it is a prefix unary operation. 5219 bool isPostfixUpdate() const { return IsPostfixUpdate; } 5220 5221 private: 5222 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 5223 unsigned NoteId = 0); 5224 }; 5225 } // namespace 5226 5227 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 5228 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 5229 ExprAnalysisErrorCode ErrorFound = NoError; 5230 SourceLocation ErrorLoc, NoteLoc; 5231 SourceRange ErrorRange, NoteRange; 5232 // Allowed constructs are: 5233 // x = x binop expr; 5234 // x = expr binop x; 5235 if (AtomicBinOp->getOpcode() == BO_Assign) { 5236 X = AtomicBinOp->getLHS(); 5237 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 5238 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 5239 if (AtomicInnerBinOp->isMultiplicativeOp() || 5240 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 5241 AtomicInnerBinOp->isBitwiseOp()) { 5242 Op = AtomicInnerBinOp->getOpcode(); 5243 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 5244 auto *LHS = AtomicInnerBinOp->getLHS(); 5245 auto *RHS = AtomicInnerBinOp->getRHS(); 5246 llvm::FoldingSetNodeID XId, LHSId, RHSId; 5247 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 5248 /*Canonical=*/true); 5249 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 5250 /*Canonical=*/true); 5251 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 5252 /*Canonical=*/true); 5253 if (XId == LHSId) { 5254 E = RHS; 5255 IsXLHSInRHSPart = true; 5256 } else if (XId == RHSId) { 5257 E = LHS; 5258 IsXLHSInRHSPart = false; 5259 } else { 5260 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 5261 ErrorRange = AtomicInnerBinOp->getSourceRange(); 5262 NoteLoc = X->getExprLoc(); 5263 NoteRange = X->getSourceRange(); 5264 ErrorFound = NotAnUpdateExpression; 5265 } 5266 } else { 5267 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 5268 ErrorRange = AtomicInnerBinOp->getSourceRange(); 5269 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 5270 NoteRange = SourceRange(NoteLoc, NoteLoc); 5271 ErrorFound = NotABinaryOperator; 5272 } 5273 } else { 5274 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 5275 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 5276 ErrorFound = NotABinaryExpression; 5277 } 5278 } else { 5279 ErrorLoc = AtomicBinOp->getExprLoc(); 5280 ErrorRange = AtomicBinOp->getSourceRange(); 5281 NoteLoc = AtomicBinOp->getOperatorLoc(); 5282 NoteRange = SourceRange(NoteLoc, NoteLoc); 5283 ErrorFound = NotAnAssignmentOp; 5284 } 5285 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5286 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5287 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5288 return true; 5289 } else if (SemaRef.CurContext->isDependentContext()) 5290 E = X = UpdateExpr = nullptr; 5291 return ErrorFound != NoError; 5292 } 5293 5294 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 5295 unsigned NoteId) { 5296 ExprAnalysisErrorCode ErrorFound = NoError; 5297 SourceLocation ErrorLoc, NoteLoc; 5298 SourceRange ErrorRange, NoteRange; 5299 // Allowed constructs are: 5300 // x++; 5301 // x--; 5302 // ++x; 5303 // --x; 5304 // x binop= expr; 5305 // x = x binop expr; 5306 // x = expr binop x; 5307 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 5308 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 5309 if (AtomicBody->getType()->isScalarType() || 5310 AtomicBody->isInstantiationDependent()) { 5311 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 5312 AtomicBody->IgnoreParenImpCasts())) { 5313 // Check for Compound Assignment Operation 5314 Op = BinaryOperator::getOpForCompoundAssignment( 5315 AtomicCompAssignOp->getOpcode()); 5316 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 5317 E = AtomicCompAssignOp->getRHS(); 5318 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 5319 IsXLHSInRHSPart = true; 5320 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 5321 AtomicBody->IgnoreParenImpCasts())) { 5322 // Check for Binary Operation 5323 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 5324 return true; 5325 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 5326 AtomicBody->IgnoreParenImpCasts())) { 5327 // Check for Unary Operation 5328 if (AtomicUnaryOp->isIncrementDecrementOp()) { 5329 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 5330 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 5331 OpLoc = AtomicUnaryOp->getOperatorLoc(); 5332 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 5333 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 5334 IsXLHSInRHSPart = true; 5335 } else { 5336 ErrorFound = NotAnUnaryIncDecExpression; 5337 ErrorLoc = AtomicUnaryOp->getExprLoc(); 5338 ErrorRange = AtomicUnaryOp->getSourceRange(); 5339 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 5340 NoteRange = SourceRange(NoteLoc, NoteLoc); 5341 } 5342 } else if (!AtomicBody->isInstantiationDependent()) { 5343 ErrorFound = NotABinaryOrUnaryExpression; 5344 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 5345 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 5346 } 5347 } else { 5348 ErrorFound = NotAScalarType; 5349 NoteLoc = ErrorLoc = AtomicBody->getLocStart(); 5350 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5351 } 5352 } else { 5353 ErrorFound = NotAnExpression; 5354 NoteLoc = ErrorLoc = S->getLocStart(); 5355 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5356 } 5357 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5358 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5359 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5360 return true; 5361 } else if (SemaRef.CurContext->isDependentContext()) 5362 E = X = UpdateExpr = nullptr; 5363 if (ErrorFound == NoError && E && X) { 5364 // Build an update expression of form 'OpaqueValueExpr(x) binop 5365 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 5366 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 5367 auto *OVEX = new (SemaRef.getASTContext()) 5368 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 5369 auto *OVEExpr = new (SemaRef.getASTContext()) 5370 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 5371 auto Update = 5372 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 5373 IsXLHSInRHSPart ? OVEExpr : OVEX); 5374 if (Update.isInvalid()) 5375 return true; 5376 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 5377 Sema::AA_Casting); 5378 if (Update.isInvalid()) 5379 return true; 5380 UpdateExpr = Update.get(); 5381 } 5382 return ErrorFound != NoError; 5383 } 5384 5385 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 5386 Stmt *AStmt, 5387 SourceLocation StartLoc, 5388 SourceLocation EndLoc) { 5389 if (!AStmt) 5390 return StmtError(); 5391 5392 auto *CS = cast<CapturedStmt>(AStmt); 5393 // 1.2.2 OpenMP Language Terminology 5394 // Structured block - An executable statement with a single entry at the 5395 // top and a single exit at the bottom. 5396 // The point of exit cannot be a branch out of the structured block. 5397 // longjmp() and throw() must not violate the entry/exit criteria. 5398 OpenMPClauseKind AtomicKind = OMPC_unknown; 5399 SourceLocation AtomicKindLoc; 5400 for (auto *C : Clauses) { 5401 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 5402 C->getClauseKind() == OMPC_update || 5403 C->getClauseKind() == OMPC_capture) { 5404 if (AtomicKind != OMPC_unknown) { 5405 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses) 5406 << SourceRange(C->getLocStart(), C->getLocEnd()); 5407 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 5408 << getOpenMPClauseName(AtomicKind); 5409 } else { 5410 AtomicKind = C->getClauseKind(); 5411 AtomicKindLoc = C->getLocStart(); 5412 } 5413 } 5414 } 5415 5416 auto Body = CS->getCapturedStmt(); 5417 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 5418 Body = EWC->getSubExpr(); 5419 5420 Expr *X = nullptr; 5421 Expr *V = nullptr; 5422 Expr *E = nullptr; 5423 Expr *UE = nullptr; 5424 bool IsXLHSInRHSPart = false; 5425 bool IsPostfixUpdate = false; 5426 // OpenMP [2.12.6, atomic Construct] 5427 // In the next expressions: 5428 // * x and v (as applicable) are both l-value expressions with scalar type. 5429 // * During the execution of an atomic region, multiple syntactic 5430 // occurrences of x must designate the same storage location. 5431 // * Neither of v and expr (as applicable) may access the storage location 5432 // designated by x. 5433 // * Neither of x and expr (as applicable) may access the storage location 5434 // designated by v. 5435 // * expr is an expression with scalar type. 5436 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 5437 // * binop, binop=, ++, and -- are not overloaded operators. 5438 // * The expression x binop expr must be numerically equivalent to x binop 5439 // (expr). This requirement is satisfied if the operators in expr have 5440 // precedence greater than binop, or by using parentheses around expr or 5441 // subexpressions of expr. 5442 // * The expression expr binop x must be numerically equivalent to (expr) 5443 // binop x. This requirement is satisfied if the operators in expr have 5444 // precedence equal to or greater than binop, or by using parentheses around 5445 // expr or subexpressions of expr. 5446 // * For forms that allow multiple occurrences of x, the number of times 5447 // that x is evaluated is unspecified. 5448 if (AtomicKind == OMPC_read) { 5449 enum { 5450 NotAnExpression, 5451 NotAnAssignmentOp, 5452 NotAScalarType, 5453 NotAnLValue, 5454 NoError 5455 } ErrorFound = NoError; 5456 SourceLocation ErrorLoc, NoteLoc; 5457 SourceRange ErrorRange, NoteRange; 5458 // If clause is read: 5459 // v = x; 5460 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5461 auto *AtomicBinOp = 5462 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5463 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5464 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 5465 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 5466 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 5467 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 5468 if (!X->isLValue() || !V->isLValue()) { 5469 auto NotLValueExpr = X->isLValue() ? V : X; 5470 ErrorFound = NotAnLValue; 5471 ErrorLoc = AtomicBinOp->getExprLoc(); 5472 ErrorRange = AtomicBinOp->getSourceRange(); 5473 NoteLoc = NotLValueExpr->getExprLoc(); 5474 NoteRange = NotLValueExpr->getSourceRange(); 5475 } 5476 } else if (!X->isInstantiationDependent() || 5477 !V->isInstantiationDependent()) { 5478 auto NotScalarExpr = 5479 (X->isInstantiationDependent() || X->getType()->isScalarType()) 5480 ? V 5481 : X; 5482 ErrorFound = NotAScalarType; 5483 ErrorLoc = AtomicBinOp->getExprLoc(); 5484 ErrorRange = AtomicBinOp->getSourceRange(); 5485 NoteLoc = NotScalarExpr->getExprLoc(); 5486 NoteRange = NotScalarExpr->getSourceRange(); 5487 } 5488 } else if (!AtomicBody->isInstantiationDependent()) { 5489 ErrorFound = NotAnAssignmentOp; 5490 ErrorLoc = AtomicBody->getExprLoc(); 5491 ErrorRange = AtomicBody->getSourceRange(); 5492 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5493 : AtomicBody->getExprLoc(); 5494 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5495 : AtomicBody->getSourceRange(); 5496 } 5497 } else { 5498 ErrorFound = NotAnExpression; 5499 NoteLoc = ErrorLoc = Body->getLocStart(); 5500 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5501 } 5502 if (ErrorFound != NoError) { 5503 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 5504 << ErrorRange; 5505 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 5506 << NoteRange; 5507 return StmtError(); 5508 } else if (CurContext->isDependentContext()) 5509 V = X = nullptr; 5510 } else if (AtomicKind == OMPC_write) { 5511 enum { 5512 NotAnExpression, 5513 NotAnAssignmentOp, 5514 NotAScalarType, 5515 NotAnLValue, 5516 NoError 5517 } ErrorFound = NoError; 5518 SourceLocation ErrorLoc, NoteLoc; 5519 SourceRange ErrorRange, NoteRange; 5520 // If clause is write: 5521 // x = expr; 5522 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5523 auto *AtomicBinOp = 5524 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5525 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5526 X = AtomicBinOp->getLHS(); 5527 E = AtomicBinOp->getRHS(); 5528 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 5529 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 5530 if (!X->isLValue()) { 5531 ErrorFound = NotAnLValue; 5532 ErrorLoc = AtomicBinOp->getExprLoc(); 5533 ErrorRange = AtomicBinOp->getSourceRange(); 5534 NoteLoc = X->getExprLoc(); 5535 NoteRange = X->getSourceRange(); 5536 } 5537 } else if (!X->isInstantiationDependent() || 5538 !E->isInstantiationDependent()) { 5539 auto NotScalarExpr = 5540 (X->isInstantiationDependent() || X->getType()->isScalarType()) 5541 ? E 5542 : X; 5543 ErrorFound = NotAScalarType; 5544 ErrorLoc = AtomicBinOp->getExprLoc(); 5545 ErrorRange = AtomicBinOp->getSourceRange(); 5546 NoteLoc = NotScalarExpr->getExprLoc(); 5547 NoteRange = NotScalarExpr->getSourceRange(); 5548 } 5549 } else if (!AtomicBody->isInstantiationDependent()) { 5550 ErrorFound = NotAnAssignmentOp; 5551 ErrorLoc = AtomicBody->getExprLoc(); 5552 ErrorRange = AtomicBody->getSourceRange(); 5553 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5554 : AtomicBody->getExprLoc(); 5555 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5556 : AtomicBody->getSourceRange(); 5557 } 5558 } else { 5559 ErrorFound = NotAnExpression; 5560 NoteLoc = ErrorLoc = Body->getLocStart(); 5561 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5562 } 5563 if (ErrorFound != NoError) { 5564 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 5565 << ErrorRange; 5566 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 5567 << NoteRange; 5568 return StmtError(); 5569 } else if (CurContext->isDependentContext()) 5570 E = X = nullptr; 5571 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 5572 // If clause is update: 5573 // x++; 5574 // x--; 5575 // ++x; 5576 // --x; 5577 // x binop= expr; 5578 // x = x binop expr; 5579 // x = expr binop x; 5580 OpenMPAtomicUpdateChecker Checker(*this); 5581 if (Checker.checkStatement( 5582 Body, (AtomicKind == OMPC_update) 5583 ? diag::err_omp_atomic_update_not_expression_statement 5584 : diag::err_omp_atomic_not_expression_statement, 5585 diag::note_omp_atomic_update)) 5586 return StmtError(); 5587 if (!CurContext->isDependentContext()) { 5588 E = Checker.getExpr(); 5589 X = Checker.getX(); 5590 UE = Checker.getUpdateExpr(); 5591 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5592 } 5593 } else if (AtomicKind == OMPC_capture) { 5594 enum { 5595 NotAnAssignmentOp, 5596 NotACompoundStatement, 5597 NotTwoSubstatements, 5598 NotASpecificExpression, 5599 NoError 5600 } ErrorFound = NoError; 5601 SourceLocation ErrorLoc, NoteLoc; 5602 SourceRange ErrorRange, NoteRange; 5603 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5604 // If clause is a capture: 5605 // v = x++; 5606 // v = x--; 5607 // v = ++x; 5608 // v = --x; 5609 // v = x binop= expr; 5610 // v = x = x binop expr; 5611 // v = x = expr binop x; 5612 auto *AtomicBinOp = 5613 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5614 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5615 V = AtomicBinOp->getLHS(); 5616 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 5617 OpenMPAtomicUpdateChecker Checker(*this); 5618 if (Checker.checkStatement( 5619 Body, diag::err_omp_atomic_capture_not_expression_statement, 5620 diag::note_omp_atomic_update)) 5621 return StmtError(); 5622 E = Checker.getExpr(); 5623 X = Checker.getX(); 5624 UE = Checker.getUpdateExpr(); 5625 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5626 IsPostfixUpdate = Checker.isPostfixUpdate(); 5627 } else if (!AtomicBody->isInstantiationDependent()) { 5628 ErrorLoc = AtomicBody->getExprLoc(); 5629 ErrorRange = AtomicBody->getSourceRange(); 5630 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5631 : AtomicBody->getExprLoc(); 5632 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5633 : AtomicBody->getSourceRange(); 5634 ErrorFound = NotAnAssignmentOp; 5635 } 5636 if (ErrorFound != NoError) { 5637 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 5638 << ErrorRange; 5639 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 5640 return StmtError(); 5641 } else if (CurContext->isDependentContext()) { 5642 UE = V = E = X = nullptr; 5643 } 5644 } else { 5645 // If clause is a capture: 5646 // { v = x; x = expr; } 5647 // { v = x; x++; } 5648 // { v = x; x--; } 5649 // { v = x; ++x; } 5650 // { v = x; --x; } 5651 // { v = x; x binop= expr; } 5652 // { v = x; x = x binop expr; } 5653 // { v = x; x = expr binop x; } 5654 // { x++; v = x; } 5655 // { x--; v = x; } 5656 // { ++x; v = x; } 5657 // { --x; v = x; } 5658 // { x binop= expr; v = x; } 5659 // { x = x binop expr; v = x; } 5660 // { x = expr binop x; v = x; } 5661 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 5662 // Check that this is { expr1; expr2; } 5663 if (CS->size() == 2) { 5664 auto *First = CS->body_front(); 5665 auto *Second = CS->body_back(); 5666 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 5667 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 5668 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 5669 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 5670 // Need to find what subexpression is 'v' and what is 'x'. 5671 OpenMPAtomicUpdateChecker Checker(*this); 5672 bool IsUpdateExprFound = !Checker.checkStatement(Second); 5673 BinaryOperator *BinOp = nullptr; 5674 if (IsUpdateExprFound) { 5675 BinOp = dyn_cast<BinaryOperator>(First); 5676 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 5677 } 5678 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 5679 // { v = x; x++; } 5680 // { v = x; x--; } 5681 // { v = x; ++x; } 5682 // { v = x; --x; } 5683 // { v = x; x binop= expr; } 5684 // { v = x; x = x binop expr; } 5685 // { v = x; x = expr binop x; } 5686 // Check that the first expression has form v = x. 5687 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 5688 llvm::FoldingSetNodeID XId, PossibleXId; 5689 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 5690 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 5691 IsUpdateExprFound = XId == PossibleXId; 5692 if (IsUpdateExprFound) { 5693 V = BinOp->getLHS(); 5694 X = Checker.getX(); 5695 E = Checker.getExpr(); 5696 UE = Checker.getUpdateExpr(); 5697 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5698 IsPostfixUpdate = true; 5699 } 5700 } 5701 if (!IsUpdateExprFound) { 5702 IsUpdateExprFound = !Checker.checkStatement(First); 5703 BinOp = nullptr; 5704 if (IsUpdateExprFound) { 5705 BinOp = dyn_cast<BinaryOperator>(Second); 5706 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 5707 } 5708 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 5709 // { x++; v = x; } 5710 // { x--; v = x; } 5711 // { ++x; v = x; } 5712 // { --x; v = x; } 5713 // { x binop= expr; v = x; } 5714 // { x = x binop expr; v = x; } 5715 // { x = expr binop x; v = x; } 5716 // Check that the second expression has form v = x. 5717 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 5718 llvm::FoldingSetNodeID XId, PossibleXId; 5719 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 5720 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 5721 IsUpdateExprFound = XId == PossibleXId; 5722 if (IsUpdateExprFound) { 5723 V = BinOp->getLHS(); 5724 X = Checker.getX(); 5725 E = Checker.getExpr(); 5726 UE = Checker.getUpdateExpr(); 5727 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5728 IsPostfixUpdate = false; 5729 } 5730 } 5731 } 5732 if (!IsUpdateExprFound) { 5733 // { v = x; x = expr; } 5734 auto *FirstExpr = dyn_cast<Expr>(First); 5735 auto *SecondExpr = dyn_cast<Expr>(Second); 5736 if (!FirstExpr || !SecondExpr || 5737 !(FirstExpr->isInstantiationDependent() || 5738 SecondExpr->isInstantiationDependent())) { 5739 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 5740 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 5741 ErrorFound = NotAnAssignmentOp; 5742 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 5743 : First->getLocStart(); 5744 NoteRange = ErrorRange = FirstBinOp 5745 ? FirstBinOp->getSourceRange() 5746 : SourceRange(ErrorLoc, ErrorLoc); 5747 } else { 5748 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 5749 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 5750 ErrorFound = NotAnAssignmentOp; 5751 NoteLoc = ErrorLoc = SecondBinOp 5752 ? SecondBinOp->getOperatorLoc() 5753 : Second->getLocStart(); 5754 NoteRange = ErrorRange = 5755 SecondBinOp ? SecondBinOp->getSourceRange() 5756 : SourceRange(ErrorLoc, ErrorLoc); 5757 } else { 5758 auto *PossibleXRHSInFirst = 5759 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 5760 auto *PossibleXLHSInSecond = 5761 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 5762 llvm::FoldingSetNodeID X1Id, X2Id; 5763 PossibleXRHSInFirst->Profile(X1Id, Context, 5764 /*Canonical=*/true); 5765 PossibleXLHSInSecond->Profile(X2Id, Context, 5766 /*Canonical=*/true); 5767 IsUpdateExprFound = X1Id == X2Id; 5768 if (IsUpdateExprFound) { 5769 V = FirstBinOp->getLHS(); 5770 X = SecondBinOp->getLHS(); 5771 E = SecondBinOp->getRHS(); 5772 UE = nullptr; 5773 IsXLHSInRHSPart = false; 5774 IsPostfixUpdate = true; 5775 } else { 5776 ErrorFound = NotASpecificExpression; 5777 ErrorLoc = FirstBinOp->getExprLoc(); 5778 ErrorRange = FirstBinOp->getSourceRange(); 5779 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 5780 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 5781 } 5782 } 5783 } 5784 } 5785 } 5786 } else { 5787 NoteLoc = ErrorLoc = Body->getLocStart(); 5788 NoteRange = ErrorRange = 5789 SourceRange(Body->getLocStart(), Body->getLocStart()); 5790 ErrorFound = NotTwoSubstatements; 5791 } 5792 } else { 5793 NoteLoc = ErrorLoc = Body->getLocStart(); 5794 NoteRange = ErrorRange = 5795 SourceRange(Body->getLocStart(), Body->getLocStart()); 5796 ErrorFound = NotACompoundStatement; 5797 } 5798 if (ErrorFound != NoError) { 5799 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 5800 << ErrorRange; 5801 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 5802 return StmtError(); 5803 } else if (CurContext->isDependentContext()) { 5804 UE = V = E = X = nullptr; 5805 } 5806 } 5807 } 5808 5809 getCurFunction()->setHasBranchProtectedScope(); 5810 5811 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5812 X, V, E, UE, IsXLHSInRHSPart, 5813 IsPostfixUpdate); 5814 } 5815 5816 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 5817 Stmt *AStmt, 5818 SourceLocation StartLoc, 5819 SourceLocation EndLoc) { 5820 if (!AStmt) 5821 return StmtError(); 5822 5823 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5824 // 1.2.2 OpenMP Language Terminology 5825 // Structured block - An executable statement with a single entry at the 5826 // top and a single exit at the bottom. 5827 // The point of exit cannot be a branch out of the structured block. 5828 // longjmp() and throw() must not violate the entry/exit criteria. 5829 CS->getCapturedDecl()->setNothrow(); 5830 5831 // OpenMP [2.16, Nesting of Regions] 5832 // If specified, a teams construct must be contained within a target 5833 // construct. That target construct must contain no statements or directives 5834 // outside of the teams construct. 5835 if (DSAStack->hasInnerTeamsRegion()) { 5836 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true); 5837 bool OMPTeamsFound = true; 5838 if (auto *CS = dyn_cast<CompoundStmt>(S)) { 5839 auto I = CS->body_begin(); 5840 while (I != CS->body_end()) { 5841 auto *OED = dyn_cast<OMPExecutableDirective>(*I); 5842 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) { 5843 OMPTeamsFound = false; 5844 break; 5845 } 5846 ++I; 5847 } 5848 assert(I != CS->body_end() && "Not found statement"); 5849 S = *I; 5850 } else { 5851 auto *OED = dyn_cast<OMPExecutableDirective>(S); 5852 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 5853 } 5854 if (!OMPTeamsFound) { 5855 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 5856 Diag(DSAStack->getInnerTeamsRegionLoc(), 5857 diag::note_omp_nested_teams_construct_here); 5858 Diag(S->getLocStart(), diag::note_omp_nested_statement_here) 5859 << isa<OMPExecutableDirective>(S); 5860 return StmtError(); 5861 } 5862 } 5863 5864 getCurFunction()->setHasBranchProtectedScope(); 5865 5866 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5867 } 5868 5869 StmtResult 5870 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 5871 Stmt *AStmt, SourceLocation StartLoc, 5872 SourceLocation EndLoc) { 5873 if (!AStmt) 5874 return StmtError(); 5875 5876 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5877 // 1.2.2 OpenMP Language Terminology 5878 // Structured block - An executable statement with a single entry at the 5879 // top and a single exit at the bottom. 5880 // The point of exit cannot be a branch out of the structured block. 5881 // longjmp() and throw() must not violate the entry/exit criteria. 5882 CS->getCapturedDecl()->setNothrow(); 5883 5884 getCurFunction()->setHasBranchProtectedScope(); 5885 5886 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 5887 AStmt); 5888 } 5889 5890 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 5891 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5892 SourceLocation EndLoc, 5893 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5894 if (!AStmt) 5895 return StmtError(); 5896 5897 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5898 // 1.2.2 OpenMP Language Terminology 5899 // Structured block - An executable statement with a single entry at the 5900 // top and a single exit at the bottom. 5901 // The point of exit cannot be a branch out of the structured block. 5902 // longjmp() and throw() must not violate the entry/exit criteria. 5903 CS->getCapturedDecl()->setNothrow(); 5904 5905 OMPLoopDirective::HelperExprs B; 5906 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5907 // define the nested loops number. 5908 unsigned NestedLoopCount = 5909 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 5910 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5911 VarsWithImplicitDSA, B); 5912 if (NestedLoopCount == 0) 5913 return StmtError(); 5914 5915 assert((CurContext->isDependentContext() || B.builtAll()) && 5916 "omp target parallel for loop exprs were not built"); 5917 5918 if (!CurContext->isDependentContext()) { 5919 // Finalize the clauses that need pre-built expressions for CodeGen. 5920 for (auto C : Clauses) { 5921 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5922 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5923 B.NumIterations, *this, CurScope, 5924 DSAStack)) 5925 return StmtError(); 5926 } 5927 } 5928 5929 getCurFunction()->setHasBranchProtectedScope(); 5930 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc, 5931 NestedLoopCount, Clauses, AStmt, 5932 B, DSAStack->isCancelRegion()); 5933 } 5934 5935 /// \brief Check for existence of a map clause in the list of clauses. 5936 static bool HasMapClause(ArrayRef<OMPClause *> Clauses) { 5937 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end(); 5938 I != E; ++I) { 5939 if (*I != nullptr && (*I)->getClauseKind() == OMPC_map) { 5940 return true; 5941 } 5942 } 5943 5944 return false; 5945 } 5946 5947 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 5948 Stmt *AStmt, 5949 SourceLocation StartLoc, 5950 SourceLocation EndLoc) { 5951 if (!AStmt) 5952 return StmtError(); 5953 5954 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5955 5956 // OpenMP [2.10.1, Restrictions, p. 97] 5957 // At least one map clause must appear on the directive. 5958 if (!HasMapClause(Clauses)) { 5959 Diag(StartLoc, diag::err_omp_no_map_for_directive) 5960 << getOpenMPDirectiveName(OMPD_target_data); 5961 return StmtError(); 5962 } 5963 5964 getCurFunction()->setHasBranchProtectedScope(); 5965 5966 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 5967 AStmt); 5968 } 5969 5970 StmtResult 5971 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 5972 SourceLocation StartLoc, 5973 SourceLocation EndLoc) { 5974 // OpenMP [2.10.2, Restrictions, p. 99] 5975 // At least one map clause must appear on the directive. 5976 if (!HasMapClause(Clauses)) { 5977 Diag(StartLoc, diag::err_omp_no_map_for_directive) 5978 << getOpenMPDirectiveName(OMPD_target_enter_data); 5979 return StmtError(); 5980 } 5981 5982 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, 5983 Clauses); 5984 } 5985 5986 StmtResult 5987 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 5988 SourceLocation StartLoc, 5989 SourceLocation EndLoc) { 5990 // OpenMP [2.10.3, Restrictions, p. 102] 5991 // At least one map clause must appear on the directive. 5992 if (!HasMapClause(Clauses)) { 5993 Diag(StartLoc, diag::err_omp_no_map_for_directive) 5994 << getOpenMPDirectiveName(OMPD_target_exit_data); 5995 return StmtError(); 5996 } 5997 5998 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses); 5999 } 6000 6001 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 6002 SourceLocation StartLoc, 6003 SourceLocation EndLoc) { 6004 bool seenMotionClause = false; 6005 for (auto *C : Clauses) { 6006 if (C->getClauseKind() == OMPC_to || C->getClauseKind() == OMPC_from) 6007 seenMotionClause = true; 6008 } 6009 if (!seenMotionClause) { 6010 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 6011 return StmtError(); 6012 } 6013 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses); 6014 } 6015 6016 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 6017 Stmt *AStmt, SourceLocation StartLoc, 6018 SourceLocation EndLoc) { 6019 if (!AStmt) 6020 return StmtError(); 6021 6022 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6023 // 1.2.2 OpenMP Language Terminology 6024 // Structured block - An executable statement with a single entry at the 6025 // top and a single exit at the bottom. 6026 // The point of exit cannot be a branch out of the structured block. 6027 // longjmp() and throw() must not violate the entry/exit criteria. 6028 CS->getCapturedDecl()->setNothrow(); 6029 6030 getCurFunction()->setHasBranchProtectedScope(); 6031 6032 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6033 } 6034 6035 StmtResult 6036 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 6037 SourceLocation EndLoc, 6038 OpenMPDirectiveKind CancelRegion) { 6039 if (DSAStack->isParentNowaitRegion()) { 6040 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 6041 return StmtError(); 6042 } 6043 if (DSAStack->isParentOrderedRegion()) { 6044 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 6045 return StmtError(); 6046 } 6047 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 6048 CancelRegion); 6049 } 6050 6051 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 6052 SourceLocation StartLoc, 6053 SourceLocation EndLoc, 6054 OpenMPDirectiveKind CancelRegion) { 6055 if (DSAStack->isParentNowaitRegion()) { 6056 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 6057 return StmtError(); 6058 } 6059 if (DSAStack->isParentOrderedRegion()) { 6060 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 6061 return StmtError(); 6062 } 6063 DSAStack->setParentCancelRegion(/*Cancel=*/true); 6064 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 6065 CancelRegion); 6066 } 6067 6068 static bool checkGrainsizeNumTasksClauses(Sema &S, 6069 ArrayRef<OMPClause *> Clauses) { 6070 OMPClause *PrevClause = nullptr; 6071 bool ErrorFound = false; 6072 for (auto *C : Clauses) { 6073 if (C->getClauseKind() == OMPC_grainsize || 6074 C->getClauseKind() == OMPC_num_tasks) { 6075 if (!PrevClause) 6076 PrevClause = C; 6077 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 6078 S.Diag(C->getLocStart(), 6079 diag::err_omp_grainsize_num_tasks_mutually_exclusive) 6080 << getOpenMPClauseName(C->getClauseKind()) 6081 << getOpenMPClauseName(PrevClause->getClauseKind()); 6082 S.Diag(PrevClause->getLocStart(), 6083 diag::note_omp_previous_grainsize_num_tasks) 6084 << getOpenMPClauseName(PrevClause->getClauseKind()); 6085 ErrorFound = true; 6086 } 6087 } 6088 } 6089 return ErrorFound; 6090 } 6091 6092 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 6093 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6094 SourceLocation EndLoc, 6095 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6096 if (!AStmt) 6097 return StmtError(); 6098 6099 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6100 OMPLoopDirective::HelperExprs B; 6101 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6102 // define the nested loops number. 6103 unsigned NestedLoopCount = 6104 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 6105 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 6106 VarsWithImplicitDSA, B); 6107 if (NestedLoopCount == 0) 6108 return StmtError(); 6109 6110 assert((CurContext->isDependentContext() || B.builtAll()) && 6111 "omp for loop exprs were not built"); 6112 6113 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6114 // The grainsize clause and num_tasks clause are mutually exclusive and may 6115 // not appear on the same taskloop directive. 6116 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 6117 return StmtError(); 6118 6119 getCurFunction()->setHasBranchProtectedScope(); 6120 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 6121 NestedLoopCount, Clauses, AStmt, B); 6122 } 6123 6124 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 6125 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6126 SourceLocation EndLoc, 6127 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6128 if (!AStmt) 6129 return StmtError(); 6130 6131 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6132 OMPLoopDirective::HelperExprs B; 6133 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6134 // define the nested loops number. 6135 unsigned NestedLoopCount = 6136 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 6137 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 6138 VarsWithImplicitDSA, B); 6139 if (NestedLoopCount == 0) 6140 return StmtError(); 6141 6142 assert((CurContext->isDependentContext() || B.builtAll()) && 6143 "omp for loop exprs were not built"); 6144 6145 if (!CurContext->isDependentContext()) { 6146 // Finalize the clauses that need pre-built expressions for CodeGen. 6147 for (auto C : Clauses) { 6148 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6149 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6150 B.NumIterations, *this, CurScope, 6151 DSAStack)) 6152 return StmtError(); 6153 } 6154 } 6155 6156 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6157 // The grainsize clause and num_tasks clause are mutually exclusive and may 6158 // not appear on the same taskloop directive. 6159 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 6160 return StmtError(); 6161 6162 getCurFunction()->setHasBranchProtectedScope(); 6163 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 6164 NestedLoopCount, Clauses, AStmt, B); 6165 } 6166 6167 StmtResult Sema::ActOnOpenMPDistributeDirective( 6168 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6169 SourceLocation EndLoc, 6170 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6171 if (!AStmt) 6172 return StmtError(); 6173 6174 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6175 OMPLoopDirective::HelperExprs B; 6176 // In presence of clause 'collapse' with number of loops, it will 6177 // define the nested loops number. 6178 unsigned NestedLoopCount = 6179 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 6180 nullptr /*ordered not a clause on distribute*/, AStmt, 6181 *this, *DSAStack, VarsWithImplicitDSA, B); 6182 if (NestedLoopCount == 0) 6183 return StmtError(); 6184 6185 assert((CurContext->isDependentContext() || B.builtAll()) && 6186 "omp for loop exprs were not built"); 6187 6188 getCurFunction()->setHasBranchProtectedScope(); 6189 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 6190 NestedLoopCount, Clauses, AStmt, B); 6191 } 6192 6193 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 6194 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6195 SourceLocation EndLoc, 6196 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6197 if (!AStmt) 6198 return StmtError(); 6199 6200 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6201 // 1.2.2 OpenMP Language Terminology 6202 // Structured block - An executable statement with a single entry at the 6203 // top and a single exit at the bottom. 6204 // The point of exit cannot be a branch out of the structured block. 6205 // longjmp() and throw() must not violate the entry/exit criteria. 6206 CS->getCapturedDecl()->setNothrow(); 6207 6208 OMPLoopDirective::HelperExprs B; 6209 // In presence of clause 'collapse' with number of loops, it will 6210 // define the nested loops number. 6211 unsigned NestedLoopCount = CheckOpenMPLoop( 6212 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 6213 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6214 VarsWithImplicitDSA, B); 6215 if (NestedLoopCount == 0) 6216 return StmtError(); 6217 6218 assert((CurContext->isDependentContext() || B.builtAll()) && 6219 "omp for loop exprs were not built"); 6220 6221 getCurFunction()->setHasBranchProtectedScope(); 6222 return OMPDistributeParallelForDirective::Create( 6223 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6224 } 6225 6226 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 6227 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6228 SourceLocation EndLoc, 6229 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6230 if (!AStmt) 6231 return StmtError(); 6232 6233 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6234 // 1.2.2 OpenMP Language Terminology 6235 // Structured block - An executable statement with a single entry at the 6236 // top and a single exit at the bottom. 6237 // The point of exit cannot be a branch out of the structured block. 6238 // longjmp() and throw() must not violate the entry/exit criteria. 6239 CS->getCapturedDecl()->setNothrow(); 6240 6241 OMPLoopDirective::HelperExprs B; 6242 // In presence of clause 'collapse' with number of loops, it will 6243 // define the nested loops number. 6244 unsigned NestedLoopCount = CheckOpenMPLoop( 6245 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 6246 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6247 VarsWithImplicitDSA, B); 6248 if (NestedLoopCount == 0) 6249 return StmtError(); 6250 6251 assert((CurContext->isDependentContext() || B.builtAll()) && 6252 "omp for loop exprs were not built"); 6253 6254 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6255 return StmtError(); 6256 6257 getCurFunction()->setHasBranchProtectedScope(); 6258 return OMPDistributeParallelForSimdDirective::Create( 6259 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6260 } 6261 6262 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 6263 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6264 SourceLocation EndLoc, 6265 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6266 if (!AStmt) 6267 return StmtError(); 6268 6269 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6270 // 1.2.2 OpenMP Language Terminology 6271 // Structured block - An executable statement with a single entry at the 6272 // top and a single exit at the bottom. 6273 // The point of exit cannot be a branch out of the structured block. 6274 // longjmp() and throw() must not violate the entry/exit criteria. 6275 CS->getCapturedDecl()->setNothrow(); 6276 6277 OMPLoopDirective::HelperExprs B; 6278 // In presence of clause 'collapse' with number of loops, it will 6279 // define the nested loops number. 6280 unsigned NestedLoopCount = 6281 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 6282 nullptr /*ordered not a clause on distribute*/, AStmt, 6283 *this, *DSAStack, VarsWithImplicitDSA, B); 6284 if (NestedLoopCount == 0) 6285 return StmtError(); 6286 6287 assert((CurContext->isDependentContext() || B.builtAll()) && 6288 "omp for loop exprs were not built"); 6289 6290 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6291 return StmtError(); 6292 6293 getCurFunction()->setHasBranchProtectedScope(); 6294 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 6295 NestedLoopCount, Clauses, AStmt, B); 6296 } 6297 6298 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 6299 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6300 SourceLocation EndLoc, 6301 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6302 if (!AStmt) 6303 return StmtError(); 6304 6305 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6306 // 1.2.2 OpenMP Language Terminology 6307 // Structured block - An executable statement with a single entry at the 6308 // top and a single exit at the bottom. 6309 // The point of exit cannot be a branch out of the structured block. 6310 // longjmp() and throw() must not violate the entry/exit criteria. 6311 CS->getCapturedDecl()->setNothrow(); 6312 6313 OMPLoopDirective::HelperExprs B; 6314 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6315 // define the nested loops number. 6316 unsigned NestedLoopCount = CheckOpenMPLoop( 6317 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 6318 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6319 VarsWithImplicitDSA, B); 6320 if (NestedLoopCount == 0) 6321 return StmtError(); 6322 6323 assert((CurContext->isDependentContext() || B.builtAll()) && 6324 "omp target parallel for simd loop exprs were not built"); 6325 6326 if (!CurContext->isDependentContext()) { 6327 // Finalize the clauses that need pre-built expressions for CodeGen. 6328 for (auto C : Clauses) { 6329 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6330 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6331 B.NumIterations, *this, CurScope, 6332 DSAStack)) 6333 return StmtError(); 6334 } 6335 } 6336 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6337 return StmtError(); 6338 6339 getCurFunction()->setHasBranchProtectedScope(); 6340 return OMPTargetParallelForSimdDirective::Create( 6341 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6342 } 6343 6344 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 6345 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6346 SourceLocation EndLoc, 6347 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6348 if (!AStmt) 6349 return StmtError(); 6350 6351 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6352 // 1.2.2 OpenMP Language Terminology 6353 // Structured block - An executable statement with a single entry at the 6354 // top and a single exit at the bottom. 6355 // The point of exit cannot be a branch out of the structured block. 6356 // longjmp() and throw() must not violate the entry/exit criteria. 6357 CS->getCapturedDecl()->setNothrow(); 6358 6359 OMPLoopDirective::HelperExprs B; 6360 // In presence of clause 'collapse' with number of loops, it will define the 6361 // nested loops number. 6362 unsigned NestedLoopCount = 6363 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 6364 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6365 VarsWithImplicitDSA, B); 6366 if (NestedLoopCount == 0) 6367 return StmtError(); 6368 6369 assert((CurContext->isDependentContext() || B.builtAll()) && 6370 "omp target simd loop exprs were not built"); 6371 6372 if (!CurContext->isDependentContext()) { 6373 // Finalize the clauses that need pre-built expressions for CodeGen. 6374 for (auto C : Clauses) { 6375 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6376 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6377 B.NumIterations, *this, CurScope, 6378 DSAStack)) 6379 return StmtError(); 6380 } 6381 } 6382 6383 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6384 return StmtError(); 6385 6386 getCurFunction()->setHasBranchProtectedScope(); 6387 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 6388 NestedLoopCount, Clauses, AStmt, B); 6389 } 6390 6391 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 6392 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6393 SourceLocation EndLoc, 6394 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6395 if (!AStmt) 6396 return StmtError(); 6397 6398 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6399 // 1.2.2 OpenMP Language Terminology 6400 // Structured block - An executable statement with a single entry at the 6401 // top and a single exit at the bottom. 6402 // The point of exit cannot be a branch out of the structured block. 6403 // longjmp() and throw() must not violate the entry/exit criteria. 6404 CS->getCapturedDecl()->setNothrow(); 6405 6406 OMPLoopDirective::HelperExprs B; 6407 // In presence of clause 'collapse' with number of loops, it will 6408 // define the nested loops number. 6409 unsigned NestedLoopCount = 6410 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 6411 nullptr /*ordered not a clause on distribute*/, AStmt, 6412 *this, *DSAStack, VarsWithImplicitDSA, B); 6413 if (NestedLoopCount == 0) 6414 return StmtError(); 6415 6416 assert((CurContext->isDependentContext() || B.builtAll()) && 6417 "omp teams distribute loop exprs were not built"); 6418 6419 getCurFunction()->setHasBranchProtectedScope(); 6420 return OMPTeamsDistributeDirective::Create( 6421 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6422 } 6423 6424 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 6425 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6426 SourceLocation EndLoc, 6427 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6428 if (!AStmt) 6429 return StmtError(); 6430 6431 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6432 // 1.2.2 OpenMP Language Terminology 6433 // Structured block - An executable statement with a single entry at the 6434 // top and a single exit at the bottom. 6435 // The point of exit cannot be a branch out of the structured block. 6436 // longjmp() and throw() must not violate the entry/exit criteria. 6437 CS->getCapturedDecl()->setNothrow(); 6438 6439 OMPLoopDirective::HelperExprs B; 6440 // In presence of clause 'collapse' with number of loops, it will 6441 // define the nested loops number. 6442 unsigned NestedLoopCount = CheckOpenMPLoop( 6443 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 6444 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6445 VarsWithImplicitDSA, B); 6446 6447 if (NestedLoopCount == 0) 6448 return StmtError(); 6449 6450 assert((CurContext->isDependentContext() || B.builtAll()) && 6451 "omp teams distribute simd loop exprs were not built"); 6452 6453 if (!CurContext->isDependentContext()) { 6454 // Finalize the clauses that need pre-built expressions for CodeGen. 6455 for (auto C : Clauses) { 6456 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6457 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6458 B.NumIterations, *this, CurScope, 6459 DSAStack)) 6460 return StmtError(); 6461 } 6462 } 6463 6464 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6465 return StmtError(); 6466 6467 getCurFunction()->setHasBranchProtectedScope(); 6468 return OMPTeamsDistributeSimdDirective::Create( 6469 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6470 } 6471 6472 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 6473 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6474 SourceLocation EndLoc, 6475 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6476 if (!AStmt) 6477 return StmtError(); 6478 6479 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6480 // 1.2.2 OpenMP Language Terminology 6481 // Structured block - An executable statement with a single entry at the 6482 // top and a single exit at the bottom. 6483 // The point of exit cannot be a branch out of the structured block. 6484 // longjmp() and throw() must not violate the entry/exit criteria. 6485 CS->getCapturedDecl()->setNothrow(); 6486 6487 OMPLoopDirective::HelperExprs B; 6488 // In presence of clause 'collapse' with number of loops, it will 6489 // define the nested loops number. 6490 auto NestedLoopCount = CheckOpenMPLoop( 6491 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 6492 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6493 VarsWithImplicitDSA, B); 6494 6495 if (NestedLoopCount == 0) 6496 return StmtError(); 6497 6498 assert((CurContext->isDependentContext() || B.builtAll()) && 6499 "omp for loop exprs were not built"); 6500 6501 if (!CurContext->isDependentContext()) { 6502 // Finalize the clauses that need pre-built expressions for CodeGen. 6503 for (auto C : Clauses) { 6504 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6505 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6506 B.NumIterations, *this, CurScope, 6507 DSAStack)) 6508 return StmtError(); 6509 } 6510 } 6511 6512 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6513 return StmtError(); 6514 6515 getCurFunction()->setHasBranchProtectedScope(); 6516 return OMPTeamsDistributeParallelForSimdDirective::Create( 6517 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6518 } 6519 6520 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 6521 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6522 SourceLocation EndLoc, 6523 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6524 if (!AStmt) 6525 return StmtError(); 6526 6527 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6528 // 1.2.2 OpenMP Language Terminology 6529 // Structured block - An executable statement with a single entry at the 6530 // top and a single exit at the bottom. 6531 // The point of exit cannot be a branch out of the structured block. 6532 // longjmp() and throw() must not violate the entry/exit criteria. 6533 CS->getCapturedDecl()->setNothrow(); 6534 6535 OMPLoopDirective::HelperExprs B; 6536 // In presence of clause 'collapse' with number of loops, it will 6537 // define the nested loops number. 6538 unsigned NestedLoopCount = CheckOpenMPLoop( 6539 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 6540 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6541 VarsWithImplicitDSA, B); 6542 6543 if (NestedLoopCount == 0) 6544 return StmtError(); 6545 6546 assert((CurContext->isDependentContext() || B.builtAll()) && 6547 "omp for loop exprs were not built"); 6548 6549 if (!CurContext->isDependentContext()) { 6550 // Finalize the clauses that need pre-built expressions for CodeGen. 6551 for (auto C : Clauses) { 6552 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6553 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6554 B.NumIterations, *this, CurScope, 6555 DSAStack)) 6556 return StmtError(); 6557 } 6558 } 6559 6560 getCurFunction()->setHasBranchProtectedScope(); 6561 return OMPTeamsDistributeParallelForDirective::Create( 6562 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6563 } 6564 6565 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 6566 Stmt *AStmt, 6567 SourceLocation StartLoc, 6568 SourceLocation EndLoc) { 6569 if (!AStmt) 6570 return StmtError(); 6571 6572 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6573 // 1.2.2 OpenMP Language Terminology 6574 // Structured block - An executable statement with a single entry at the 6575 // top and a single exit at the bottom. 6576 // The point of exit cannot be a branch out of the structured block. 6577 // longjmp() and throw() must not violate the entry/exit criteria. 6578 CS->getCapturedDecl()->setNothrow(); 6579 6580 getCurFunction()->setHasBranchProtectedScope(); 6581 6582 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 6583 AStmt); 6584 } 6585 6586 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 6587 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6588 SourceLocation EndLoc, 6589 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6590 if (!AStmt) 6591 return StmtError(); 6592 6593 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6594 // 1.2.2 OpenMP Language Terminology 6595 // Structured block - An executable statement with a single entry at the 6596 // top and a single exit at the bottom. 6597 // The point of exit cannot be a branch out of the structured block. 6598 // longjmp() and throw() must not violate the entry/exit criteria. 6599 CS->getCapturedDecl()->setNothrow(); 6600 6601 OMPLoopDirective::HelperExprs B; 6602 // In presence of clause 'collapse' with number of loops, it will 6603 // define the nested loops number. 6604 auto NestedLoopCount = CheckOpenMPLoop( 6605 OMPD_target_teams_distribute, 6606 getCollapseNumberExpr(Clauses), 6607 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6608 VarsWithImplicitDSA, B); 6609 if (NestedLoopCount == 0) 6610 return StmtError(); 6611 6612 assert((CurContext->isDependentContext() || B.builtAll()) && 6613 "omp target teams distribute loop exprs were not built"); 6614 6615 getCurFunction()->setHasBranchProtectedScope(); 6616 return OMPTargetTeamsDistributeDirective::Create( 6617 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6618 } 6619 6620 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 6621 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6622 SourceLocation EndLoc, 6623 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6624 if (!AStmt) 6625 return StmtError(); 6626 6627 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6628 // 1.2.2 OpenMP Language Terminology 6629 // Structured block - An executable statement with a single entry at the 6630 // top and a single exit at the bottom. 6631 // The point of exit cannot be a branch out of the structured block. 6632 // longjmp() and throw() must not violate the entry/exit criteria. 6633 CS->getCapturedDecl()->setNothrow(); 6634 6635 OMPLoopDirective::HelperExprs B; 6636 // In presence of clause 'collapse' with number of loops, it will 6637 // define the nested loops number. 6638 auto NestedLoopCount = CheckOpenMPLoop( 6639 OMPD_target_teams_distribute_parallel_for, 6640 getCollapseNumberExpr(Clauses), 6641 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6642 VarsWithImplicitDSA, B); 6643 if (NestedLoopCount == 0) 6644 return StmtError(); 6645 6646 assert((CurContext->isDependentContext() || B.builtAll()) && 6647 "omp target teams distribute parallel for loop exprs were not built"); 6648 6649 if (!CurContext->isDependentContext()) { 6650 // Finalize the clauses that need pre-built expressions for CodeGen. 6651 for (auto C : Clauses) { 6652 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6653 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6654 B.NumIterations, *this, CurScope, 6655 DSAStack)) 6656 return StmtError(); 6657 } 6658 } 6659 6660 getCurFunction()->setHasBranchProtectedScope(); 6661 return OMPTargetTeamsDistributeParallelForDirective::Create( 6662 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6663 } 6664 6665 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 6666 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6667 SourceLocation EndLoc, 6668 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6669 if (!AStmt) 6670 return StmtError(); 6671 6672 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6673 // 1.2.2 OpenMP Language Terminology 6674 // Structured block - An executable statement with a single entry at the 6675 // top and a single exit at the bottom. 6676 // The point of exit cannot be a branch out of the structured block. 6677 // longjmp() and throw() must not violate the entry/exit criteria. 6678 CS->getCapturedDecl()->setNothrow(); 6679 6680 OMPLoopDirective::HelperExprs B; 6681 // In presence of clause 'collapse' with number of loops, it will 6682 // define the nested loops number. 6683 auto NestedLoopCount = CheckOpenMPLoop( 6684 OMPD_target_teams_distribute_parallel_for_simd, 6685 getCollapseNumberExpr(Clauses), 6686 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6687 VarsWithImplicitDSA, B); 6688 if (NestedLoopCount == 0) 6689 return StmtError(); 6690 6691 assert((CurContext->isDependentContext() || B.builtAll()) && 6692 "omp target teams distribute parallel for simd loop exprs were not " 6693 "built"); 6694 6695 if (!CurContext->isDependentContext()) { 6696 // Finalize the clauses that need pre-built expressions for CodeGen. 6697 for (auto C : Clauses) { 6698 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6699 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6700 B.NumIterations, *this, CurScope, 6701 DSAStack)) 6702 return StmtError(); 6703 } 6704 } 6705 6706 getCurFunction()->setHasBranchProtectedScope(); 6707 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 6708 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6709 } 6710 6711 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 6712 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6713 SourceLocation EndLoc, 6714 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6715 if (!AStmt) 6716 return StmtError(); 6717 6718 auto *CS = cast<CapturedStmt>(AStmt); 6719 // 1.2.2 OpenMP Language Terminology 6720 // Structured block - An executable statement with a single entry at the 6721 // top and a single exit at the bottom. 6722 // The point of exit cannot be a branch out of the structured block. 6723 // longjmp() and throw() must not violate the entry/exit criteria. 6724 CS->getCapturedDecl()->setNothrow(); 6725 6726 OMPLoopDirective::HelperExprs B; 6727 // In presence of clause 'collapse' with number of loops, it will 6728 // define the nested loops number. 6729 auto NestedLoopCount = CheckOpenMPLoop( 6730 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 6731 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6732 VarsWithImplicitDSA, B); 6733 if (NestedLoopCount == 0) 6734 return StmtError(); 6735 6736 assert((CurContext->isDependentContext() || B.builtAll()) && 6737 "omp target teams distribute simd loop exprs were not built"); 6738 6739 getCurFunction()->setHasBranchProtectedScope(); 6740 return OMPTargetTeamsDistributeSimdDirective::Create( 6741 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6742 } 6743 6744 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 6745 SourceLocation StartLoc, 6746 SourceLocation LParenLoc, 6747 SourceLocation EndLoc) { 6748 OMPClause *Res = nullptr; 6749 switch (Kind) { 6750 case OMPC_final: 6751 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 6752 break; 6753 case OMPC_num_threads: 6754 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 6755 break; 6756 case OMPC_safelen: 6757 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 6758 break; 6759 case OMPC_simdlen: 6760 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 6761 break; 6762 case OMPC_collapse: 6763 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 6764 break; 6765 case OMPC_ordered: 6766 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 6767 break; 6768 case OMPC_device: 6769 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc); 6770 break; 6771 case OMPC_num_teams: 6772 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 6773 break; 6774 case OMPC_thread_limit: 6775 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 6776 break; 6777 case OMPC_priority: 6778 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 6779 break; 6780 case OMPC_grainsize: 6781 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 6782 break; 6783 case OMPC_num_tasks: 6784 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 6785 break; 6786 case OMPC_hint: 6787 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 6788 break; 6789 case OMPC_if: 6790 case OMPC_default: 6791 case OMPC_proc_bind: 6792 case OMPC_schedule: 6793 case OMPC_private: 6794 case OMPC_firstprivate: 6795 case OMPC_lastprivate: 6796 case OMPC_shared: 6797 case OMPC_reduction: 6798 case OMPC_linear: 6799 case OMPC_aligned: 6800 case OMPC_copyin: 6801 case OMPC_copyprivate: 6802 case OMPC_nowait: 6803 case OMPC_untied: 6804 case OMPC_mergeable: 6805 case OMPC_threadprivate: 6806 case OMPC_flush: 6807 case OMPC_read: 6808 case OMPC_write: 6809 case OMPC_update: 6810 case OMPC_capture: 6811 case OMPC_seq_cst: 6812 case OMPC_depend: 6813 case OMPC_threads: 6814 case OMPC_simd: 6815 case OMPC_map: 6816 case OMPC_nogroup: 6817 case OMPC_dist_schedule: 6818 case OMPC_defaultmap: 6819 case OMPC_unknown: 6820 case OMPC_uniform: 6821 case OMPC_to: 6822 case OMPC_from: 6823 case OMPC_use_device_ptr: 6824 case OMPC_is_device_ptr: 6825 llvm_unreachable("Clause is not allowed."); 6826 } 6827 return Res; 6828 } 6829 6830 // An OpenMP directive such as 'target parallel' has two captured regions: 6831 // for the 'target' and 'parallel' respectively. This function returns 6832 // the region in which to capture expressions associated with a clause. 6833 // A return value of OMPD_unknown signifies that the expression should not 6834 // be captured. 6835 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 6836 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 6837 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 6838 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 6839 6840 switch (CKind) { 6841 case OMPC_if: 6842 switch (DKind) { 6843 case OMPD_target_parallel: 6844 // If this clause applies to the nested 'parallel' region, capture within 6845 // the 'target' region, otherwise do not capture. 6846 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 6847 CaptureRegion = OMPD_target; 6848 break; 6849 case OMPD_cancel: 6850 case OMPD_parallel: 6851 case OMPD_parallel_sections: 6852 case OMPD_parallel_for: 6853 case OMPD_parallel_for_simd: 6854 case OMPD_target: 6855 case OMPD_target_simd: 6856 case OMPD_target_parallel_for: 6857 case OMPD_target_parallel_for_simd: 6858 case OMPD_target_teams: 6859 case OMPD_target_teams_distribute: 6860 case OMPD_target_teams_distribute_simd: 6861 case OMPD_target_teams_distribute_parallel_for: 6862 case OMPD_target_teams_distribute_parallel_for_simd: 6863 case OMPD_teams_distribute_parallel_for: 6864 case OMPD_teams_distribute_parallel_for_simd: 6865 case OMPD_distribute_parallel_for: 6866 case OMPD_distribute_parallel_for_simd: 6867 case OMPD_task: 6868 case OMPD_taskloop: 6869 case OMPD_taskloop_simd: 6870 case OMPD_target_data: 6871 case OMPD_target_enter_data: 6872 case OMPD_target_exit_data: 6873 case OMPD_target_update: 6874 // Do not capture if-clause expressions. 6875 break; 6876 case OMPD_threadprivate: 6877 case OMPD_taskyield: 6878 case OMPD_barrier: 6879 case OMPD_taskwait: 6880 case OMPD_cancellation_point: 6881 case OMPD_flush: 6882 case OMPD_declare_reduction: 6883 case OMPD_declare_simd: 6884 case OMPD_declare_target: 6885 case OMPD_end_declare_target: 6886 case OMPD_teams: 6887 case OMPD_simd: 6888 case OMPD_for: 6889 case OMPD_for_simd: 6890 case OMPD_sections: 6891 case OMPD_section: 6892 case OMPD_single: 6893 case OMPD_master: 6894 case OMPD_critical: 6895 case OMPD_taskgroup: 6896 case OMPD_distribute: 6897 case OMPD_ordered: 6898 case OMPD_atomic: 6899 case OMPD_distribute_simd: 6900 case OMPD_teams_distribute: 6901 case OMPD_teams_distribute_simd: 6902 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 6903 case OMPD_unknown: 6904 llvm_unreachable("Unknown OpenMP directive"); 6905 } 6906 break; 6907 case OMPC_num_threads: 6908 switch (DKind) { 6909 case OMPD_target_parallel: 6910 CaptureRegion = OMPD_target; 6911 break; 6912 case OMPD_cancel: 6913 case OMPD_parallel: 6914 case OMPD_parallel_sections: 6915 case OMPD_parallel_for: 6916 case OMPD_parallel_for_simd: 6917 case OMPD_target: 6918 case OMPD_target_simd: 6919 case OMPD_target_parallel_for: 6920 case OMPD_target_parallel_for_simd: 6921 case OMPD_target_teams: 6922 case OMPD_target_teams_distribute: 6923 case OMPD_target_teams_distribute_simd: 6924 case OMPD_target_teams_distribute_parallel_for: 6925 case OMPD_target_teams_distribute_parallel_for_simd: 6926 case OMPD_teams_distribute_parallel_for: 6927 case OMPD_teams_distribute_parallel_for_simd: 6928 case OMPD_distribute_parallel_for: 6929 case OMPD_distribute_parallel_for_simd: 6930 case OMPD_task: 6931 case OMPD_taskloop: 6932 case OMPD_taskloop_simd: 6933 case OMPD_target_data: 6934 case OMPD_target_enter_data: 6935 case OMPD_target_exit_data: 6936 case OMPD_target_update: 6937 // Do not capture num_threads-clause expressions. 6938 break; 6939 case OMPD_threadprivate: 6940 case OMPD_taskyield: 6941 case OMPD_barrier: 6942 case OMPD_taskwait: 6943 case OMPD_cancellation_point: 6944 case OMPD_flush: 6945 case OMPD_declare_reduction: 6946 case OMPD_declare_simd: 6947 case OMPD_declare_target: 6948 case OMPD_end_declare_target: 6949 case OMPD_teams: 6950 case OMPD_simd: 6951 case OMPD_for: 6952 case OMPD_for_simd: 6953 case OMPD_sections: 6954 case OMPD_section: 6955 case OMPD_single: 6956 case OMPD_master: 6957 case OMPD_critical: 6958 case OMPD_taskgroup: 6959 case OMPD_distribute: 6960 case OMPD_ordered: 6961 case OMPD_atomic: 6962 case OMPD_distribute_simd: 6963 case OMPD_teams_distribute: 6964 case OMPD_teams_distribute_simd: 6965 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 6966 case OMPD_unknown: 6967 llvm_unreachable("Unknown OpenMP directive"); 6968 } 6969 break; 6970 case OMPC_num_teams: 6971 switch (DKind) { 6972 case OMPD_target_teams: 6973 CaptureRegion = OMPD_target; 6974 break; 6975 case OMPD_cancel: 6976 case OMPD_parallel: 6977 case OMPD_parallel_sections: 6978 case OMPD_parallel_for: 6979 case OMPD_parallel_for_simd: 6980 case OMPD_target: 6981 case OMPD_target_simd: 6982 case OMPD_target_parallel: 6983 case OMPD_target_parallel_for: 6984 case OMPD_target_parallel_for_simd: 6985 case OMPD_target_teams_distribute: 6986 case OMPD_target_teams_distribute_simd: 6987 case OMPD_target_teams_distribute_parallel_for: 6988 case OMPD_target_teams_distribute_parallel_for_simd: 6989 case OMPD_teams_distribute_parallel_for: 6990 case OMPD_teams_distribute_parallel_for_simd: 6991 case OMPD_distribute_parallel_for: 6992 case OMPD_distribute_parallel_for_simd: 6993 case OMPD_task: 6994 case OMPD_taskloop: 6995 case OMPD_taskloop_simd: 6996 case OMPD_target_data: 6997 case OMPD_target_enter_data: 6998 case OMPD_target_exit_data: 6999 case OMPD_target_update: 7000 case OMPD_teams: 7001 case OMPD_teams_distribute: 7002 case OMPD_teams_distribute_simd: 7003 // Do not capture num_teams-clause expressions. 7004 break; 7005 case OMPD_threadprivate: 7006 case OMPD_taskyield: 7007 case OMPD_barrier: 7008 case OMPD_taskwait: 7009 case OMPD_cancellation_point: 7010 case OMPD_flush: 7011 case OMPD_declare_reduction: 7012 case OMPD_declare_simd: 7013 case OMPD_declare_target: 7014 case OMPD_end_declare_target: 7015 case OMPD_simd: 7016 case OMPD_for: 7017 case OMPD_for_simd: 7018 case OMPD_sections: 7019 case OMPD_section: 7020 case OMPD_single: 7021 case OMPD_master: 7022 case OMPD_critical: 7023 case OMPD_taskgroup: 7024 case OMPD_distribute: 7025 case OMPD_ordered: 7026 case OMPD_atomic: 7027 case OMPD_distribute_simd: 7028 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 7029 case OMPD_unknown: 7030 llvm_unreachable("Unknown OpenMP directive"); 7031 } 7032 break; 7033 case OMPC_thread_limit: 7034 switch (DKind) { 7035 case OMPD_target_teams: 7036 CaptureRegion = OMPD_target; 7037 break; 7038 case OMPD_cancel: 7039 case OMPD_parallel: 7040 case OMPD_parallel_sections: 7041 case OMPD_parallel_for: 7042 case OMPD_parallel_for_simd: 7043 case OMPD_target: 7044 case OMPD_target_simd: 7045 case OMPD_target_parallel: 7046 case OMPD_target_parallel_for: 7047 case OMPD_target_parallel_for_simd: 7048 case OMPD_target_teams_distribute: 7049 case OMPD_target_teams_distribute_simd: 7050 case OMPD_target_teams_distribute_parallel_for: 7051 case OMPD_target_teams_distribute_parallel_for_simd: 7052 case OMPD_teams_distribute_parallel_for: 7053 case OMPD_teams_distribute_parallel_for_simd: 7054 case OMPD_distribute_parallel_for: 7055 case OMPD_distribute_parallel_for_simd: 7056 case OMPD_task: 7057 case OMPD_taskloop: 7058 case OMPD_taskloop_simd: 7059 case OMPD_target_data: 7060 case OMPD_target_enter_data: 7061 case OMPD_target_exit_data: 7062 case OMPD_target_update: 7063 case OMPD_teams: 7064 case OMPD_teams_distribute: 7065 case OMPD_teams_distribute_simd: 7066 // Do not capture thread_limit-clause expressions. 7067 break; 7068 case OMPD_threadprivate: 7069 case OMPD_taskyield: 7070 case OMPD_barrier: 7071 case OMPD_taskwait: 7072 case OMPD_cancellation_point: 7073 case OMPD_flush: 7074 case OMPD_declare_reduction: 7075 case OMPD_declare_simd: 7076 case OMPD_declare_target: 7077 case OMPD_end_declare_target: 7078 case OMPD_simd: 7079 case OMPD_for: 7080 case OMPD_for_simd: 7081 case OMPD_sections: 7082 case OMPD_section: 7083 case OMPD_single: 7084 case OMPD_master: 7085 case OMPD_critical: 7086 case OMPD_taskgroup: 7087 case OMPD_distribute: 7088 case OMPD_ordered: 7089 case OMPD_atomic: 7090 case OMPD_distribute_simd: 7091 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 7092 case OMPD_unknown: 7093 llvm_unreachable("Unknown OpenMP directive"); 7094 } 7095 break; 7096 case OMPC_schedule: 7097 case OMPC_dist_schedule: 7098 case OMPC_firstprivate: 7099 case OMPC_lastprivate: 7100 case OMPC_reduction: 7101 case OMPC_linear: 7102 case OMPC_default: 7103 case OMPC_proc_bind: 7104 case OMPC_final: 7105 case OMPC_safelen: 7106 case OMPC_simdlen: 7107 case OMPC_collapse: 7108 case OMPC_private: 7109 case OMPC_shared: 7110 case OMPC_aligned: 7111 case OMPC_copyin: 7112 case OMPC_copyprivate: 7113 case OMPC_ordered: 7114 case OMPC_nowait: 7115 case OMPC_untied: 7116 case OMPC_mergeable: 7117 case OMPC_threadprivate: 7118 case OMPC_flush: 7119 case OMPC_read: 7120 case OMPC_write: 7121 case OMPC_update: 7122 case OMPC_capture: 7123 case OMPC_seq_cst: 7124 case OMPC_depend: 7125 case OMPC_device: 7126 case OMPC_threads: 7127 case OMPC_simd: 7128 case OMPC_map: 7129 case OMPC_priority: 7130 case OMPC_grainsize: 7131 case OMPC_nogroup: 7132 case OMPC_num_tasks: 7133 case OMPC_hint: 7134 case OMPC_defaultmap: 7135 case OMPC_unknown: 7136 case OMPC_uniform: 7137 case OMPC_to: 7138 case OMPC_from: 7139 case OMPC_use_device_ptr: 7140 case OMPC_is_device_ptr: 7141 llvm_unreachable("Unexpected OpenMP clause."); 7142 } 7143 return CaptureRegion; 7144 } 7145 7146 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 7147 Expr *Condition, SourceLocation StartLoc, 7148 SourceLocation LParenLoc, 7149 SourceLocation NameModifierLoc, 7150 SourceLocation ColonLoc, 7151 SourceLocation EndLoc) { 7152 Expr *ValExpr = Condition; 7153 Stmt *HelperValStmt = nullptr; 7154 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 7155 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 7156 !Condition->isInstantiationDependent() && 7157 !Condition->containsUnexpandedParameterPack()) { 7158 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 7159 if (Val.isInvalid()) 7160 return nullptr; 7161 7162 ValExpr = MakeFullExpr(Val.get()).get(); 7163 7164 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 7165 CaptureRegion = 7166 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier); 7167 if (CaptureRegion != OMPD_unknown) { 7168 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7169 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7170 HelperValStmt = buildPreInits(Context, Captures); 7171 } 7172 } 7173 7174 return new (Context) 7175 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 7176 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 7177 } 7178 7179 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 7180 SourceLocation StartLoc, 7181 SourceLocation LParenLoc, 7182 SourceLocation EndLoc) { 7183 Expr *ValExpr = Condition; 7184 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 7185 !Condition->isInstantiationDependent() && 7186 !Condition->containsUnexpandedParameterPack()) { 7187 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 7188 if (Val.isInvalid()) 7189 return nullptr; 7190 7191 ValExpr = MakeFullExpr(Val.get()).get(); 7192 } 7193 7194 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 7195 } 7196 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 7197 Expr *Op) { 7198 if (!Op) 7199 return ExprError(); 7200 7201 class IntConvertDiagnoser : public ICEConvertDiagnoser { 7202 public: 7203 IntConvertDiagnoser() 7204 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 7205 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 7206 QualType T) override { 7207 return S.Diag(Loc, diag::err_omp_not_integral) << T; 7208 } 7209 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 7210 QualType T) override { 7211 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 7212 } 7213 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 7214 QualType T, 7215 QualType ConvTy) override { 7216 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 7217 } 7218 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 7219 QualType ConvTy) override { 7220 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 7221 << ConvTy->isEnumeralType() << ConvTy; 7222 } 7223 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 7224 QualType T) override { 7225 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 7226 } 7227 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 7228 QualType ConvTy) override { 7229 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 7230 << ConvTy->isEnumeralType() << ConvTy; 7231 } 7232 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 7233 QualType) override { 7234 llvm_unreachable("conversion functions are permitted"); 7235 } 7236 } ConvertDiagnoser; 7237 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 7238 } 7239 7240 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, 7241 OpenMPClauseKind CKind, 7242 bool StrictlyPositive) { 7243 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 7244 !ValExpr->isInstantiationDependent()) { 7245 SourceLocation Loc = ValExpr->getExprLoc(); 7246 ExprResult Value = 7247 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 7248 if (Value.isInvalid()) 7249 return false; 7250 7251 ValExpr = Value.get(); 7252 // The expression must evaluate to a non-negative integer value. 7253 llvm::APSInt Result; 7254 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && 7255 Result.isSigned() && 7256 !((!StrictlyPositive && Result.isNonNegative()) || 7257 (StrictlyPositive && Result.isStrictlyPositive()))) { 7258 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 7259 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 7260 << ValExpr->getSourceRange(); 7261 return false; 7262 } 7263 } 7264 return true; 7265 } 7266 7267 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 7268 SourceLocation StartLoc, 7269 SourceLocation LParenLoc, 7270 SourceLocation EndLoc) { 7271 Expr *ValExpr = NumThreads; 7272 Stmt *HelperValStmt = nullptr; 7273 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 7274 7275 // OpenMP [2.5, Restrictions] 7276 // The num_threads expression must evaluate to a positive integer value. 7277 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 7278 /*StrictlyPositive=*/true)) 7279 return nullptr; 7280 7281 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 7282 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads); 7283 if (CaptureRegion != OMPD_unknown) { 7284 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7285 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7286 HelperValStmt = buildPreInits(Context, Captures); 7287 } 7288 7289 return new (Context) OMPNumThreadsClause( 7290 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 7291 } 7292 7293 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 7294 OpenMPClauseKind CKind, 7295 bool StrictlyPositive) { 7296 if (!E) 7297 return ExprError(); 7298 if (E->isValueDependent() || E->isTypeDependent() || 7299 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 7300 return E; 7301 llvm::APSInt Result; 7302 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 7303 if (ICE.isInvalid()) 7304 return ExprError(); 7305 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 7306 (!StrictlyPositive && !Result.isNonNegative())) { 7307 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 7308 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 7309 << E->getSourceRange(); 7310 return ExprError(); 7311 } 7312 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 7313 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 7314 << E->getSourceRange(); 7315 return ExprError(); 7316 } 7317 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 7318 DSAStack->setAssociatedLoops(Result.getExtValue()); 7319 else if (CKind == OMPC_ordered) 7320 DSAStack->setAssociatedLoops(Result.getExtValue()); 7321 return ICE; 7322 } 7323 7324 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 7325 SourceLocation LParenLoc, 7326 SourceLocation EndLoc) { 7327 // OpenMP [2.8.1, simd construct, Description] 7328 // The parameter of the safelen clause must be a constant 7329 // positive integer expression. 7330 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 7331 if (Safelen.isInvalid()) 7332 return nullptr; 7333 return new (Context) 7334 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 7335 } 7336 7337 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 7338 SourceLocation LParenLoc, 7339 SourceLocation EndLoc) { 7340 // OpenMP [2.8.1, simd construct, Description] 7341 // The parameter of the simdlen clause must be a constant 7342 // positive integer expression. 7343 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 7344 if (Simdlen.isInvalid()) 7345 return nullptr; 7346 return new (Context) 7347 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 7348 } 7349 7350 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 7351 SourceLocation StartLoc, 7352 SourceLocation LParenLoc, 7353 SourceLocation EndLoc) { 7354 // OpenMP [2.7.1, loop construct, Description] 7355 // OpenMP [2.8.1, simd construct, Description] 7356 // OpenMP [2.9.6, distribute construct, Description] 7357 // The parameter of the collapse clause must be a constant 7358 // positive integer expression. 7359 ExprResult NumForLoopsResult = 7360 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 7361 if (NumForLoopsResult.isInvalid()) 7362 return nullptr; 7363 return new (Context) 7364 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 7365 } 7366 7367 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 7368 SourceLocation EndLoc, 7369 SourceLocation LParenLoc, 7370 Expr *NumForLoops) { 7371 // OpenMP [2.7.1, loop construct, Description] 7372 // OpenMP [2.8.1, simd construct, Description] 7373 // OpenMP [2.9.6, distribute construct, Description] 7374 // The parameter of the ordered clause must be a constant 7375 // positive integer expression if any. 7376 if (NumForLoops && LParenLoc.isValid()) { 7377 ExprResult NumForLoopsResult = 7378 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 7379 if (NumForLoopsResult.isInvalid()) 7380 return nullptr; 7381 NumForLoops = NumForLoopsResult.get(); 7382 } else 7383 NumForLoops = nullptr; 7384 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops); 7385 return new (Context) 7386 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc); 7387 } 7388 7389 OMPClause *Sema::ActOnOpenMPSimpleClause( 7390 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 7391 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 7392 OMPClause *Res = nullptr; 7393 switch (Kind) { 7394 case OMPC_default: 7395 Res = 7396 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 7397 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 7398 break; 7399 case OMPC_proc_bind: 7400 Res = ActOnOpenMPProcBindClause( 7401 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 7402 LParenLoc, EndLoc); 7403 break; 7404 case OMPC_if: 7405 case OMPC_final: 7406 case OMPC_num_threads: 7407 case OMPC_safelen: 7408 case OMPC_simdlen: 7409 case OMPC_collapse: 7410 case OMPC_schedule: 7411 case OMPC_private: 7412 case OMPC_firstprivate: 7413 case OMPC_lastprivate: 7414 case OMPC_shared: 7415 case OMPC_reduction: 7416 case OMPC_linear: 7417 case OMPC_aligned: 7418 case OMPC_copyin: 7419 case OMPC_copyprivate: 7420 case OMPC_ordered: 7421 case OMPC_nowait: 7422 case OMPC_untied: 7423 case OMPC_mergeable: 7424 case OMPC_threadprivate: 7425 case OMPC_flush: 7426 case OMPC_read: 7427 case OMPC_write: 7428 case OMPC_update: 7429 case OMPC_capture: 7430 case OMPC_seq_cst: 7431 case OMPC_depend: 7432 case OMPC_device: 7433 case OMPC_threads: 7434 case OMPC_simd: 7435 case OMPC_map: 7436 case OMPC_num_teams: 7437 case OMPC_thread_limit: 7438 case OMPC_priority: 7439 case OMPC_grainsize: 7440 case OMPC_nogroup: 7441 case OMPC_num_tasks: 7442 case OMPC_hint: 7443 case OMPC_dist_schedule: 7444 case OMPC_defaultmap: 7445 case OMPC_unknown: 7446 case OMPC_uniform: 7447 case OMPC_to: 7448 case OMPC_from: 7449 case OMPC_use_device_ptr: 7450 case OMPC_is_device_ptr: 7451 llvm_unreachable("Clause is not allowed."); 7452 } 7453 return Res; 7454 } 7455 7456 static std::string 7457 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 7458 ArrayRef<unsigned> Exclude = llvm::None) { 7459 std::string Values; 7460 unsigned Bound = Last >= 2 ? Last - 2 : 0; 7461 unsigned Skipped = Exclude.size(); 7462 auto S = Exclude.begin(), E = Exclude.end(); 7463 for (unsigned i = First; i < Last; ++i) { 7464 if (std::find(S, E, i) != E) { 7465 --Skipped; 7466 continue; 7467 } 7468 Values += "'"; 7469 Values += getOpenMPSimpleClauseTypeName(K, i); 7470 Values += "'"; 7471 if (i == Bound - Skipped) 7472 Values += " or "; 7473 else if (i != Bound + 1 - Skipped) 7474 Values += ", "; 7475 } 7476 return Values; 7477 } 7478 7479 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 7480 SourceLocation KindKwLoc, 7481 SourceLocation StartLoc, 7482 SourceLocation LParenLoc, 7483 SourceLocation EndLoc) { 7484 if (Kind == OMPC_DEFAULT_unknown) { 7485 static_assert(OMPC_DEFAULT_unknown > 0, 7486 "OMPC_DEFAULT_unknown not greater than 0"); 7487 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 7488 << getListOfPossibleValues(OMPC_default, /*First=*/0, 7489 /*Last=*/OMPC_DEFAULT_unknown) 7490 << getOpenMPClauseName(OMPC_default); 7491 return nullptr; 7492 } 7493 switch (Kind) { 7494 case OMPC_DEFAULT_none: 7495 DSAStack->setDefaultDSANone(KindKwLoc); 7496 break; 7497 case OMPC_DEFAULT_shared: 7498 DSAStack->setDefaultDSAShared(KindKwLoc); 7499 break; 7500 case OMPC_DEFAULT_unknown: 7501 llvm_unreachable("Clause kind is not allowed."); 7502 break; 7503 } 7504 return new (Context) 7505 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 7506 } 7507 7508 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 7509 SourceLocation KindKwLoc, 7510 SourceLocation StartLoc, 7511 SourceLocation LParenLoc, 7512 SourceLocation EndLoc) { 7513 if (Kind == OMPC_PROC_BIND_unknown) { 7514 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 7515 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0, 7516 /*Last=*/OMPC_PROC_BIND_unknown) 7517 << getOpenMPClauseName(OMPC_proc_bind); 7518 return nullptr; 7519 } 7520 return new (Context) 7521 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 7522 } 7523 7524 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 7525 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 7526 SourceLocation StartLoc, SourceLocation LParenLoc, 7527 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 7528 SourceLocation EndLoc) { 7529 OMPClause *Res = nullptr; 7530 switch (Kind) { 7531 case OMPC_schedule: 7532 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 7533 assert(Argument.size() == NumberOfElements && 7534 ArgumentLoc.size() == NumberOfElements); 7535 Res = ActOnOpenMPScheduleClause( 7536 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 7537 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 7538 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 7539 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 7540 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 7541 break; 7542 case OMPC_if: 7543 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 7544 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 7545 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 7546 DelimLoc, EndLoc); 7547 break; 7548 case OMPC_dist_schedule: 7549 Res = ActOnOpenMPDistScheduleClause( 7550 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 7551 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 7552 break; 7553 case OMPC_defaultmap: 7554 enum { Modifier, DefaultmapKind }; 7555 Res = ActOnOpenMPDefaultmapClause( 7556 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 7557 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 7558 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 7559 EndLoc); 7560 break; 7561 case OMPC_final: 7562 case OMPC_num_threads: 7563 case OMPC_safelen: 7564 case OMPC_simdlen: 7565 case OMPC_collapse: 7566 case OMPC_default: 7567 case OMPC_proc_bind: 7568 case OMPC_private: 7569 case OMPC_firstprivate: 7570 case OMPC_lastprivate: 7571 case OMPC_shared: 7572 case OMPC_reduction: 7573 case OMPC_linear: 7574 case OMPC_aligned: 7575 case OMPC_copyin: 7576 case OMPC_copyprivate: 7577 case OMPC_ordered: 7578 case OMPC_nowait: 7579 case OMPC_untied: 7580 case OMPC_mergeable: 7581 case OMPC_threadprivate: 7582 case OMPC_flush: 7583 case OMPC_read: 7584 case OMPC_write: 7585 case OMPC_update: 7586 case OMPC_capture: 7587 case OMPC_seq_cst: 7588 case OMPC_depend: 7589 case OMPC_device: 7590 case OMPC_threads: 7591 case OMPC_simd: 7592 case OMPC_map: 7593 case OMPC_num_teams: 7594 case OMPC_thread_limit: 7595 case OMPC_priority: 7596 case OMPC_grainsize: 7597 case OMPC_nogroup: 7598 case OMPC_num_tasks: 7599 case OMPC_hint: 7600 case OMPC_unknown: 7601 case OMPC_uniform: 7602 case OMPC_to: 7603 case OMPC_from: 7604 case OMPC_use_device_ptr: 7605 case OMPC_is_device_ptr: 7606 llvm_unreachable("Clause is not allowed."); 7607 } 7608 return Res; 7609 } 7610 7611 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 7612 OpenMPScheduleClauseModifier M2, 7613 SourceLocation M1Loc, SourceLocation M2Loc) { 7614 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 7615 SmallVector<unsigned, 2> Excluded; 7616 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 7617 Excluded.push_back(M2); 7618 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 7619 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 7620 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 7621 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 7622 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 7623 << getListOfPossibleValues(OMPC_schedule, 7624 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 7625 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 7626 Excluded) 7627 << getOpenMPClauseName(OMPC_schedule); 7628 return true; 7629 } 7630 return false; 7631 } 7632 7633 OMPClause *Sema::ActOnOpenMPScheduleClause( 7634 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 7635 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 7636 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 7637 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 7638 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 7639 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 7640 return nullptr; 7641 // OpenMP, 2.7.1, Loop Construct, Restrictions 7642 // Either the monotonic modifier or the nonmonotonic modifier can be specified 7643 // but not both. 7644 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 7645 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 7646 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 7647 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 7648 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 7649 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 7650 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 7651 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 7652 return nullptr; 7653 } 7654 if (Kind == OMPC_SCHEDULE_unknown) { 7655 std::string Values; 7656 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 7657 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 7658 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 7659 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 7660 Exclude); 7661 } else { 7662 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 7663 /*Last=*/OMPC_SCHEDULE_unknown); 7664 } 7665 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 7666 << Values << getOpenMPClauseName(OMPC_schedule); 7667 return nullptr; 7668 } 7669 // OpenMP, 2.7.1, Loop Construct, Restrictions 7670 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 7671 // schedule(guided). 7672 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 7673 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 7674 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 7675 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 7676 diag::err_omp_schedule_nonmonotonic_static); 7677 return nullptr; 7678 } 7679 Expr *ValExpr = ChunkSize; 7680 Stmt *HelperValStmt = nullptr; 7681 if (ChunkSize) { 7682 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 7683 !ChunkSize->isInstantiationDependent() && 7684 !ChunkSize->containsUnexpandedParameterPack()) { 7685 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 7686 ExprResult Val = 7687 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 7688 if (Val.isInvalid()) 7689 return nullptr; 7690 7691 ValExpr = Val.get(); 7692 7693 // OpenMP [2.7.1, Restrictions] 7694 // chunk_size must be a loop invariant integer expression with a positive 7695 // value. 7696 llvm::APSInt Result; 7697 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 7698 if (Result.isSigned() && !Result.isStrictlyPositive()) { 7699 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 7700 << "schedule" << 1 << ChunkSize->getSourceRange(); 7701 return nullptr; 7702 } 7703 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 7704 !CurContext->isDependentContext()) { 7705 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7706 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7707 HelperValStmt = buildPreInits(Context, Captures); 7708 } 7709 } 7710 } 7711 7712 return new (Context) 7713 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 7714 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 7715 } 7716 7717 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 7718 SourceLocation StartLoc, 7719 SourceLocation EndLoc) { 7720 OMPClause *Res = nullptr; 7721 switch (Kind) { 7722 case OMPC_ordered: 7723 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 7724 break; 7725 case OMPC_nowait: 7726 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 7727 break; 7728 case OMPC_untied: 7729 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 7730 break; 7731 case OMPC_mergeable: 7732 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 7733 break; 7734 case OMPC_read: 7735 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 7736 break; 7737 case OMPC_write: 7738 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 7739 break; 7740 case OMPC_update: 7741 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 7742 break; 7743 case OMPC_capture: 7744 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 7745 break; 7746 case OMPC_seq_cst: 7747 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 7748 break; 7749 case OMPC_threads: 7750 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 7751 break; 7752 case OMPC_simd: 7753 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 7754 break; 7755 case OMPC_nogroup: 7756 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 7757 break; 7758 case OMPC_if: 7759 case OMPC_final: 7760 case OMPC_num_threads: 7761 case OMPC_safelen: 7762 case OMPC_simdlen: 7763 case OMPC_collapse: 7764 case OMPC_schedule: 7765 case OMPC_private: 7766 case OMPC_firstprivate: 7767 case OMPC_lastprivate: 7768 case OMPC_shared: 7769 case OMPC_reduction: 7770 case OMPC_linear: 7771 case OMPC_aligned: 7772 case OMPC_copyin: 7773 case OMPC_copyprivate: 7774 case OMPC_default: 7775 case OMPC_proc_bind: 7776 case OMPC_threadprivate: 7777 case OMPC_flush: 7778 case OMPC_depend: 7779 case OMPC_device: 7780 case OMPC_map: 7781 case OMPC_num_teams: 7782 case OMPC_thread_limit: 7783 case OMPC_priority: 7784 case OMPC_grainsize: 7785 case OMPC_num_tasks: 7786 case OMPC_hint: 7787 case OMPC_dist_schedule: 7788 case OMPC_defaultmap: 7789 case OMPC_unknown: 7790 case OMPC_uniform: 7791 case OMPC_to: 7792 case OMPC_from: 7793 case OMPC_use_device_ptr: 7794 case OMPC_is_device_ptr: 7795 llvm_unreachable("Clause is not allowed."); 7796 } 7797 return Res; 7798 } 7799 7800 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 7801 SourceLocation EndLoc) { 7802 DSAStack->setNowaitRegion(); 7803 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 7804 } 7805 7806 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 7807 SourceLocation EndLoc) { 7808 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 7809 } 7810 7811 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 7812 SourceLocation EndLoc) { 7813 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 7814 } 7815 7816 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 7817 SourceLocation EndLoc) { 7818 return new (Context) OMPReadClause(StartLoc, EndLoc); 7819 } 7820 7821 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 7822 SourceLocation EndLoc) { 7823 return new (Context) OMPWriteClause(StartLoc, EndLoc); 7824 } 7825 7826 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 7827 SourceLocation EndLoc) { 7828 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 7829 } 7830 7831 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 7832 SourceLocation EndLoc) { 7833 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 7834 } 7835 7836 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 7837 SourceLocation EndLoc) { 7838 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 7839 } 7840 7841 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 7842 SourceLocation EndLoc) { 7843 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 7844 } 7845 7846 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 7847 SourceLocation EndLoc) { 7848 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 7849 } 7850 7851 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 7852 SourceLocation EndLoc) { 7853 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 7854 } 7855 7856 OMPClause *Sema::ActOnOpenMPVarListClause( 7857 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 7858 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 7859 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 7860 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind, 7861 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier, 7862 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 7863 SourceLocation DepLinMapLoc) { 7864 OMPClause *Res = nullptr; 7865 switch (Kind) { 7866 case OMPC_private: 7867 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7868 break; 7869 case OMPC_firstprivate: 7870 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7871 break; 7872 case OMPC_lastprivate: 7873 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7874 break; 7875 case OMPC_shared: 7876 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 7877 break; 7878 case OMPC_reduction: 7879 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 7880 EndLoc, ReductionIdScopeSpec, ReductionId); 7881 break; 7882 case OMPC_linear: 7883 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 7884 LinKind, DepLinMapLoc, ColonLoc, EndLoc); 7885 break; 7886 case OMPC_aligned: 7887 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 7888 ColonLoc, EndLoc); 7889 break; 7890 case OMPC_copyin: 7891 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 7892 break; 7893 case OMPC_copyprivate: 7894 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 7895 break; 7896 case OMPC_flush: 7897 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 7898 break; 7899 case OMPC_depend: 7900 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, 7901 StartLoc, LParenLoc, EndLoc); 7902 break; 7903 case OMPC_map: 7904 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit, 7905 DepLinMapLoc, ColonLoc, VarList, StartLoc, 7906 LParenLoc, EndLoc); 7907 break; 7908 case OMPC_to: 7909 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc); 7910 break; 7911 case OMPC_from: 7912 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc); 7913 break; 7914 case OMPC_use_device_ptr: 7915 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 7916 break; 7917 case OMPC_is_device_ptr: 7918 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 7919 break; 7920 case OMPC_if: 7921 case OMPC_final: 7922 case OMPC_num_threads: 7923 case OMPC_safelen: 7924 case OMPC_simdlen: 7925 case OMPC_collapse: 7926 case OMPC_default: 7927 case OMPC_proc_bind: 7928 case OMPC_schedule: 7929 case OMPC_ordered: 7930 case OMPC_nowait: 7931 case OMPC_untied: 7932 case OMPC_mergeable: 7933 case OMPC_threadprivate: 7934 case OMPC_read: 7935 case OMPC_write: 7936 case OMPC_update: 7937 case OMPC_capture: 7938 case OMPC_seq_cst: 7939 case OMPC_device: 7940 case OMPC_threads: 7941 case OMPC_simd: 7942 case OMPC_num_teams: 7943 case OMPC_thread_limit: 7944 case OMPC_priority: 7945 case OMPC_grainsize: 7946 case OMPC_nogroup: 7947 case OMPC_num_tasks: 7948 case OMPC_hint: 7949 case OMPC_dist_schedule: 7950 case OMPC_defaultmap: 7951 case OMPC_unknown: 7952 case OMPC_uniform: 7953 llvm_unreachable("Clause is not allowed."); 7954 } 7955 return Res; 7956 } 7957 7958 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 7959 ExprObjectKind OK, SourceLocation Loc) { 7960 ExprResult Res = BuildDeclRefExpr( 7961 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 7962 if (!Res.isUsable()) 7963 return ExprError(); 7964 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 7965 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 7966 if (!Res.isUsable()) 7967 return ExprError(); 7968 } 7969 if (VK != VK_LValue && Res.get()->isGLValue()) { 7970 Res = DefaultLvalueConversion(Res.get()); 7971 if (!Res.isUsable()) 7972 return ExprError(); 7973 } 7974 return Res; 7975 } 7976 7977 static std::pair<ValueDecl *, bool> 7978 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 7979 SourceRange &ERange, bool AllowArraySection = false) { 7980 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 7981 RefExpr->containsUnexpandedParameterPack()) 7982 return std::make_pair(nullptr, true); 7983 7984 // OpenMP [3.1, C/C++] 7985 // A list item is a variable name. 7986 // OpenMP [2.9.3.3, Restrictions, p.1] 7987 // A variable that is part of another variable (as an array or 7988 // structure element) cannot appear in a private clause. 7989 RefExpr = RefExpr->IgnoreParens(); 7990 enum { 7991 NoArrayExpr = -1, 7992 ArraySubscript = 0, 7993 OMPArraySection = 1 7994 } IsArrayExpr = NoArrayExpr; 7995 if (AllowArraySection) { 7996 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 7997 auto *Base = ASE->getBase()->IgnoreParenImpCasts(); 7998 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 7999 Base = TempASE->getBase()->IgnoreParenImpCasts(); 8000 RefExpr = Base; 8001 IsArrayExpr = ArraySubscript; 8002 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 8003 auto *Base = OASE->getBase()->IgnoreParenImpCasts(); 8004 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 8005 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 8006 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 8007 Base = TempASE->getBase()->IgnoreParenImpCasts(); 8008 RefExpr = Base; 8009 IsArrayExpr = OMPArraySection; 8010 } 8011 } 8012 ELoc = RefExpr->getExprLoc(); 8013 ERange = RefExpr->getSourceRange(); 8014 RefExpr = RefExpr->IgnoreParenImpCasts(); 8015 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 8016 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 8017 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 8018 (S.getCurrentThisType().isNull() || !ME || 8019 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 8020 !isa<FieldDecl>(ME->getMemberDecl()))) { 8021 if (IsArrayExpr != NoArrayExpr) 8022 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 8023 << ERange; 8024 else { 8025 S.Diag(ELoc, 8026 AllowArraySection 8027 ? diag::err_omp_expected_var_name_member_expr_or_array_item 8028 : diag::err_omp_expected_var_name_member_expr) 8029 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 8030 } 8031 return std::make_pair(nullptr, false); 8032 } 8033 return std::make_pair(DE ? DE->getDecl() : ME->getMemberDecl(), false); 8034 } 8035 8036 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 8037 SourceLocation StartLoc, 8038 SourceLocation LParenLoc, 8039 SourceLocation EndLoc) { 8040 SmallVector<Expr *, 8> Vars; 8041 SmallVector<Expr *, 8> PrivateCopies; 8042 for (auto &RefExpr : VarList) { 8043 assert(RefExpr && "NULL expr in OpenMP private clause."); 8044 SourceLocation ELoc; 8045 SourceRange ERange; 8046 Expr *SimpleRefExpr = RefExpr; 8047 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8048 if (Res.second) { 8049 // It will be analyzed later. 8050 Vars.push_back(RefExpr); 8051 PrivateCopies.push_back(nullptr); 8052 } 8053 ValueDecl *D = Res.first; 8054 if (!D) 8055 continue; 8056 8057 QualType Type = D->getType(); 8058 auto *VD = dyn_cast<VarDecl>(D); 8059 8060 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8061 // A variable that appears in a private clause must not have an incomplete 8062 // type or a reference type. 8063 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 8064 continue; 8065 Type = Type.getNonReferenceType(); 8066 8067 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8068 // in a Construct] 8069 // Variables with the predetermined data-sharing attributes may not be 8070 // listed in data-sharing attributes clauses, except for the cases 8071 // listed below. For these exceptions only, listing a predetermined 8072 // variable in a data-sharing attribute clause is allowed and overrides 8073 // the variable's predetermined data-sharing attributes. 8074 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8075 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 8076 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 8077 << getOpenMPClauseName(OMPC_private); 8078 ReportOriginalDSA(*this, DSAStack, D, DVar); 8079 continue; 8080 } 8081 8082 auto CurrDir = DSAStack->getCurrentDirective(); 8083 // Variably modified types are not supported for tasks. 8084 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 8085 isOpenMPTaskingDirective(CurrDir)) { 8086 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 8087 << getOpenMPClauseName(OMPC_private) << Type 8088 << getOpenMPDirectiveName(CurrDir); 8089 bool IsDecl = 8090 !VD || 8091 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8092 Diag(D->getLocation(), 8093 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8094 << D; 8095 continue; 8096 } 8097 8098 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 8099 // A list item cannot appear in both a map clause and a data-sharing 8100 // attribute clause on the same construct 8101 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || 8102 CurrDir == OMPD_target_teams || 8103 CurrDir == OMPD_target_teams_distribute || 8104 CurrDir == OMPD_target_teams_distribute_parallel_for || 8105 CurrDir == OMPD_target_teams_distribute_parallel_for_simd || 8106 CurrDir == OMPD_target_teams_distribute_simd || 8107 CurrDir == OMPD_target_parallel_for_simd || 8108 CurrDir == OMPD_target_parallel_for) { 8109 OpenMPClauseKind ConflictKind; 8110 if (DSAStack->checkMappableExprComponentListsForDecl( 8111 VD, /*CurrentRegionOnly=*/true, 8112 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 8113 OpenMPClauseKind WhereFoundClauseKind) -> bool { 8114 ConflictKind = WhereFoundClauseKind; 8115 return true; 8116 })) { 8117 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 8118 << getOpenMPClauseName(OMPC_private) 8119 << getOpenMPClauseName(ConflictKind) 8120 << getOpenMPDirectiveName(CurrDir); 8121 ReportOriginalDSA(*this, DSAStack, D, DVar); 8122 continue; 8123 } 8124 } 8125 8126 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 8127 // A variable of class type (or array thereof) that appears in a private 8128 // clause requires an accessible, unambiguous default constructor for the 8129 // class type. 8130 // Generate helper private variable and initialize it with the default 8131 // value. The address of the original variable is replaced by the address of 8132 // the new private variable in CodeGen. This new variable is not added to 8133 // IdResolver, so the code in the OpenMP region uses original variable for 8134 // proper diagnostics. 8135 Type = Type.getUnqualifiedType(); 8136 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 8137 D->hasAttrs() ? &D->getAttrs() : nullptr); 8138 ActOnUninitializedDecl(VDPrivate); 8139 if (VDPrivate->isInvalidDecl()) 8140 continue; 8141 auto VDPrivateRefExpr = buildDeclRefExpr( 8142 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 8143 8144 DeclRefExpr *Ref = nullptr; 8145 if (!VD && !CurContext->isDependentContext()) 8146 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 8147 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 8148 Vars.push_back((VD || CurContext->isDependentContext()) 8149 ? RefExpr->IgnoreParens() 8150 : Ref); 8151 PrivateCopies.push_back(VDPrivateRefExpr); 8152 } 8153 8154 if (Vars.empty()) 8155 return nullptr; 8156 8157 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 8158 PrivateCopies); 8159 } 8160 8161 namespace { 8162 class DiagsUninitializedSeveretyRAII { 8163 private: 8164 DiagnosticsEngine &Diags; 8165 SourceLocation SavedLoc; 8166 bool IsIgnored; 8167 8168 public: 8169 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 8170 bool IsIgnored) 8171 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 8172 if (!IsIgnored) { 8173 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 8174 /*Map*/ diag::Severity::Ignored, Loc); 8175 } 8176 } 8177 ~DiagsUninitializedSeveretyRAII() { 8178 if (!IsIgnored) 8179 Diags.popMappings(SavedLoc); 8180 } 8181 }; 8182 } 8183 8184 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 8185 SourceLocation StartLoc, 8186 SourceLocation LParenLoc, 8187 SourceLocation EndLoc) { 8188 SmallVector<Expr *, 8> Vars; 8189 SmallVector<Expr *, 8> PrivateCopies; 8190 SmallVector<Expr *, 8> Inits; 8191 SmallVector<Decl *, 4> ExprCaptures; 8192 bool IsImplicitClause = 8193 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 8194 auto ImplicitClauseLoc = DSAStack->getConstructLoc(); 8195 8196 for (auto &RefExpr : VarList) { 8197 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 8198 SourceLocation ELoc; 8199 SourceRange ERange; 8200 Expr *SimpleRefExpr = RefExpr; 8201 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8202 if (Res.second) { 8203 // It will be analyzed later. 8204 Vars.push_back(RefExpr); 8205 PrivateCopies.push_back(nullptr); 8206 Inits.push_back(nullptr); 8207 } 8208 ValueDecl *D = Res.first; 8209 if (!D) 8210 continue; 8211 8212 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 8213 QualType Type = D->getType(); 8214 auto *VD = dyn_cast<VarDecl>(D); 8215 8216 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8217 // A variable that appears in a private clause must not have an incomplete 8218 // type or a reference type. 8219 if (RequireCompleteType(ELoc, Type, 8220 diag::err_omp_firstprivate_incomplete_type)) 8221 continue; 8222 Type = Type.getNonReferenceType(); 8223 8224 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 8225 // A variable of class type (or array thereof) that appears in a private 8226 // clause requires an accessible, unambiguous copy constructor for the 8227 // class type. 8228 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 8229 8230 // If an implicit firstprivate variable found it was checked already. 8231 DSAStackTy::DSAVarData TopDVar; 8232 if (!IsImplicitClause) { 8233 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8234 TopDVar = DVar; 8235 bool IsConstant = ElemType.isConstant(Context); 8236 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 8237 // A list item that specifies a given variable may not appear in more 8238 // than one clause on the same directive, except that a variable may be 8239 // specified in both firstprivate and lastprivate clauses. 8240 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 8241 DVar.CKind != OMPC_lastprivate && DVar.RefExpr) { 8242 Diag(ELoc, diag::err_omp_wrong_dsa) 8243 << getOpenMPClauseName(DVar.CKind) 8244 << getOpenMPClauseName(OMPC_firstprivate); 8245 ReportOriginalDSA(*this, DSAStack, D, DVar); 8246 continue; 8247 } 8248 8249 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8250 // in a Construct] 8251 // Variables with the predetermined data-sharing attributes may not be 8252 // listed in data-sharing attributes clauses, except for the cases 8253 // listed below. For these exceptions only, listing a predetermined 8254 // variable in a data-sharing attribute clause is allowed and overrides 8255 // the variable's predetermined data-sharing attributes. 8256 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8257 // in a Construct, C/C++, p.2] 8258 // Variables with const-qualified type having no mutable member may be 8259 // listed in a firstprivate clause, even if they are static data members. 8260 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 8261 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 8262 Diag(ELoc, diag::err_omp_wrong_dsa) 8263 << getOpenMPClauseName(DVar.CKind) 8264 << getOpenMPClauseName(OMPC_firstprivate); 8265 ReportOriginalDSA(*this, DSAStack, D, DVar); 8266 continue; 8267 } 8268 8269 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8270 // OpenMP [2.9.3.4, Restrictions, p.2] 8271 // A list item that is private within a parallel region must not appear 8272 // in a firstprivate clause on a worksharing construct if any of the 8273 // worksharing regions arising from the worksharing construct ever bind 8274 // to any of the parallel regions arising from the parallel construct. 8275 if (isOpenMPWorksharingDirective(CurrDir) && 8276 !isOpenMPParallelDirective(CurrDir) && 8277 !isOpenMPTeamsDirective(CurrDir)) { 8278 DVar = DSAStack->getImplicitDSA(D, true); 8279 if (DVar.CKind != OMPC_shared && 8280 (isOpenMPParallelDirective(DVar.DKind) || 8281 DVar.DKind == OMPD_unknown)) { 8282 Diag(ELoc, diag::err_omp_required_access) 8283 << getOpenMPClauseName(OMPC_firstprivate) 8284 << getOpenMPClauseName(OMPC_shared); 8285 ReportOriginalDSA(*this, DSAStack, D, DVar); 8286 continue; 8287 } 8288 } 8289 // OpenMP [2.9.3.4, Restrictions, p.3] 8290 // A list item that appears in a reduction clause of a parallel construct 8291 // must not appear in a firstprivate clause on a worksharing or task 8292 // construct if any of the worksharing or task regions arising from the 8293 // worksharing or task construct ever bind to any of the parallel regions 8294 // arising from the parallel construct. 8295 // OpenMP [2.9.3.4, Restrictions, p.4] 8296 // A list item that appears in a reduction clause in worksharing 8297 // construct must not appear in a firstprivate clause in a task construct 8298 // encountered during execution of any of the worksharing regions arising 8299 // from the worksharing construct. 8300 if (isOpenMPTaskingDirective(CurrDir)) { 8301 DVar = DSAStack->hasInnermostDSA( 8302 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 8303 [](OpenMPDirectiveKind K) -> bool { 8304 return isOpenMPParallelDirective(K) || 8305 isOpenMPWorksharingDirective(K); 8306 }, 8307 false); 8308 if (DVar.CKind == OMPC_reduction && 8309 (isOpenMPParallelDirective(DVar.DKind) || 8310 isOpenMPWorksharingDirective(DVar.DKind))) { 8311 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 8312 << getOpenMPDirectiveName(DVar.DKind); 8313 ReportOriginalDSA(*this, DSAStack, D, DVar); 8314 continue; 8315 } 8316 } 8317 8318 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 8319 // A list item that is private within a teams region must not appear in a 8320 // firstprivate clause on a distribute construct if any of the distribute 8321 // regions arising from the distribute construct ever bind to any of the 8322 // teams regions arising from the teams construct. 8323 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 8324 // A list item that appears in a reduction clause of a teams construct 8325 // must not appear in a firstprivate clause on a distribute construct if 8326 // any of the distribute regions arising from the distribute construct 8327 // ever bind to any of the teams regions arising from the teams construct. 8328 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 8329 // A list item may appear in a firstprivate or lastprivate clause but not 8330 // both. 8331 if (CurrDir == OMPD_distribute) { 8332 DVar = DSAStack->hasInnermostDSA( 8333 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_private; }, 8334 [](OpenMPDirectiveKind K) -> bool { 8335 return isOpenMPTeamsDirective(K); 8336 }, 8337 false); 8338 if (DVar.CKind == OMPC_private && isOpenMPTeamsDirective(DVar.DKind)) { 8339 Diag(ELoc, diag::err_omp_firstprivate_distribute_private_teams); 8340 ReportOriginalDSA(*this, DSAStack, D, DVar); 8341 continue; 8342 } 8343 DVar = DSAStack->hasInnermostDSA( 8344 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 8345 [](OpenMPDirectiveKind K) -> bool { 8346 return isOpenMPTeamsDirective(K); 8347 }, 8348 false); 8349 if (DVar.CKind == OMPC_reduction && 8350 isOpenMPTeamsDirective(DVar.DKind)) { 8351 Diag(ELoc, diag::err_omp_firstprivate_distribute_in_teams_reduction); 8352 ReportOriginalDSA(*this, DSAStack, D, DVar); 8353 continue; 8354 } 8355 DVar = DSAStack->getTopDSA(D, false); 8356 if (DVar.CKind == OMPC_lastprivate) { 8357 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute); 8358 ReportOriginalDSA(*this, DSAStack, D, DVar); 8359 continue; 8360 } 8361 } 8362 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 8363 // A list item cannot appear in both a map clause and a data-sharing 8364 // attribute clause on the same construct 8365 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || 8366 CurrDir == OMPD_target_teams || 8367 CurrDir == OMPD_target_teams_distribute || 8368 CurrDir == OMPD_target_teams_distribute_parallel_for || 8369 CurrDir == OMPD_target_teams_distribute_parallel_for_simd || 8370 CurrDir == OMPD_target_teams_distribute_simd || 8371 CurrDir == OMPD_target_parallel_for_simd || 8372 CurrDir == OMPD_target_parallel_for) { 8373 OpenMPClauseKind ConflictKind; 8374 if (DSAStack->checkMappableExprComponentListsForDecl( 8375 VD, /*CurrentRegionOnly=*/true, 8376 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 8377 OpenMPClauseKind WhereFoundClauseKind) -> bool { 8378 ConflictKind = WhereFoundClauseKind; 8379 return true; 8380 })) { 8381 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 8382 << getOpenMPClauseName(OMPC_firstprivate) 8383 << getOpenMPClauseName(ConflictKind) 8384 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8385 ReportOriginalDSA(*this, DSAStack, D, DVar); 8386 continue; 8387 } 8388 } 8389 } 8390 8391 // Variably modified types are not supported for tasks. 8392 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 8393 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 8394 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 8395 << getOpenMPClauseName(OMPC_firstprivate) << Type 8396 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8397 bool IsDecl = 8398 !VD || 8399 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8400 Diag(D->getLocation(), 8401 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8402 << D; 8403 continue; 8404 } 8405 8406 Type = Type.getUnqualifiedType(); 8407 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 8408 D->hasAttrs() ? &D->getAttrs() : nullptr); 8409 // Generate helper private variable and initialize it with the value of the 8410 // original variable. The address of the original variable is replaced by 8411 // the address of the new private variable in the CodeGen. This new variable 8412 // is not added to IdResolver, so the code in the OpenMP region uses 8413 // original variable for proper diagnostics and variable capturing. 8414 Expr *VDInitRefExpr = nullptr; 8415 // For arrays generate initializer for single element and replace it by the 8416 // original array element in CodeGen. 8417 if (Type->isArrayType()) { 8418 auto VDInit = 8419 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 8420 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 8421 auto Init = DefaultLvalueConversion(VDInitRefExpr).get(); 8422 ElemType = ElemType.getUnqualifiedType(); 8423 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 8424 ".firstprivate.temp"); 8425 InitializedEntity Entity = 8426 InitializedEntity::InitializeVariable(VDInitTemp); 8427 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 8428 8429 InitializationSequence InitSeq(*this, Entity, Kind, Init); 8430 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 8431 if (Result.isInvalid()) 8432 VDPrivate->setInvalidDecl(); 8433 else 8434 VDPrivate->setInit(Result.getAs<Expr>()); 8435 // Remove temp variable declaration. 8436 Context.Deallocate(VDInitTemp); 8437 } else { 8438 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 8439 ".firstprivate.temp"); 8440 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 8441 RefExpr->getExprLoc()); 8442 AddInitializerToDecl(VDPrivate, 8443 DefaultLvalueConversion(VDInitRefExpr).get(), 8444 /*DirectInit=*/false); 8445 } 8446 if (VDPrivate->isInvalidDecl()) { 8447 if (IsImplicitClause) { 8448 Diag(RefExpr->getExprLoc(), 8449 diag::note_omp_task_predetermined_firstprivate_here); 8450 } 8451 continue; 8452 } 8453 CurContext->addDecl(VDPrivate); 8454 auto VDPrivateRefExpr = buildDeclRefExpr( 8455 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 8456 RefExpr->getExprLoc()); 8457 DeclRefExpr *Ref = nullptr; 8458 if (!VD && !CurContext->isDependentContext()) { 8459 if (TopDVar.CKind == OMPC_lastprivate) 8460 Ref = TopDVar.PrivateCopy; 8461 else { 8462 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 8463 if (!IsOpenMPCapturedDecl(D)) 8464 ExprCaptures.push_back(Ref->getDecl()); 8465 } 8466 } 8467 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 8468 Vars.push_back((VD || CurContext->isDependentContext()) 8469 ? RefExpr->IgnoreParens() 8470 : Ref); 8471 PrivateCopies.push_back(VDPrivateRefExpr); 8472 Inits.push_back(VDInitRefExpr); 8473 } 8474 8475 if (Vars.empty()) 8476 return nullptr; 8477 8478 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 8479 Vars, PrivateCopies, Inits, 8480 buildPreInits(Context, ExprCaptures)); 8481 } 8482 8483 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 8484 SourceLocation StartLoc, 8485 SourceLocation LParenLoc, 8486 SourceLocation EndLoc) { 8487 SmallVector<Expr *, 8> Vars; 8488 SmallVector<Expr *, 8> SrcExprs; 8489 SmallVector<Expr *, 8> DstExprs; 8490 SmallVector<Expr *, 8> AssignmentOps; 8491 SmallVector<Decl *, 4> ExprCaptures; 8492 SmallVector<Expr *, 4> ExprPostUpdates; 8493 for (auto &RefExpr : VarList) { 8494 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 8495 SourceLocation ELoc; 8496 SourceRange ERange; 8497 Expr *SimpleRefExpr = RefExpr; 8498 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8499 if (Res.second) { 8500 // It will be analyzed later. 8501 Vars.push_back(RefExpr); 8502 SrcExprs.push_back(nullptr); 8503 DstExprs.push_back(nullptr); 8504 AssignmentOps.push_back(nullptr); 8505 } 8506 ValueDecl *D = Res.first; 8507 if (!D) 8508 continue; 8509 8510 QualType Type = D->getType(); 8511 auto *VD = dyn_cast<VarDecl>(D); 8512 8513 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 8514 // A variable that appears in a lastprivate clause must not have an 8515 // incomplete type or a reference type. 8516 if (RequireCompleteType(ELoc, Type, 8517 diag::err_omp_lastprivate_incomplete_type)) 8518 continue; 8519 Type = Type.getNonReferenceType(); 8520 8521 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 8522 // in a Construct] 8523 // Variables with the predetermined data-sharing attributes may not be 8524 // listed in data-sharing attributes clauses, except for the cases 8525 // listed below. 8526 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8527 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 8528 DVar.CKind != OMPC_firstprivate && 8529 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 8530 Diag(ELoc, diag::err_omp_wrong_dsa) 8531 << getOpenMPClauseName(DVar.CKind) 8532 << getOpenMPClauseName(OMPC_lastprivate); 8533 ReportOriginalDSA(*this, DSAStack, D, DVar); 8534 continue; 8535 } 8536 8537 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8538 // OpenMP [2.14.3.5, Restrictions, p.2] 8539 // A list item that is private within a parallel region, or that appears in 8540 // the reduction clause of a parallel construct, must not appear in a 8541 // lastprivate clause on a worksharing construct if any of the corresponding 8542 // worksharing regions ever binds to any of the corresponding parallel 8543 // regions. 8544 DSAStackTy::DSAVarData TopDVar = DVar; 8545 if (isOpenMPWorksharingDirective(CurrDir) && 8546 !isOpenMPParallelDirective(CurrDir) && 8547 !isOpenMPTeamsDirective(CurrDir)) { 8548 DVar = DSAStack->getImplicitDSA(D, true); 8549 if (DVar.CKind != OMPC_shared) { 8550 Diag(ELoc, diag::err_omp_required_access) 8551 << getOpenMPClauseName(OMPC_lastprivate) 8552 << getOpenMPClauseName(OMPC_shared); 8553 ReportOriginalDSA(*this, DSAStack, D, DVar); 8554 continue; 8555 } 8556 } 8557 8558 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 8559 // A list item may appear in a firstprivate or lastprivate clause but not 8560 // both. 8561 if (CurrDir == OMPD_distribute) { 8562 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8563 if (DVar.CKind == OMPC_firstprivate) { 8564 Diag(ELoc, diag::err_omp_firstprivate_and_lastprivate_in_distribute); 8565 ReportOriginalDSA(*this, DSAStack, D, DVar); 8566 continue; 8567 } 8568 } 8569 8570 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 8571 // A variable of class type (or array thereof) that appears in a 8572 // lastprivate clause requires an accessible, unambiguous default 8573 // constructor for the class type, unless the list item is also specified 8574 // in a firstprivate clause. 8575 // A variable of class type (or array thereof) that appears in a 8576 // lastprivate clause requires an accessible, unambiguous copy assignment 8577 // operator for the class type. 8578 Type = Context.getBaseElementType(Type).getNonReferenceType(); 8579 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(), 8580 Type.getUnqualifiedType(), ".lastprivate.src", 8581 D->hasAttrs() ? &D->getAttrs() : nullptr); 8582 auto *PseudoSrcExpr = 8583 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 8584 auto *DstVD = 8585 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 8586 D->hasAttrs() ? &D->getAttrs() : nullptr); 8587 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 8588 // For arrays generate assignment operation for single element and replace 8589 // it by the original array element in CodeGen. 8590 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 8591 PseudoDstExpr, PseudoSrcExpr); 8592 if (AssignmentOp.isInvalid()) 8593 continue; 8594 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 8595 /*DiscardedValue=*/true); 8596 if (AssignmentOp.isInvalid()) 8597 continue; 8598 8599 DeclRefExpr *Ref = nullptr; 8600 if (!VD && !CurContext->isDependentContext()) { 8601 if (TopDVar.CKind == OMPC_firstprivate) 8602 Ref = TopDVar.PrivateCopy; 8603 else { 8604 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 8605 if (!IsOpenMPCapturedDecl(D)) 8606 ExprCaptures.push_back(Ref->getDecl()); 8607 } 8608 if (TopDVar.CKind == OMPC_firstprivate || 8609 (!IsOpenMPCapturedDecl(D) && 8610 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 8611 ExprResult RefRes = DefaultLvalueConversion(Ref); 8612 if (!RefRes.isUsable()) 8613 continue; 8614 ExprResult PostUpdateRes = 8615 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 8616 RefRes.get()); 8617 if (!PostUpdateRes.isUsable()) 8618 continue; 8619 ExprPostUpdates.push_back( 8620 IgnoredValueConversions(PostUpdateRes.get()).get()); 8621 } 8622 } 8623 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 8624 Vars.push_back((VD || CurContext->isDependentContext()) 8625 ? RefExpr->IgnoreParens() 8626 : Ref); 8627 SrcExprs.push_back(PseudoSrcExpr); 8628 DstExprs.push_back(PseudoDstExpr); 8629 AssignmentOps.push_back(AssignmentOp.get()); 8630 } 8631 8632 if (Vars.empty()) 8633 return nullptr; 8634 8635 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 8636 Vars, SrcExprs, DstExprs, AssignmentOps, 8637 buildPreInits(Context, ExprCaptures), 8638 buildPostUpdate(*this, ExprPostUpdates)); 8639 } 8640 8641 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 8642 SourceLocation StartLoc, 8643 SourceLocation LParenLoc, 8644 SourceLocation EndLoc) { 8645 SmallVector<Expr *, 8> Vars; 8646 for (auto &RefExpr : VarList) { 8647 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 8648 SourceLocation ELoc; 8649 SourceRange ERange; 8650 Expr *SimpleRefExpr = RefExpr; 8651 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8652 if (Res.second) { 8653 // It will be analyzed later. 8654 Vars.push_back(RefExpr); 8655 } 8656 ValueDecl *D = Res.first; 8657 if (!D) 8658 continue; 8659 8660 auto *VD = dyn_cast<VarDecl>(D); 8661 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8662 // in a Construct] 8663 // Variables with the predetermined data-sharing attributes may not be 8664 // listed in data-sharing attributes clauses, except for the cases 8665 // listed below. For these exceptions only, listing a predetermined 8666 // variable in a data-sharing attribute clause is allowed and overrides 8667 // the variable's predetermined data-sharing attributes. 8668 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8669 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 8670 DVar.RefExpr) { 8671 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 8672 << getOpenMPClauseName(OMPC_shared); 8673 ReportOriginalDSA(*this, DSAStack, D, DVar); 8674 continue; 8675 } 8676 8677 DeclRefExpr *Ref = nullptr; 8678 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 8679 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 8680 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 8681 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 8682 ? RefExpr->IgnoreParens() 8683 : Ref); 8684 } 8685 8686 if (Vars.empty()) 8687 return nullptr; 8688 8689 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 8690 } 8691 8692 namespace { 8693 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 8694 DSAStackTy *Stack; 8695 8696 public: 8697 bool VisitDeclRefExpr(DeclRefExpr *E) { 8698 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { 8699 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false); 8700 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 8701 return false; 8702 if (DVar.CKind != OMPC_unknown) 8703 return true; 8704 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 8705 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 8706 false); 8707 if (DVarPrivate.CKind != OMPC_unknown) 8708 return true; 8709 return false; 8710 } 8711 return false; 8712 } 8713 bool VisitStmt(Stmt *S) { 8714 for (auto Child : S->children()) { 8715 if (Child && Visit(Child)) 8716 return true; 8717 } 8718 return false; 8719 } 8720 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 8721 }; 8722 } // namespace 8723 8724 namespace { 8725 // Transform MemberExpression for specified FieldDecl of current class to 8726 // DeclRefExpr to specified OMPCapturedExprDecl. 8727 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 8728 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 8729 ValueDecl *Field; 8730 DeclRefExpr *CapturedExpr; 8731 8732 public: 8733 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 8734 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 8735 8736 ExprResult TransformMemberExpr(MemberExpr *E) { 8737 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 8738 E->getMemberDecl() == Field) { 8739 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 8740 return CapturedExpr; 8741 } 8742 return BaseTransform::TransformMemberExpr(E); 8743 } 8744 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 8745 }; 8746 } // namespace 8747 8748 template <typename T> 8749 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups, 8750 const llvm::function_ref<T(ValueDecl *)> &Gen) { 8751 for (auto &Set : Lookups) { 8752 for (auto *D : Set) { 8753 if (auto Res = Gen(cast<ValueDecl>(D))) 8754 return Res; 8755 } 8756 } 8757 return T(); 8758 } 8759 8760 static ExprResult 8761 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 8762 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 8763 const DeclarationNameInfo &ReductionId, QualType Ty, 8764 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 8765 if (ReductionIdScopeSpec.isInvalid()) 8766 return ExprError(); 8767 SmallVector<UnresolvedSet<8>, 4> Lookups; 8768 if (S) { 8769 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 8770 Lookup.suppressDiagnostics(); 8771 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 8772 auto *D = Lookup.getRepresentativeDecl(); 8773 do { 8774 S = S->getParent(); 8775 } while (S && !S->isDeclScope(D)); 8776 if (S) 8777 S = S->getParent(); 8778 Lookups.push_back(UnresolvedSet<8>()); 8779 Lookups.back().append(Lookup.begin(), Lookup.end()); 8780 Lookup.clear(); 8781 } 8782 } else if (auto *ULE = 8783 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 8784 Lookups.push_back(UnresolvedSet<8>()); 8785 Decl *PrevD = nullptr; 8786 for (auto *D : ULE->decls()) { 8787 if (D == PrevD) 8788 Lookups.push_back(UnresolvedSet<8>()); 8789 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D)) 8790 Lookups.back().addDecl(DRD); 8791 PrevD = D; 8792 } 8793 } 8794 if (Ty->isDependentType() || Ty->isInstantiationDependentType() || 8795 Ty->containsUnexpandedParameterPack() || 8796 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool { 8797 return !D->isInvalidDecl() && 8798 (D->getType()->isDependentType() || 8799 D->getType()->isInstantiationDependentType() || 8800 D->getType()->containsUnexpandedParameterPack()); 8801 })) { 8802 UnresolvedSet<8> ResSet; 8803 for (auto &Set : Lookups) { 8804 ResSet.append(Set.begin(), Set.end()); 8805 // The last item marks the end of all declarations at the specified scope. 8806 ResSet.addDecl(Set[Set.size() - 1]); 8807 } 8808 return UnresolvedLookupExpr::Create( 8809 SemaRef.Context, /*NamingClass=*/nullptr, 8810 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 8811 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 8812 } 8813 if (auto *VD = filterLookupForUDR<ValueDecl *>( 8814 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 8815 if (!D->isInvalidDecl() && 8816 SemaRef.Context.hasSameType(D->getType(), Ty)) 8817 return D; 8818 return nullptr; 8819 })) 8820 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 8821 if (auto *VD = filterLookupForUDR<ValueDecl *>( 8822 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 8823 if (!D->isInvalidDecl() && 8824 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 8825 !Ty.isMoreQualifiedThan(D->getType())) 8826 return D; 8827 return nullptr; 8828 })) { 8829 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 8830 /*DetectVirtual=*/false); 8831 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 8832 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 8833 VD->getType().getUnqualifiedType()))) { 8834 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(), 8835 /*DiagID=*/0) != 8836 Sema::AR_inaccessible) { 8837 SemaRef.BuildBasePathArray(Paths, BasePath); 8838 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 8839 } 8840 } 8841 } 8842 } 8843 if (ReductionIdScopeSpec.isSet()) { 8844 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range; 8845 return ExprError(); 8846 } 8847 return ExprEmpty(); 8848 } 8849 8850 OMPClause *Sema::ActOnOpenMPReductionClause( 8851 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 8852 SourceLocation ColonLoc, SourceLocation EndLoc, 8853 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 8854 ArrayRef<Expr *> UnresolvedReductions) { 8855 auto DN = ReductionId.getName(); 8856 auto OOK = DN.getCXXOverloadedOperator(); 8857 BinaryOperatorKind BOK = BO_Comma; 8858 8859 // OpenMP [2.14.3.6, reduction clause] 8860 // C 8861 // reduction-identifier is either an identifier or one of the following 8862 // operators: +, -, *, &, |, ^, && and || 8863 // C++ 8864 // reduction-identifier is either an id-expression or one of the following 8865 // operators: +, -, *, &, |, ^, && and || 8866 // FIXME: Only 'min' and 'max' identifiers are supported for now. 8867 switch (OOK) { 8868 case OO_Plus: 8869 case OO_Minus: 8870 BOK = BO_Add; 8871 break; 8872 case OO_Star: 8873 BOK = BO_Mul; 8874 break; 8875 case OO_Amp: 8876 BOK = BO_And; 8877 break; 8878 case OO_Pipe: 8879 BOK = BO_Or; 8880 break; 8881 case OO_Caret: 8882 BOK = BO_Xor; 8883 break; 8884 case OO_AmpAmp: 8885 BOK = BO_LAnd; 8886 break; 8887 case OO_PipePipe: 8888 BOK = BO_LOr; 8889 break; 8890 case OO_New: 8891 case OO_Delete: 8892 case OO_Array_New: 8893 case OO_Array_Delete: 8894 case OO_Slash: 8895 case OO_Percent: 8896 case OO_Tilde: 8897 case OO_Exclaim: 8898 case OO_Equal: 8899 case OO_Less: 8900 case OO_Greater: 8901 case OO_LessEqual: 8902 case OO_GreaterEqual: 8903 case OO_PlusEqual: 8904 case OO_MinusEqual: 8905 case OO_StarEqual: 8906 case OO_SlashEqual: 8907 case OO_PercentEqual: 8908 case OO_CaretEqual: 8909 case OO_AmpEqual: 8910 case OO_PipeEqual: 8911 case OO_LessLess: 8912 case OO_GreaterGreater: 8913 case OO_LessLessEqual: 8914 case OO_GreaterGreaterEqual: 8915 case OO_EqualEqual: 8916 case OO_ExclaimEqual: 8917 case OO_PlusPlus: 8918 case OO_MinusMinus: 8919 case OO_Comma: 8920 case OO_ArrowStar: 8921 case OO_Arrow: 8922 case OO_Call: 8923 case OO_Subscript: 8924 case OO_Conditional: 8925 case OO_Coawait: 8926 case NUM_OVERLOADED_OPERATORS: 8927 llvm_unreachable("Unexpected reduction identifier"); 8928 case OO_None: 8929 if (auto II = DN.getAsIdentifierInfo()) { 8930 if (II->isStr("max")) 8931 BOK = BO_GT; 8932 else if (II->isStr("min")) 8933 BOK = BO_LT; 8934 } 8935 break; 8936 } 8937 SourceRange ReductionIdRange; 8938 if (ReductionIdScopeSpec.isValid()) 8939 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 8940 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 8941 8942 SmallVector<Expr *, 8> Vars; 8943 SmallVector<Expr *, 8> Privates; 8944 SmallVector<Expr *, 8> LHSs; 8945 SmallVector<Expr *, 8> RHSs; 8946 SmallVector<Expr *, 8> ReductionOps; 8947 SmallVector<Decl *, 4> ExprCaptures; 8948 SmallVector<Expr *, 4> ExprPostUpdates; 8949 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 8950 bool FirstIter = true; 8951 for (auto RefExpr : VarList) { 8952 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 8953 // OpenMP [2.1, C/C++] 8954 // A list item is a variable or array section, subject to the restrictions 8955 // specified in Section 2.4 on page 42 and in each of the sections 8956 // describing clauses and directives for which a list appears. 8957 // OpenMP [2.14.3.3, Restrictions, p.1] 8958 // A variable that is part of another variable (as an array or 8959 // structure element) cannot appear in a private clause. 8960 if (!FirstIter && IR != ER) 8961 ++IR; 8962 FirstIter = false; 8963 SourceLocation ELoc; 8964 SourceRange ERange; 8965 Expr *SimpleRefExpr = RefExpr; 8966 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 8967 /*AllowArraySection=*/true); 8968 if (Res.second) { 8969 // It will be analyzed later. 8970 Vars.push_back(RefExpr); 8971 Privates.push_back(nullptr); 8972 LHSs.push_back(nullptr); 8973 RHSs.push_back(nullptr); 8974 // Try to find 'declare reduction' corresponding construct before using 8975 // builtin/overloaded operators. 8976 QualType Type = Context.DependentTy; 8977 CXXCastPath BasePath; 8978 ExprResult DeclareReductionRef = buildDeclareReductionRef( 8979 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec, 8980 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 8981 if (CurContext->isDependentContext() && 8982 (DeclareReductionRef.isUnset() || 8983 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 8984 ReductionOps.push_back(DeclareReductionRef.get()); 8985 else 8986 ReductionOps.push_back(nullptr); 8987 } 8988 ValueDecl *D = Res.first; 8989 if (!D) 8990 continue; 8991 8992 QualType Type; 8993 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 8994 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 8995 if (ASE) 8996 Type = ASE->getType().getNonReferenceType(); 8997 else if (OASE) { 8998 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 8999 if (auto *ATy = BaseType->getAsArrayTypeUnsafe()) 9000 Type = ATy->getElementType(); 9001 else 9002 Type = BaseType->getPointeeType(); 9003 Type = Type.getNonReferenceType(); 9004 } else 9005 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 9006 auto *VD = dyn_cast<VarDecl>(D); 9007 9008 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 9009 // A variable that appears in a private clause must not have an incomplete 9010 // type or a reference type. 9011 if (RequireCompleteType(ELoc, Type, 9012 diag::err_omp_reduction_incomplete_type)) 9013 continue; 9014 // OpenMP [2.14.3.6, reduction clause, Restrictions] 9015 // A list item that appears in a reduction clause must not be 9016 // const-qualified. 9017 if (Type.getNonReferenceType().isConstant(Context)) { 9018 Diag(ELoc, diag::err_omp_const_reduction_list_item) 9019 << getOpenMPClauseName(OMPC_reduction) << Type << ERange; 9020 if (!ASE && !OASE) { 9021 bool IsDecl = !VD || 9022 VD->isThisDeclarationADefinition(Context) == 9023 VarDecl::DeclarationOnly; 9024 Diag(D->getLocation(), 9025 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9026 << D; 9027 } 9028 continue; 9029 } 9030 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 9031 // If a list-item is a reference type then it must bind to the same object 9032 // for all threads of the team. 9033 if (!ASE && !OASE && VD) { 9034 VarDecl *VDDef = VD->getDefinition(); 9035 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 9036 DSARefChecker Check(DSAStack); 9037 if (Check.Visit(VDDef->getInit())) { 9038 Diag(ELoc, diag::err_omp_reduction_ref_type_arg) << ERange; 9039 Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 9040 continue; 9041 } 9042 } 9043 } 9044 9045 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 9046 // in a Construct] 9047 // Variables with the predetermined data-sharing attributes may not be 9048 // listed in data-sharing attributes clauses, except for the cases 9049 // listed below. For these exceptions only, listing a predetermined 9050 // variable in a data-sharing attribute clause is allowed and overrides 9051 // the variable's predetermined data-sharing attributes. 9052 // OpenMP [2.14.3.6, Restrictions, p.3] 9053 // Any number of reduction clauses can be specified on the directive, 9054 // but a list item can appear only once in the reduction clauses for that 9055 // directive. 9056 DSAStackTy::DSAVarData DVar; 9057 DVar = DSAStack->getTopDSA(D, false); 9058 if (DVar.CKind == OMPC_reduction) { 9059 Diag(ELoc, diag::err_omp_once_referenced) 9060 << getOpenMPClauseName(OMPC_reduction); 9061 if (DVar.RefExpr) 9062 Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 9063 } else if (DVar.CKind != OMPC_unknown) { 9064 Diag(ELoc, diag::err_omp_wrong_dsa) 9065 << getOpenMPClauseName(DVar.CKind) 9066 << getOpenMPClauseName(OMPC_reduction); 9067 ReportOriginalDSA(*this, DSAStack, D, DVar); 9068 continue; 9069 } 9070 9071 // OpenMP [2.14.3.6, Restrictions, p.1] 9072 // A list item that appears in a reduction clause of a worksharing 9073 // construct must be shared in the parallel regions to which any of the 9074 // worksharing regions arising from the worksharing construct bind. 9075 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 9076 if (isOpenMPWorksharingDirective(CurrDir) && 9077 !isOpenMPParallelDirective(CurrDir) && 9078 !isOpenMPTeamsDirective(CurrDir)) { 9079 DVar = DSAStack->getImplicitDSA(D, true); 9080 if (DVar.CKind != OMPC_shared) { 9081 Diag(ELoc, diag::err_omp_required_access) 9082 << getOpenMPClauseName(OMPC_reduction) 9083 << getOpenMPClauseName(OMPC_shared); 9084 ReportOriginalDSA(*this, DSAStack, D, DVar); 9085 continue; 9086 } 9087 } 9088 9089 // Try to find 'declare reduction' corresponding construct before using 9090 // builtin/overloaded operators. 9091 CXXCastPath BasePath; 9092 ExprResult DeclareReductionRef = buildDeclareReductionRef( 9093 *this, ELoc, ERange, DSAStack->getCurScope(), ReductionIdScopeSpec, 9094 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 9095 if (DeclareReductionRef.isInvalid()) 9096 continue; 9097 if (CurContext->isDependentContext() && 9098 (DeclareReductionRef.isUnset() || 9099 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 9100 Vars.push_back(RefExpr); 9101 Privates.push_back(nullptr); 9102 LHSs.push_back(nullptr); 9103 RHSs.push_back(nullptr); 9104 ReductionOps.push_back(DeclareReductionRef.get()); 9105 continue; 9106 } 9107 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 9108 // Not allowed reduction identifier is found. 9109 Diag(ReductionId.getLocStart(), 9110 diag::err_omp_unknown_reduction_identifier) 9111 << Type << ReductionIdRange; 9112 continue; 9113 } 9114 9115 // OpenMP [2.14.3.6, reduction clause, Restrictions] 9116 // The type of a list item that appears in a reduction clause must be valid 9117 // for the reduction-identifier. For a max or min reduction in C, the type 9118 // of the list item must be an allowed arithmetic data type: char, int, 9119 // float, double, or _Bool, possibly modified with long, short, signed, or 9120 // unsigned. For a max or min reduction in C++, the type of the list item 9121 // must be an allowed arithmetic data type: char, wchar_t, int, float, 9122 // double, or bool, possibly modified with long, short, signed, or unsigned. 9123 if (DeclareReductionRef.isUnset()) { 9124 if ((BOK == BO_GT || BOK == BO_LT) && 9125 !(Type->isScalarType() || 9126 (getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 9127 Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 9128 << getLangOpts().CPlusPlus; 9129 if (!ASE && !OASE) { 9130 bool IsDecl = !VD || 9131 VD->isThisDeclarationADefinition(Context) == 9132 VarDecl::DeclarationOnly; 9133 Diag(D->getLocation(), 9134 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9135 << D; 9136 } 9137 continue; 9138 } 9139 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 9140 !getLangOpts().CPlusPlus && Type->isFloatingType()) { 9141 Diag(ELoc, diag::err_omp_clause_floating_type_arg); 9142 if (!ASE && !OASE) { 9143 bool IsDecl = !VD || 9144 VD->isThisDeclarationADefinition(Context) == 9145 VarDecl::DeclarationOnly; 9146 Diag(D->getLocation(), 9147 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9148 << D; 9149 } 9150 continue; 9151 } 9152 } 9153 9154 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 9155 auto *LHSVD = buildVarDecl(*this, ELoc, Type, ".reduction.lhs", 9156 D->hasAttrs() ? &D->getAttrs() : nullptr); 9157 auto *RHSVD = buildVarDecl(*this, ELoc, Type, D->getName(), 9158 D->hasAttrs() ? &D->getAttrs() : nullptr); 9159 auto PrivateTy = Type; 9160 if (OASE || 9161 (!ASE && 9162 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 9163 // For arrays/array sections only: 9164 // Create pseudo array type for private copy. The size for this array will 9165 // be generated during codegen. 9166 // For array subscripts or single variables Private Ty is the same as Type 9167 // (type of the variable or single array element). 9168 PrivateTy = Context.getVariableArrayType( 9169 Type, new (Context) OpaqueValueExpr(SourceLocation(), 9170 Context.getSizeType(), VK_RValue), 9171 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 9172 } else if (!ASE && !OASE && 9173 Context.getAsArrayType(D->getType().getNonReferenceType())) 9174 PrivateTy = D->getType().getNonReferenceType(); 9175 // Private copy. 9176 auto *PrivateVD = buildVarDecl(*this, ELoc, PrivateTy, D->getName(), 9177 D->hasAttrs() ? &D->getAttrs() : nullptr); 9178 // Add initializer for private variable. 9179 Expr *Init = nullptr; 9180 auto *LHSDRE = buildDeclRefExpr(*this, LHSVD, Type, ELoc); 9181 auto *RHSDRE = buildDeclRefExpr(*this, RHSVD, Type, ELoc); 9182 if (DeclareReductionRef.isUsable()) { 9183 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 9184 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 9185 if (DRD->getInitializer()) { 9186 Init = DRDRef; 9187 RHSVD->setInit(DRDRef); 9188 RHSVD->setInitStyle(VarDecl::CallInit); 9189 } 9190 } else { 9191 switch (BOK) { 9192 case BO_Add: 9193 case BO_Xor: 9194 case BO_Or: 9195 case BO_LOr: 9196 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 9197 if (Type->isScalarType() || Type->isAnyComplexType()) 9198 Init = ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 9199 break; 9200 case BO_Mul: 9201 case BO_LAnd: 9202 if (Type->isScalarType() || Type->isAnyComplexType()) { 9203 // '*' and '&&' reduction ops - initializer is '1'. 9204 Init = ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 9205 } 9206 break; 9207 case BO_And: { 9208 // '&' reduction op - initializer is '~0'. 9209 QualType OrigType = Type; 9210 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 9211 Type = ComplexTy->getElementType(); 9212 if (Type->isRealFloatingType()) { 9213 llvm::APFloat InitValue = 9214 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), 9215 /*isIEEE=*/true); 9216 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 9217 Type, ELoc); 9218 } else if (Type->isScalarType()) { 9219 auto Size = Context.getTypeSize(Type); 9220 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 9221 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 9222 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 9223 } 9224 if (Init && OrigType->isAnyComplexType()) { 9225 // Init = 0xFFFF + 0xFFFFi; 9226 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 9227 Init = CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 9228 } 9229 Type = OrigType; 9230 break; 9231 } 9232 case BO_LT: 9233 case BO_GT: { 9234 // 'min' reduction op - initializer is 'Largest representable number in 9235 // the reduction list item type'. 9236 // 'max' reduction op - initializer is 'Least representable number in 9237 // the reduction list item type'. 9238 if (Type->isIntegerType() || Type->isPointerType()) { 9239 bool IsSigned = Type->hasSignedIntegerRepresentation(); 9240 auto Size = Context.getTypeSize(Type); 9241 QualType IntTy = 9242 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 9243 llvm::APInt InitValue = 9244 (BOK != BO_LT) 9245 ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 9246 : llvm::APInt::getMinValue(Size) 9247 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 9248 : llvm::APInt::getMaxValue(Size); 9249 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 9250 if (Type->isPointerType()) { 9251 // Cast to pointer type. 9252 auto CastExpr = BuildCStyleCastExpr( 9253 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc), 9254 SourceLocation(), Init); 9255 if (CastExpr.isInvalid()) 9256 continue; 9257 Init = CastExpr.get(); 9258 } 9259 } else if (Type->isRealFloatingType()) { 9260 llvm::APFloat InitValue = llvm::APFloat::getLargest( 9261 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 9262 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 9263 Type, ELoc); 9264 } 9265 break; 9266 } 9267 case BO_PtrMemD: 9268 case BO_PtrMemI: 9269 case BO_MulAssign: 9270 case BO_Div: 9271 case BO_Rem: 9272 case BO_Sub: 9273 case BO_Shl: 9274 case BO_Shr: 9275 case BO_LE: 9276 case BO_GE: 9277 case BO_EQ: 9278 case BO_NE: 9279 case BO_AndAssign: 9280 case BO_XorAssign: 9281 case BO_OrAssign: 9282 case BO_Assign: 9283 case BO_AddAssign: 9284 case BO_SubAssign: 9285 case BO_DivAssign: 9286 case BO_RemAssign: 9287 case BO_ShlAssign: 9288 case BO_ShrAssign: 9289 case BO_Comma: 9290 llvm_unreachable("Unexpected reduction operation"); 9291 } 9292 } 9293 if (Init && DeclareReductionRef.isUnset()) { 9294 AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 9295 } else if (!Init) 9296 ActOnUninitializedDecl(RHSVD); 9297 if (RHSVD->isInvalidDecl()) 9298 continue; 9299 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 9300 Diag(ELoc, diag::err_omp_reduction_id_not_compatible) << Type 9301 << ReductionIdRange; 9302 bool IsDecl = 9303 !VD || 9304 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9305 Diag(D->getLocation(), 9306 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9307 << D; 9308 continue; 9309 } 9310 // Store initializer for single element in private copy. Will be used during 9311 // codegen. 9312 PrivateVD->setInit(RHSVD->getInit()); 9313 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 9314 auto *PrivateDRE = buildDeclRefExpr(*this, PrivateVD, PrivateTy, ELoc); 9315 ExprResult ReductionOp; 9316 if (DeclareReductionRef.isUsable()) { 9317 QualType RedTy = DeclareReductionRef.get()->getType(); 9318 QualType PtrRedTy = Context.getPointerType(RedTy); 9319 ExprResult LHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 9320 ExprResult RHS = CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 9321 if (!BasePath.empty()) { 9322 LHS = DefaultLvalueConversion(LHS.get()); 9323 RHS = DefaultLvalueConversion(RHS.get()); 9324 LHS = ImplicitCastExpr::Create(Context, PtrRedTy, 9325 CK_UncheckedDerivedToBase, LHS.get(), 9326 &BasePath, LHS.get()->getValueKind()); 9327 RHS = ImplicitCastExpr::Create(Context, PtrRedTy, 9328 CK_UncheckedDerivedToBase, RHS.get(), 9329 &BasePath, RHS.get()->getValueKind()); 9330 } 9331 FunctionProtoType::ExtProtoInfo EPI; 9332 QualType Params[] = {PtrRedTy, PtrRedTy}; 9333 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 9334 auto *OVE = new (Context) OpaqueValueExpr( 9335 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 9336 DefaultLvalueConversion(DeclareReductionRef.get()).get()); 9337 Expr *Args[] = {LHS.get(), RHS.get()}; 9338 ReductionOp = new (Context) 9339 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); 9340 } else { 9341 ReductionOp = BuildBinOp(DSAStack->getCurScope(), 9342 ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE); 9343 if (ReductionOp.isUsable()) { 9344 if (BOK != BO_LT && BOK != BO_GT) { 9345 ReductionOp = 9346 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), 9347 BO_Assign, LHSDRE, ReductionOp.get()); 9348 } else { 9349 auto *ConditionalOp = new (Context) ConditionalOperator( 9350 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(), 9351 RHSDRE, Type, VK_LValue, OK_Ordinary); 9352 ReductionOp = 9353 BuildBinOp(DSAStack->getCurScope(), ReductionId.getLocStart(), 9354 BO_Assign, LHSDRE, ConditionalOp); 9355 } 9356 ReductionOp = ActOnFinishFullExpr(ReductionOp.get()); 9357 } 9358 if (ReductionOp.isInvalid()) 9359 continue; 9360 } 9361 9362 DeclRefExpr *Ref = nullptr; 9363 Expr *VarsExpr = RefExpr->IgnoreParens(); 9364 if (!VD && !CurContext->isDependentContext()) { 9365 if (ASE || OASE) { 9366 TransformExprToCaptures RebuildToCapture(*this, D); 9367 VarsExpr = 9368 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 9369 Ref = RebuildToCapture.getCapturedExpr(); 9370 } else { 9371 VarsExpr = Ref = 9372 buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 9373 } 9374 if (!IsOpenMPCapturedDecl(D)) { 9375 ExprCaptures.push_back(Ref->getDecl()); 9376 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 9377 ExprResult RefRes = DefaultLvalueConversion(Ref); 9378 if (!RefRes.isUsable()) 9379 continue; 9380 ExprResult PostUpdateRes = 9381 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 9382 SimpleRefExpr, RefRes.get()); 9383 if (!PostUpdateRes.isUsable()) 9384 continue; 9385 ExprPostUpdates.push_back( 9386 IgnoredValueConversions(PostUpdateRes.get()).get()); 9387 } 9388 } 9389 } 9390 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref); 9391 Vars.push_back(VarsExpr); 9392 Privates.push_back(PrivateDRE); 9393 LHSs.push_back(LHSDRE); 9394 RHSs.push_back(RHSDRE); 9395 ReductionOps.push_back(ReductionOp.get()); 9396 } 9397 9398 if (Vars.empty()) 9399 return nullptr; 9400 9401 return OMPReductionClause::Create( 9402 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, Vars, 9403 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, Privates, 9404 LHSs, RHSs, ReductionOps, buildPreInits(Context, ExprCaptures), 9405 buildPostUpdate(*this, ExprPostUpdates)); 9406 } 9407 9408 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 9409 SourceLocation LinLoc) { 9410 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 9411 LinKind == OMPC_LINEAR_unknown) { 9412 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 9413 return true; 9414 } 9415 return false; 9416 } 9417 9418 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc, 9419 OpenMPLinearClauseKind LinKind, 9420 QualType Type) { 9421 auto *VD = dyn_cast_or_null<VarDecl>(D); 9422 // A variable must not have an incomplete type or a reference type. 9423 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 9424 return true; 9425 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 9426 !Type->isReferenceType()) { 9427 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 9428 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 9429 return true; 9430 } 9431 Type = Type.getNonReferenceType(); 9432 9433 // A list item must not be const-qualified. 9434 if (Type.isConstant(Context)) { 9435 Diag(ELoc, diag::err_omp_const_variable) 9436 << getOpenMPClauseName(OMPC_linear); 9437 if (D) { 9438 bool IsDecl = 9439 !VD || 9440 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9441 Diag(D->getLocation(), 9442 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9443 << D; 9444 } 9445 return true; 9446 } 9447 9448 // A list item must be of integral or pointer type. 9449 Type = Type.getUnqualifiedType().getCanonicalType(); 9450 const auto *Ty = Type.getTypePtrOrNull(); 9451 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 9452 !Ty->isPointerType())) { 9453 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 9454 if (D) { 9455 bool IsDecl = 9456 !VD || 9457 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9458 Diag(D->getLocation(), 9459 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9460 << D; 9461 } 9462 return true; 9463 } 9464 return false; 9465 } 9466 9467 OMPClause *Sema::ActOnOpenMPLinearClause( 9468 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 9469 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 9470 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 9471 SmallVector<Expr *, 8> Vars; 9472 SmallVector<Expr *, 8> Privates; 9473 SmallVector<Expr *, 8> Inits; 9474 SmallVector<Decl *, 4> ExprCaptures; 9475 SmallVector<Expr *, 4> ExprPostUpdates; 9476 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 9477 LinKind = OMPC_LINEAR_val; 9478 for (auto &RefExpr : VarList) { 9479 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9480 SourceLocation ELoc; 9481 SourceRange ERange; 9482 Expr *SimpleRefExpr = RefExpr; 9483 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9484 /*AllowArraySection=*/false); 9485 if (Res.second) { 9486 // It will be analyzed later. 9487 Vars.push_back(RefExpr); 9488 Privates.push_back(nullptr); 9489 Inits.push_back(nullptr); 9490 } 9491 ValueDecl *D = Res.first; 9492 if (!D) 9493 continue; 9494 9495 QualType Type = D->getType(); 9496 auto *VD = dyn_cast<VarDecl>(D); 9497 9498 // OpenMP [2.14.3.7, linear clause] 9499 // A list-item cannot appear in more than one linear clause. 9500 // A list-item that appears in a linear clause cannot appear in any 9501 // other data-sharing attribute clause. 9502 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 9503 if (DVar.RefExpr) { 9504 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 9505 << getOpenMPClauseName(OMPC_linear); 9506 ReportOriginalDSA(*this, DSAStack, D, DVar); 9507 continue; 9508 } 9509 9510 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 9511 continue; 9512 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 9513 9514 // Build private copy of original var. 9515 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(), 9516 D->hasAttrs() ? &D->getAttrs() : nullptr); 9517 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 9518 // Build var to save initial value. 9519 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 9520 Expr *InitExpr; 9521 DeclRefExpr *Ref = nullptr; 9522 if (!VD && !CurContext->isDependentContext()) { 9523 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 9524 if (!IsOpenMPCapturedDecl(D)) { 9525 ExprCaptures.push_back(Ref->getDecl()); 9526 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 9527 ExprResult RefRes = DefaultLvalueConversion(Ref); 9528 if (!RefRes.isUsable()) 9529 continue; 9530 ExprResult PostUpdateRes = 9531 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 9532 SimpleRefExpr, RefRes.get()); 9533 if (!PostUpdateRes.isUsable()) 9534 continue; 9535 ExprPostUpdates.push_back( 9536 IgnoredValueConversions(PostUpdateRes.get()).get()); 9537 } 9538 } 9539 } 9540 if (LinKind == OMPC_LINEAR_uval) 9541 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 9542 else 9543 InitExpr = VD ? SimpleRefExpr : Ref; 9544 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 9545 /*DirectInit=*/false); 9546 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 9547 9548 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 9549 Vars.push_back((VD || CurContext->isDependentContext()) 9550 ? RefExpr->IgnoreParens() 9551 : Ref); 9552 Privates.push_back(PrivateRef); 9553 Inits.push_back(InitRef); 9554 } 9555 9556 if (Vars.empty()) 9557 return nullptr; 9558 9559 Expr *StepExpr = Step; 9560 Expr *CalcStepExpr = nullptr; 9561 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 9562 !Step->isInstantiationDependent() && 9563 !Step->containsUnexpandedParameterPack()) { 9564 SourceLocation StepLoc = Step->getLocStart(); 9565 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 9566 if (Val.isInvalid()) 9567 return nullptr; 9568 StepExpr = Val.get(); 9569 9570 // Build var to save the step value. 9571 VarDecl *SaveVar = 9572 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 9573 ExprResult SaveRef = 9574 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 9575 ExprResult CalcStep = 9576 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 9577 CalcStep = ActOnFinishFullExpr(CalcStep.get()); 9578 9579 // Warn about zero linear step (it would be probably better specified as 9580 // making corresponding variables 'const'). 9581 llvm::APSInt Result; 9582 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); 9583 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) 9584 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 9585 << (Vars.size() > 1); 9586 if (!IsConstant && CalcStep.isUsable()) { 9587 // Calculate the step beforehand instead of doing this on each iteration. 9588 // (This is not used if the number of iterations may be kfold-ed). 9589 CalcStepExpr = CalcStep.get(); 9590 } 9591 } 9592 9593 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 9594 ColonLoc, EndLoc, Vars, Privates, Inits, 9595 StepExpr, CalcStepExpr, 9596 buildPreInits(Context, ExprCaptures), 9597 buildPostUpdate(*this, ExprPostUpdates)); 9598 } 9599 9600 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 9601 Expr *NumIterations, Sema &SemaRef, 9602 Scope *S, DSAStackTy *Stack) { 9603 // Walk the vars and build update/final expressions for the CodeGen. 9604 SmallVector<Expr *, 8> Updates; 9605 SmallVector<Expr *, 8> Finals; 9606 Expr *Step = Clause.getStep(); 9607 Expr *CalcStep = Clause.getCalcStep(); 9608 // OpenMP [2.14.3.7, linear clause] 9609 // If linear-step is not specified it is assumed to be 1. 9610 if (Step == nullptr) 9611 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 9612 else if (CalcStep) { 9613 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 9614 } 9615 bool HasErrors = false; 9616 auto CurInit = Clause.inits().begin(); 9617 auto CurPrivate = Clause.privates().begin(); 9618 auto LinKind = Clause.getModifier(); 9619 for (auto &RefExpr : Clause.varlists()) { 9620 SourceLocation ELoc; 9621 SourceRange ERange; 9622 Expr *SimpleRefExpr = RefExpr; 9623 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange, 9624 /*AllowArraySection=*/false); 9625 ValueDecl *D = Res.first; 9626 if (Res.second || !D) { 9627 Updates.push_back(nullptr); 9628 Finals.push_back(nullptr); 9629 HasErrors = true; 9630 continue; 9631 } 9632 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) { 9633 D = cast<MemberExpr>(CED->getInit()->IgnoreParenImpCasts()) 9634 ->getMemberDecl(); 9635 } 9636 auto &&Info = Stack->isLoopControlVariable(D); 9637 Expr *InitExpr = *CurInit; 9638 9639 // Build privatized reference to the current linear var. 9640 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 9641 Expr *CapturedRef; 9642 if (LinKind == OMPC_LINEAR_uval) 9643 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 9644 else 9645 CapturedRef = 9646 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 9647 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 9648 /*RefersToCapture=*/true); 9649 9650 // Build update: Var = InitExpr + IV * Step 9651 ExprResult Update; 9652 if (!Info.first) { 9653 Update = 9654 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, 9655 InitExpr, IV, Step, /* Subtract */ false); 9656 } else 9657 Update = *CurPrivate; 9658 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(), 9659 /*DiscardedValue=*/true); 9660 9661 // Build final: Var = InitExpr + NumIterations * Step 9662 ExprResult Final; 9663 if (!Info.first) { 9664 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 9665 InitExpr, NumIterations, Step, 9666 /* Subtract */ false); 9667 } else 9668 Final = *CurPrivate; 9669 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(), 9670 /*DiscardedValue=*/true); 9671 9672 if (!Update.isUsable() || !Final.isUsable()) { 9673 Updates.push_back(nullptr); 9674 Finals.push_back(nullptr); 9675 HasErrors = true; 9676 } else { 9677 Updates.push_back(Update.get()); 9678 Finals.push_back(Final.get()); 9679 } 9680 ++CurInit; 9681 ++CurPrivate; 9682 } 9683 Clause.setUpdates(Updates); 9684 Clause.setFinals(Finals); 9685 return HasErrors; 9686 } 9687 9688 OMPClause *Sema::ActOnOpenMPAlignedClause( 9689 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 9690 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 9691 9692 SmallVector<Expr *, 8> Vars; 9693 for (auto &RefExpr : VarList) { 9694 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9695 SourceLocation ELoc; 9696 SourceRange ERange; 9697 Expr *SimpleRefExpr = RefExpr; 9698 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9699 /*AllowArraySection=*/false); 9700 if (Res.second) { 9701 // It will be analyzed later. 9702 Vars.push_back(RefExpr); 9703 } 9704 ValueDecl *D = Res.first; 9705 if (!D) 9706 continue; 9707 9708 QualType QType = D->getType(); 9709 auto *VD = dyn_cast<VarDecl>(D); 9710 9711 // OpenMP [2.8.1, simd construct, Restrictions] 9712 // The type of list items appearing in the aligned clause must be 9713 // array, pointer, reference to array, or reference to pointer. 9714 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 9715 const Type *Ty = QType.getTypePtrOrNull(); 9716 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 9717 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 9718 << QType << getLangOpts().CPlusPlus << ERange; 9719 bool IsDecl = 9720 !VD || 9721 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9722 Diag(D->getLocation(), 9723 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9724 << D; 9725 continue; 9726 } 9727 9728 // OpenMP [2.8.1, simd construct, Restrictions] 9729 // A list-item cannot appear in more than one aligned clause. 9730 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 9731 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange; 9732 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 9733 << getOpenMPClauseName(OMPC_aligned); 9734 continue; 9735 } 9736 9737 DeclRefExpr *Ref = nullptr; 9738 if (!VD && IsOpenMPCapturedDecl(D)) 9739 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 9740 Vars.push_back(DefaultFunctionArrayConversion( 9741 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 9742 .get()); 9743 } 9744 9745 // OpenMP [2.8.1, simd construct, Description] 9746 // The parameter of the aligned clause, alignment, must be a constant 9747 // positive integer expression. 9748 // If no optional parameter is specified, implementation-defined default 9749 // alignments for SIMD instructions on the target platforms are assumed. 9750 if (Alignment != nullptr) { 9751 ExprResult AlignResult = 9752 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 9753 if (AlignResult.isInvalid()) 9754 return nullptr; 9755 Alignment = AlignResult.get(); 9756 } 9757 if (Vars.empty()) 9758 return nullptr; 9759 9760 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 9761 EndLoc, Vars, Alignment); 9762 } 9763 9764 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 9765 SourceLocation StartLoc, 9766 SourceLocation LParenLoc, 9767 SourceLocation EndLoc) { 9768 SmallVector<Expr *, 8> Vars; 9769 SmallVector<Expr *, 8> SrcExprs; 9770 SmallVector<Expr *, 8> DstExprs; 9771 SmallVector<Expr *, 8> AssignmentOps; 9772 for (auto &RefExpr : VarList) { 9773 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 9774 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 9775 // It will be analyzed later. 9776 Vars.push_back(RefExpr); 9777 SrcExprs.push_back(nullptr); 9778 DstExprs.push_back(nullptr); 9779 AssignmentOps.push_back(nullptr); 9780 continue; 9781 } 9782 9783 SourceLocation ELoc = RefExpr->getExprLoc(); 9784 // OpenMP [2.1, C/C++] 9785 // A list item is a variable name. 9786 // OpenMP [2.14.4.1, Restrictions, p.1] 9787 // A list item that appears in a copyin clause must be threadprivate. 9788 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 9789 if (!DE || !isa<VarDecl>(DE->getDecl())) { 9790 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 9791 << 0 << RefExpr->getSourceRange(); 9792 continue; 9793 } 9794 9795 Decl *D = DE->getDecl(); 9796 VarDecl *VD = cast<VarDecl>(D); 9797 9798 QualType Type = VD->getType(); 9799 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 9800 // It will be analyzed later. 9801 Vars.push_back(DE); 9802 SrcExprs.push_back(nullptr); 9803 DstExprs.push_back(nullptr); 9804 AssignmentOps.push_back(nullptr); 9805 continue; 9806 } 9807 9808 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 9809 // A list item that appears in a copyin clause must be threadprivate. 9810 if (!DSAStack->isThreadPrivate(VD)) { 9811 Diag(ELoc, diag::err_omp_required_access) 9812 << getOpenMPClauseName(OMPC_copyin) 9813 << getOpenMPDirectiveName(OMPD_threadprivate); 9814 continue; 9815 } 9816 9817 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 9818 // A variable of class type (or array thereof) that appears in a 9819 // copyin clause requires an accessible, unambiguous copy assignment 9820 // operator for the class type. 9821 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 9822 auto *SrcVD = 9823 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(), 9824 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 9825 auto *PseudoSrcExpr = buildDeclRefExpr( 9826 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 9827 auto *DstVD = 9828 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst", 9829 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 9830 auto *PseudoDstExpr = 9831 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 9832 // For arrays generate assignment operation for single element and replace 9833 // it by the original array element in CodeGen. 9834 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, 9835 PseudoDstExpr, PseudoSrcExpr); 9836 if (AssignmentOp.isInvalid()) 9837 continue; 9838 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 9839 /*DiscardedValue=*/true); 9840 if (AssignmentOp.isInvalid()) 9841 continue; 9842 9843 DSAStack->addDSA(VD, DE, OMPC_copyin); 9844 Vars.push_back(DE); 9845 SrcExprs.push_back(PseudoSrcExpr); 9846 DstExprs.push_back(PseudoDstExpr); 9847 AssignmentOps.push_back(AssignmentOp.get()); 9848 } 9849 9850 if (Vars.empty()) 9851 return nullptr; 9852 9853 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 9854 SrcExprs, DstExprs, AssignmentOps); 9855 } 9856 9857 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 9858 SourceLocation StartLoc, 9859 SourceLocation LParenLoc, 9860 SourceLocation EndLoc) { 9861 SmallVector<Expr *, 8> Vars; 9862 SmallVector<Expr *, 8> SrcExprs; 9863 SmallVector<Expr *, 8> DstExprs; 9864 SmallVector<Expr *, 8> AssignmentOps; 9865 for (auto &RefExpr : VarList) { 9866 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9867 SourceLocation ELoc; 9868 SourceRange ERange; 9869 Expr *SimpleRefExpr = RefExpr; 9870 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9871 /*AllowArraySection=*/false); 9872 if (Res.second) { 9873 // It will be analyzed later. 9874 Vars.push_back(RefExpr); 9875 SrcExprs.push_back(nullptr); 9876 DstExprs.push_back(nullptr); 9877 AssignmentOps.push_back(nullptr); 9878 } 9879 ValueDecl *D = Res.first; 9880 if (!D) 9881 continue; 9882 9883 QualType Type = D->getType(); 9884 auto *VD = dyn_cast<VarDecl>(D); 9885 9886 // OpenMP [2.14.4.2, Restrictions, p.2] 9887 // A list item that appears in a copyprivate clause may not appear in a 9888 // private or firstprivate clause on the single construct. 9889 if (!VD || !DSAStack->isThreadPrivate(VD)) { 9890 auto DVar = DSAStack->getTopDSA(D, false); 9891 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 9892 DVar.RefExpr) { 9893 Diag(ELoc, diag::err_omp_wrong_dsa) 9894 << getOpenMPClauseName(DVar.CKind) 9895 << getOpenMPClauseName(OMPC_copyprivate); 9896 ReportOriginalDSA(*this, DSAStack, D, DVar); 9897 continue; 9898 } 9899 9900 // OpenMP [2.11.4.2, Restrictions, p.1] 9901 // All list items that appear in a copyprivate clause must be either 9902 // threadprivate or private in the enclosing context. 9903 if (DVar.CKind == OMPC_unknown) { 9904 DVar = DSAStack->getImplicitDSA(D, false); 9905 if (DVar.CKind == OMPC_shared) { 9906 Diag(ELoc, diag::err_omp_required_access) 9907 << getOpenMPClauseName(OMPC_copyprivate) 9908 << "threadprivate or private in the enclosing context"; 9909 ReportOriginalDSA(*this, DSAStack, D, DVar); 9910 continue; 9911 } 9912 } 9913 } 9914 9915 // Variably modified types are not supported. 9916 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 9917 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 9918 << getOpenMPClauseName(OMPC_copyprivate) << Type 9919 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 9920 bool IsDecl = 9921 !VD || 9922 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9923 Diag(D->getLocation(), 9924 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9925 << D; 9926 continue; 9927 } 9928 9929 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 9930 // A variable of class type (or array thereof) that appears in a 9931 // copyin clause requires an accessible, unambiguous copy assignment 9932 // operator for the class type. 9933 Type = Context.getBaseElementType(Type.getNonReferenceType()) 9934 .getUnqualifiedType(); 9935 auto *SrcVD = 9936 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src", 9937 D->hasAttrs() ? &D->getAttrs() : nullptr); 9938 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 9939 auto *DstVD = 9940 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst", 9941 D->hasAttrs() ? &D->getAttrs() : nullptr); 9942 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 9943 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 9944 PseudoDstExpr, PseudoSrcExpr); 9945 if (AssignmentOp.isInvalid()) 9946 continue; 9947 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 9948 /*DiscardedValue=*/true); 9949 if (AssignmentOp.isInvalid()) 9950 continue; 9951 9952 // No need to mark vars as copyprivate, they are already threadprivate or 9953 // implicitly private. 9954 assert(VD || IsOpenMPCapturedDecl(D)); 9955 Vars.push_back( 9956 VD ? RefExpr->IgnoreParens() 9957 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 9958 SrcExprs.push_back(PseudoSrcExpr); 9959 DstExprs.push_back(PseudoDstExpr); 9960 AssignmentOps.push_back(AssignmentOp.get()); 9961 } 9962 9963 if (Vars.empty()) 9964 return nullptr; 9965 9966 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 9967 Vars, SrcExprs, DstExprs, AssignmentOps); 9968 } 9969 9970 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 9971 SourceLocation StartLoc, 9972 SourceLocation LParenLoc, 9973 SourceLocation EndLoc) { 9974 if (VarList.empty()) 9975 return nullptr; 9976 9977 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 9978 } 9979 9980 OMPClause * 9981 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, 9982 SourceLocation DepLoc, SourceLocation ColonLoc, 9983 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 9984 SourceLocation LParenLoc, SourceLocation EndLoc) { 9985 if (DSAStack->getCurrentDirective() == OMPD_ordered && 9986 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 9987 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 9988 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 9989 return nullptr; 9990 } 9991 if (DSAStack->getCurrentDirective() != OMPD_ordered && 9992 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 9993 DepKind == OMPC_DEPEND_sink)) { 9994 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink}; 9995 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 9996 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 9997 /*Last=*/OMPC_DEPEND_unknown, Except) 9998 << getOpenMPClauseName(OMPC_depend); 9999 return nullptr; 10000 } 10001 SmallVector<Expr *, 8> Vars; 10002 DSAStackTy::OperatorOffsetTy OpsOffs; 10003 llvm::APSInt DepCounter(/*BitWidth=*/32); 10004 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 10005 if (DepKind == OMPC_DEPEND_sink) { 10006 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) { 10007 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 10008 TotalDepCount.setIsUnsigned(/*Val=*/true); 10009 } 10010 } 10011 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) || 10012 DSAStack->getParentOrderedRegionParam()) { 10013 for (auto &RefExpr : VarList) { 10014 assert(RefExpr && "NULL expr in OpenMP shared clause."); 10015 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 10016 // It will be analyzed later. 10017 Vars.push_back(RefExpr); 10018 continue; 10019 } 10020 10021 SourceLocation ELoc = RefExpr->getExprLoc(); 10022 auto *SimpleExpr = RefExpr->IgnoreParenCasts(); 10023 if (DepKind == OMPC_DEPEND_sink) { 10024 if (DepCounter >= TotalDepCount) { 10025 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 10026 continue; 10027 } 10028 ++DepCounter; 10029 // OpenMP [2.13.9, Summary] 10030 // depend(dependence-type : vec), where dependence-type is: 10031 // 'sink' and where vec is the iteration vector, which has the form: 10032 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 10033 // where n is the value specified by the ordered clause in the loop 10034 // directive, xi denotes the loop iteration variable of the i-th nested 10035 // loop associated with the loop directive, and di is a constant 10036 // non-negative integer. 10037 if (CurContext->isDependentContext()) { 10038 // It will be analyzed later. 10039 Vars.push_back(RefExpr); 10040 continue; 10041 } 10042 SimpleExpr = SimpleExpr->IgnoreImplicit(); 10043 OverloadedOperatorKind OOK = OO_None; 10044 SourceLocation OOLoc; 10045 Expr *LHS = SimpleExpr; 10046 Expr *RHS = nullptr; 10047 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 10048 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 10049 OOLoc = BO->getOperatorLoc(); 10050 LHS = BO->getLHS()->IgnoreParenImpCasts(); 10051 RHS = BO->getRHS()->IgnoreParenImpCasts(); 10052 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 10053 OOK = OCE->getOperator(); 10054 OOLoc = OCE->getOperatorLoc(); 10055 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 10056 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 10057 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 10058 OOK = MCE->getMethodDecl() 10059 ->getNameInfo() 10060 .getName() 10061 .getCXXOverloadedOperator(); 10062 OOLoc = MCE->getCallee()->getExprLoc(); 10063 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 10064 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 10065 } 10066 SourceLocation ELoc; 10067 SourceRange ERange; 10068 auto Res = getPrivateItem(*this, LHS, ELoc, ERange, 10069 /*AllowArraySection=*/false); 10070 if (Res.second) { 10071 // It will be analyzed later. 10072 Vars.push_back(RefExpr); 10073 } 10074 ValueDecl *D = Res.first; 10075 if (!D) 10076 continue; 10077 10078 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 10079 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 10080 continue; 10081 } 10082 if (RHS) { 10083 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 10084 RHS, OMPC_depend, /*StrictlyPositive=*/false); 10085 if (RHSRes.isInvalid()) 10086 continue; 10087 } 10088 if (!CurContext->isDependentContext() && 10089 DSAStack->getParentOrderedRegionParam() && 10090 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 10091 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 10092 << DSAStack->getParentLoopControlVariable( 10093 DepCounter.getZExtValue()); 10094 continue; 10095 } 10096 OpsOffs.push_back({RHS, OOK}); 10097 } else { 10098 // OpenMP [2.11.1.1, Restrictions, p.3] 10099 // A variable that is part of another variable (such as a field of a 10100 // structure) but is not an array element or an array section cannot 10101 // appear in a depend clause. 10102 auto *DE = dyn_cast<DeclRefExpr>(SimpleExpr); 10103 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 10104 auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr); 10105 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 10106 (!ASE && !DE && !OASE) || (DE && !isa<VarDecl>(DE->getDecl())) || 10107 (ASE && 10108 !ASE->getBase() 10109 ->getType() 10110 .getNonReferenceType() 10111 ->isPointerType() && 10112 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 10113 Diag(ELoc, diag::err_omp_expected_var_name_member_expr_or_array_item) 10114 << 0 << RefExpr->getSourceRange(); 10115 continue; 10116 } 10117 } 10118 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 10119 } 10120 10121 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 10122 TotalDepCount > VarList.size() && 10123 DSAStack->getParentOrderedRegionParam()) { 10124 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) 10125 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 10126 } 10127 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 10128 Vars.empty()) 10129 return nullptr; 10130 } 10131 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10132 DepKind, DepLoc, ColonLoc, Vars); 10133 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) 10134 DSAStack->addDoacrossDependClause(C, OpsOffs); 10135 return C; 10136 } 10137 10138 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, 10139 SourceLocation LParenLoc, 10140 SourceLocation EndLoc) { 10141 Expr *ValExpr = Device; 10142 10143 // OpenMP [2.9.1, Restrictions] 10144 // The device expression must evaluate to a non-negative integer value. 10145 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 10146 /*StrictlyPositive=*/false)) 10147 return nullptr; 10148 10149 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc); 10150 } 10151 10152 static bool IsCXXRecordForMappable(Sema &SemaRef, SourceLocation Loc, 10153 DSAStackTy *Stack, CXXRecordDecl *RD) { 10154 if (!RD || RD->isInvalidDecl()) 10155 return true; 10156 10157 auto QTy = SemaRef.Context.getRecordType(RD); 10158 if (RD->isDynamicClass()) { 10159 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 10160 SemaRef.Diag(RD->getLocation(), diag::note_omp_polymorphic_in_target); 10161 return false; 10162 } 10163 auto *DC = RD; 10164 bool IsCorrect = true; 10165 for (auto *I : DC->decls()) { 10166 if (I) { 10167 if (auto *MD = dyn_cast<CXXMethodDecl>(I)) { 10168 if (MD->isStatic()) { 10169 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 10170 SemaRef.Diag(MD->getLocation(), 10171 diag::note_omp_static_member_in_target); 10172 IsCorrect = false; 10173 } 10174 } else if (auto *VD = dyn_cast<VarDecl>(I)) { 10175 if (VD->isStaticDataMember()) { 10176 SemaRef.Diag(Loc, diag::err_omp_not_mappable_type) << QTy; 10177 SemaRef.Diag(VD->getLocation(), 10178 diag::note_omp_static_member_in_target); 10179 IsCorrect = false; 10180 } 10181 } 10182 } 10183 } 10184 10185 for (auto &I : RD->bases()) { 10186 if (!IsCXXRecordForMappable(SemaRef, I.getLocStart(), Stack, 10187 I.getType()->getAsCXXRecordDecl())) 10188 IsCorrect = false; 10189 } 10190 return IsCorrect; 10191 } 10192 10193 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 10194 DSAStackTy *Stack, QualType QTy) { 10195 NamedDecl *ND; 10196 if (QTy->isIncompleteType(&ND)) { 10197 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 10198 return false; 10199 } else if (CXXRecordDecl *RD = dyn_cast_or_null<CXXRecordDecl>(ND)) { 10200 if (!RD->isInvalidDecl() && !IsCXXRecordForMappable(SemaRef, SL, Stack, RD)) 10201 return false; 10202 } 10203 return true; 10204 } 10205 10206 /// \brief Return true if it can be proven that the provided array expression 10207 /// (array section or array subscript) does NOT specify the whole size of the 10208 /// array whose base type is \a BaseQTy. 10209 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 10210 const Expr *E, 10211 QualType BaseQTy) { 10212 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 10213 10214 // If this is an array subscript, it refers to the whole size if the size of 10215 // the dimension is constant and equals 1. Also, an array section assumes the 10216 // format of an array subscript if no colon is used. 10217 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) { 10218 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 10219 return ATy->getSize().getSExtValue() != 1; 10220 // Size can't be evaluated statically. 10221 return false; 10222 } 10223 10224 assert(OASE && "Expecting array section if not an array subscript."); 10225 auto *LowerBound = OASE->getLowerBound(); 10226 auto *Length = OASE->getLength(); 10227 10228 // If there is a lower bound that does not evaluates to zero, we are not 10229 // covering the whole dimension. 10230 if (LowerBound) { 10231 llvm::APSInt ConstLowerBound; 10232 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext())) 10233 return false; // Can't get the integer value as a constant. 10234 if (ConstLowerBound.getSExtValue()) 10235 return true; 10236 } 10237 10238 // If we don't have a length we covering the whole dimension. 10239 if (!Length) 10240 return false; 10241 10242 // If the base is a pointer, we don't have a way to get the size of the 10243 // pointee. 10244 if (BaseQTy->isPointerType()) 10245 return false; 10246 10247 // We can only check if the length is the same as the size of the dimension 10248 // if we have a constant array. 10249 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 10250 if (!CATy) 10251 return false; 10252 10253 llvm::APSInt ConstLength; 10254 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 10255 return false; // Can't get the integer value as a constant. 10256 10257 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 10258 } 10259 10260 // Return true if it can be proven that the provided array expression (array 10261 // section or array subscript) does NOT specify a single element of the array 10262 // whose base type is \a BaseQTy. 10263 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 10264 const Expr *E, 10265 QualType BaseQTy) { 10266 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 10267 10268 // An array subscript always refer to a single element. Also, an array section 10269 // assumes the format of an array subscript if no colon is used. 10270 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) 10271 return false; 10272 10273 assert(OASE && "Expecting array section if not an array subscript."); 10274 auto *Length = OASE->getLength(); 10275 10276 // If we don't have a length we have to check if the array has unitary size 10277 // for this dimension. Also, we should always expect a length if the base type 10278 // is pointer. 10279 if (!Length) { 10280 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 10281 return ATy->getSize().getSExtValue() != 1; 10282 // We cannot assume anything. 10283 return false; 10284 } 10285 10286 // Check if the length evaluates to 1. 10287 llvm::APSInt ConstLength; 10288 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 10289 return false; // Can't get the integer value as a constant. 10290 10291 return ConstLength.getSExtValue() != 1; 10292 } 10293 10294 // Return the expression of the base of the mappable expression or null if it 10295 // cannot be determined and do all the necessary checks to see if the expression 10296 // is valid as a standalone mappable expression. In the process, record all the 10297 // components of the expression. 10298 static Expr *CheckMapClauseExpressionBase( 10299 Sema &SemaRef, Expr *E, 10300 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 10301 OpenMPClauseKind CKind) { 10302 SourceLocation ELoc = E->getExprLoc(); 10303 SourceRange ERange = E->getSourceRange(); 10304 10305 // The base of elements of list in a map clause have to be either: 10306 // - a reference to variable or field. 10307 // - a member expression. 10308 // - an array expression. 10309 // 10310 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 10311 // reference to 'r'. 10312 // 10313 // If we have: 10314 // 10315 // struct SS { 10316 // Bla S; 10317 // foo() { 10318 // #pragma omp target map (S.Arr[:12]); 10319 // } 10320 // } 10321 // 10322 // We want to retrieve the member expression 'this->S'; 10323 10324 Expr *RelevantExpr = nullptr; 10325 10326 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2] 10327 // If a list item is an array section, it must specify contiguous storage. 10328 // 10329 // For this restriction it is sufficient that we make sure only references 10330 // to variables or fields and array expressions, and that no array sections 10331 // exist except in the rightmost expression (unless they cover the whole 10332 // dimension of the array). E.g. these would be invalid: 10333 // 10334 // r.ArrS[3:5].Arr[6:7] 10335 // 10336 // r.ArrS[3:5].x 10337 // 10338 // but these would be valid: 10339 // r.ArrS[3].Arr[6:7] 10340 // 10341 // r.ArrS[3].x 10342 10343 bool AllowUnitySizeArraySection = true; 10344 bool AllowWholeSizeArraySection = true; 10345 10346 while (!RelevantExpr) { 10347 E = E->IgnoreParenImpCasts(); 10348 10349 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) { 10350 if (!isa<VarDecl>(CurE->getDecl())) 10351 break; 10352 10353 RelevantExpr = CurE; 10354 10355 // If we got a reference to a declaration, we should not expect any array 10356 // section before that. 10357 AllowUnitySizeArraySection = false; 10358 AllowWholeSizeArraySection = false; 10359 10360 // Record the component. 10361 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent( 10362 CurE, CurE->getDecl())); 10363 continue; 10364 } 10365 10366 if (auto *CurE = dyn_cast<MemberExpr>(E)) { 10367 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts(); 10368 10369 if (isa<CXXThisExpr>(BaseE)) 10370 // We found a base expression: this->Val. 10371 RelevantExpr = CurE; 10372 else 10373 E = BaseE; 10374 10375 if (!isa<FieldDecl>(CurE->getMemberDecl())) { 10376 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 10377 << CurE->getSourceRange(); 10378 break; 10379 } 10380 10381 auto *FD = cast<FieldDecl>(CurE->getMemberDecl()); 10382 10383 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 10384 // A bit-field cannot appear in a map clause. 10385 // 10386 if (FD->isBitField()) { 10387 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 10388 << CurE->getSourceRange() << getOpenMPClauseName(CKind); 10389 break; 10390 } 10391 10392 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10393 // If the type of a list item is a reference to a type T then the type 10394 // will be considered to be T for all purposes of this clause. 10395 QualType CurType = BaseE->getType().getNonReferenceType(); 10396 10397 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 10398 // A list item cannot be a variable that is a member of a structure with 10399 // a union type. 10400 // 10401 if (auto *RT = CurType->getAs<RecordType>()) 10402 if (RT->isUnionType()) { 10403 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 10404 << CurE->getSourceRange(); 10405 break; 10406 } 10407 10408 // If we got a member expression, we should not expect any array section 10409 // before that: 10410 // 10411 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 10412 // If a list item is an element of a structure, only the rightmost symbol 10413 // of the variable reference can be an array section. 10414 // 10415 AllowUnitySizeArraySection = false; 10416 AllowWholeSizeArraySection = false; 10417 10418 // Record the component. 10419 CurComponents.push_back( 10420 OMPClauseMappableExprCommon::MappableComponent(CurE, FD)); 10421 continue; 10422 } 10423 10424 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) { 10425 E = CurE->getBase()->IgnoreParenImpCasts(); 10426 10427 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 10428 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 10429 << 0 << CurE->getSourceRange(); 10430 break; 10431 } 10432 10433 // If we got an array subscript that express the whole dimension we 10434 // can have any array expressions before. If it only expressing part of 10435 // the dimension, we can only have unitary-size array expressions. 10436 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, 10437 E->getType())) 10438 AllowWholeSizeArraySection = false; 10439 10440 // Record the component - we don't have any declaration associated. 10441 CurComponents.push_back( 10442 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 10443 continue; 10444 } 10445 10446 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) { 10447 E = CurE->getBase()->IgnoreParenImpCasts(); 10448 10449 auto CurType = 10450 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 10451 10452 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10453 // If the type of a list item is a reference to a type T then the type 10454 // will be considered to be T for all purposes of this clause. 10455 if (CurType->isReferenceType()) 10456 CurType = CurType->getPointeeType(); 10457 10458 bool IsPointer = CurType->isAnyPointerType(); 10459 10460 if (!IsPointer && !CurType->isArrayType()) { 10461 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 10462 << 0 << CurE->getSourceRange(); 10463 break; 10464 } 10465 10466 bool NotWhole = 10467 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType); 10468 bool NotUnity = 10469 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType); 10470 10471 if (AllowWholeSizeArraySection) { 10472 // Any array section is currently allowed. Allowing a whole size array 10473 // section implies allowing a unity array section as well. 10474 // 10475 // If this array section refers to the whole dimension we can still 10476 // accept other array sections before this one, except if the base is a 10477 // pointer. Otherwise, only unitary sections are accepted. 10478 if (NotWhole || IsPointer) 10479 AllowWholeSizeArraySection = false; 10480 } else if (AllowUnitySizeArraySection && NotUnity) { 10481 // A unity or whole array section is not allowed and that is not 10482 // compatible with the properties of the current array section. 10483 SemaRef.Diag( 10484 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 10485 << CurE->getSourceRange(); 10486 break; 10487 } 10488 10489 // Record the component - we don't have any declaration associated. 10490 CurComponents.push_back( 10491 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 10492 continue; 10493 } 10494 10495 // If nothing else worked, this is not a valid map clause expression. 10496 SemaRef.Diag(ELoc, 10497 diag::err_omp_expected_named_var_member_or_array_expression) 10498 << ERange; 10499 break; 10500 } 10501 10502 return RelevantExpr; 10503 } 10504 10505 // Return true if expression E associated with value VD has conflicts with other 10506 // map information. 10507 static bool CheckMapConflicts( 10508 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E, 10509 bool CurrentRegionOnly, 10510 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 10511 OpenMPClauseKind CKind) { 10512 assert(VD && E); 10513 SourceLocation ELoc = E->getExprLoc(); 10514 SourceRange ERange = E->getSourceRange(); 10515 10516 // In order to easily check the conflicts we need to match each component of 10517 // the expression under test with the components of the expressions that are 10518 // already in the stack. 10519 10520 assert(!CurComponents.empty() && "Map clause expression with no components!"); 10521 assert(CurComponents.back().getAssociatedDeclaration() == VD && 10522 "Map clause expression with unexpected base!"); 10523 10524 // Variables to help detecting enclosing problems in data environment nests. 10525 bool IsEnclosedByDataEnvironmentExpr = false; 10526 const Expr *EnclosingExpr = nullptr; 10527 10528 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 10529 VD, CurrentRegionOnly, 10530 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 10531 StackComponents, 10532 OpenMPClauseKind) -> bool { 10533 10534 assert(!StackComponents.empty() && 10535 "Map clause expression with no components!"); 10536 assert(StackComponents.back().getAssociatedDeclaration() == VD && 10537 "Map clause expression with unexpected base!"); 10538 10539 // The whole expression in the stack. 10540 auto *RE = StackComponents.front().getAssociatedExpression(); 10541 10542 // Expressions must start from the same base. Here we detect at which 10543 // point both expressions diverge from each other and see if we can 10544 // detect if the memory referred to both expressions is contiguous and 10545 // do not overlap. 10546 auto CI = CurComponents.rbegin(); 10547 auto CE = CurComponents.rend(); 10548 auto SI = StackComponents.rbegin(); 10549 auto SE = StackComponents.rend(); 10550 for (; CI != CE && SI != SE; ++CI, ++SI) { 10551 10552 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 10553 // At most one list item can be an array item derived from a given 10554 // variable in map clauses of the same construct. 10555 if (CurrentRegionOnly && 10556 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 10557 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) && 10558 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 10559 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) { 10560 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 10561 diag::err_omp_multiple_array_items_in_map_clause) 10562 << CI->getAssociatedExpression()->getSourceRange(); 10563 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 10564 diag::note_used_here) 10565 << SI->getAssociatedExpression()->getSourceRange(); 10566 return true; 10567 } 10568 10569 // Do both expressions have the same kind? 10570 if (CI->getAssociatedExpression()->getStmtClass() != 10571 SI->getAssociatedExpression()->getStmtClass()) 10572 break; 10573 10574 // Are we dealing with different variables/fields? 10575 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 10576 break; 10577 } 10578 // Check if the extra components of the expressions in the enclosing 10579 // data environment are redundant for the current base declaration. 10580 // If they are, the maps completely overlap, which is legal. 10581 for (; SI != SE; ++SI) { 10582 QualType Type; 10583 if (auto *ASE = 10584 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 10585 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 10586 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>( 10587 SI->getAssociatedExpression())) { 10588 auto *E = OASE->getBase()->IgnoreParenImpCasts(); 10589 Type = 10590 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 10591 } 10592 if (Type.isNull() || Type->isAnyPointerType() || 10593 CheckArrayExpressionDoesNotReferToWholeSize( 10594 SemaRef, SI->getAssociatedExpression(), Type)) 10595 break; 10596 } 10597 10598 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 10599 // List items of map clauses in the same construct must not share 10600 // original storage. 10601 // 10602 // If the expressions are exactly the same or one is a subset of the 10603 // other, it means they are sharing storage. 10604 if (CI == CE && SI == SE) { 10605 if (CurrentRegionOnly) { 10606 if (CKind == OMPC_map) 10607 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 10608 else { 10609 assert(CKind == OMPC_to || CKind == OMPC_from); 10610 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 10611 << ERange; 10612 } 10613 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10614 << RE->getSourceRange(); 10615 return true; 10616 } else { 10617 // If we find the same expression in the enclosing data environment, 10618 // that is legal. 10619 IsEnclosedByDataEnvironmentExpr = true; 10620 return false; 10621 } 10622 } 10623 10624 QualType DerivedType = 10625 std::prev(CI)->getAssociatedDeclaration()->getType(); 10626 SourceLocation DerivedLoc = 10627 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 10628 10629 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10630 // If the type of a list item is a reference to a type T then the type 10631 // will be considered to be T for all purposes of this clause. 10632 DerivedType = DerivedType.getNonReferenceType(); 10633 10634 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 10635 // A variable for which the type is pointer and an array section 10636 // derived from that variable must not appear as list items of map 10637 // clauses of the same construct. 10638 // 10639 // Also, cover one of the cases in: 10640 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 10641 // If any part of the original storage of a list item has corresponding 10642 // storage in the device data environment, all of the original storage 10643 // must have corresponding storage in the device data environment. 10644 // 10645 if (DerivedType->isAnyPointerType()) { 10646 if (CI == CE || SI == SE) { 10647 SemaRef.Diag( 10648 DerivedLoc, 10649 diag::err_omp_pointer_mapped_along_with_derived_section) 10650 << DerivedLoc; 10651 } else { 10652 assert(CI != CE && SI != SE); 10653 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced) 10654 << DerivedLoc; 10655 } 10656 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10657 << RE->getSourceRange(); 10658 return true; 10659 } 10660 10661 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 10662 // List items of map clauses in the same construct must not share 10663 // original storage. 10664 // 10665 // An expression is a subset of the other. 10666 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 10667 if (CKind == OMPC_map) 10668 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 10669 else { 10670 assert(CKind == OMPC_to || CKind == OMPC_from); 10671 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 10672 << ERange; 10673 } 10674 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 10675 << RE->getSourceRange(); 10676 return true; 10677 } 10678 10679 // The current expression uses the same base as other expression in the 10680 // data environment but does not contain it completely. 10681 if (!CurrentRegionOnly && SI != SE) 10682 EnclosingExpr = RE; 10683 10684 // The current expression is a subset of the expression in the data 10685 // environment. 10686 IsEnclosedByDataEnvironmentExpr |= 10687 (!CurrentRegionOnly && CI != CE && SI == SE); 10688 10689 return false; 10690 }); 10691 10692 if (CurrentRegionOnly) 10693 return FoundError; 10694 10695 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 10696 // If any part of the original storage of a list item has corresponding 10697 // storage in the device data environment, all of the original storage must 10698 // have corresponding storage in the device data environment. 10699 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 10700 // If a list item is an element of a structure, and a different element of 10701 // the structure has a corresponding list item in the device data environment 10702 // prior to a task encountering the construct associated with the map clause, 10703 // then the list item must also have a corresponding list item in the device 10704 // data environment prior to the task encountering the construct. 10705 // 10706 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 10707 SemaRef.Diag(ELoc, 10708 diag::err_omp_original_storage_is_shared_and_does_not_contain) 10709 << ERange; 10710 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 10711 << EnclosingExpr->getSourceRange(); 10712 return true; 10713 } 10714 10715 return FoundError; 10716 } 10717 10718 namespace { 10719 // Utility struct that gathers all the related lists associated with a mappable 10720 // expression. 10721 struct MappableVarListInfo final { 10722 // The list of expressions. 10723 ArrayRef<Expr *> VarList; 10724 // The list of processed expressions. 10725 SmallVector<Expr *, 16> ProcessedVarList; 10726 // The mappble components for each expression. 10727 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 10728 // The base declaration of the variable. 10729 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 10730 10731 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 10732 // We have a list of components and base declarations for each entry in the 10733 // variable list. 10734 VarComponents.reserve(VarList.size()); 10735 VarBaseDeclarations.reserve(VarList.size()); 10736 } 10737 }; 10738 } 10739 10740 // Check the validity of the provided variable list for the provided clause kind 10741 // \a CKind. In the check process the valid expressions, and mappable expression 10742 // components and variables are extracted and used to fill \a Vars, 10743 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and 10744 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'. 10745 static void 10746 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS, 10747 OpenMPClauseKind CKind, MappableVarListInfo &MVLI, 10748 SourceLocation StartLoc, 10749 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 10750 bool IsMapTypeImplicit = false) { 10751 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 10752 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 10753 "Unexpected clause kind with mappable expressions!"); 10754 10755 // Keep track of the mappable components and base declarations in this clause. 10756 // Each entry in the list is going to have a list of components associated. We 10757 // record each set of the components so that we can build the clause later on. 10758 // In the end we should have the same amount of declarations and component 10759 // lists. 10760 10761 for (auto &RE : MVLI.VarList) { 10762 assert(RE && "Null expr in omp to/from/map clause"); 10763 SourceLocation ELoc = RE->getExprLoc(); 10764 10765 auto *VE = RE->IgnoreParenLValueCasts(); 10766 10767 if (VE->isValueDependent() || VE->isTypeDependent() || 10768 VE->isInstantiationDependent() || 10769 VE->containsUnexpandedParameterPack()) { 10770 // We can only analyze this information once the missing information is 10771 // resolved. 10772 MVLI.ProcessedVarList.push_back(RE); 10773 continue; 10774 } 10775 10776 auto *SimpleExpr = RE->IgnoreParenCasts(); 10777 10778 if (!RE->IgnoreParenImpCasts()->isLValue()) { 10779 SemaRef.Diag(ELoc, 10780 diag::err_omp_expected_named_var_member_or_array_expression) 10781 << RE->getSourceRange(); 10782 continue; 10783 } 10784 10785 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 10786 ValueDecl *CurDeclaration = nullptr; 10787 10788 // Obtain the array or member expression bases if required. Also, fill the 10789 // components array with all the components identified in the process. 10790 auto *BE = 10791 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind); 10792 if (!BE) 10793 continue; 10794 10795 assert(!CurComponents.empty() && 10796 "Invalid mappable expression information."); 10797 10798 // For the following checks, we rely on the base declaration which is 10799 // expected to be associated with the last component. The declaration is 10800 // expected to be a variable or a field (if 'this' is being mapped). 10801 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 10802 assert(CurDeclaration && "Null decl on map clause."); 10803 assert( 10804 CurDeclaration->isCanonicalDecl() && 10805 "Expecting components to have associated only canonical declarations."); 10806 10807 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 10808 auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 10809 10810 assert((VD || FD) && "Only variables or fields are expected here!"); 10811 (void)FD; 10812 10813 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 10814 // threadprivate variables cannot appear in a map clause. 10815 // OpenMP 4.5 [2.10.5, target update Construct] 10816 // threadprivate variables cannot appear in a from clause. 10817 if (VD && DSAS->isThreadPrivate(VD)) { 10818 auto DVar = DSAS->getTopDSA(VD, false); 10819 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 10820 << getOpenMPClauseName(CKind); 10821 ReportOriginalDSA(SemaRef, DSAS, VD, DVar); 10822 continue; 10823 } 10824 10825 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 10826 // A list item cannot appear in both a map clause and a data-sharing 10827 // attribute clause on the same construct. 10828 10829 // Check conflicts with other map clause expressions. We check the conflicts 10830 // with the current construct separately from the enclosing data 10831 // environment, because the restrictions are different. We only have to 10832 // check conflicts across regions for the map clauses. 10833 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 10834 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 10835 break; 10836 if (CKind == OMPC_map && 10837 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 10838 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 10839 break; 10840 10841 // OpenMP 4.5 [2.10.5, target update Construct] 10842 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10843 // If the type of a list item is a reference to a type T then the type will 10844 // be considered to be T for all purposes of this clause. 10845 QualType Type = CurDeclaration->getType().getNonReferenceType(); 10846 10847 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 10848 // A list item in a to or from clause must have a mappable type. 10849 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 10850 // A list item must have a mappable type. 10851 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 10852 DSAS, Type)) 10853 continue; 10854 10855 if (CKind == OMPC_map) { 10856 // target enter data 10857 // OpenMP [2.10.2, Restrictions, p. 99] 10858 // A map-type must be specified in all map clauses and must be either 10859 // to or alloc. 10860 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 10861 if (DKind == OMPD_target_enter_data && 10862 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 10863 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 10864 << (IsMapTypeImplicit ? 1 : 0) 10865 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 10866 << getOpenMPDirectiveName(DKind); 10867 continue; 10868 } 10869 10870 // target exit_data 10871 // OpenMP [2.10.3, Restrictions, p. 102] 10872 // A map-type must be specified in all map clauses and must be either 10873 // from, release, or delete. 10874 if (DKind == OMPD_target_exit_data && 10875 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 10876 MapType == OMPC_MAP_delete)) { 10877 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 10878 << (IsMapTypeImplicit ? 1 : 0) 10879 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 10880 << getOpenMPDirectiveName(DKind); 10881 continue; 10882 } 10883 10884 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 10885 // A list item cannot appear in both a map clause and a data-sharing 10886 // attribute clause on the same construct 10887 if ((DKind == OMPD_target || DKind == OMPD_target_teams || 10888 DKind == OMPD_target_teams_distribute || 10889 DKind == OMPD_target_teams_distribute_parallel_for || 10890 DKind == OMPD_target_teams_distribute_parallel_for_simd || 10891 DKind == OMPD_target_teams_distribute_simd) && VD) { 10892 auto DVar = DSAS->getTopDSA(VD, false); 10893 if (isOpenMPPrivate(DVar.CKind)) { 10894 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 10895 << getOpenMPClauseName(DVar.CKind) 10896 << getOpenMPClauseName(OMPC_map) 10897 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 10898 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar); 10899 continue; 10900 } 10901 } 10902 } 10903 10904 // Save the current expression. 10905 MVLI.ProcessedVarList.push_back(RE); 10906 10907 // Store the components in the stack so that they can be used to check 10908 // against other clauses later on. 10909 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 10910 /*WhereFoundClauseKind=*/OMPC_map); 10911 10912 // Save the components and declaration to create the clause. For purposes of 10913 // the clause creation, any component list that has has base 'this' uses 10914 // null as base declaration. 10915 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 10916 MVLI.VarComponents.back().append(CurComponents.begin(), 10917 CurComponents.end()); 10918 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 10919 : CurDeclaration); 10920 } 10921 } 10922 10923 OMPClause * 10924 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier, 10925 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 10926 SourceLocation MapLoc, SourceLocation ColonLoc, 10927 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 10928 SourceLocation LParenLoc, SourceLocation EndLoc) { 10929 MappableVarListInfo MVLI(VarList); 10930 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc, 10931 MapType, IsMapTypeImplicit); 10932 10933 // We need to produce a map clause even if we don't have variables so that 10934 // other diagnostics related with non-existing map clauses are accurate. 10935 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10936 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 10937 MVLI.VarComponents, MapTypeModifier, MapType, 10938 IsMapTypeImplicit, MapLoc); 10939 } 10940 10941 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 10942 TypeResult ParsedType) { 10943 assert(ParsedType.isUsable()); 10944 10945 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 10946 if (ReductionType.isNull()) 10947 return QualType(); 10948 10949 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 10950 // A type name in a declare reduction directive cannot be a function type, an 10951 // array type, a reference type, or a type qualified with const, volatile or 10952 // restrict. 10953 if (ReductionType.hasQualifiers()) { 10954 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 10955 return QualType(); 10956 } 10957 10958 if (ReductionType->isFunctionType()) { 10959 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 10960 return QualType(); 10961 } 10962 if (ReductionType->isReferenceType()) { 10963 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 10964 return QualType(); 10965 } 10966 if (ReductionType->isArrayType()) { 10967 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 10968 return QualType(); 10969 } 10970 return ReductionType; 10971 } 10972 10973 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 10974 Scope *S, DeclContext *DC, DeclarationName Name, 10975 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 10976 AccessSpecifier AS, Decl *PrevDeclInScope) { 10977 SmallVector<Decl *, 8> Decls; 10978 Decls.reserve(ReductionTypes.size()); 10979 10980 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 10981 ForRedeclaration); 10982 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 10983 // A reduction-identifier may not be re-declared in the current scope for the 10984 // same type or for a type that is compatible according to the base language 10985 // rules. 10986 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 10987 OMPDeclareReductionDecl *PrevDRD = nullptr; 10988 bool InCompoundScope = true; 10989 if (S != nullptr) { 10990 // Find previous declaration with the same name not referenced in other 10991 // declarations. 10992 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 10993 InCompoundScope = 10994 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 10995 LookupName(Lookup, S); 10996 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 10997 /*AllowInlineNamespace=*/false); 10998 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 10999 auto Filter = Lookup.makeFilter(); 11000 while (Filter.hasNext()) { 11001 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 11002 if (InCompoundScope) { 11003 auto I = UsedAsPrevious.find(PrevDecl); 11004 if (I == UsedAsPrevious.end()) 11005 UsedAsPrevious[PrevDecl] = false; 11006 if (auto *D = PrevDecl->getPrevDeclInScope()) 11007 UsedAsPrevious[D] = true; 11008 } 11009 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 11010 PrevDecl->getLocation(); 11011 } 11012 Filter.done(); 11013 if (InCompoundScope) { 11014 for (auto &PrevData : UsedAsPrevious) { 11015 if (!PrevData.second) { 11016 PrevDRD = PrevData.first; 11017 break; 11018 } 11019 } 11020 } 11021 } else if (PrevDeclInScope != nullptr) { 11022 auto *PrevDRDInScope = PrevDRD = 11023 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 11024 do { 11025 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 11026 PrevDRDInScope->getLocation(); 11027 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 11028 } while (PrevDRDInScope != nullptr); 11029 } 11030 for (auto &TyData : ReductionTypes) { 11031 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 11032 bool Invalid = false; 11033 if (I != PreviousRedeclTypes.end()) { 11034 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 11035 << TyData.first; 11036 Diag(I->second, diag::note_previous_definition); 11037 Invalid = true; 11038 } 11039 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 11040 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 11041 Name, TyData.first, PrevDRD); 11042 DC->addDecl(DRD); 11043 DRD->setAccess(AS); 11044 Decls.push_back(DRD); 11045 if (Invalid) 11046 DRD->setInvalidDecl(); 11047 else 11048 PrevDRD = DRD; 11049 } 11050 11051 return DeclGroupPtrTy::make( 11052 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 11053 } 11054 11055 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 11056 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11057 11058 // Enter new function scope. 11059 PushFunctionScope(); 11060 getCurFunction()->setHasBranchProtectedScope(); 11061 getCurFunction()->setHasOMPDeclareReductionCombiner(); 11062 11063 if (S != nullptr) 11064 PushDeclContext(S, DRD); 11065 else 11066 CurContext = DRD; 11067 11068 PushExpressionEvaluationContext( 11069 ExpressionEvaluationContext::PotentiallyEvaluated); 11070 11071 QualType ReductionType = DRD->getType(); 11072 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 11073 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 11074 // uses semantics of argument handles by value, but it should be passed by 11075 // reference. C lang does not support references, so pass all parameters as 11076 // pointers. 11077 // Create 'T omp_in;' variable. 11078 auto *OmpInParm = 11079 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 11080 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 11081 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 11082 // uses semantics of argument handles by value, but it should be passed by 11083 // reference. C lang does not support references, so pass all parameters as 11084 // pointers. 11085 // Create 'T omp_out;' variable. 11086 auto *OmpOutParm = 11087 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 11088 if (S != nullptr) { 11089 PushOnScopeChains(OmpInParm, S); 11090 PushOnScopeChains(OmpOutParm, S); 11091 } else { 11092 DRD->addDecl(OmpInParm); 11093 DRD->addDecl(OmpOutParm); 11094 } 11095 } 11096 11097 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 11098 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11099 DiscardCleanupsInEvaluationContext(); 11100 PopExpressionEvaluationContext(); 11101 11102 PopDeclContext(); 11103 PopFunctionScopeInfo(); 11104 11105 if (Combiner != nullptr) 11106 DRD->setCombiner(Combiner); 11107 else 11108 DRD->setInvalidDecl(); 11109 } 11110 11111 void Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 11112 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11113 11114 // Enter new function scope. 11115 PushFunctionScope(); 11116 getCurFunction()->setHasBranchProtectedScope(); 11117 11118 if (S != nullptr) 11119 PushDeclContext(S, DRD); 11120 else 11121 CurContext = DRD; 11122 11123 PushExpressionEvaluationContext( 11124 ExpressionEvaluationContext::PotentiallyEvaluated); 11125 11126 QualType ReductionType = DRD->getType(); 11127 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 11128 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 11129 // uses semantics of argument handles by value, but it should be passed by 11130 // reference. C lang does not support references, so pass all parameters as 11131 // pointers. 11132 // Create 'T omp_priv;' variable. 11133 auto *OmpPrivParm = 11134 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 11135 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 11136 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 11137 // uses semantics of argument handles by value, but it should be passed by 11138 // reference. C lang does not support references, so pass all parameters as 11139 // pointers. 11140 // Create 'T omp_orig;' variable. 11141 auto *OmpOrigParm = 11142 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 11143 if (S != nullptr) { 11144 PushOnScopeChains(OmpPrivParm, S); 11145 PushOnScopeChains(OmpOrigParm, S); 11146 } else { 11147 DRD->addDecl(OmpPrivParm); 11148 DRD->addDecl(OmpOrigParm); 11149 } 11150 } 11151 11152 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, 11153 Expr *Initializer) { 11154 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11155 DiscardCleanupsInEvaluationContext(); 11156 PopExpressionEvaluationContext(); 11157 11158 PopDeclContext(); 11159 PopFunctionScopeInfo(); 11160 11161 if (Initializer != nullptr) 11162 DRD->setInitializer(Initializer); 11163 else 11164 DRD->setInvalidDecl(); 11165 } 11166 11167 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 11168 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 11169 for (auto *D : DeclReductions.get()) { 11170 if (IsValid) { 11171 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11172 if (S != nullptr) 11173 PushOnScopeChains(DRD, S, /*AddToContext=*/false); 11174 } else 11175 D->setInvalidDecl(); 11176 } 11177 return DeclReductions; 11178 } 11179 11180 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 11181 SourceLocation StartLoc, 11182 SourceLocation LParenLoc, 11183 SourceLocation EndLoc) { 11184 Expr *ValExpr = NumTeams; 11185 Stmt *HelperValStmt = nullptr; 11186 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 11187 11188 // OpenMP [teams Constrcut, Restrictions] 11189 // The num_teams expression must evaluate to a positive integer value. 11190 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 11191 /*StrictlyPositive=*/true)) 11192 return nullptr; 11193 11194 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 11195 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams); 11196 if (CaptureRegion != OMPD_unknown) { 11197 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11198 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11199 HelperValStmt = buildPreInits(Context, Captures); 11200 } 11201 11202 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 11203 StartLoc, LParenLoc, EndLoc); 11204 } 11205 11206 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 11207 SourceLocation StartLoc, 11208 SourceLocation LParenLoc, 11209 SourceLocation EndLoc) { 11210 Expr *ValExpr = ThreadLimit; 11211 Stmt *HelperValStmt = nullptr; 11212 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 11213 11214 // OpenMP [teams Constrcut, Restrictions] 11215 // The thread_limit expression must evaluate to a positive integer value. 11216 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 11217 /*StrictlyPositive=*/true)) 11218 return nullptr; 11219 11220 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 11221 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit); 11222 if (CaptureRegion != OMPD_unknown) { 11223 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11224 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11225 HelperValStmt = buildPreInits(Context, Captures); 11226 } 11227 11228 return new (Context) OMPThreadLimitClause( 11229 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 11230 } 11231 11232 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 11233 SourceLocation StartLoc, 11234 SourceLocation LParenLoc, 11235 SourceLocation EndLoc) { 11236 Expr *ValExpr = Priority; 11237 11238 // OpenMP [2.9.1, task Constrcut] 11239 // The priority-value is a non-negative numerical scalar expression. 11240 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority, 11241 /*StrictlyPositive=*/false)) 11242 return nullptr; 11243 11244 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11245 } 11246 11247 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 11248 SourceLocation StartLoc, 11249 SourceLocation LParenLoc, 11250 SourceLocation EndLoc) { 11251 Expr *ValExpr = Grainsize; 11252 11253 // OpenMP [2.9.2, taskloop Constrcut] 11254 // The parameter of the grainsize clause must be a positive integer 11255 // expression. 11256 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize, 11257 /*StrictlyPositive=*/true)) 11258 return nullptr; 11259 11260 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11261 } 11262 11263 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 11264 SourceLocation StartLoc, 11265 SourceLocation LParenLoc, 11266 SourceLocation EndLoc) { 11267 Expr *ValExpr = NumTasks; 11268 11269 // OpenMP [2.9.2, taskloop Constrcut] 11270 // The parameter of the num_tasks clause must be a positive integer 11271 // expression. 11272 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks, 11273 /*StrictlyPositive=*/true)) 11274 return nullptr; 11275 11276 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11277 } 11278 11279 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 11280 SourceLocation LParenLoc, 11281 SourceLocation EndLoc) { 11282 // OpenMP [2.13.2, critical construct, Description] 11283 // ... where hint-expression is an integer constant expression that evaluates 11284 // to a valid lock hint. 11285 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 11286 if (HintExpr.isInvalid()) 11287 return nullptr; 11288 return new (Context) 11289 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 11290 } 11291 11292 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 11293 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 11294 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 11295 SourceLocation EndLoc) { 11296 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 11297 std::string Values; 11298 Values += "'"; 11299 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 11300 Values += "'"; 11301 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 11302 << Values << getOpenMPClauseName(OMPC_dist_schedule); 11303 return nullptr; 11304 } 11305 Expr *ValExpr = ChunkSize; 11306 Stmt *HelperValStmt = nullptr; 11307 if (ChunkSize) { 11308 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 11309 !ChunkSize->isInstantiationDependent() && 11310 !ChunkSize->containsUnexpandedParameterPack()) { 11311 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 11312 ExprResult Val = 11313 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 11314 if (Val.isInvalid()) 11315 return nullptr; 11316 11317 ValExpr = Val.get(); 11318 11319 // OpenMP [2.7.1, Restrictions] 11320 // chunk_size must be a loop invariant integer expression with a positive 11321 // value. 11322 llvm::APSInt Result; 11323 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 11324 if (Result.isSigned() && !Result.isStrictlyPositive()) { 11325 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 11326 << "dist_schedule" << ChunkSize->getSourceRange(); 11327 return nullptr; 11328 } 11329 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 11330 !CurContext->isDependentContext()) { 11331 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11332 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11333 HelperValStmt = buildPreInits(Context, Captures); 11334 } 11335 } 11336 } 11337 11338 return new (Context) 11339 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 11340 Kind, ValExpr, HelperValStmt); 11341 } 11342 11343 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 11344 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 11345 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 11346 SourceLocation KindLoc, SourceLocation EndLoc) { 11347 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)' 11348 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) { 11349 std::string Value; 11350 SourceLocation Loc; 11351 Value += "'"; 11352 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 11353 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 11354 OMPC_DEFAULTMAP_MODIFIER_tofrom); 11355 Loc = MLoc; 11356 } else { 11357 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 11358 OMPC_DEFAULTMAP_scalar); 11359 Loc = KindLoc; 11360 } 11361 Value += "'"; 11362 Diag(Loc, diag::err_omp_unexpected_clause_value) 11363 << Value << getOpenMPClauseName(OMPC_defaultmap); 11364 return nullptr; 11365 } 11366 11367 return new (Context) 11368 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 11369 } 11370 11371 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 11372 DeclContext *CurLexicalContext = getCurLexicalContext(); 11373 if (!CurLexicalContext->isFileContext() && 11374 !CurLexicalContext->isExternCContext() && 11375 !CurLexicalContext->isExternCXXContext()) { 11376 Diag(Loc, diag::err_omp_region_not_file_context); 11377 return false; 11378 } 11379 if (IsInOpenMPDeclareTargetContext) { 11380 Diag(Loc, diag::err_omp_enclosed_declare_target); 11381 return false; 11382 } 11383 11384 IsInOpenMPDeclareTargetContext = true; 11385 return true; 11386 } 11387 11388 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 11389 assert(IsInOpenMPDeclareTargetContext && 11390 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 11391 11392 IsInOpenMPDeclareTargetContext = false; 11393 } 11394 11395 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, 11396 CXXScopeSpec &ScopeSpec, 11397 const DeclarationNameInfo &Id, 11398 OMPDeclareTargetDeclAttr::MapTypeTy MT, 11399 NamedDeclSetType &SameDirectiveDecls) { 11400 LookupResult Lookup(*this, Id, LookupOrdinaryName); 11401 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 11402 11403 if (Lookup.isAmbiguous()) 11404 return; 11405 Lookup.suppressDiagnostics(); 11406 11407 if (!Lookup.isSingleResult()) { 11408 if (TypoCorrection Corrected = 11409 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, 11410 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this), 11411 CTK_ErrorRecovery)) { 11412 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 11413 << Id.getName()); 11414 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 11415 return; 11416 } 11417 11418 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 11419 return; 11420 } 11421 11422 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 11423 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 11424 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 11425 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 11426 11427 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) { 11428 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT); 11429 ND->addAttr(A); 11430 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11431 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 11432 checkDeclIsAllowedInOpenMPTarget(nullptr, ND); 11433 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) { 11434 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link) 11435 << Id.getName(); 11436 } 11437 } else 11438 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 11439 } 11440 11441 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 11442 Sema &SemaRef, Decl *D) { 11443 if (!D) 11444 return; 11445 Decl *LD = nullptr; 11446 if (isa<TagDecl>(D)) { 11447 LD = cast<TagDecl>(D)->getDefinition(); 11448 } else if (isa<VarDecl>(D)) { 11449 LD = cast<VarDecl>(D)->getDefinition(); 11450 11451 // If this is an implicit variable that is legal and we do not need to do 11452 // anything. 11453 if (cast<VarDecl>(D)->isImplicit()) { 11454 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11455 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11456 D->addAttr(A); 11457 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11458 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11459 return; 11460 } 11461 11462 } else if (isa<FunctionDecl>(D)) { 11463 const FunctionDecl *FD = nullptr; 11464 if (cast<FunctionDecl>(D)->hasBody(FD)) 11465 LD = const_cast<FunctionDecl *>(FD); 11466 11467 // If the definition is associated with the current declaration in the 11468 // target region (it can be e.g. a lambda) that is legal and we do not need 11469 // to do anything else. 11470 if (LD == D) { 11471 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11472 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11473 D->addAttr(A); 11474 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11475 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11476 return; 11477 } 11478 } 11479 if (!LD) 11480 LD = D; 11481 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() && 11482 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) { 11483 // Outlined declaration is not declared target. 11484 if (LD->isOutOfLine()) { 11485 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 11486 SemaRef.Diag(SL, diag::note_used_here) << SR; 11487 } else { 11488 DeclContext *DC = LD->getDeclContext(); 11489 while (DC) { 11490 if (isa<FunctionDecl>(DC) && 11491 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>()) 11492 break; 11493 DC = DC->getParent(); 11494 } 11495 if (DC) 11496 return; 11497 11498 // Is not declared in target context. 11499 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 11500 SemaRef.Diag(SL, diag::note_used_here) << SR; 11501 } 11502 // Mark decl as declared target to prevent further diagnostic. 11503 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11504 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11505 D->addAttr(A); 11506 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11507 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11508 } 11509 } 11510 11511 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 11512 Sema &SemaRef, DSAStackTy *Stack, 11513 ValueDecl *VD) { 11514 if (VD->hasAttr<OMPDeclareTargetDeclAttr>()) 11515 return true; 11516 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType())) 11517 return false; 11518 return true; 11519 } 11520 11521 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) { 11522 if (!D || D->isInvalidDecl()) 11523 return; 11524 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 11525 SourceLocation SL = E ? E->getLocStart() : D->getLocation(); 11526 // 2.10.6: threadprivate variable cannot appear in a declare target directive. 11527 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 11528 if (DSAStack->isThreadPrivate(VD)) { 11529 Diag(SL, diag::err_omp_threadprivate_in_target); 11530 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 11531 return; 11532 } 11533 } 11534 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 11535 // Problem if any with var declared with incomplete type will be reported 11536 // as normal, so no need to check it here. 11537 if ((E || !VD->getType()->isIncompleteType()) && 11538 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) { 11539 // Mark decl as declared target to prevent further diagnostic. 11540 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) { 11541 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11542 Context, OMPDeclareTargetDeclAttr::MT_To); 11543 VD->addAttr(A); 11544 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11545 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A); 11546 } 11547 return; 11548 } 11549 } 11550 if (!E) { 11551 // Checking declaration inside declare target region. 11552 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() && 11553 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) { 11554 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11555 Context, OMPDeclareTargetDeclAttr::MT_To); 11556 D->addAttr(A); 11557 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11558 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11559 } 11560 return; 11561 } 11562 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 11563 } 11564 11565 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, 11566 SourceLocation StartLoc, 11567 SourceLocation LParenLoc, 11568 SourceLocation EndLoc) { 11569 MappableVarListInfo MVLI(VarList); 11570 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc); 11571 if (MVLI.ProcessedVarList.empty()) 11572 return nullptr; 11573 11574 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11575 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11576 MVLI.VarComponents); 11577 } 11578 11579 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, 11580 SourceLocation StartLoc, 11581 SourceLocation LParenLoc, 11582 SourceLocation EndLoc) { 11583 MappableVarListInfo MVLI(VarList); 11584 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc); 11585 if (MVLI.ProcessedVarList.empty()) 11586 return nullptr; 11587 11588 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11589 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11590 MVLI.VarComponents); 11591 } 11592 11593 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 11594 SourceLocation StartLoc, 11595 SourceLocation LParenLoc, 11596 SourceLocation EndLoc) { 11597 MappableVarListInfo MVLI(VarList); 11598 SmallVector<Expr *, 8> PrivateCopies; 11599 SmallVector<Expr *, 8> Inits; 11600 11601 for (auto &RefExpr : VarList) { 11602 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 11603 SourceLocation ELoc; 11604 SourceRange ERange; 11605 Expr *SimpleRefExpr = RefExpr; 11606 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11607 if (Res.second) { 11608 // It will be analyzed later. 11609 MVLI.ProcessedVarList.push_back(RefExpr); 11610 PrivateCopies.push_back(nullptr); 11611 Inits.push_back(nullptr); 11612 } 11613 ValueDecl *D = Res.first; 11614 if (!D) 11615 continue; 11616 11617 QualType Type = D->getType(); 11618 Type = Type.getNonReferenceType().getUnqualifiedType(); 11619 11620 auto *VD = dyn_cast<VarDecl>(D); 11621 11622 // Item should be a pointer or reference to pointer. 11623 if (!Type->isPointerType()) { 11624 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 11625 << 0 << RefExpr->getSourceRange(); 11626 continue; 11627 } 11628 11629 // Build the private variable and the expression that refers to it. 11630 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 11631 D->hasAttrs() ? &D->getAttrs() : nullptr); 11632 if (VDPrivate->isInvalidDecl()) 11633 continue; 11634 11635 CurContext->addDecl(VDPrivate); 11636 auto VDPrivateRefExpr = buildDeclRefExpr( 11637 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 11638 11639 // Add temporary variable to initialize the private copy of the pointer. 11640 auto *VDInit = 11641 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 11642 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 11643 RefExpr->getExprLoc()); 11644 AddInitializerToDecl(VDPrivate, 11645 DefaultLvalueConversion(VDInitRefExpr).get(), 11646 /*DirectInit=*/false); 11647 11648 // If required, build a capture to implement the privatization initialized 11649 // with the current list item value. 11650 DeclRefExpr *Ref = nullptr; 11651 if (!VD) 11652 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 11653 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 11654 PrivateCopies.push_back(VDPrivateRefExpr); 11655 Inits.push_back(VDInitRefExpr); 11656 11657 // We need to add a data sharing attribute for this variable to make sure it 11658 // is correctly captured. A variable that shows up in a use_device_ptr has 11659 // similar properties of a first private variable. 11660 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 11661 11662 // Create a mappable component for the list item. List items in this clause 11663 // only need a component. 11664 MVLI.VarBaseDeclarations.push_back(D); 11665 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 11666 MVLI.VarComponents.back().push_back( 11667 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D)); 11668 } 11669 11670 if (MVLI.ProcessedVarList.empty()) 11671 return nullptr; 11672 11673 return OMPUseDevicePtrClause::Create( 11674 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 11675 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents); 11676 } 11677 11678 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 11679 SourceLocation StartLoc, 11680 SourceLocation LParenLoc, 11681 SourceLocation EndLoc) { 11682 MappableVarListInfo MVLI(VarList); 11683 for (auto &RefExpr : VarList) { 11684 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 11685 SourceLocation ELoc; 11686 SourceRange ERange; 11687 Expr *SimpleRefExpr = RefExpr; 11688 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 11689 if (Res.second) { 11690 // It will be analyzed later. 11691 MVLI.ProcessedVarList.push_back(RefExpr); 11692 } 11693 ValueDecl *D = Res.first; 11694 if (!D) 11695 continue; 11696 11697 QualType Type = D->getType(); 11698 // item should be a pointer or array or reference to pointer or array 11699 if (!Type.getNonReferenceType()->isPointerType() && 11700 !Type.getNonReferenceType()->isArrayType()) { 11701 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 11702 << 0 << RefExpr->getSourceRange(); 11703 continue; 11704 } 11705 11706 // Check if the declaration in the clause does not show up in any data 11707 // sharing attribute. 11708 auto DVar = DSAStack->getTopDSA(D, false); 11709 if (isOpenMPPrivate(DVar.CKind)) { 11710 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 11711 << getOpenMPClauseName(DVar.CKind) 11712 << getOpenMPClauseName(OMPC_is_device_ptr) 11713 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 11714 ReportOriginalDSA(*this, DSAStack, D, DVar); 11715 continue; 11716 } 11717 11718 Expr *ConflictExpr; 11719 if (DSAStack->checkMappableExprComponentListsForDecl( 11720 D, /*CurrentRegionOnly=*/true, 11721 [&ConflictExpr]( 11722 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 11723 OpenMPClauseKind) -> bool { 11724 ConflictExpr = R.front().getAssociatedExpression(); 11725 return true; 11726 })) { 11727 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 11728 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 11729 << ConflictExpr->getSourceRange(); 11730 continue; 11731 } 11732 11733 // Store the components in the stack so that they can be used to check 11734 // against other clauses later on. 11735 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D); 11736 DSAStack->addMappableExpressionComponents( 11737 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 11738 11739 // Record the expression we've just processed. 11740 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 11741 11742 // Create a mappable component for the list item. List items in this clause 11743 // only need a component. We use a null declaration to signal fields in 11744 // 'this'. 11745 assert((isa<DeclRefExpr>(SimpleRefExpr) || 11746 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 11747 "Unexpected device pointer expression!"); 11748 MVLI.VarBaseDeclarations.push_back( 11749 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 11750 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 11751 MVLI.VarComponents.back().push_back(MC); 11752 } 11753 11754 if (MVLI.ProcessedVarList.empty()) 11755 return nullptr; 11756 11757 return OMPIsDevicePtrClause::Create( 11758 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 11759 MVLI.VarBaseDeclarations, MVLI.VarComponents); 11760 } 11761