1 //===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// \file 10 /// \brief This file implements semantic analysis for OpenMP directives and 11 /// clauses. 12 /// 13 //===----------------------------------------------------------------------===// 14 15 #include "TreeTransform.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTMutationListener.h" 18 #include "clang/AST/CXXInheritance.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclOpenMP.h" 22 #include "clang/AST/StmtCXX.h" 23 #include "clang/AST/StmtOpenMP.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/Basic/OpenMPKinds.h" 26 #include "clang/Sema/Initialization.h" 27 #include "clang/Sema/Lookup.h" 28 #include "clang/Sema/Scope.h" 29 #include "clang/Sema/ScopeInfo.h" 30 #include "clang/Sema/SemaInternal.h" 31 #include "llvm/ADT/PointerEmbeddedInt.h" 32 using namespace clang; 33 34 //===----------------------------------------------------------------------===// 35 // Stack of data-sharing attributes for variables 36 //===----------------------------------------------------------------------===// 37 38 namespace { 39 /// \brief Default data sharing attributes, which can be applied to directive. 40 enum DefaultDataSharingAttributes { 41 DSA_unspecified = 0, /// \brief Data sharing attribute not specified. 42 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'. 43 DSA_shared = 1 << 1 /// \brief Default data sharing attribute 'shared'. 44 }; 45 46 /// \brief Stack for tracking declarations used in OpenMP directives and 47 /// clauses and their data-sharing attributes. 48 class DSAStackTy final { 49 public: 50 struct DSAVarData final { 51 OpenMPDirectiveKind DKind = OMPD_unknown; 52 OpenMPClauseKind CKind = OMPC_unknown; 53 Expr *RefExpr = nullptr; 54 DeclRefExpr *PrivateCopy = nullptr; 55 SourceLocation ImplicitDSALoc; 56 DSAVarData() = default; 57 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, Expr *RefExpr, 58 DeclRefExpr *PrivateCopy, SourceLocation ImplicitDSALoc) 59 : DKind(DKind), CKind(CKind), RefExpr(RefExpr), 60 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {} 61 }; 62 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4> 63 OperatorOffsetTy; 64 65 private: 66 struct DSAInfo final { 67 OpenMPClauseKind Attributes = OMPC_unknown; 68 /// Pointer to a reference expression and a flag which shows that the 69 /// variable is marked as lastprivate(true) or not (false). 70 llvm::PointerIntPair<Expr *, 1, bool> RefExpr; 71 DeclRefExpr *PrivateCopy = nullptr; 72 }; 73 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy; 74 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy; 75 typedef std::pair<unsigned, VarDecl *> LCDeclInfo; 76 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy; 77 /// Struct that associates a component with the clause kind where they are 78 /// found. 79 struct MappedExprComponentTy { 80 OMPClauseMappableExprCommon::MappableExprComponentLists Components; 81 OpenMPClauseKind Kind = OMPC_unknown; 82 }; 83 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy> 84 MappedExprComponentsTy; 85 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>> 86 CriticalsWithHintsTy; 87 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy> 88 DoacrossDependMapTy; 89 struct ReductionData { 90 typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType; 91 SourceRange ReductionRange; 92 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp; 93 ReductionData() = default; 94 void set(BinaryOperatorKind BO, SourceRange RR) { 95 ReductionRange = RR; 96 ReductionOp = BO; 97 } 98 void set(const Expr *RefExpr, SourceRange RR) { 99 ReductionRange = RR; 100 ReductionOp = RefExpr; 101 } 102 }; 103 typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy; 104 105 struct SharingMapTy final { 106 DeclSAMapTy SharingMap; 107 DeclReductionMapTy ReductionMap; 108 AlignedMapTy AlignedMap; 109 MappedExprComponentsTy MappedExprComponents; 110 LoopControlVariablesMapTy LCVMap; 111 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified; 112 SourceLocation DefaultAttrLoc; 113 OpenMPDirectiveKind Directive = OMPD_unknown; 114 DeclarationNameInfo DirectiveName; 115 Scope *CurScope = nullptr; 116 SourceLocation ConstructLoc; 117 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to 118 /// get the data (loop counters etc.) about enclosing loop-based construct. 119 /// This data is required during codegen. 120 DoacrossDependMapTy DoacrossDepends; 121 /// \brief first argument (Expr *) contains optional argument of the 122 /// 'ordered' clause, the second one is true if the regions has 'ordered' 123 /// clause, false otherwise. 124 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion; 125 bool NowaitRegion = false; 126 bool CancelRegion = false; 127 unsigned AssociatedLoops = 1; 128 SourceLocation InnerTeamsRegionLoc; 129 /// Reference to the taskgroup task_reduction reference expression. 130 Expr *TaskgroupReductionRef = nullptr; 131 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name, 132 Scope *CurScope, SourceLocation Loc) 133 : Directive(DKind), DirectiveName(Name), CurScope(CurScope), 134 ConstructLoc(Loc) {} 135 SharingMapTy() = default; 136 }; 137 138 typedef SmallVector<SharingMapTy, 4> StackTy; 139 140 /// \brief Stack of used declaration and their data-sharing attributes. 141 DeclSAMapTy Threadprivates; 142 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr; 143 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack; 144 /// \brief true, if check for DSA must be from parent directive, false, if 145 /// from current directive. 146 OpenMPClauseKind ClauseKindMode = OMPC_unknown; 147 Sema &SemaRef; 148 bool ForceCapturing = false; 149 CriticalsWithHintsTy Criticals; 150 151 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator; 152 153 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D); 154 155 /// \brief Checks if the variable is a local for OpenMP region. 156 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter); 157 158 bool isStackEmpty() const { 159 return Stack.empty() || 160 Stack.back().second != CurrentNonCapturingFunctionScope || 161 Stack.back().first.empty(); 162 } 163 164 public: 165 explicit DSAStackTy(Sema &S) : SemaRef(S) {} 166 167 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; } 168 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; } 169 170 bool isForceVarCapturing() const { return ForceCapturing; } 171 void setForceVarCapturing(bool V) { ForceCapturing = V; } 172 173 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName, 174 Scope *CurScope, SourceLocation Loc) { 175 if (Stack.empty() || 176 Stack.back().second != CurrentNonCapturingFunctionScope) 177 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope); 178 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc); 179 Stack.back().first.back().DefaultAttrLoc = Loc; 180 } 181 182 void pop() { 183 assert(!Stack.back().first.empty() && 184 "Data-sharing attributes stack is empty!"); 185 Stack.back().first.pop_back(); 186 } 187 188 /// Start new OpenMP region stack in new non-capturing function. 189 void pushFunction() { 190 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction(); 191 assert(!isa<CapturingScopeInfo>(CurFnScope)); 192 CurrentNonCapturingFunctionScope = CurFnScope; 193 } 194 /// Pop region stack for non-capturing function. 195 void popFunction(const FunctionScopeInfo *OldFSI) { 196 if (!Stack.empty() && Stack.back().second == OldFSI) { 197 assert(Stack.back().first.empty()); 198 Stack.pop_back(); 199 } 200 CurrentNonCapturingFunctionScope = nullptr; 201 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) { 202 if (!isa<CapturingScopeInfo>(FSI)) { 203 CurrentNonCapturingFunctionScope = FSI; 204 break; 205 } 206 } 207 } 208 209 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) { 210 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint); 211 } 212 const std::pair<OMPCriticalDirective *, llvm::APSInt> 213 getCriticalWithHint(const DeclarationNameInfo &Name) const { 214 auto I = Criticals.find(Name.getAsString()); 215 if (I != Criticals.end()) 216 return I->second; 217 return std::make_pair(nullptr, llvm::APSInt()); 218 } 219 /// \brief If 'aligned' declaration for given variable \a D was not seen yet, 220 /// add it and return NULL; otherwise return previous occurrence's expression 221 /// for diagnostics. 222 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE); 223 224 /// \brief Register specified variable as loop control variable. 225 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture); 226 /// \brief Check if the specified variable is a loop control variable for 227 /// current region. 228 /// \return The index of the loop control variable in the list of associated 229 /// for-loops (from outer to inner). 230 LCDeclInfo isLoopControlVariable(ValueDecl *D); 231 /// \brief Check if the specified variable is a loop control variable for 232 /// parent region. 233 /// \return The index of the loop control variable in the list of associated 234 /// for-loops (from outer to inner). 235 LCDeclInfo isParentLoopControlVariable(ValueDecl *D); 236 /// \brief Get the loop control variable for the I-th loop (or nullptr) in 237 /// parent directive. 238 ValueDecl *getParentLoopControlVariable(unsigned I); 239 240 /// \brief Adds explicit data sharing attribute to the specified declaration. 241 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, 242 DeclRefExpr *PrivateCopy = nullptr); 243 244 /// Adds additional information for the reduction items with the reduction id 245 /// represented as an operator. 246 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR, 247 BinaryOperatorKind BOK); 248 /// Adds additional information for the reduction items with the reduction id 249 /// represented as reduction identifier. 250 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR, 251 const Expr *ReductionRef); 252 /// Returns the location and reduction operation from the innermost parent 253 /// region for the given \p D. 254 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR, 255 BinaryOperatorKind &BOK, 256 Expr *&TaskgroupDescriptor); 257 /// Returns the location and reduction operation from the innermost parent 258 /// region for the given \p D. 259 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR, 260 const Expr *&ReductionRef, 261 Expr *&TaskgroupDescriptor); 262 /// Return reduction reference expression for the current taskgroup. 263 Expr *getTaskgroupReductionRef() const { 264 assert(Stack.back().first.back().Directive == OMPD_taskgroup && 265 "taskgroup reference expression requested for non taskgroup " 266 "directive."); 267 return Stack.back().first.back().TaskgroupReductionRef; 268 } 269 /// Checks if the given \p VD declaration is actually a taskgroup reduction 270 /// descriptor variable at the \p Level of OpenMP regions. 271 bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const { 272 return Stack.back().first[Level].TaskgroupReductionRef && 273 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef) 274 ->getDecl() == VD; 275 } 276 277 /// \brief Returns data sharing attributes from top of the stack for the 278 /// specified declaration. 279 DSAVarData getTopDSA(ValueDecl *D, bool FromParent); 280 /// \brief Returns data-sharing attributes for the specified declaration. 281 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent); 282 /// \brief Checks if the specified variables has data-sharing attributes which 283 /// match specified \a CPred predicate in any directive which matches \a DPred 284 /// predicate. 285 DSAVarData hasDSA(ValueDecl *D, 286 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 287 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 288 bool FromParent); 289 /// \brief Checks if the specified variables has data-sharing attributes which 290 /// match specified \a CPred predicate in any innermost directive which 291 /// matches \a DPred predicate. 292 DSAVarData 293 hasInnermostDSA(ValueDecl *D, 294 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 295 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 296 bool FromParent); 297 /// \brief Checks if the specified variables has explicit data-sharing 298 /// attributes which match specified \a CPred predicate at the specified 299 /// OpenMP region. 300 bool hasExplicitDSA(ValueDecl *D, 301 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 302 unsigned Level, bool NotLastprivate = false); 303 304 /// \brief Returns true if the directive at level \Level matches in the 305 /// specified \a DPred predicate. 306 bool hasExplicitDirective( 307 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 308 unsigned Level); 309 310 /// \brief Finds a directive which matches specified \a DPred predicate. 311 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind, 312 const DeclarationNameInfo &, 313 SourceLocation)> &DPred, 314 bool FromParent); 315 316 /// \brief Returns currently analyzed directive. 317 OpenMPDirectiveKind getCurrentDirective() const { 318 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive; 319 } 320 /// \brief Returns parent directive. 321 OpenMPDirectiveKind getParentDirective() const { 322 if (isStackEmpty() || Stack.back().first.size() == 1) 323 return OMPD_unknown; 324 return std::next(Stack.back().first.rbegin())->Directive; 325 } 326 327 /// \brief Set default data sharing attribute to none. 328 void setDefaultDSANone(SourceLocation Loc) { 329 assert(!isStackEmpty()); 330 Stack.back().first.back().DefaultAttr = DSA_none; 331 Stack.back().first.back().DefaultAttrLoc = Loc; 332 } 333 /// \brief Set default data sharing attribute to shared. 334 void setDefaultDSAShared(SourceLocation Loc) { 335 assert(!isStackEmpty()); 336 Stack.back().first.back().DefaultAttr = DSA_shared; 337 Stack.back().first.back().DefaultAttrLoc = Loc; 338 } 339 340 DefaultDataSharingAttributes getDefaultDSA() const { 341 return isStackEmpty() ? DSA_unspecified 342 : Stack.back().first.back().DefaultAttr; 343 } 344 SourceLocation getDefaultDSALocation() const { 345 return isStackEmpty() ? SourceLocation() 346 : Stack.back().first.back().DefaultAttrLoc; 347 } 348 349 /// \brief Checks if the specified variable is a threadprivate. 350 bool isThreadPrivate(VarDecl *D) { 351 DSAVarData DVar = getTopDSA(D, false); 352 return isOpenMPThreadPrivate(DVar.CKind); 353 } 354 355 /// \brief Marks current region as ordered (it has an 'ordered' clause). 356 void setOrderedRegion(bool IsOrdered, Expr *Param) { 357 assert(!isStackEmpty()); 358 Stack.back().first.back().OrderedRegion.setInt(IsOrdered); 359 Stack.back().first.back().OrderedRegion.setPointer(Param); 360 } 361 /// \brief Returns true, if parent region is ordered (has associated 362 /// 'ordered' clause), false - otherwise. 363 bool isParentOrderedRegion() const { 364 if (isStackEmpty() || Stack.back().first.size() == 1) 365 return false; 366 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt(); 367 } 368 /// \brief Returns optional parameter for the ordered region. 369 Expr *getParentOrderedRegionParam() const { 370 if (isStackEmpty() || Stack.back().first.size() == 1) 371 return nullptr; 372 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer(); 373 } 374 /// \brief Marks current region as nowait (it has a 'nowait' clause). 375 void setNowaitRegion(bool IsNowait = true) { 376 assert(!isStackEmpty()); 377 Stack.back().first.back().NowaitRegion = IsNowait; 378 } 379 /// \brief Returns true, if parent region is nowait (has associated 380 /// 'nowait' clause), false - otherwise. 381 bool isParentNowaitRegion() const { 382 if (isStackEmpty() || Stack.back().first.size() == 1) 383 return false; 384 return std::next(Stack.back().first.rbegin())->NowaitRegion; 385 } 386 /// \brief Marks parent region as cancel region. 387 void setParentCancelRegion(bool Cancel = true) { 388 if (!isStackEmpty() && Stack.back().first.size() > 1) { 389 auto &StackElemRef = *std::next(Stack.back().first.rbegin()); 390 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel; 391 } 392 } 393 /// \brief Return true if current region has inner cancel construct. 394 bool isCancelRegion() const { 395 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion; 396 } 397 398 /// \brief Set collapse value for the region. 399 void setAssociatedLoops(unsigned Val) { 400 assert(!isStackEmpty()); 401 Stack.back().first.back().AssociatedLoops = Val; 402 } 403 /// \brief Return collapse value for region. 404 unsigned getAssociatedLoops() const { 405 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops; 406 } 407 408 /// \brief Marks current target region as one with closely nested teams 409 /// region. 410 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) { 411 if (!isStackEmpty() && Stack.back().first.size() > 1) { 412 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc = 413 TeamsRegionLoc; 414 } 415 } 416 /// \brief Returns true, if current region has closely nested teams region. 417 bool hasInnerTeamsRegion() const { 418 return getInnerTeamsRegionLoc().isValid(); 419 } 420 /// \brief Returns location of the nested teams region (if any). 421 SourceLocation getInnerTeamsRegionLoc() const { 422 return isStackEmpty() ? SourceLocation() 423 : Stack.back().first.back().InnerTeamsRegionLoc; 424 } 425 426 Scope *getCurScope() const { 427 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope; 428 } 429 Scope *getCurScope() { 430 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope; 431 } 432 SourceLocation getConstructLoc() { 433 return isStackEmpty() ? SourceLocation() 434 : Stack.back().first.back().ConstructLoc; 435 } 436 437 /// Do the check specified in \a Check to all component lists and return true 438 /// if any issue is found. 439 bool checkMappableExprComponentListsForDecl( 440 ValueDecl *VD, bool CurrentRegionOnly, 441 const llvm::function_ref< 442 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 443 OpenMPClauseKind)> &Check) { 444 if (isStackEmpty()) 445 return false; 446 auto SI = Stack.back().first.rbegin(); 447 auto SE = Stack.back().first.rend(); 448 449 if (SI == SE) 450 return false; 451 452 if (CurrentRegionOnly) { 453 SE = std::next(SI); 454 } else { 455 ++SI; 456 } 457 458 for (; SI != SE; ++SI) { 459 auto MI = SI->MappedExprComponents.find(VD); 460 if (MI != SI->MappedExprComponents.end()) 461 for (auto &L : MI->second.Components) 462 if (Check(L, MI->second.Kind)) 463 return true; 464 } 465 return false; 466 } 467 468 /// Do the check specified in \a Check to all component lists at a given level 469 /// and return true if any issue is found. 470 bool checkMappableExprComponentListsForDeclAtLevel( 471 ValueDecl *VD, unsigned Level, 472 const llvm::function_ref< 473 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef, 474 OpenMPClauseKind)> &Check) { 475 if (isStackEmpty()) 476 return false; 477 478 auto StartI = Stack.back().first.begin(); 479 auto EndI = Stack.back().first.end(); 480 if (std::distance(StartI, EndI) <= (int)Level) 481 return false; 482 std::advance(StartI, Level); 483 484 auto MI = StartI->MappedExprComponents.find(VD); 485 if (MI != StartI->MappedExprComponents.end()) 486 for (auto &L : MI->second.Components) 487 if (Check(L, MI->second.Kind)) 488 return true; 489 return false; 490 } 491 492 /// Create a new mappable expression component list associated with a given 493 /// declaration and initialize it with the provided list of components. 494 void addMappableExpressionComponents( 495 ValueDecl *VD, 496 OMPClauseMappableExprCommon::MappableExprComponentListRef Components, 497 OpenMPClauseKind WhereFoundClauseKind) { 498 assert(!isStackEmpty() && 499 "Not expecting to retrieve components from a empty stack!"); 500 auto &MEC = Stack.back().first.back().MappedExprComponents[VD]; 501 // Create new entry and append the new components there. 502 MEC.Components.resize(MEC.Components.size() + 1); 503 MEC.Components.back().append(Components.begin(), Components.end()); 504 MEC.Kind = WhereFoundClauseKind; 505 } 506 507 unsigned getNestingLevel() const { 508 assert(!isStackEmpty()); 509 return Stack.back().first.size() - 1; 510 } 511 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) { 512 assert(!isStackEmpty() && Stack.back().first.size() > 1); 513 auto &StackElem = *std::next(Stack.back().first.rbegin()); 514 assert(isOpenMPWorksharingDirective(StackElem.Directive)); 515 StackElem.DoacrossDepends.insert({C, OpsOffs}); 516 } 517 llvm::iterator_range<DoacrossDependMapTy::const_iterator> 518 getDoacrossDependClauses() const { 519 assert(!isStackEmpty()); 520 auto &StackElem = Stack.back().first.back(); 521 if (isOpenMPWorksharingDirective(StackElem.Directive)) { 522 auto &Ref = StackElem.DoacrossDepends; 523 return llvm::make_range(Ref.begin(), Ref.end()); 524 } 525 return llvm::make_range(StackElem.DoacrossDepends.end(), 526 StackElem.DoacrossDepends.end()); 527 } 528 }; 529 bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) { 530 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) || 531 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown; 532 } 533 } // namespace 534 535 static Expr *getExprAsWritten(Expr *E) { 536 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E)) 537 E = ExprTemp->getSubExpr(); 538 539 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) 540 E = MTE->GetTemporaryExpr(); 541 542 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E)) 543 E = Binder->getSubExpr(); 544 545 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E)) 546 E = ICE->getSubExprAsWritten(); 547 return E->IgnoreParens(); 548 } 549 550 static ValueDecl *getCanonicalDecl(ValueDecl *D) { 551 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D)) 552 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 553 D = ME->getMemberDecl(); 554 auto *VD = dyn_cast<VarDecl>(D); 555 auto *FD = dyn_cast<FieldDecl>(D); 556 if (VD != nullptr) { 557 VD = VD->getCanonicalDecl(); 558 D = VD; 559 } else { 560 assert(FD); 561 FD = FD->getCanonicalDecl(); 562 D = FD; 563 } 564 return D; 565 } 566 567 DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter, 568 ValueDecl *D) { 569 D = getCanonicalDecl(D); 570 auto *VD = dyn_cast<VarDecl>(D); 571 auto *FD = dyn_cast<FieldDecl>(D); 572 DSAVarData DVar; 573 if (isStackEmpty() || Iter == Stack.back().first.rend()) { 574 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 575 // in a region but not in construct] 576 // File-scope or namespace-scope variables referenced in called routines 577 // in the region are shared unless they appear in a threadprivate 578 // directive. 579 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D)) 580 DVar.CKind = OMPC_shared; 581 582 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced 583 // in a region but not in construct] 584 // Variables with static storage duration that are declared in called 585 // routines in the region are shared. 586 if (VD && VD->hasGlobalStorage()) 587 DVar.CKind = OMPC_shared; 588 589 // Non-static data members are shared by default. 590 if (FD) 591 DVar.CKind = OMPC_shared; 592 593 return DVar; 594 } 595 596 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 597 // in a Construct, C/C++, predetermined, p.1] 598 // Variables with automatic storage duration that are declared in a scope 599 // inside the construct are private. 600 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() && 601 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) { 602 DVar.CKind = OMPC_private; 603 return DVar; 604 } 605 606 DVar.DKind = Iter->Directive; 607 // Explicitly specified attributes and local variables with predetermined 608 // attributes. 609 if (Iter->SharingMap.count(D)) { 610 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer(); 611 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy; 612 DVar.CKind = Iter->SharingMap[D].Attributes; 613 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 614 return DVar; 615 } 616 617 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 618 // in a Construct, C/C++, implicitly determined, p.1] 619 // In a parallel or task construct, the data-sharing attributes of these 620 // variables are determined by the default clause, if present. 621 switch (Iter->DefaultAttr) { 622 case DSA_shared: 623 DVar.CKind = OMPC_shared; 624 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 625 return DVar; 626 case DSA_none: 627 return DVar; 628 case DSA_unspecified: 629 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 630 // in a Construct, implicitly determined, p.2] 631 // In a parallel construct, if no default clause is present, these 632 // variables are shared. 633 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc; 634 if (isOpenMPParallelDirective(DVar.DKind) || 635 isOpenMPTeamsDirective(DVar.DKind)) { 636 DVar.CKind = OMPC_shared; 637 return DVar; 638 } 639 640 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 641 // in a Construct, implicitly determined, p.4] 642 // In a task construct, if no default clause is present, a variable that in 643 // the enclosing context is determined to be shared by all implicit tasks 644 // bound to the current team is shared. 645 if (isOpenMPTaskingDirective(DVar.DKind)) { 646 DSAVarData DVarTemp; 647 auto I = Iter, E = Stack.back().first.rend(); 648 do { 649 ++I; 650 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables 651 // Referenced in a Construct, implicitly determined, p.6] 652 // In a task construct, if no default clause is present, a variable 653 // whose data-sharing attribute is not determined by the rules above is 654 // firstprivate. 655 DVarTemp = getDSA(I, D); 656 if (DVarTemp.CKind != OMPC_shared) { 657 DVar.RefExpr = nullptr; 658 DVar.CKind = OMPC_firstprivate; 659 return DVar; 660 } 661 } while (I != E && !isParallelOrTaskRegion(I->Directive)); 662 DVar.CKind = 663 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared; 664 return DVar; 665 } 666 } 667 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 668 // in a Construct, implicitly determined, p.3] 669 // For constructs other than task, if no default clause is present, these 670 // variables inherit their data-sharing attributes from the enclosing 671 // context. 672 return getDSA(++Iter, D); 673 } 674 675 Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) { 676 assert(!isStackEmpty() && "Data sharing attributes stack is empty"); 677 D = getCanonicalDecl(D); 678 auto &StackElem = Stack.back().first.back(); 679 auto It = StackElem.AlignedMap.find(D); 680 if (It == StackElem.AlignedMap.end()) { 681 assert(NewDE && "Unexpected nullptr expr to be added into aligned map"); 682 StackElem.AlignedMap[D] = NewDE; 683 return nullptr; 684 } else { 685 assert(It->second && "Unexpected nullptr expr in the aligned map"); 686 return It->second; 687 } 688 return nullptr; 689 } 690 691 void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) { 692 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 693 D = getCanonicalDecl(D); 694 auto &StackElem = Stack.back().first.back(); 695 StackElem.LCVMap.insert( 696 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)}); 697 } 698 699 DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) { 700 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 701 D = getCanonicalDecl(D); 702 auto &StackElem = Stack.back().first.back(); 703 auto It = StackElem.LCVMap.find(D); 704 if (It != StackElem.LCVMap.end()) 705 return It->second; 706 return {0, nullptr}; 707 } 708 709 DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) { 710 assert(!isStackEmpty() && Stack.back().first.size() > 1 && 711 "Data-sharing attributes stack is empty"); 712 D = getCanonicalDecl(D); 713 auto &StackElem = *std::next(Stack.back().first.rbegin()); 714 auto It = StackElem.LCVMap.find(D); 715 if (It != StackElem.LCVMap.end()) 716 return It->second; 717 return {0, nullptr}; 718 } 719 720 ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) { 721 assert(!isStackEmpty() && Stack.back().first.size() > 1 && 722 "Data-sharing attributes stack is empty"); 723 auto &StackElem = *std::next(Stack.back().first.rbegin()); 724 if (StackElem.LCVMap.size() < I) 725 return nullptr; 726 for (auto &Pair : StackElem.LCVMap) 727 if (Pair.second.first == I) 728 return Pair.first; 729 return nullptr; 730 } 731 732 void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A, 733 DeclRefExpr *PrivateCopy) { 734 D = getCanonicalDecl(D); 735 if (A == OMPC_threadprivate) { 736 auto &Data = Threadprivates[D]; 737 Data.Attributes = A; 738 Data.RefExpr.setPointer(E); 739 Data.PrivateCopy = nullptr; 740 } else { 741 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 742 auto &Data = Stack.back().first.back().SharingMap[D]; 743 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) || 744 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) || 745 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) || 746 (isLoopControlVariable(D).first && A == OMPC_private)); 747 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) { 748 Data.RefExpr.setInt(/*IntVal=*/true); 749 return; 750 } 751 const bool IsLastprivate = 752 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate; 753 Data.Attributes = A; 754 Data.RefExpr.setPointerAndInt(E, IsLastprivate); 755 Data.PrivateCopy = PrivateCopy; 756 if (PrivateCopy) { 757 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()]; 758 Data.Attributes = A; 759 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate); 760 Data.PrivateCopy = nullptr; 761 } 762 } 763 } 764 765 /// \brief Build a variable declaration for OpenMP loop iteration variable. 766 static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type, 767 StringRef Name, const AttrVec *Attrs = nullptr) { 768 DeclContext *DC = SemaRef.CurContext; 769 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name); 770 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc); 771 VarDecl *Decl = 772 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None); 773 if (Attrs) { 774 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end()); 775 I != E; ++I) 776 Decl->addAttr(*I); 777 } 778 Decl->setImplicit(); 779 return Decl; 780 } 781 782 static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty, 783 SourceLocation Loc, 784 bool RefersToCapture = false) { 785 D->setReferenced(); 786 D->markUsed(S.Context); 787 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(), 788 SourceLocation(), D, RefersToCapture, Loc, Ty, 789 VK_LValue); 790 } 791 792 void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR, 793 BinaryOperatorKind BOK) { 794 D = getCanonicalDecl(D); 795 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 796 assert( 797 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && 798 "Additional reduction info may be specified only for reduction items."); 799 auto &ReductionData = Stack.back().first.back().ReductionMap[D]; 800 assert(ReductionData.ReductionRange.isInvalid() && 801 Stack.back().first.back().Directive == OMPD_taskgroup && 802 "Additional reduction info may be specified only once for reduction " 803 "items."); 804 ReductionData.set(BOK, SR); 805 Expr *&TaskgroupReductionRef = 806 Stack.back().first.back().TaskgroupReductionRef; 807 if (!TaskgroupReductionRef) { 808 auto *VD = buildVarDecl(SemaRef, SourceLocation(), 809 SemaRef.Context.VoidPtrTy, ".task_red."); 810 TaskgroupReductionRef = buildDeclRefExpr( 811 SemaRef, VD, SemaRef.Context.VoidPtrTy, SourceLocation()); 812 } 813 } 814 815 void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR, 816 const Expr *ReductionRef) { 817 D = getCanonicalDecl(D); 818 assert(!isStackEmpty() && "Data-sharing attributes stack is empty"); 819 assert( 820 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction && 821 "Additional reduction info may be specified only for reduction items."); 822 auto &ReductionData = Stack.back().first.back().ReductionMap[D]; 823 assert(ReductionData.ReductionRange.isInvalid() && 824 Stack.back().first.back().Directive == OMPD_taskgroup && 825 "Additional reduction info may be specified only once for reduction " 826 "items."); 827 ReductionData.set(ReductionRef, SR); 828 Expr *&TaskgroupReductionRef = 829 Stack.back().first.back().TaskgroupReductionRef; 830 if (!TaskgroupReductionRef) { 831 auto *VD = buildVarDecl(SemaRef, SourceLocation(), 832 SemaRef.Context.VoidPtrTy, ".task_red."); 833 TaskgroupReductionRef = buildDeclRefExpr( 834 SemaRef, VD, SemaRef.Context.VoidPtrTy, SourceLocation()); 835 } 836 } 837 838 DSAStackTy::DSAVarData 839 DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR, 840 BinaryOperatorKind &BOK, 841 Expr *&TaskgroupDescriptor) { 842 D = getCanonicalDecl(D); 843 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 844 if (Stack.back().first.empty()) 845 return DSAVarData(); 846 for (auto I = std::next(Stack.back().first.rbegin(), 1), 847 E = Stack.back().first.rend(); 848 I != E; std::advance(I, 1)) { 849 auto &Data = I->SharingMap[D]; 850 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) 851 continue; 852 auto &ReductionData = I->ReductionMap[D]; 853 if (!ReductionData.ReductionOp || 854 ReductionData.ReductionOp.is<const Expr *>()) 855 return DSAVarData(); 856 SR = ReductionData.ReductionRange; 857 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>(); 858 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 859 "expression for the descriptor is not " 860 "set."); 861 TaskgroupDescriptor = I->TaskgroupReductionRef; 862 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), 863 Data.PrivateCopy, I->DefaultAttrLoc); 864 } 865 return DSAVarData(); 866 } 867 868 DSAStackTy::DSAVarData 869 DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR, 870 const Expr *&ReductionRef, 871 Expr *&TaskgroupDescriptor) { 872 D = getCanonicalDecl(D); 873 assert(!isStackEmpty() && "Data-sharing attributes stack is empty."); 874 if (Stack.back().first.empty()) 875 return DSAVarData(); 876 for (auto I = std::next(Stack.back().first.rbegin(), 1), 877 E = Stack.back().first.rend(); 878 I != E; std::advance(I, 1)) { 879 auto &Data = I->SharingMap[D]; 880 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup) 881 continue; 882 auto &ReductionData = I->ReductionMap[D]; 883 if (!ReductionData.ReductionOp || 884 !ReductionData.ReductionOp.is<const Expr *>()) 885 return DSAVarData(); 886 SR = ReductionData.ReductionRange; 887 ReductionRef = ReductionData.ReductionOp.get<const Expr *>(); 888 assert(I->TaskgroupReductionRef && "taskgroup reduction reference " 889 "expression for the descriptor is not " 890 "set."); 891 TaskgroupDescriptor = I->TaskgroupReductionRef; 892 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(), 893 Data.PrivateCopy, I->DefaultAttrLoc); 894 } 895 return DSAVarData(); 896 } 897 898 bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) { 899 D = D->getCanonicalDecl(); 900 if (!isStackEmpty() && Stack.back().first.size() > 1) { 901 reverse_iterator I = Iter, E = Stack.back().first.rend(); 902 Scope *TopScope = nullptr; 903 while (I != E && !isParallelOrTaskRegion(I->Directive)) 904 ++I; 905 if (I == E) 906 return false; 907 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr; 908 Scope *CurScope = getCurScope(); 909 while (CurScope != TopScope && !CurScope->isDeclScope(D)) 910 CurScope = CurScope->getParent(); 911 return CurScope != TopScope; 912 } 913 return false; 914 } 915 916 DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) { 917 D = getCanonicalDecl(D); 918 DSAVarData DVar; 919 920 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 921 // in a Construct, C/C++, predetermined, p.1] 922 // Variables appearing in threadprivate directives are threadprivate. 923 auto *VD = dyn_cast<VarDecl>(D); 924 if ((VD && VD->getTLSKind() != VarDecl::TLS_None && 925 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 926 SemaRef.getLangOpts().OpenMPUseTLS && 927 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) || 928 (VD && VD->getStorageClass() == SC_Register && 929 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) { 930 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(), 931 D->getLocation()), 932 OMPC_threadprivate); 933 } 934 auto TI = Threadprivates.find(D); 935 if (TI != Threadprivates.end()) { 936 DVar.RefExpr = TI->getSecond().RefExpr.getPointer(); 937 DVar.CKind = OMPC_threadprivate; 938 return DVar; 939 } 940 941 if (isStackEmpty()) 942 // Not in OpenMP execution region and top scope was already checked. 943 return DVar; 944 945 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 946 // in a Construct, C/C++, predetermined, p.4] 947 // Static data members are shared. 948 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 949 // in a Construct, C/C++, predetermined, p.7] 950 // Variables with static storage duration that are declared in a scope 951 // inside the construct are shared. 952 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; }; 953 if (VD && VD->isStaticDataMember()) { 954 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent); 955 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr) 956 return DVar; 957 958 DVar.CKind = OMPC_shared; 959 return DVar; 960 } 961 962 QualType Type = D->getType().getNonReferenceType().getCanonicalType(); 963 bool IsConstant = Type.isConstant(SemaRef.getASTContext()); 964 Type = SemaRef.getASTContext().getBaseElementType(Type); 965 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 966 // in a Construct, C/C++, predetermined, p.6] 967 // Variables with const qualified type having no mutable member are 968 // shared. 969 CXXRecordDecl *RD = 970 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr; 971 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD)) 972 if (auto *CTD = CTSD->getSpecializedTemplate()) 973 RD = CTD->getTemplatedDecl(); 974 if (IsConstant && 975 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() && 976 RD->hasMutableFields())) { 977 // Variables with const-qualified type having no mutable member may be 978 // listed in a firstprivate clause, even if they are static data members. 979 DSAVarData DVarTemp = hasDSA( 980 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; }, 981 MatchesAlways, FromParent); 982 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr) 983 return DVar; 984 985 DVar.CKind = OMPC_shared; 986 return DVar; 987 } 988 989 // Explicitly specified attributes and local variables with predetermined 990 // attributes. 991 auto I = Stack.back().first.rbegin(); 992 auto EndI = Stack.back().first.rend(); 993 if (FromParent && I != EndI) 994 std::advance(I, 1); 995 if (I->SharingMap.count(D)) { 996 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer(); 997 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy; 998 DVar.CKind = I->SharingMap[D].Attributes; 999 DVar.ImplicitDSALoc = I->DefaultAttrLoc; 1000 DVar.DKind = I->Directive; 1001 } 1002 1003 return DVar; 1004 } 1005 1006 DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D, 1007 bool FromParent) { 1008 if (isStackEmpty()) { 1009 StackTy::reverse_iterator I; 1010 return getDSA(I, D); 1011 } 1012 D = getCanonicalDecl(D); 1013 auto StartI = Stack.back().first.rbegin(); 1014 auto EndI = Stack.back().first.rend(); 1015 if (FromParent && StartI != EndI) 1016 std::advance(StartI, 1); 1017 return getDSA(StartI, D); 1018 } 1019 1020 DSAStackTy::DSAVarData 1021 DSAStackTy::hasDSA(ValueDecl *D, 1022 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 1023 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 1024 bool FromParent) { 1025 if (isStackEmpty()) 1026 return {}; 1027 D = getCanonicalDecl(D); 1028 auto I = Stack.back().first.rbegin(); 1029 auto EndI = Stack.back().first.rend(); 1030 if (FromParent && I != EndI) 1031 std::advance(I, 1); 1032 for (; I != EndI; std::advance(I, 1)) { 1033 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive)) 1034 continue; 1035 auto NewI = I; 1036 DSAVarData DVar = getDSA(NewI, D); 1037 if (I == NewI && CPred(DVar.CKind)) 1038 return DVar; 1039 } 1040 return {}; 1041 } 1042 1043 DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA( 1044 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 1045 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 1046 bool FromParent) { 1047 if (isStackEmpty()) 1048 return {}; 1049 D = getCanonicalDecl(D); 1050 auto StartI = Stack.back().first.rbegin(); 1051 auto EndI = Stack.back().first.rend(); 1052 if (FromParent && StartI != EndI) 1053 std::advance(StartI, 1); 1054 if (StartI == EndI || !DPred(StartI->Directive)) 1055 return {}; 1056 auto NewI = StartI; 1057 DSAVarData DVar = getDSA(NewI, D); 1058 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData(); 1059 } 1060 1061 bool DSAStackTy::hasExplicitDSA( 1062 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred, 1063 unsigned Level, bool NotLastprivate) { 1064 if (CPred(ClauseKindMode)) 1065 return true; 1066 if (isStackEmpty()) 1067 return false; 1068 D = getCanonicalDecl(D); 1069 auto StartI = Stack.back().first.begin(); 1070 auto EndI = Stack.back().first.end(); 1071 if (std::distance(StartI, EndI) <= (int)Level) 1072 return false; 1073 std::advance(StartI, Level); 1074 return (StartI->SharingMap.count(D) > 0) && 1075 StartI->SharingMap[D].RefExpr.getPointer() && 1076 CPred(StartI->SharingMap[D].Attributes) && 1077 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt()); 1078 } 1079 1080 bool DSAStackTy::hasExplicitDirective( 1081 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred, 1082 unsigned Level) { 1083 if (isStackEmpty()) 1084 return false; 1085 auto StartI = Stack.back().first.begin(); 1086 auto EndI = Stack.back().first.end(); 1087 if (std::distance(StartI, EndI) <= (int)Level) 1088 return false; 1089 std::advance(StartI, Level); 1090 return DPred(StartI->Directive); 1091 } 1092 1093 bool DSAStackTy::hasDirective( 1094 const llvm::function_ref<bool(OpenMPDirectiveKind, 1095 const DeclarationNameInfo &, SourceLocation)> 1096 &DPred, 1097 bool FromParent) { 1098 // We look only in the enclosing region. 1099 if (isStackEmpty()) 1100 return false; 1101 auto StartI = std::next(Stack.back().first.rbegin()); 1102 auto EndI = Stack.back().first.rend(); 1103 if (FromParent && StartI != EndI) 1104 StartI = std::next(StartI); 1105 for (auto I = StartI, EE = EndI; I != EE; ++I) { 1106 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc)) 1107 return true; 1108 } 1109 return false; 1110 } 1111 1112 void Sema::InitDataSharingAttributesStack() { 1113 VarDataSharingAttributesStack = new DSAStackTy(*this); 1114 } 1115 1116 #define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack) 1117 1118 void Sema::pushOpenMPFunctionRegion() { 1119 DSAStack->pushFunction(); 1120 } 1121 1122 void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) { 1123 DSAStack->popFunction(OldFSI); 1124 } 1125 1126 bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) { 1127 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1128 1129 auto &Ctx = getASTContext(); 1130 bool IsByRef = true; 1131 1132 // Find the directive that is associated with the provided scope. 1133 D = cast<ValueDecl>(D->getCanonicalDecl()); 1134 auto Ty = D->getType(); 1135 1136 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) { 1137 // This table summarizes how a given variable should be passed to the device 1138 // given its type and the clauses where it appears. This table is based on 1139 // the description in OpenMP 4.5 [2.10.4, target Construct] and 1140 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses]. 1141 // 1142 // ========================================================================= 1143 // | type | defaultmap | pvt | first | is_device_ptr | map | res. | 1144 // | |(tofrom:scalar)| | pvt | | | | 1145 // ========================================================================= 1146 // | scl | | | | - | | bycopy| 1147 // | scl | | - | x | - | - | bycopy| 1148 // | scl | | x | - | - | - | null | 1149 // | scl | x | | | - | | byref | 1150 // | scl | x | - | x | - | - | bycopy| 1151 // | scl | x | x | - | - | - | null | 1152 // | scl | | - | - | - | x | byref | 1153 // | scl | x | - | - | - | x | byref | 1154 // 1155 // | agg | n.a. | | | - | | byref | 1156 // | agg | n.a. | - | x | - | - | byref | 1157 // | agg | n.a. | x | - | - | - | null | 1158 // | agg | n.a. | - | - | - | x | byref | 1159 // | agg | n.a. | - | - | - | x[] | byref | 1160 // 1161 // | ptr | n.a. | | | - | | bycopy| 1162 // | ptr | n.a. | - | x | - | - | bycopy| 1163 // | ptr | n.a. | x | - | - | - | null | 1164 // | ptr | n.a. | - | - | - | x | byref | 1165 // | ptr | n.a. | - | - | - | x[] | bycopy| 1166 // | ptr | n.a. | - | - | x | | bycopy| 1167 // | ptr | n.a. | - | - | x | x | bycopy| 1168 // | ptr | n.a. | - | - | x | x[] | bycopy| 1169 // ========================================================================= 1170 // Legend: 1171 // scl - scalar 1172 // ptr - pointer 1173 // agg - aggregate 1174 // x - applies 1175 // - - invalid in this combination 1176 // [] - mapped with an array section 1177 // byref - should be mapped by reference 1178 // byval - should be mapped by value 1179 // null - initialize a local variable to null on the device 1180 // 1181 // Observations: 1182 // - All scalar declarations that show up in a map clause have to be passed 1183 // by reference, because they may have been mapped in the enclosing data 1184 // environment. 1185 // - If the scalar value does not fit the size of uintptr, it has to be 1186 // passed by reference, regardless the result in the table above. 1187 // - For pointers mapped by value that have either an implicit map or an 1188 // array section, the runtime library may pass the NULL value to the 1189 // device instead of the value passed to it by the compiler. 1190 1191 if (Ty->isReferenceType()) 1192 Ty = Ty->castAs<ReferenceType>()->getPointeeType(); 1193 1194 // Locate map clauses and see if the variable being captured is referred to 1195 // in any of those clauses. Here we only care about variables, not fields, 1196 // because fields are part of aggregates. 1197 bool IsVariableUsedInMapClause = false; 1198 bool IsVariableAssociatedWithSection = false; 1199 1200 DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1201 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 1202 MapExprComponents, 1203 OpenMPClauseKind WhereFoundClauseKind) { 1204 // Only the map clause information influences how a variable is 1205 // captured. E.g. is_device_ptr does not require changing the default 1206 // behavior. 1207 if (WhereFoundClauseKind != OMPC_map) 1208 return false; 1209 1210 auto EI = MapExprComponents.rbegin(); 1211 auto EE = MapExprComponents.rend(); 1212 1213 assert(EI != EE && "Invalid map expression!"); 1214 1215 if (isa<DeclRefExpr>(EI->getAssociatedExpression())) 1216 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D; 1217 1218 ++EI; 1219 if (EI == EE) 1220 return false; 1221 1222 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) || 1223 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) || 1224 isa<MemberExpr>(EI->getAssociatedExpression())) { 1225 IsVariableAssociatedWithSection = true; 1226 // There is nothing more we need to know about this variable. 1227 return true; 1228 } 1229 1230 // Keep looking for more map info. 1231 return false; 1232 }); 1233 1234 if (IsVariableUsedInMapClause) { 1235 // If variable is identified in a map clause it is always captured by 1236 // reference except if it is a pointer that is dereferenced somehow. 1237 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection); 1238 } else { 1239 // By default, all the data that has a scalar type is mapped by copy. 1240 IsByRef = !Ty->isScalarType(); 1241 } 1242 } 1243 1244 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) { 1245 IsByRef = !DSAStack->hasExplicitDSA( 1246 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; }, 1247 Level, /*NotLastprivate=*/true); 1248 } 1249 1250 // When passing data by copy, we need to make sure it fits the uintptr size 1251 // and alignment, because the runtime library only deals with uintptr types. 1252 // If it does not fit the uintptr size, we need to pass the data by reference 1253 // instead. 1254 if (!IsByRef && 1255 (Ctx.getTypeSizeInChars(Ty) > 1256 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) || 1257 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) { 1258 IsByRef = true; 1259 } 1260 1261 return IsByRef; 1262 } 1263 1264 unsigned Sema::getOpenMPNestingLevel() const { 1265 assert(getLangOpts().OpenMP); 1266 return DSAStack->getNestingLevel(); 1267 } 1268 1269 VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) { 1270 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1271 D = getCanonicalDecl(D); 1272 1273 // If we are attempting to capture a global variable in a directive with 1274 // 'target' we return true so that this global is also mapped to the device. 1275 // 1276 // FIXME: If the declaration is enclosed in a 'declare target' directive, 1277 // then it should not be captured. Therefore, an extra check has to be 1278 // inserted here once support for 'declare target' is added. 1279 // 1280 auto *VD = dyn_cast<VarDecl>(D); 1281 if (VD && !VD->hasLocalStorage()) { 1282 if (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) && 1283 !DSAStack->isClauseParsingMode()) 1284 return VD; 1285 if (DSAStack->hasDirective( 1286 [](OpenMPDirectiveKind K, const DeclarationNameInfo &, 1287 SourceLocation) -> bool { 1288 return isOpenMPTargetExecutionDirective(K); 1289 }, 1290 false)) 1291 return VD; 1292 } 1293 1294 if (DSAStack->getCurrentDirective() != OMPD_unknown && 1295 (!DSAStack->isClauseParsingMode() || 1296 DSAStack->getParentDirective() != OMPD_unknown)) { 1297 auto &&Info = DSAStack->isLoopControlVariable(D); 1298 if (Info.first || 1299 (VD && VD->hasLocalStorage() && 1300 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) || 1301 (VD && DSAStack->isForceVarCapturing())) 1302 return VD ? VD : Info.second; 1303 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode()); 1304 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind)) 1305 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1306 DVarPrivate = DSAStack->hasDSA( 1307 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 1308 DSAStack->isClauseParsingMode()); 1309 if (DVarPrivate.CKind != OMPC_unknown) 1310 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl()); 1311 } 1312 return nullptr; 1313 } 1314 1315 bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) { 1316 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1317 return DSAStack->hasExplicitDSA( 1318 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; }, 1319 Level) || 1320 // Consider taskgroup reduction descriptor variable a private to avoid 1321 // possible capture in the region. 1322 (DSAStack->hasExplicitDirective( 1323 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; }, 1324 Level) && 1325 DSAStack->isTaskgroupReductionRef(D, Level)); 1326 } 1327 1328 void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) { 1329 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1330 D = getCanonicalDecl(D); 1331 OpenMPClauseKind OMPC = OMPC_unknown; 1332 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) { 1333 const unsigned NewLevel = I - 1; 1334 if (DSAStack->hasExplicitDSA(D, 1335 [&OMPC](const OpenMPClauseKind K) { 1336 if (isOpenMPPrivate(K)) { 1337 OMPC = K; 1338 return true; 1339 } 1340 return false; 1341 }, 1342 NewLevel)) 1343 break; 1344 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel( 1345 D, NewLevel, 1346 [](OMPClauseMappableExprCommon::MappableExprComponentListRef, 1347 OpenMPClauseKind) { return true; })) { 1348 OMPC = OMPC_map; 1349 break; 1350 } 1351 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1352 NewLevel)) { 1353 OMPC = OMPC_firstprivate; 1354 break; 1355 } 1356 } 1357 if (OMPC != OMPC_unknown) 1358 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC)); 1359 } 1360 1361 bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) { 1362 assert(LangOpts.OpenMP && "OpenMP is not allowed"); 1363 // Return true if the current level is no longer enclosed in a target region. 1364 1365 auto *VD = dyn_cast<VarDecl>(D); 1366 return VD && !VD->hasLocalStorage() && 1367 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, 1368 Level); 1369 } 1370 1371 void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; } 1372 1373 void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind, 1374 const DeclarationNameInfo &DirName, 1375 Scope *CurScope, SourceLocation Loc) { 1376 DSAStack->push(DKind, DirName, CurScope, Loc); 1377 PushExpressionEvaluationContext( 1378 ExpressionEvaluationContext::PotentiallyEvaluated); 1379 } 1380 1381 void Sema::StartOpenMPClause(OpenMPClauseKind K) { 1382 DSAStack->setClauseParsingMode(K); 1383 } 1384 1385 void Sema::EndOpenMPClause() { 1386 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown); 1387 } 1388 1389 void Sema::EndOpenMPDSABlock(Stmt *CurDirective) { 1390 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1] 1391 // A variable of class type (or array thereof) that appears in a lastprivate 1392 // clause requires an accessible, unambiguous default constructor for the 1393 // class type, unless the list item is also specified in a firstprivate 1394 // clause. 1395 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) { 1396 for (auto *C : D->clauses()) { 1397 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) { 1398 SmallVector<Expr *, 8> PrivateCopies; 1399 for (auto *DE : Clause->varlists()) { 1400 if (DE->isValueDependent() || DE->isTypeDependent()) { 1401 PrivateCopies.push_back(nullptr); 1402 continue; 1403 } 1404 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens()); 1405 VarDecl *VD = cast<VarDecl>(DRE->getDecl()); 1406 QualType Type = VD->getType().getNonReferenceType(); 1407 auto DVar = DSAStack->getTopDSA(VD, false); 1408 if (DVar.CKind == OMPC_lastprivate) { 1409 // Generate helper private variable and initialize it with the 1410 // default value. The address of the original variable is replaced 1411 // by the address of the new private variable in CodeGen. This new 1412 // variable is not added to IdResolver, so the code in the OpenMP 1413 // region uses original variable for proper diagnostics. 1414 auto *VDPrivate = buildVarDecl( 1415 *this, DE->getExprLoc(), Type.getUnqualifiedType(), 1416 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr); 1417 ActOnUninitializedDecl(VDPrivate); 1418 if (VDPrivate->isInvalidDecl()) 1419 continue; 1420 PrivateCopies.push_back(buildDeclRefExpr( 1421 *this, VDPrivate, DE->getType(), DE->getExprLoc())); 1422 } else { 1423 // The variable is also a firstprivate, so initialization sequence 1424 // for private copy is generated already. 1425 PrivateCopies.push_back(nullptr); 1426 } 1427 } 1428 // Set initializers to private copies if no errors were found. 1429 if (PrivateCopies.size() == Clause->varlist_size()) 1430 Clause->setPrivateCopies(PrivateCopies); 1431 } 1432 } 1433 } 1434 1435 DSAStack->pop(); 1436 DiscardCleanupsInEvaluationContext(); 1437 PopExpressionEvaluationContext(); 1438 } 1439 1440 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 1441 Expr *NumIterations, Sema &SemaRef, 1442 Scope *S, DSAStackTy *Stack); 1443 1444 namespace { 1445 1446 class VarDeclFilterCCC : public CorrectionCandidateCallback { 1447 private: 1448 Sema &SemaRef; 1449 1450 public: 1451 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {} 1452 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1453 NamedDecl *ND = Candidate.getCorrectionDecl(); 1454 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) { 1455 return VD->hasGlobalStorage() && 1456 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1457 SemaRef.getCurScope()); 1458 } 1459 return false; 1460 } 1461 }; 1462 1463 class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback { 1464 private: 1465 Sema &SemaRef; 1466 1467 public: 1468 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {} 1469 bool ValidateCandidate(const TypoCorrection &Candidate) override { 1470 NamedDecl *ND = Candidate.getCorrectionDecl(); 1471 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 1472 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(), 1473 SemaRef.getCurScope()); 1474 } 1475 return false; 1476 } 1477 }; 1478 1479 } // namespace 1480 1481 ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope, 1482 CXXScopeSpec &ScopeSpec, 1483 const DeclarationNameInfo &Id) { 1484 LookupResult Lookup(*this, Id, LookupOrdinaryName); 1485 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 1486 1487 if (Lookup.isAmbiguous()) 1488 return ExprError(); 1489 1490 VarDecl *VD; 1491 if (!Lookup.isSingleResult()) { 1492 if (TypoCorrection Corrected = CorrectTypo( 1493 Id, LookupOrdinaryName, CurScope, nullptr, 1494 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) { 1495 diagnoseTypo(Corrected, 1496 PDiag(Lookup.empty() 1497 ? diag::err_undeclared_var_use_suggest 1498 : diag::err_omp_expected_var_arg_suggest) 1499 << Id.getName()); 1500 VD = Corrected.getCorrectionDeclAs<VarDecl>(); 1501 } else { 1502 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use 1503 : diag::err_omp_expected_var_arg) 1504 << Id.getName(); 1505 return ExprError(); 1506 } 1507 } else { 1508 if (!(VD = Lookup.getAsSingle<VarDecl>())) { 1509 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName(); 1510 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at); 1511 return ExprError(); 1512 } 1513 } 1514 Lookup.suppressDiagnostics(); 1515 1516 // OpenMP [2.9.2, Syntax, C/C++] 1517 // Variables must be file-scope, namespace-scope, or static block-scope. 1518 if (!VD->hasGlobalStorage()) { 1519 Diag(Id.getLoc(), diag::err_omp_global_var_arg) 1520 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal(); 1521 bool IsDecl = 1522 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1523 Diag(VD->getLocation(), 1524 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1525 << VD; 1526 return ExprError(); 1527 } 1528 1529 VarDecl *CanonicalVD = VD->getCanonicalDecl(); 1530 NamedDecl *ND = cast<NamedDecl>(CanonicalVD); 1531 // OpenMP [2.9.2, Restrictions, C/C++, p.2] 1532 // A threadprivate directive for file-scope variables must appear outside 1533 // any definition or declaration. 1534 if (CanonicalVD->getDeclContext()->isTranslationUnit() && 1535 !getCurLexicalContext()->isTranslationUnit()) { 1536 Diag(Id.getLoc(), diag::err_omp_var_scope) 1537 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1538 bool IsDecl = 1539 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1540 Diag(VD->getLocation(), 1541 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1542 << VD; 1543 return ExprError(); 1544 } 1545 // OpenMP [2.9.2, Restrictions, C/C++, p.3] 1546 // A threadprivate directive for static class member variables must appear 1547 // in the class definition, in the same scope in which the member 1548 // variables are declared. 1549 if (CanonicalVD->isStaticDataMember() && 1550 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) { 1551 Diag(Id.getLoc(), diag::err_omp_var_scope) 1552 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1553 bool IsDecl = 1554 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1555 Diag(VD->getLocation(), 1556 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1557 << VD; 1558 return ExprError(); 1559 } 1560 // OpenMP [2.9.2, Restrictions, C/C++, p.4] 1561 // A threadprivate directive for namespace-scope variables must appear 1562 // outside any definition or declaration other than the namespace 1563 // definition itself. 1564 if (CanonicalVD->getDeclContext()->isNamespace() && 1565 (!getCurLexicalContext()->isFileContext() || 1566 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) { 1567 Diag(Id.getLoc(), diag::err_omp_var_scope) 1568 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1569 bool IsDecl = 1570 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1571 Diag(VD->getLocation(), 1572 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1573 << VD; 1574 return ExprError(); 1575 } 1576 // OpenMP [2.9.2, Restrictions, C/C++, p.6] 1577 // A threadprivate directive for static block-scope variables must appear 1578 // in the scope of the variable and not in a nested scope. 1579 if (CanonicalVD->isStaticLocal() && CurScope && 1580 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) { 1581 Diag(Id.getLoc(), diag::err_omp_var_scope) 1582 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1583 bool IsDecl = 1584 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1585 Diag(VD->getLocation(), 1586 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1587 << VD; 1588 return ExprError(); 1589 } 1590 1591 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6] 1592 // A threadprivate directive must lexically precede all references to any 1593 // of the variables in its list. 1594 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) { 1595 Diag(Id.getLoc(), diag::err_omp_var_used) 1596 << getOpenMPDirectiveName(OMPD_threadprivate) << VD; 1597 return ExprError(); 1598 } 1599 1600 QualType ExprType = VD->getType().getNonReferenceType(); 1601 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(), 1602 SourceLocation(), VD, 1603 /*RefersToEnclosingVariableOrCapture=*/false, 1604 Id.getLoc(), ExprType, VK_LValue); 1605 } 1606 1607 Sema::DeclGroupPtrTy 1608 Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc, 1609 ArrayRef<Expr *> VarList) { 1610 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) { 1611 CurContext->addDecl(D); 1612 return DeclGroupPtrTy::make(DeclGroupRef(D)); 1613 } 1614 return nullptr; 1615 } 1616 1617 namespace { 1618 class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> { 1619 Sema &SemaRef; 1620 1621 public: 1622 bool VisitDeclRefExpr(const DeclRefExpr *E) { 1623 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1624 if (VD->hasLocalStorage()) { 1625 SemaRef.Diag(E->getLocStart(), 1626 diag::err_omp_local_var_in_threadprivate_init) 1627 << E->getSourceRange(); 1628 SemaRef.Diag(VD->getLocation(), diag::note_defined_here) 1629 << VD << VD->getSourceRange(); 1630 return true; 1631 } 1632 } 1633 return false; 1634 } 1635 bool VisitStmt(const Stmt *S) { 1636 for (auto Child : S->children()) { 1637 if (Child && Visit(Child)) 1638 return true; 1639 } 1640 return false; 1641 } 1642 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {} 1643 }; 1644 } // namespace 1645 1646 OMPThreadPrivateDecl * 1647 Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) { 1648 SmallVector<Expr *, 8> Vars; 1649 for (auto &RefExpr : VarList) { 1650 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr); 1651 VarDecl *VD = cast<VarDecl>(DE->getDecl()); 1652 SourceLocation ILoc = DE->getExprLoc(); 1653 1654 // Mark variable as used. 1655 VD->setReferenced(); 1656 VD->markUsed(Context); 1657 1658 QualType QType = VD->getType(); 1659 if (QType->isDependentType() || QType->isInstantiationDependentType()) { 1660 // It will be analyzed later. 1661 Vars.push_back(DE); 1662 continue; 1663 } 1664 1665 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1666 // A threadprivate variable must not have an incomplete type. 1667 if (RequireCompleteType(ILoc, VD->getType(), 1668 diag::err_omp_threadprivate_incomplete_type)) { 1669 continue; 1670 } 1671 1672 // OpenMP [2.9.2, Restrictions, C/C++, p.10] 1673 // A threadprivate variable must not have a reference type. 1674 if (VD->getType()->isReferenceType()) { 1675 Diag(ILoc, diag::err_omp_ref_type_arg) 1676 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType(); 1677 bool IsDecl = 1678 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1679 Diag(VD->getLocation(), 1680 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1681 << VD; 1682 continue; 1683 } 1684 1685 // Check if this is a TLS variable. If TLS is not being supported, produce 1686 // the corresponding diagnostic. 1687 if ((VD->getTLSKind() != VarDecl::TLS_None && 1688 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() && 1689 getLangOpts().OpenMPUseTLS && 1690 getASTContext().getTargetInfo().isTLSSupported())) || 1691 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() && 1692 !VD->isLocalVarDecl())) { 1693 Diag(ILoc, diag::err_omp_var_thread_local) 1694 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1); 1695 bool IsDecl = 1696 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 1697 Diag(VD->getLocation(), 1698 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 1699 << VD; 1700 continue; 1701 } 1702 1703 // Check if initial value of threadprivate variable reference variable with 1704 // local storage (it is not supported by runtime). 1705 if (auto Init = VD->getAnyInitializer()) { 1706 LocalVarRefChecker Checker(*this); 1707 if (Checker.Visit(Init)) 1708 continue; 1709 } 1710 1711 Vars.push_back(RefExpr); 1712 DSAStack->addDSA(VD, DE, OMPC_threadprivate); 1713 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit( 1714 Context, SourceRange(Loc, Loc))); 1715 if (auto *ML = Context.getASTMutationListener()) 1716 ML->DeclarationMarkedOpenMPThreadPrivate(VD); 1717 } 1718 OMPThreadPrivateDecl *D = nullptr; 1719 if (!Vars.empty()) { 1720 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc, 1721 Vars); 1722 D->setAccess(AS_public); 1723 } 1724 return D; 1725 } 1726 1727 static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack, 1728 const ValueDecl *D, DSAStackTy::DSAVarData DVar, 1729 bool IsLoopIterVar = false) { 1730 if (DVar.RefExpr) { 1731 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa) 1732 << getOpenMPClauseName(DVar.CKind); 1733 return; 1734 } 1735 enum { 1736 PDSA_StaticMemberShared, 1737 PDSA_StaticLocalVarShared, 1738 PDSA_LoopIterVarPrivate, 1739 PDSA_LoopIterVarLinear, 1740 PDSA_LoopIterVarLastprivate, 1741 PDSA_ConstVarShared, 1742 PDSA_GlobalVarShared, 1743 PDSA_TaskVarFirstprivate, 1744 PDSA_LocalVarPrivate, 1745 PDSA_Implicit 1746 } Reason = PDSA_Implicit; 1747 bool ReportHint = false; 1748 auto ReportLoc = D->getLocation(); 1749 auto *VD = dyn_cast<VarDecl>(D); 1750 if (IsLoopIterVar) { 1751 if (DVar.CKind == OMPC_private) 1752 Reason = PDSA_LoopIterVarPrivate; 1753 else if (DVar.CKind == OMPC_lastprivate) 1754 Reason = PDSA_LoopIterVarLastprivate; 1755 else 1756 Reason = PDSA_LoopIterVarLinear; 1757 } else if (isOpenMPTaskingDirective(DVar.DKind) && 1758 DVar.CKind == OMPC_firstprivate) { 1759 Reason = PDSA_TaskVarFirstprivate; 1760 ReportLoc = DVar.ImplicitDSALoc; 1761 } else if (VD && VD->isStaticLocal()) 1762 Reason = PDSA_StaticLocalVarShared; 1763 else if (VD && VD->isStaticDataMember()) 1764 Reason = PDSA_StaticMemberShared; 1765 else if (VD && VD->isFileVarDecl()) 1766 Reason = PDSA_GlobalVarShared; 1767 else if (D->getType().isConstant(SemaRef.getASTContext())) 1768 Reason = PDSA_ConstVarShared; 1769 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) { 1770 ReportHint = true; 1771 Reason = PDSA_LocalVarPrivate; 1772 } 1773 if (Reason != PDSA_Implicit) { 1774 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa) 1775 << Reason << ReportHint 1776 << getOpenMPDirectiveName(Stack->getCurrentDirective()); 1777 } else if (DVar.ImplicitDSALoc.isValid()) { 1778 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa) 1779 << getOpenMPClauseName(DVar.CKind); 1780 } 1781 } 1782 1783 namespace { 1784 class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> { 1785 DSAStackTy *Stack; 1786 Sema &SemaRef; 1787 bool ErrorFound; 1788 CapturedStmt *CS; 1789 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate; 1790 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 1791 llvm::DenseSet<ValueDecl *> ImplicitDeclarations; 1792 1793 public: 1794 void VisitDeclRefExpr(DeclRefExpr *E) { 1795 if (E->isTypeDependent() || E->isValueDependent() || 1796 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1797 return; 1798 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) { 1799 VD = VD->getCanonicalDecl(); 1800 // Skip internally declared variables. 1801 if (VD->isLocalVarDecl() && !CS->capturesVariable(VD)) 1802 return; 1803 1804 auto DVar = Stack->getTopDSA(VD, false); 1805 // Check if the variable has explicit DSA set and stop analysis if it so. 1806 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second) 1807 return; 1808 1809 auto ELoc = E->getExprLoc(); 1810 auto DKind = Stack->getCurrentDirective(); 1811 // The default(none) clause requires that each variable that is referenced 1812 // in the construct, and does not have a predetermined data-sharing 1813 // attribute, must have its data-sharing attribute explicitly determined 1814 // by being listed in a data-sharing attribute clause. 1815 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none && 1816 isParallelOrTaskRegion(DKind) && 1817 VarsWithInheritedDSA.count(VD) == 0) { 1818 VarsWithInheritedDSA[VD] = E; 1819 return; 1820 } 1821 1822 // OpenMP [2.9.3.6, Restrictions, p.2] 1823 // A list item that appears in a reduction clause of the innermost 1824 // enclosing worksharing or parallel construct may not be accessed in an 1825 // explicit task. 1826 DVar = Stack->hasInnermostDSA( 1827 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 1828 [](OpenMPDirectiveKind K) -> bool { 1829 return isOpenMPParallelDirective(K) || 1830 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K); 1831 }, 1832 /*FromParent=*/true); 1833 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 1834 ErrorFound = true; 1835 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1836 ReportOriginalDSA(SemaRef, Stack, VD, DVar); 1837 return; 1838 } 1839 1840 // Define implicit data-sharing attributes for task. 1841 DVar = Stack->getImplicitDSA(VD, false); 1842 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 1843 !Stack->isLoopControlVariable(VD).first) 1844 ImplicitFirstprivate.push_back(E); 1845 } 1846 } 1847 void VisitMemberExpr(MemberExpr *E) { 1848 if (E->isTypeDependent() || E->isValueDependent() || 1849 E->containsUnexpandedParameterPack() || E->isInstantiationDependent()) 1850 return; 1851 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) { 1852 if (auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) { 1853 auto DVar = Stack->getTopDSA(FD, false); 1854 // Check if the variable has explicit DSA set and stop analysis if it 1855 // so. 1856 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second) 1857 return; 1858 1859 auto ELoc = E->getExprLoc(); 1860 auto DKind = Stack->getCurrentDirective(); 1861 // OpenMP [2.9.3.6, Restrictions, p.2] 1862 // A list item that appears in a reduction clause of the innermost 1863 // enclosing worksharing or parallel construct may not be accessed in 1864 // an explicit task. 1865 DVar = Stack->hasInnermostDSA( 1866 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 1867 [](OpenMPDirectiveKind K) -> bool { 1868 return isOpenMPParallelDirective(K) || 1869 isOpenMPWorksharingDirective(K) || 1870 isOpenMPTeamsDirective(K); 1871 }, 1872 /*FromParent=*/true); 1873 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) { 1874 ErrorFound = true; 1875 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task); 1876 ReportOriginalDSA(SemaRef, Stack, FD, DVar); 1877 return; 1878 } 1879 1880 // Define implicit data-sharing attributes for task. 1881 DVar = Stack->getImplicitDSA(FD, false); 1882 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared && 1883 !Stack->isLoopControlVariable(FD).first) 1884 ImplicitFirstprivate.push_back(E); 1885 } 1886 } else 1887 Visit(E->getBase()); 1888 } 1889 void VisitOMPExecutableDirective(OMPExecutableDirective *S) { 1890 for (auto *C : S->clauses()) { 1891 // Skip analysis of arguments of implicitly defined firstprivate clause 1892 // for task directives. 1893 if (C && (!isa<OMPFirstprivateClause>(C) || C->getLocStart().isValid())) 1894 for (auto *CC : C->children()) { 1895 if (CC) 1896 Visit(CC); 1897 } 1898 } 1899 } 1900 void VisitStmt(Stmt *S) { 1901 for (auto *C : S->children()) { 1902 if (C && !isa<OMPExecutableDirective>(C)) 1903 Visit(C); 1904 } 1905 } 1906 1907 bool isErrorFound() { return ErrorFound; } 1908 ArrayRef<Expr *> getImplicitFirstprivate() { return ImplicitFirstprivate; } 1909 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() { 1910 return VarsWithInheritedDSA; 1911 } 1912 1913 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS) 1914 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {} 1915 }; 1916 } // namespace 1917 1918 void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) { 1919 switch (DKind) { 1920 case OMPD_parallel: 1921 case OMPD_parallel_for: 1922 case OMPD_parallel_for_simd: 1923 case OMPD_parallel_sections: 1924 case OMPD_teams: { 1925 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1926 QualType KmpInt32PtrTy = 1927 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1928 Sema::CapturedParamNameType Params[] = { 1929 std::make_pair(".global_tid.", KmpInt32PtrTy), 1930 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1931 std::make_pair(StringRef(), QualType()) // __context with shared vars 1932 }; 1933 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1934 Params); 1935 break; 1936 } 1937 case OMPD_target_teams: 1938 case OMPD_target_parallel: { 1939 Sema::CapturedParamNameType ParamsTarget[] = { 1940 std::make_pair(StringRef(), QualType()) // __context with shared vars 1941 }; 1942 // Start a captured region for 'target' with no implicit parameters. 1943 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1944 ParamsTarget); 1945 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1946 QualType KmpInt32PtrTy = 1947 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 1948 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = { 1949 std::make_pair(".global_tid.", KmpInt32PtrTy), 1950 std::make_pair(".bound_tid.", KmpInt32PtrTy), 1951 std::make_pair(StringRef(), QualType()) // __context with shared vars 1952 }; 1953 // Start a captured region for 'teams' or 'parallel'. Both regions have 1954 // the same implicit parameters. 1955 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1956 ParamsTeamsOrParallel); 1957 break; 1958 } 1959 case OMPD_simd: 1960 case OMPD_for: 1961 case OMPD_for_simd: 1962 case OMPD_sections: 1963 case OMPD_section: 1964 case OMPD_single: 1965 case OMPD_master: 1966 case OMPD_critical: 1967 case OMPD_taskgroup: 1968 case OMPD_distribute: 1969 case OMPD_ordered: 1970 case OMPD_atomic: 1971 case OMPD_target_data: 1972 case OMPD_target: 1973 case OMPD_target_parallel_for: 1974 case OMPD_target_parallel_for_simd: 1975 case OMPD_target_simd: { 1976 Sema::CapturedParamNameType Params[] = { 1977 std::make_pair(StringRef(), QualType()) // __context with shared vars 1978 }; 1979 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1980 Params); 1981 break; 1982 } 1983 case OMPD_task: { 1984 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 1985 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 1986 FunctionProtoType::ExtProtoInfo EPI; 1987 EPI.Variadic = true; 1988 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 1989 Sema::CapturedParamNameType Params[] = { 1990 std::make_pair(".global_tid.", KmpInt32Ty), 1991 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 1992 std::make_pair(".privates.", Context.VoidPtrTy.withConst()), 1993 std::make_pair(".copy_fn.", 1994 Context.getPointerType(CopyFnType).withConst()), 1995 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 1996 std::make_pair(StringRef(), QualType()) // __context with shared vars 1997 }; 1998 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 1999 Params); 2000 // Mark this captured region as inlined, because we don't use outlined 2001 // function directly. 2002 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2003 AlwaysInlineAttr::CreateImplicit( 2004 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 2005 break; 2006 } 2007 case OMPD_taskloop: 2008 case OMPD_taskloop_simd: { 2009 QualType KmpInt32Ty = 2010 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1); 2011 QualType KmpUInt64Ty = 2012 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 2013 QualType KmpInt64Ty = 2014 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 2015 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()}; 2016 FunctionProtoType::ExtProtoInfo EPI; 2017 EPI.Variadic = true; 2018 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI); 2019 Sema::CapturedParamNameType Params[] = { 2020 std::make_pair(".global_tid.", KmpInt32Ty), 2021 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)), 2022 std::make_pair(".privates.", 2023 Context.VoidPtrTy.withConst().withRestrict()), 2024 std::make_pair( 2025 ".copy_fn.", 2026 Context.getPointerType(CopyFnType).withConst().withRestrict()), 2027 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()), 2028 std::make_pair(".lb.", KmpUInt64Ty), 2029 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty), 2030 std::make_pair(".liter.", KmpInt32Ty), 2031 std::make_pair(".reductions.", 2032 Context.VoidPtrTy.withConst().withRestrict()), 2033 std::make_pair(StringRef(), QualType()) // __context with shared vars 2034 }; 2035 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2036 Params); 2037 // Mark this captured region as inlined, because we don't use outlined 2038 // function directly. 2039 getCurCapturedRegion()->TheCapturedDecl->addAttr( 2040 AlwaysInlineAttr::CreateImplicit( 2041 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange())); 2042 break; 2043 } 2044 case OMPD_distribute_parallel_for_simd: 2045 case OMPD_distribute_simd: 2046 case OMPD_distribute_parallel_for: 2047 case OMPD_teams_distribute: 2048 case OMPD_teams_distribute_simd: 2049 case OMPD_teams_distribute_parallel_for_simd: 2050 case OMPD_teams_distribute_parallel_for: 2051 case OMPD_target_teams_distribute: 2052 case OMPD_target_teams_distribute_parallel_for: 2053 case OMPD_target_teams_distribute_parallel_for_simd: 2054 case OMPD_target_teams_distribute_simd: { 2055 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1); 2056 QualType KmpInt32PtrTy = 2057 Context.getPointerType(KmpInt32Ty).withConst().withRestrict(); 2058 Sema::CapturedParamNameType Params[] = { 2059 std::make_pair(".global_tid.", KmpInt32PtrTy), 2060 std::make_pair(".bound_tid.", KmpInt32PtrTy), 2061 std::make_pair(".previous.lb.", Context.getSizeType()), 2062 std::make_pair(".previous.ub.", Context.getSizeType()), 2063 std::make_pair(StringRef(), QualType()) // __context with shared vars 2064 }; 2065 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP, 2066 Params); 2067 break; 2068 } 2069 case OMPD_threadprivate: 2070 case OMPD_taskyield: 2071 case OMPD_barrier: 2072 case OMPD_taskwait: 2073 case OMPD_cancellation_point: 2074 case OMPD_cancel: 2075 case OMPD_flush: 2076 case OMPD_target_enter_data: 2077 case OMPD_target_exit_data: 2078 case OMPD_declare_reduction: 2079 case OMPD_declare_simd: 2080 case OMPD_declare_target: 2081 case OMPD_end_declare_target: 2082 case OMPD_target_update: 2083 llvm_unreachable("OpenMP Directive is not allowed"); 2084 case OMPD_unknown: 2085 llvm_unreachable("Unknown OpenMP directive"); 2086 } 2087 } 2088 2089 int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) { 2090 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2091 getOpenMPCaptureRegions(CaptureRegions, DKind); 2092 return CaptureRegions.size(); 2093 } 2094 2095 static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id, 2096 Expr *CaptureExpr, bool WithInit, 2097 bool AsExpression) { 2098 assert(CaptureExpr); 2099 ASTContext &C = S.getASTContext(); 2100 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts(); 2101 QualType Ty = Init->getType(); 2102 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) { 2103 if (S.getLangOpts().CPlusPlus) 2104 Ty = C.getLValueReferenceType(Ty); 2105 else { 2106 Ty = C.getPointerType(Ty); 2107 ExprResult Res = 2108 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init); 2109 if (!Res.isUsable()) 2110 return nullptr; 2111 Init = Res.get(); 2112 } 2113 WithInit = true; 2114 } 2115 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty, 2116 CaptureExpr->getLocStart()); 2117 if (!WithInit) 2118 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange())); 2119 S.CurContext->addHiddenDecl(CED); 2120 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false); 2121 return CED; 2122 } 2123 2124 static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr, 2125 bool WithInit) { 2126 OMPCapturedExprDecl *CD; 2127 if (auto *VD = S.IsOpenMPCapturedDecl(D)) 2128 CD = cast<OMPCapturedExprDecl>(VD); 2129 else 2130 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit, 2131 /*AsExpression=*/false); 2132 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 2133 CaptureExpr->getExprLoc()); 2134 } 2135 2136 static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) { 2137 if (!Ref) { 2138 auto *CD = 2139 buildCaptureDecl(S, &S.getASTContext().Idents.get(".capture_expr."), 2140 CaptureExpr, /*WithInit=*/true, /*AsExpression=*/true); 2141 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(), 2142 CaptureExpr->getExprLoc()); 2143 } 2144 ExprResult Res = Ref; 2145 if (!S.getLangOpts().CPlusPlus && 2146 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() && 2147 Ref->getType()->isPointerType()) 2148 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref); 2149 if (!Res.isUsable()) 2150 return ExprError(); 2151 return CaptureExpr->isGLValue() ? Res : S.DefaultLvalueConversion(Res.get()); 2152 } 2153 2154 namespace { 2155 // OpenMP directives parsed in this section are represented as a 2156 // CapturedStatement with an associated statement. If a syntax error 2157 // is detected during the parsing of the associated statement, the 2158 // compiler must abort processing and close the CapturedStatement. 2159 // 2160 // Combined directives such as 'target parallel' have more than one 2161 // nested CapturedStatements. This RAII ensures that we unwind out 2162 // of all the nested CapturedStatements when an error is found. 2163 class CaptureRegionUnwinderRAII { 2164 private: 2165 Sema &S; 2166 bool &ErrorFound; 2167 OpenMPDirectiveKind DKind; 2168 2169 public: 2170 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound, 2171 OpenMPDirectiveKind DKind) 2172 : S(S), ErrorFound(ErrorFound), DKind(DKind) {} 2173 ~CaptureRegionUnwinderRAII() { 2174 if (ErrorFound) { 2175 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind); 2176 while (--ThisCaptureLevel >= 0) 2177 S.ActOnCapturedRegionError(); 2178 } 2179 } 2180 }; 2181 } // namespace 2182 2183 StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S, 2184 ArrayRef<OMPClause *> Clauses) { 2185 bool ErrorFound = false; 2186 CaptureRegionUnwinderRAII CaptureRegionUnwinder( 2187 *this, ErrorFound, DSAStack->getCurrentDirective()); 2188 if (!S.isUsable()) { 2189 ErrorFound = true; 2190 return StmtError(); 2191 } 2192 2193 OMPOrderedClause *OC = nullptr; 2194 OMPScheduleClause *SC = nullptr; 2195 SmallVector<OMPLinearClause *, 4> LCs; 2196 SmallVector<OMPClauseWithPreInit *, 8> PICs; 2197 // This is required for proper codegen. 2198 for (auto *Clause : Clauses) { 2199 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) && 2200 Clause->getClauseKind() == OMPC_in_reduction) { 2201 // Capture taskgroup task_reduction descriptors inside the tasking regions 2202 // with the corresponding in_reduction items. 2203 auto *IRC = cast<OMPInReductionClause>(Clause); 2204 for (auto *E : IRC->taskgroup_descriptors()) 2205 if (E) 2206 MarkDeclarationsReferencedInExpr(E); 2207 } 2208 if (isOpenMPPrivate(Clause->getClauseKind()) || 2209 Clause->getClauseKind() == OMPC_copyprivate || 2210 (getLangOpts().OpenMPUseTLS && 2211 getASTContext().getTargetInfo().isTLSSupported() && 2212 Clause->getClauseKind() == OMPC_copyin)) { 2213 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin); 2214 // Mark all variables in private list clauses as used in inner region. 2215 for (auto *VarRef : Clause->children()) { 2216 if (auto *E = cast_or_null<Expr>(VarRef)) { 2217 MarkDeclarationsReferencedInExpr(E); 2218 } 2219 } 2220 DSAStack->setForceVarCapturing(/*V=*/false); 2221 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { 2222 if (auto *C = OMPClauseWithPreInit::get(Clause)) 2223 PICs.push_back(C); 2224 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) { 2225 if (auto *E = C->getPostUpdateExpr()) 2226 MarkDeclarationsReferencedInExpr(E); 2227 } 2228 } 2229 if (Clause->getClauseKind() == OMPC_schedule) 2230 SC = cast<OMPScheduleClause>(Clause); 2231 else if (Clause->getClauseKind() == OMPC_ordered) 2232 OC = cast<OMPOrderedClause>(Clause); 2233 else if (Clause->getClauseKind() == OMPC_linear) 2234 LCs.push_back(cast<OMPLinearClause>(Clause)); 2235 } 2236 // OpenMP, 2.7.1 Loop Construct, Restrictions 2237 // The nonmonotonic modifier cannot be specified if an ordered clause is 2238 // specified. 2239 if (SC && 2240 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 2241 SC->getSecondScheduleModifier() == 2242 OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 2243 OC) { 2244 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic 2245 ? SC->getFirstScheduleModifierLoc() 2246 : SC->getSecondScheduleModifierLoc(), 2247 diag::err_omp_schedule_nonmonotonic_ordered) 2248 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 2249 ErrorFound = true; 2250 } 2251 if (!LCs.empty() && OC && OC->getNumForLoops()) { 2252 for (auto *C : LCs) { 2253 Diag(C->getLocStart(), diag::err_omp_linear_ordered) 2254 << SourceRange(OC->getLocStart(), OC->getLocEnd()); 2255 } 2256 ErrorFound = true; 2257 } 2258 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) && 2259 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC && 2260 OC->getNumForLoops()) { 2261 Diag(OC->getLocStart(), diag::err_omp_ordered_simd) 2262 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 2263 ErrorFound = true; 2264 } 2265 if (ErrorFound) { 2266 return StmtError(); 2267 } 2268 StmtResult SR = S; 2269 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions; 2270 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective()); 2271 for (auto ThisCaptureRegion : llvm::reverse(CaptureRegions)) { 2272 // Mark all variables in private list clauses as used in inner region. 2273 // Required for proper codegen of combined directives. 2274 // TODO: add processing for other clauses. 2275 if (isParallelOrTaskRegion(DSAStack->getCurrentDirective())) { 2276 for (auto *C : PICs) { 2277 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion(); 2278 // Find the particular capture region for the clause if the 2279 // directive is a combined one with multiple capture regions. 2280 // If the directive is not a combined one, the capture region 2281 // associated with the clause is OMPD_unknown and is generated 2282 // only once. 2283 if (CaptureRegion == ThisCaptureRegion || 2284 CaptureRegion == OMPD_unknown) { 2285 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) { 2286 for (auto *D : DS->decls()) 2287 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D)); 2288 } 2289 } 2290 } 2291 } 2292 SR = ActOnCapturedRegionEnd(SR.get()); 2293 } 2294 return SR; 2295 } 2296 2297 static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion, 2298 OpenMPDirectiveKind CancelRegion, 2299 SourceLocation StartLoc) { 2300 // CancelRegion is only needed for cancel and cancellation_point. 2301 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point) 2302 return false; 2303 2304 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for || 2305 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup) 2306 return false; 2307 2308 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region) 2309 << getOpenMPDirectiveName(CancelRegion); 2310 return true; 2311 } 2312 2313 static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack, 2314 OpenMPDirectiveKind CurrentRegion, 2315 const DeclarationNameInfo &CurrentName, 2316 OpenMPDirectiveKind CancelRegion, 2317 SourceLocation StartLoc) { 2318 if (Stack->getCurScope()) { 2319 auto ParentRegion = Stack->getParentDirective(); 2320 auto OffendingRegion = ParentRegion; 2321 bool NestingProhibited = false; 2322 bool CloseNesting = true; 2323 bool OrphanSeen = false; 2324 enum { 2325 NoRecommend, 2326 ShouldBeInParallelRegion, 2327 ShouldBeInOrderedRegion, 2328 ShouldBeInTargetRegion, 2329 ShouldBeInTeamsRegion 2330 } Recommend = NoRecommend; 2331 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) { 2332 // OpenMP [2.16, Nesting of Regions] 2333 // OpenMP constructs may not be nested inside a simd region. 2334 // OpenMP [2.8.1,simd Construct, Restrictions] 2335 // An ordered construct with the simd clause is the only OpenMP 2336 // construct that can appear in the simd region. 2337 // Allowing a SIMD construct nested in another SIMD construct is an 2338 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning 2339 // message. 2340 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd) 2341 ? diag::err_omp_prohibited_region_simd 2342 : diag::warn_omp_nesting_simd); 2343 return CurrentRegion != OMPD_simd; 2344 } 2345 if (ParentRegion == OMPD_atomic) { 2346 // OpenMP [2.16, Nesting of Regions] 2347 // OpenMP constructs may not be nested inside an atomic region. 2348 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic); 2349 return true; 2350 } 2351 if (CurrentRegion == OMPD_section) { 2352 // OpenMP [2.7.2, sections Construct, Restrictions] 2353 // Orphaned section directives are prohibited. That is, the section 2354 // directives must appear within the sections construct and must not be 2355 // encountered elsewhere in the sections region. 2356 if (ParentRegion != OMPD_sections && 2357 ParentRegion != OMPD_parallel_sections) { 2358 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive) 2359 << (ParentRegion != OMPD_unknown) 2360 << getOpenMPDirectiveName(ParentRegion); 2361 return true; 2362 } 2363 return false; 2364 } 2365 // Allow some constructs (except teams) to be orphaned (they could be 2366 // used in functions, called from OpenMP regions with the required 2367 // preconditions). 2368 if (ParentRegion == OMPD_unknown && 2369 !isOpenMPNestingTeamsDirective(CurrentRegion)) 2370 return false; 2371 if (CurrentRegion == OMPD_cancellation_point || 2372 CurrentRegion == OMPD_cancel) { 2373 // OpenMP [2.16, Nesting of Regions] 2374 // A cancellation point construct for which construct-type-clause is 2375 // taskgroup must be nested inside a task construct. A cancellation 2376 // point construct for which construct-type-clause is not taskgroup must 2377 // be closely nested inside an OpenMP construct that matches the type 2378 // specified in construct-type-clause. 2379 // A cancel construct for which construct-type-clause is taskgroup must be 2380 // nested inside a task construct. A cancel construct for which 2381 // construct-type-clause is not taskgroup must be closely nested inside an 2382 // OpenMP construct that matches the type specified in 2383 // construct-type-clause. 2384 NestingProhibited = 2385 !((CancelRegion == OMPD_parallel && 2386 (ParentRegion == OMPD_parallel || 2387 ParentRegion == OMPD_target_parallel)) || 2388 (CancelRegion == OMPD_for && 2389 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for || 2390 ParentRegion == OMPD_target_parallel_for)) || 2391 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) || 2392 (CancelRegion == OMPD_sections && 2393 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections || 2394 ParentRegion == OMPD_parallel_sections))); 2395 } else if (CurrentRegion == OMPD_master) { 2396 // OpenMP [2.16, Nesting of Regions] 2397 // A master region may not be closely nested inside a worksharing, 2398 // atomic, or explicit task region. 2399 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2400 isOpenMPTaskingDirective(ParentRegion); 2401 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) { 2402 // OpenMP [2.16, Nesting of Regions] 2403 // A critical region may not be nested (closely or otherwise) inside a 2404 // critical region with the same name. Note that this restriction is not 2405 // sufficient to prevent deadlock. 2406 SourceLocation PreviousCriticalLoc; 2407 bool DeadLock = Stack->hasDirective( 2408 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K, 2409 const DeclarationNameInfo &DNI, 2410 SourceLocation Loc) -> bool { 2411 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) { 2412 PreviousCriticalLoc = Loc; 2413 return true; 2414 } else 2415 return false; 2416 }, 2417 false /* skip top directive */); 2418 if (DeadLock) { 2419 SemaRef.Diag(StartLoc, 2420 diag::err_omp_prohibited_region_critical_same_name) 2421 << CurrentName.getName(); 2422 if (PreviousCriticalLoc.isValid()) 2423 SemaRef.Diag(PreviousCriticalLoc, 2424 diag::note_omp_previous_critical_region); 2425 return true; 2426 } 2427 } else if (CurrentRegion == OMPD_barrier) { 2428 // OpenMP [2.16, Nesting of Regions] 2429 // A barrier region may not be closely nested inside a worksharing, 2430 // explicit task, critical, ordered, atomic, or master region. 2431 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2432 isOpenMPTaskingDirective(ParentRegion) || 2433 ParentRegion == OMPD_master || 2434 ParentRegion == OMPD_critical || 2435 ParentRegion == OMPD_ordered; 2436 } else if (isOpenMPWorksharingDirective(CurrentRegion) && 2437 !isOpenMPParallelDirective(CurrentRegion) && 2438 !isOpenMPTeamsDirective(CurrentRegion)) { 2439 // OpenMP [2.16, Nesting of Regions] 2440 // A worksharing region may not be closely nested inside a worksharing, 2441 // explicit task, critical, ordered, atomic, or master region. 2442 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) || 2443 isOpenMPTaskingDirective(ParentRegion) || 2444 ParentRegion == OMPD_master || 2445 ParentRegion == OMPD_critical || 2446 ParentRegion == OMPD_ordered; 2447 Recommend = ShouldBeInParallelRegion; 2448 } else if (CurrentRegion == OMPD_ordered) { 2449 // OpenMP [2.16, Nesting of Regions] 2450 // An ordered region may not be closely nested inside a critical, 2451 // atomic, or explicit task region. 2452 // An ordered region must be closely nested inside a loop region (or 2453 // parallel loop region) with an ordered clause. 2454 // OpenMP [2.8.1,simd Construct, Restrictions] 2455 // An ordered construct with the simd clause is the only OpenMP construct 2456 // that can appear in the simd region. 2457 NestingProhibited = ParentRegion == OMPD_critical || 2458 isOpenMPTaskingDirective(ParentRegion) || 2459 !(isOpenMPSimdDirective(ParentRegion) || 2460 Stack->isParentOrderedRegion()); 2461 Recommend = ShouldBeInOrderedRegion; 2462 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) { 2463 // OpenMP [2.16, Nesting of Regions] 2464 // If specified, a teams construct must be contained within a target 2465 // construct. 2466 NestingProhibited = ParentRegion != OMPD_target; 2467 OrphanSeen = ParentRegion == OMPD_unknown; 2468 Recommend = ShouldBeInTargetRegion; 2469 Stack->setParentTeamsRegionLoc(Stack->getConstructLoc()); 2470 } 2471 if (!NestingProhibited && 2472 !isOpenMPTargetExecutionDirective(CurrentRegion) && 2473 !isOpenMPTargetDataManagementDirective(CurrentRegion) && 2474 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) { 2475 // OpenMP [2.16, Nesting of Regions] 2476 // distribute, parallel, parallel sections, parallel workshare, and the 2477 // parallel loop and parallel loop SIMD constructs are the only OpenMP 2478 // constructs that can be closely nested in the teams region. 2479 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) && 2480 !isOpenMPDistributeDirective(CurrentRegion); 2481 Recommend = ShouldBeInParallelRegion; 2482 } 2483 if (!NestingProhibited && 2484 isOpenMPNestingDistributeDirective(CurrentRegion)) { 2485 // OpenMP 4.5 [2.17 Nesting of Regions] 2486 // The region associated with the distribute construct must be strictly 2487 // nested inside a teams region 2488 NestingProhibited = 2489 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams); 2490 Recommend = ShouldBeInTeamsRegion; 2491 } 2492 if (!NestingProhibited && 2493 (isOpenMPTargetExecutionDirective(CurrentRegion) || 2494 isOpenMPTargetDataManagementDirective(CurrentRegion))) { 2495 // OpenMP 4.5 [2.17 Nesting of Regions] 2496 // If a target, target update, target data, target enter data, or 2497 // target exit data construct is encountered during execution of a 2498 // target region, the behavior is unspecified. 2499 NestingProhibited = Stack->hasDirective( 2500 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &, 2501 SourceLocation) -> bool { 2502 if (isOpenMPTargetExecutionDirective(K)) { 2503 OffendingRegion = K; 2504 return true; 2505 } else 2506 return false; 2507 }, 2508 false /* don't skip top directive */); 2509 CloseNesting = false; 2510 } 2511 if (NestingProhibited) { 2512 if (OrphanSeen) { 2513 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive) 2514 << getOpenMPDirectiveName(CurrentRegion) << Recommend; 2515 } else { 2516 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region) 2517 << CloseNesting << getOpenMPDirectiveName(OffendingRegion) 2518 << Recommend << getOpenMPDirectiveName(CurrentRegion); 2519 } 2520 return true; 2521 } 2522 } 2523 return false; 2524 } 2525 2526 static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind, 2527 ArrayRef<OMPClause *> Clauses, 2528 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) { 2529 bool ErrorFound = false; 2530 unsigned NamedModifiersNumber = 0; 2531 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers( 2532 OMPD_unknown + 1); 2533 SmallVector<SourceLocation, 4> NameModifierLoc; 2534 for (const auto *C : Clauses) { 2535 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) { 2536 // At most one if clause without a directive-name-modifier can appear on 2537 // the directive. 2538 OpenMPDirectiveKind CurNM = IC->getNameModifier(); 2539 if (FoundNameModifiers[CurNM]) { 2540 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause) 2541 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if) 2542 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM); 2543 ErrorFound = true; 2544 } else if (CurNM != OMPD_unknown) { 2545 NameModifierLoc.push_back(IC->getNameModifierLoc()); 2546 ++NamedModifiersNumber; 2547 } 2548 FoundNameModifiers[CurNM] = IC; 2549 if (CurNM == OMPD_unknown) 2550 continue; 2551 // Check if the specified name modifier is allowed for the current 2552 // directive. 2553 // At most one if clause with the particular directive-name-modifier can 2554 // appear on the directive. 2555 bool MatchFound = false; 2556 for (auto NM : AllowedNameModifiers) { 2557 if (CurNM == NM) { 2558 MatchFound = true; 2559 break; 2560 } 2561 } 2562 if (!MatchFound) { 2563 S.Diag(IC->getNameModifierLoc(), 2564 diag::err_omp_wrong_if_directive_name_modifier) 2565 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind); 2566 ErrorFound = true; 2567 } 2568 } 2569 } 2570 // If any if clause on the directive includes a directive-name-modifier then 2571 // all if clauses on the directive must include a directive-name-modifier. 2572 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) { 2573 if (NamedModifiersNumber == AllowedNameModifiers.size()) { 2574 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(), 2575 diag::err_omp_no_more_if_clause); 2576 } else { 2577 std::string Values; 2578 std::string Sep(", "); 2579 unsigned AllowedCnt = 0; 2580 unsigned TotalAllowedNum = 2581 AllowedNameModifiers.size() - NamedModifiersNumber; 2582 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End; 2583 ++Cnt) { 2584 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt]; 2585 if (!FoundNameModifiers[NM]) { 2586 Values += "'"; 2587 Values += getOpenMPDirectiveName(NM); 2588 Values += "'"; 2589 if (AllowedCnt + 2 == TotalAllowedNum) 2590 Values += " or "; 2591 else if (AllowedCnt + 1 != TotalAllowedNum) 2592 Values += Sep; 2593 ++AllowedCnt; 2594 } 2595 } 2596 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(), 2597 diag::err_omp_unnamed_if_clause) 2598 << (TotalAllowedNum > 1) << Values; 2599 } 2600 for (auto Loc : NameModifierLoc) { 2601 S.Diag(Loc, diag::note_omp_previous_named_if_clause); 2602 } 2603 ErrorFound = true; 2604 } 2605 return ErrorFound; 2606 } 2607 2608 StmtResult Sema::ActOnOpenMPExecutableDirective( 2609 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName, 2610 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses, 2611 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 2612 StmtResult Res = StmtError(); 2613 // First check CancelRegion which is then used in checkNestingOfRegions. 2614 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) || 2615 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion, 2616 StartLoc)) 2617 return StmtError(); 2618 2619 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit; 2620 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA; 2621 bool ErrorFound = false; 2622 ClausesWithImplicit.append(Clauses.begin(), Clauses.end()); 2623 if (AStmt && !CurContext->isDependentContext()) { 2624 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 2625 2626 // Check default data sharing attributes for referenced variables. 2627 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt)); 2628 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind); 2629 Stmt *S = AStmt; 2630 while (--ThisCaptureLevel >= 0) 2631 S = cast<CapturedStmt>(S)->getCapturedStmt(); 2632 DSAChecker.Visit(S); 2633 if (DSAChecker.isErrorFound()) 2634 return StmtError(); 2635 // Generate list of implicitly defined firstprivate variables. 2636 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA(); 2637 2638 SmallVector<Expr *, 4> ImplicitFirstprivates( 2639 DSAChecker.getImplicitFirstprivate().begin(), 2640 DSAChecker.getImplicitFirstprivate().end()); 2641 // Mark taskgroup task_reduction descriptors as implicitly firstprivate. 2642 for (auto *C : Clauses) { 2643 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) { 2644 for (auto *E : IRC->taskgroup_descriptors()) 2645 if (E) 2646 ImplicitFirstprivates.emplace_back(E); 2647 } 2648 } 2649 if (!ImplicitFirstprivates.empty()) { 2650 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause( 2651 ImplicitFirstprivates, SourceLocation(), SourceLocation(), 2652 SourceLocation())) { 2653 ClausesWithImplicit.push_back(Implicit); 2654 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() != 2655 ImplicitFirstprivates.size(); 2656 } else 2657 ErrorFound = true; 2658 } 2659 } 2660 2661 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers; 2662 switch (Kind) { 2663 case OMPD_parallel: 2664 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc, 2665 EndLoc); 2666 AllowedNameModifiers.push_back(OMPD_parallel); 2667 break; 2668 case OMPD_simd: 2669 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2670 VarsWithInheritedDSA); 2671 break; 2672 case OMPD_for: 2673 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc, 2674 VarsWithInheritedDSA); 2675 break; 2676 case OMPD_for_simd: 2677 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2678 EndLoc, VarsWithInheritedDSA); 2679 break; 2680 case OMPD_sections: 2681 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc, 2682 EndLoc); 2683 break; 2684 case OMPD_section: 2685 assert(ClausesWithImplicit.empty() && 2686 "No clauses are allowed for 'omp section' directive"); 2687 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc); 2688 break; 2689 case OMPD_single: 2690 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc, 2691 EndLoc); 2692 break; 2693 case OMPD_master: 2694 assert(ClausesWithImplicit.empty() && 2695 "No clauses are allowed for 'omp master' directive"); 2696 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc); 2697 break; 2698 case OMPD_critical: 2699 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt, 2700 StartLoc, EndLoc); 2701 break; 2702 case OMPD_parallel_for: 2703 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc, 2704 EndLoc, VarsWithInheritedDSA); 2705 AllowedNameModifiers.push_back(OMPD_parallel); 2706 break; 2707 case OMPD_parallel_for_simd: 2708 Res = ActOnOpenMPParallelForSimdDirective( 2709 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2710 AllowedNameModifiers.push_back(OMPD_parallel); 2711 break; 2712 case OMPD_parallel_sections: 2713 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt, 2714 StartLoc, EndLoc); 2715 AllowedNameModifiers.push_back(OMPD_parallel); 2716 break; 2717 case OMPD_task: 2718 Res = 2719 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 2720 AllowedNameModifiers.push_back(OMPD_task); 2721 break; 2722 case OMPD_taskyield: 2723 assert(ClausesWithImplicit.empty() && 2724 "No clauses are allowed for 'omp taskyield' directive"); 2725 assert(AStmt == nullptr && 2726 "No associated statement allowed for 'omp taskyield' directive"); 2727 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc); 2728 break; 2729 case OMPD_barrier: 2730 assert(ClausesWithImplicit.empty() && 2731 "No clauses are allowed for 'omp barrier' directive"); 2732 assert(AStmt == nullptr && 2733 "No associated statement allowed for 'omp barrier' directive"); 2734 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc); 2735 break; 2736 case OMPD_taskwait: 2737 assert(ClausesWithImplicit.empty() && 2738 "No clauses are allowed for 'omp taskwait' directive"); 2739 assert(AStmt == nullptr && 2740 "No associated statement allowed for 'omp taskwait' directive"); 2741 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc); 2742 break; 2743 case OMPD_taskgroup: 2744 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc, 2745 EndLoc); 2746 break; 2747 case OMPD_flush: 2748 assert(AStmt == nullptr && 2749 "No associated statement allowed for 'omp flush' directive"); 2750 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc); 2751 break; 2752 case OMPD_ordered: 2753 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc, 2754 EndLoc); 2755 break; 2756 case OMPD_atomic: 2757 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc, 2758 EndLoc); 2759 break; 2760 case OMPD_teams: 2761 Res = 2762 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc); 2763 break; 2764 case OMPD_target: 2765 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc, 2766 EndLoc); 2767 AllowedNameModifiers.push_back(OMPD_target); 2768 break; 2769 case OMPD_target_parallel: 2770 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt, 2771 StartLoc, EndLoc); 2772 AllowedNameModifiers.push_back(OMPD_target); 2773 AllowedNameModifiers.push_back(OMPD_parallel); 2774 break; 2775 case OMPD_target_parallel_for: 2776 Res = ActOnOpenMPTargetParallelForDirective( 2777 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2778 AllowedNameModifiers.push_back(OMPD_target); 2779 AllowedNameModifiers.push_back(OMPD_parallel); 2780 break; 2781 case OMPD_cancellation_point: 2782 assert(ClausesWithImplicit.empty() && 2783 "No clauses are allowed for 'omp cancellation point' directive"); 2784 assert(AStmt == nullptr && "No associated statement allowed for 'omp " 2785 "cancellation point' directive"); 2786 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion); 2787 break; 2788 case OMPD_cancel: 2789 assert(AStmt == nullptr && 2790 "No associated statement allowed for 'omp cancel' directive"); 2791 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc, 2792 CancelRegion); 2793 AllowedNameModifiers.push_back(OMPD_cancel); 2794 break; 2795 case OMPD_target_data: 2796 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc, 2797 EndLoc); 2798 AllowedNameModifiers.push_back(OMPD_target_data); 2799 break; 2800 case OMPD_target_enter_data: 2801 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc, 2802 EndLoc); 2803 AllowedNameModifiers.push_back(OMPD_target_enter_data); 2804 break; 2805 case OMPD_target_exit_data: 2806 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc, 2807 EndLoc); 2808 AllowedNameModifiers.push_back(OMPD_target_exit_data); 2809 break; 2810 case OMPD_taskloop: 2811 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc, 2812 EndLoc, VarsWithInheritedDSA); 2813 AllowedNameModifiers.push_back(OMPD_taskloop); 2814 break; 2815 case OMPD_taskloop_simd: 2816 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2817 EndLoc, VarsWithInheritedDSA); 2818 AllowedNameModifiers.push_back(OMPD_taskloop); 2819 break; 2820 case OMPD_distribute: 2821 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc, 2822 EndLoc, VarsWithInheritedDSA); 2823 break; 2824 case OMPD_target_update: 2825 assert(!AStmt && "Statement is not allowed for target update"); 2826 Res = 2827 ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc, EndLoc); 2828 AllowedNameModifiers.push_back(OMPD_target_update); 2829 break; 2830 case OMPD_distribute_parallel_for: 2831 Res = ActOnOpenMPDistributeParallelForDirective( 2832 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2833 AllowedNameModifiers.push_back(OMPD_parallel); 2834 break; 2835 case OMPD_distribute_parallel_for_simd: 2836 Res = ActOnOpenMPDistributeParallelForSimdDirective( 2837 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2838 AllowedNameModifiers.push_back(OMPD_parallel); 2839 break; 2840 case OMPD_distribute_simd: 2841 Res = ActOnOpenMPDistributeSimdDirective( 2842 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2843 break; 2844 case OMPD_target_parallel_for_simd: 2845 Res = ActOnOpenMPTargetParallelForSimdDirective( 2846 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2847 AllowedNameModifiers.push_back(OMPD_target); 2848 AllowedNameModifiers.push_back(OMPD_parallel); 2849 break; 2850 case OMPD_target_simd: 2851 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc, 2852 EndLoc, VarsWithInheritedDSA); 2853 AllowedNameModifiers.push_back(OMPD_target); 2854 break; 2855 case OMPD_teams_distribute: 2856 Res = ActOnOpenMPTeamsDistributeDirective( 2857 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2858 break; 2859 case OMPD_teams_distribute_simd: 2860 Res = ActOnOpenMPTeamsDistributeSimdDirective( 2861 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2862 break; 2863 case OMPD_teams_distribute_parallel_for_simd: 2864 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective( 2865 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2866 AllowedNameModifiers.push_back(OMPD_parallel); 2867 break; 2868 case OMPD_teams_distribute_parallel_for: 2869 Res = ActOnOpenMPTeamsDistributeParallelForDirective( 2870 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2871 AllowedNameModifiers.push_back(OMPD_parallel); 2872 break; 2873 case OMPD_target_teams: 2874 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, 2875 EndLoc); 2876 AllowedNameModifiers.push_back(OMPD_target); 2877 break; 2878 case OMPD_target_teams_distribute: 2879 Res = ActOnOpenMPTargetTeamsDistributeDirective( 2880 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2881 AllowedNameModifiers.push_back(OMPD_target); 2882 break; 2883 case OMPD_target_teams_distribute_parallel_for: 2884 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective( 2885 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2886 AllowedNameModifiers.push_back(OMPD_target); 2887 AllowedNameModifiers.push_back(OMPD_parallel); 2888 break; 2889 case OMPD_target_teams_distribute_parallel_for_simd: 2890 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 2891 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2892 AllowedNameModifiers.push_back(OMPD_target); 2893 AllowedNameModifiers.push_back(OMPD_parallel); 2894 break; 2895 case OMPD_target_teams_distribute_simd: 2896 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective( 2897 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA); 2898 AllowedNameModifiers.push_back(OMPD_target); 2899 break; 2900 case OMPD_declare_target: 2901 case OMPD_end_declare_target: 2902 case OMPD_threadprivate: 2903 case OMPD_declare_reduction: 2904 case OMPD_declare_simd: 2905 llvm_unreachable("OpenMP Directive is not allowed"); 2906 case OMPD_unknown: 2907 llvm_unreachable("Unknown OpenMP directive"); 2908 } 2909 2910 for (auto P : VarsWithInheritedDSA) { 2911 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable) 2912 << P.first << P.second->getSourceRange(); 2913 } 2914 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound; 2915 2916 if (!AllowedNameModifiers.empty()) 2917 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) || 2918 ErrorFound; 2919 2920 if (ErrorFound) 2921 return StmtError(); 2922 return Res; 2923 } 2924 2925 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective( 2926 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen, 2927 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds, 2928 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears, 2929 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) { 2930 assert(Aligneds.size() == Alignments.size()); 2931 assert(Linears.size() == LinModifiers.size()); 2932 assert(Linears.size() == Steps.size()); 2933 if (!DG || DG.get().isNull()) 2934 return DeclGroupPtrTy(); 2935 2936 if (!DG.get().isSingleDecl()) { 2937 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd); 2938 return DG; 2939 } 2940 auto *ADecl = DG.get().getSingleDecl(); 2941 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl)) 2942 ADecl = FTD->getTemplatedDecl(); 2943 2944 auto *FD = dyn_cast<FunctionDecl>(ADecl); 2945 if (!FD) { 2946 Diag(ADecl->getLocation(), diag::err_omp_function_expected); 2947 return DeclGroupPtrTy(); 2948 } 2949 2950 // OpenMP [2.8.2, declare simd construct, Description] 2951 // The parameter of the simdlen clause must be a constant positive integer 2952 // expression. 2953 ExprResult SL; 2954 if (Simdlen) 2955 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen); 2956 // OpenMP [2.8.2, declare simd construct, Description] 2957 // The special this pointer can be used as if was one of the arguments to the 2958 // function in any of the linear, aligned, or uniform clauses. 2959 // The uniform clause declares one or more arguments to have an invariant 2960 // value for all concurrent invocations of the function in the execution of a 2961 // single SIMD loop. 2962 llvm::DenseMap<Decl *, Expr *> UniformedArgs; 2963 Expr *UniformedLinearThis = nullptr; 2964 for (auto *E : Uniforms) { 2965 E = E->IgnoreParenImpCasts(); 2966 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 2967 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 2968 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 2969 FD->getParamDecl(PVD->getFunctionScopeIndex()) 2970 ->getCanonicalDecl() == PVD->getCanonicalDecl()) { 2971 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E)); 2972 continue; 2973 } 2974 if (isa<CXXThisExpr>(E)) { 2975 UniformedLinearThis = E; 2976 continue; 2977 } 2978 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 2979 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 2980 } 2981 // OpenMP [2.8.2, declare simd construct, Description] 2982 // The aligned clause declares that the object to which each list item points 2983 // is aligned to the number of bytes expressed in the optional parameter of 2984 // the aligned clause. 2985 // The special this pointer can be used as if was one of the arguments to the 2986 // function in any of the linear, aligned, or uniform clauses. 2987 // The type of list items appearing in the aligned clause must be array, 2988 // pointer, reference to array, or reference to pointer. 2989 llvm::DenseMap<Decl *, Expr *> AlignedArgs; 2990 Expr *AlignedThis = nullptr; 2991 for (auto *E : Aligneds) { 2992 E = E->IgnoreParenImpCasts(); 2993 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 2994 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 2995 auto *CanonPVD = PVD->getCanonicalDecl(); 2996 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 2997 FD->getParamDecl(PVD->getFunctionScopeIndex()) 2998 ->getCanonicalDecl() == CanonPVD) { 2999 // OpenMP [2.8.1, simd construct, Restrictions] 3000 // A list-item cannot appear in more than one aligned clause. 3001 if (AlignedArgs.count(CanonPVD) > 0) { 3002 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3003 << 1 << E->getSourceRange(); 3004 Diag(AlignedArgs[CanonPVD]->getExprLoc(), 3005 diag::note_omp_explicit_dsa) 3006 << getOpenMPClauseName(OMPC_aligned); 3007 continue; 3008 } 3009 AlignedArgs[CanonPVD] = E; 3010 QualType QTy = PVD->getType() 3011 .getNonReferenceType() 3012 .getUnqualifiedType() 3013 .getCanonicalType(); 3014 const Type *Ty = QTy.getTypePtrOrNull(); 3015 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 3016 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr) 3017 << QTy << getLangOpts().CPlusPlus << E->getSourceRange(); 3018 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD; 3019 } 3020 continue; 3021 } 3022 } 3023 if (isa<CXXThisExpr>(E)) { 3024 if (AlignedThis) { 3025 Diag(E->getExprLoc(), diag::err_omp_aligned_twice) 3026 << 2 << E->getSourceRange(); 3027 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa) 3028 << getOpenMPClauseName(OMPC_aligned); 3029 } 3030 AlignedThis = E; 3031 continue; 3032 } 3033 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3034 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3035 } 3036 // The optional parameter of the aligned clause, alignment, must be a constant 3037 // positive integer expression. If no optional parameter is specified, 3038 // implementation-defined default alignments for SIMD instructions on the 3039 // target platforms are assumed. 3040 SmallVector<Expr *, 4> NewAligns; 3041 for (auto *E : Alignments) { 3042 ExprResult Align; 3043 if (E) 3044 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned); 3045 NewAligns.push_back(Align.get()); 3046 } 3047 // OpenMP [2.8.2, declare simd construct, Description] 3048 // The linear clause declares one or more list items to be private to a SIMD 3049 // lane and to have a linear relationship with respect to the iteration space 3050 // of a loop. 3051 // The special this pointer can be used as if was one of the arguments to the 3052 // function in any of the linear, aligned, or uniform clauses. 3053 // When a linear-step expression is specified in a linear clause it must be 3054 // either a constant integer expression or an integer-typed parameter that is 3055 // specified in a uniform clause on the directive. 3056 llvm::DenseMap<Decl *, Expr *> LinearArgs; 3057 const bool IsUniformedThis = UniformedLinearThis != nullptr; 3058 auto MI = LinModifiers.begin(); 3059 for (auto *E : Linears) { 3060 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI); 3061 ++MI; 3062 E = E->IgnoreParenImpCasts(); 3063 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) 3064 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3065 auto *CanonPVD = PVD->getCanonicalDecl(); 3066 if (FD->getNumParams() > PVD->getFunctionScopeIndex() && 3067 FD->getParamDecl(PVD->getFunctionScopeIndex()) 3068 ->getCanonicalDecl() == CanonPVD) { 3069 // OpenMP [2.15.3.7, linear Clause, Restrictions] 3070 // A list-item cannot appear in more than one linear clause. 3071 if (LinearArgs.count(CanonPVD) > 0) { 3072 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3073 << getOpenMPClauseName(OMPC_linear) 3074 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange(); 3075 Diag(LinearArgs[CanonPVD]->getExprLoc(), 3076 diag::note_omp_explicit_dsa) 3077 << getOpenMPClauseName(OMPC_linear); 3078 continue; 3079 } 3080 // Each argument can appear in at most one uniform or linear clause. 3081 if (UniformedArgs.count(CanonPVD) > 0) { 3082 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3083 << getOpenMPClauseName(OMPC_linear) 3084 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange(); 3085 Diag(UniformedArgs[CanonPVD]->getExprLoc(), 3086 diag::note_omp_explicit_dsa) 3087 << getOpenMPClauseName(OMPC_uniform); 3088 continue; 3089 } 3090 LinearArgs[CanonPVD] = E; 3091 if (E->isValueDependent() || E->isTypeDependent() || 3092 E->isInstantiationDependent() || 3093 E->containsUnexpandedParameterPack()) 3094 continue; 3095 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind, 3096 PVD->getOriginalType()); 3097 continue; 3098 } 3099 } 3100 if (isa<CXXThisExpr>(E)) { 3101 if (UniformedLinearThis) { 3102 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa) 3103 << getOpenMPClauseName(OMPC_linear) 3104 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear) 3105 << E->getSourceRange(); 3106 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa) 3107 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform 3108 : OMPC_linear); 3109 continue; 3110 } 3111 UniformedLinearThis = E; 3112 if (E->isValueDependent() || E->isTypeDependent() || 3113 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 3114 continue; 3115 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind, 3116 E->getType()); 3117 continue; 3118 } 3119 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause) 3120 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0); 3121 } 3122 Expr *Step = nullptr; 3123 Expr *NewStep = nullptr; 3124 SmallVector<Expr *, 4> NewSteps; 3125 for (auto *E : Steps) { 3126 // Skip the same step expression, it was checked already. 3127 if (Step == E || !E) { 3128 NewSteps.push_back(E ? NewStep : nullptr); 3129 continue; 3130 } 3131 Step = E; 3132 if (auto *DRE = dyn_cast<DeclRefExpr>(Step)) 3133 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) { 3134 auto *CanonPVD = PVD->getCanonicalDecl(); 3135 if (UniformedArgs.count(CanonPVD) == 0) { 3136 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param) 3137 << Step->getSourceRange(); 3138 } else if (E->isValueDependent() || E->isTypeDependent() || 3139 E->isInstantiationDependent() || 3140 E->containsUnexpandedParameterPack() || 3141 CanonPVD->getType()->hasIntegerRepresentation()) 3142 NewSteps.push_back(Step); 3143 else { 3144 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param) 3145 << Step->getSourceRange(); 3146 } 3147 continue; 3148 } 3149 NewStep = Step; 3150 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 3151 !Step->isInstantiationDependent() && 3152 !Step->containsUnexpandedParameterPack()) { 3153 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step) 3154 .get(); 3155 if (NewStep) 3156 NewStep = VerifyIntegerConstantExpression(NewStep).get(); 3157 } 3158 NewSteps.push_back(NewStep); 3159 } 3160 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit( 3161 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()), 3162 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(), 3163 const_cast<Expr **>(NewAligns.data()), NewAligns.size(), 3164 const_cast<Expr **>(Linears.data()), Linears.size(), 3165 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(), 3166 NewSteps.data(), NewSteps.size(), SR); 3167 ADecl->addAttr(NewAttr); 3168 return ConvertDeclToDeclGroup(ADecl); 3169 } 3170 3171 StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses, 3172 Stmt *AStmt, 3173 SourceLocation StartLoc, 3174 SourceLocation EndLoc) { 3175 if (!AStmt) 3176 return StmtError(); 3177 3178 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 3179 // 1.2.2 OpenMP Language Terminology 3180 // Structured block - An executable statement with a single entry at the 3181 // top and a single exit at the bottom. 3182 // The point of exit cannot be a branch out of the structured block. 3183 // longjmp() and throw() must not violate the entry/exit criteria. 3184 CS->getCapturedDecl()->setNothrow(); 3185 3186 getCurFunction()->setHasBranchProtectedScope(); 3187 3188 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 3189 DSAStack->isCancelRegion()); 3190 } 3191 3192 namespace { 3193 /// \brief Helper class for checking canonical form of the OpenMP loops and 3194 /// extracting iteration space of each loop in the loop nest, that will be used 3195 /// for IR generation. 3196 class OpenMPIterationSpaceChecker { 3197 /// \brief Reference to Sema. 3198 Sema &SemaRef; 3199 /// \brief A location for diagnostics (when there is no some better location). 3200 SourceLocation DefaultLoc; 3201 /// \brief A location for diagnostics (when increment is not compatible). 3202 SourceLocation ConditionLoc; 3203 /// \brief A source location for referring to loop init later. 3204 SourceRange InitSrcRange; 3205 /// \brief A source location for referring to condition later. 3206 SourceRange ConditionSrcRange; 3207 /// \brief A source location for referring to increment later. 3208 SourceRange IncrementSrcRange; 3209 /// \brief Loop variable. 3210 ValueDecl *LCDecl = nullptr; 3211 /// \brief Reference to loop variable. 3212 Expr *LCRef = nullptr; 3213 /// \brief Lower bound (initializer for the var). 3214 Expr *LB = nullptr; 3215 /// \brief Upper bound. 3216 Expr *UB = nullptr; 3217 /// \brief Loop step (increment). 3218 Expr *Step = nullptr; 3219 /// \brief This flag is true when condition is one of: 3220 /// Var < UB 3221 /// Var <= UB 3222 /// UB > Var 3223 /// UB >= Var 3224 bool TestIsLessOp = false; 3225 /// \brief This flag is true when condition is strict ( < or > ). 3226 bool TestIsStrictOp = false; 3227 /// \brief This flag is true when step is subtracted on each iteration. 3228 bool SubtractStep = false; 3229 3230 public: 3231 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc) 3232 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {} 3233 /// \brief Check init-expr for canonical loop form and save loop counter 3234 /// variable - #Var and its initialization value - #LB. 3235 bool CheckInit(Stmt *S, bool EmitDiags = true); 3236 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags 3237 /// for less/greater and for strict/non-strict comparison. 3238 bool CheckCond(Expr *S); 3239 /// \brief Check incr-expr for canonical loop form and return true if it 3240 /// does not conform, otherwise save loop step (#Step). 3241 bool CheckInc(Expr *S); 3242 /// \brief Return the loop counter variable. 3243 ValueDecl *GetLoopDecl() const { return LCDecl; } 3244 /// \brief Return the reference expression to loop counter variable. 3245 Expr *GetLoopDeclRefExpr() const { return LCRef; } 3246 /// \brief Source range of the loop init. 3247 SourceRange GetInitSrcRange() const { return InitSrcRange; } 3248 /// \brief Source range of the loop condition. 3249 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; } 3250 /// \brief Source range of the loop increment. 3251 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; } 3252 /// \brief True if the step should be subtracted. 3253 bool ShouldSubtractStep() const { return SubtractStep; } 3254 /// \brief Build the expression to calculate the number of iterations. 3255 Expr * 3256 BuildNumIterations(Scope *S, const bool LimitedType, 3257 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 3258 /// \brief Build the precondition expression for the loops. 3259 Expr *BuildPreCond(Scope *S, Expr *Cond, 3260 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const; 3261 /// \brief Build reference expression to the counter be used for codegen. 3262 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures, 3263 DSAStackTy &DSA) const; 3264 /// \brief Build reference expression to the private counter be used for 3265 /// codegen. 3266 Expr *BuildPrivateCounterVar() const; 3267 /// \brief Build initialization of the counter be used for codegen. 3268 Expr *BuildCounterInit() const; 3269 /// \brief Build step of the counter be used for codegen. 3270 Expr *BuildCounterStep() const; 3271 /// \brief Return true if any expression is dependent. 3272 bool Dependent() const; 3273 3274 private: 3275 /// \brief Check the right-hand side of an assignment in the increment 3276 /// expression. 3277 bool CheckIncRHS(Expr *RHS); 3278 /// \brief Helper to set loop counter variable and its initializer. 3279 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB); 3280 /// \brief Helper to set upper bound. 3281 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR, 3282 SourceLocation SL); 3283 /// \brief Helper to set loop increment. 3284 bool SetStep(Expr *NewStep, bool Subtract); 3285 }; 3286 3287 bool OpenMPIterationSpaceChecker::Dependent() const { 3288 if (!LCDecl) { 3289 assert(!LB && !UB && !Step); 3290 return false; 3291 } 3292 return LCDecl->getType()->isDependentType() || 3293 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) || 3294 (Step && Step->isValueDependent()); 3295 } 3296 3297 bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl, 3298 Expr *NewLCRefExpr, 3299 Expr *NewLB) { 3300 // State consistency checking to ensure correct usage. 3301 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr && 3302 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 3303 if (!NewLCDecl || !NewLB) 3304 return true; 3305 LCDecl = getCanonicalDecl(NewLCDecl); 3306 LCRef = NewLCRefExpr; 3307 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB)) 3308 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 3309 if ((Ctor->isCopyOrMoveConstructor() || 3310 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 3311 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 3312 NewLB = CE->getArg(0)->IgnoreParenImpCasts(); 3313 LB = NewLB; 3314 return false; 3315 } 3316 3317 bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp, 3318 SourceRange SR, SourceLocation SL) { 3319 // State consistency checking to ensure correct usage. 3320 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr && 3321 Step == nullptr && !TestIsLessOp && !TestIsStrictOp); 3322 if (!NewUB) 3323 return true; 3324 UB = NewUB; 3325 TestIsLessOp = LessOp; 3326 TestIsStrictOp = StrictOp; 3327 ConditionSrcRange = SR; 3328 ConditionLoc = SL; 3329 return false; 3330 } 3331 3332 bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) { 3333 // State consistency checking to ensure correct usage. 3334 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr); 3335 if (!NewStep) 3336 return true; 3337 if (!NewStep->isValueDependent()) { 3338 // Check that the step is integer expression. 3339 SourceLocation StepLoc = NewStep->getLocStart(); 3340 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion( 3341 StepLoc, getExprAsWritten(NewStep)); 3342 if (Val.isInvalid()) 3343 return true; 3344 NewStep = Val.get(); 3345 3346 // OpenMP [2.6, Canonical Loop Form, Restrictions] 3347 // If test-expr is of form var relational-op b and relational-op is < or 3348 // <= then incr-expr must cause var to increase on each iteration of the 3349 // loop. If test-expr is of form var relational-op b and relational-op is 3350 // > or >= then incr-expr must cause var to decrease on each iteration of 3351 // the loop. 3352 // If test-expr is of form b relational-op var and relational-op is < or 3353 // <= then incr-expr must cause var to decrease on each iteration of the 3354 // loop. If test-expr is of form b relational-op var and relational-op is 3355 // > or >= then incr-expr must cause var to increase on each iteration of 3356 // the loop. 3357 llvm::APSInt Result; 3358 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context); 3359 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation(); 3360 bool IsConstNeg = 3361 IsConstant && Result.isSigned() && (Subtract != Result.isNegative()); 3362 bool IsConstPos = 3363 IsConstant && Result.isSigned() && (Subtract == Result.isNegative()); 3364 bool IsConstZero = IsConstant && !Result.getBoolValue(); 3365 if (UB && (IsConstZero || 3366 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract)) 3367 : (IsConstPos || (IsUnsigned && !Subtract))))) { 3368 SemaRef.Diag(NewStep->getExprLoc(), 3369 diag::err_omp_loop_incr_not_compatible) 3370 << LCDecl << TestIsLessOp << NewStep->getSourceRange(); 3371 SemaRef.Diag(ConditionLoc, 3372 diag::note_omp_loop_cond_requres_compatible_incr) 3373 << TestIsLessOp << ConditionSrcRange; 3374 return true; 3375 } 3376 if (TestIsLessOp == Subtract) { 3377 NewStep = 3378 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep) 3379 .get(); 3380 Subtract = !Subtract; 3381 } 3382 } 3383 3384 Step = NewStep; 3385 SubtractStep = Subtract; 3386 return false; 3387 } 3388 3389 bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) { 3390 // Check init-expr for canonical loop form and save loop counter 3391 // variable - #Var and its initialization value - #LB. 3392 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following: 3393 // var = lb 3394 // integer-type var = lb 3395 // random-access-iterator-type var = lb 3396 // pointer-type var = lb 3397 // 3398 if (!S) { 3399 if (EmitDiags) { 3400 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init); 3401 } 3402 return true; 3403 } 3404 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3405 if (!ExprTemp->cleanupsHaveSideEffects()) 3406 S = ExprTemp->getSubExpr(); 3407 3408 InitSrcRange = S->getSourceRange(); 3409 if (Expr *E = dyn_cast<Expr>(S)) 3410 S = E->IgnoreParens(); 3411 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3412 if (BO->getOpcode() == BO_Assign) { 3413 auto *LHS = BO->getLHS()->IgnoreParens(); 3414 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3415 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3416 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3417 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3418 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS()); 3419 } 3420 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3421 if (ME->isArrow() && 3422 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3423 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3424 } 3425 } 3426 } else if (auto *DS = dyn_cast<DeclStmt>(S)) { 3427 if (DS->isSingleDecl()) { 3428 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) { 3429 if (Var->hasInit() && !Var->getType()->isReferenceType()) { 3430 // Accept non-canonical init form here but emit ext. warning. 3431 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags) 3432 SemaRef.Diag(S->getLocStart(), 3433 diag::ext_omp_loop_not_canonical_init) 3434 << S->getSourceRange(); 3435 return SetLCDeclAndLB(Var, nullptr, Var->getInit()); 3436 } 3437 } 3438 } 3439 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3440 if (CE->getOperator() == OO_Equal) { 3441 auto *LHS = CE->getArg(0); 3442 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) { 3443 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl())) 3444 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit()))) 3445 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3446 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1)); 3447 } 3448 if (auto *ME = dyn_cast<MemberExpr>(LHS)) { 3449 if (ME->isArrow() && 3450 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3451 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS()); 3452 } 3453 } 3454 } 3455 3456 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3457 return false; 3458 if (EmitDiags) { 3459 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init) 3460 << S->getSourceRange(); 3461 } 3462 return true; 3463 } 3464 3465 /// \brief Ignore parenthesizes, implicit casts, copy constructor and return the 3466 /// variable (which may be the loop variable) if possible. 3467 static const ValueDecl *GetInitLCDecl(Expr *E) { 3468 if (!E) 3469 return nullptr; 3470 E = getExprAsWritten(E); 3471 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E)) 3472 if (const CXXConstructorDecl *Ctor = CE->getConstructor()) 3473 if ((Ctor->isCopyOrMoveConstructor() || 3474 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) && 3475 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr) 3476 E = CE->getArg(0)->IgnoreParenImpCasts(); 3477 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) { 3478 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl())) 3479 return getCanonicalDecl(VD); 3480 } 3481 if (auto *ME = dyn_cast_or_null<MemberExpr>(E)) 3482 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts())) 3483 return getCanonicalDecl(ME->getMemberDecl()); 3484 return nullptr; 3485 } 3486 3487 bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) { 3488 // Check test-expr for canonical form, save upper-bound UB, flags for 3489 // less/greater and for strict/non-strict comparison. 3490 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3491 // var relational-op b 3492 // b relational-op var 3493 // 3494 if (!S) { 3495 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl; 3496 return true; 3497 } 3498 S = getExprAsWritten(S); 3499 SourceLocation CondLoc = S->getLocStart(); 3500 if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3501 if (BO->isRelationalOp()) { 3502 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3503 return SetUB(BO->getRHS(), 3504 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE), 3505 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3506 BO->getSourceRange(), BO->getOperatorLoc()); 3507 if (GetInitLCDecl(BO->getRHS()) == LCDecl) 3508 return SetUB(BO->getLHS(), 3509 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE), 3510 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT), 3511 BO->getSourceRange(), BO->getOperatorLoc()); 3512 } 3513 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3514 if (CE->getNumArgs() == 2) { 3515 auto Op = CE->getOperator(); 3516 switch (Op) { 3517 case OO_Greater: 3518 case OO_GreaterEqual: 3519 case OO_Less: 3520 case OO_LessEqual: 3521 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3522 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual, 3523 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3524 CE->getOperatorLoc()); 3525 if (GetInitLCDecl(CE->getArg(1)) == LCDecl) 3526 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual, 3527 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(), 3528 CE->getOperatorLoc()); 3529 break; 3530 default: 3531 break; 3532 } 3533 } 3534 } 3535 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3536 return false; 3537 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond) 3538 << S->getSourceRange() << LCDecl; 3539 return true; 3540 } 3541 3542 bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) { 3543 // RHS of canonical loop form increment can be: 3544 // var + incr 3545 // incr + var 3546 // var - incr 3547 // 3548 RHS = RHS->IgnoreParenImpCasts(); 3549 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) { 3550 if (BO->isAdditiveOp()) { 3551 bool IsAdd = BO->getOpcode() == BO_Add; 3552 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3553 return SetStep(BO->getRHS(), !IsAdd); 3554 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl) 3555 return SetStep(BO->getLHS(), false); 3556 } 3557 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) { 3558 bool IsAdd = CE->getOperator() == OO_Plus; 3559 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) { 3560 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3561 return SetStep(CE->getArg(1), !IsAdd); 3562 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl) 3563 return SetStep(CE->getArg(0), false); 3564 } 3565 } 3566 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3567 return false; 3568 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3569 << RHS->getSourceRange() << LCDecl; 3570 return true; 3571 } 3572 3573 bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) { 3574 // Check incr-expr for canonical loop form and return true if it 3575 // does not conform. 3576 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following: 3577 // ++var 3578 // var++ 3579 // --var 3580 // var-- 3581 // var += incr 3582 // var -= incr 3583 // var = var + incr 3584 // var = incr + var 3585 // var = var - incr 3586 // 3587 if (!S) { 3588 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl; 3589 return true; 3590 } 3591 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S)) 3592 if (!ExprTemp->cleanupsHaveSideEffects()) 3593 S = ExprTemp->getSubExpr(); 3594 3595 IncrementSrcRange = S->getSourceRange(); 3596 S = S->IgnoreParens(); 3597 if (auto *UO = dyn_cast<UnaryOperator>(S)) { 3598 if (UO->isIncrementDecrementOp() && 3599 GetInitLCDecl(UO->getSubExpr()) == LCDecl) 3600 return SetStep(SemaRef 3601 .ActOnIntegerConstant(UO->getLocStart(), 3602 (UO->isDecrementOp() ? -1 : 1)) 3603 .get(), 3604 false); 3605 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) { 3606 switch (BO->getOpcode()) { 3607 case BO_AddAssign: 3608 case BO_SubAssign: 3609 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3610 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign); 3611 break; 3612 case BO_Assign: 3613 if (GetInitLCDecl(BO->getLHS()) == LCDecl) 3614 return CheckIncRHS(BO->getRHS()); 3615 break; 3616 default: 3617 break; 3618 } 3619 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) { 3620 switch (CE->getOperator()) { 3621 case OO_PlusPlus: 3622 case OO_MinusMinus: 3623 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3624 return SetStep(SemaRef 3625 .ActOnIntegerConstant( 3626 CE->getLocStart(), 3627 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1)) 3628 .get(), 3629 false); 3630 break; 3631 case OO_PlusEqual: 3632 case OO_MinusEqual: 3633 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3634 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual); 3635 break; 3636 case OO_Equal: 3637 if (GetInitLCDecl(CE->getArg(0)) == LCDecl) 3638 return CheckIncRHS(CE->getArg(1)); 3639 break; 3640 default: 3641 break; 3642 } 3643 } 3644 if (Dependent() || SemaRef.CurContext->isDependentContext()) 3645 return false; 3646 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr) 3647 << S->getSourceRange() << LCDecl; 3648 return true; 3649 } 3650 3651 static ExprResult 3652 tryBuildCapture(Sema &SemaRef, Expr *Capture, 3653 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3654 if (SemaRef.CurContext->isDependentContext()) 3655 return ExprResult(Capture); 3656 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects)) 3657 return SemaRef.PerformImplicitConversion( 3658 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting, 3659 /*AllowExplicit=*/true); 3660 auto I = Captures.find(Capture); 3661 if (I != Captures.end()) 3662 return buildCapture(SemaRef, Capture, I->second); 3663 DeclRefExpr *Ref = nullptr; 3664 ExprResult Res = buildCapture(SemaRef, Capture, Ref); 3665 Captures[Capture] = Ref; 3666 return Res; 3667 } 3668 3669 /// \brief Build the expression to calculate the number of iterations. 3670 Expr *OpenMPIterationSpaceChecker::BuildNumIterations( 3671 Scope *S, const bool LimitedType, 3672 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 3673 ExprResult Diff; 3674 auto VarType = LCDecl->getType().getNonReferenceType(); 3675 if (VarType->isIntegerType() || VarType->isPointerType() || 3676 SemaRef.getLangOpts().CPlusPlus) { 3677 // Upper - Lower 3678 auto *UBExpr = TestIsLessOp ? UB : LB; 3679 auto *LBExpr = TestIsLessOp ? LB : UB; 3680 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get(); 3681 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get(); 3682 if (!Upper || !Lower) 3683 return nullptr; 3684 3685 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower); 3686 3687 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) { 3688 // BuildBinOp already emitted error, this one is to point user to upper 3689 // and lower bound, and to tell what is passed to 'operator-'. 3690 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx) 3691 << Upper->getSourceRange() << Lower->getSourceRange(); 3692 return nullptr; 3693 } 3694 } 3695 3696 if (!Diff.isUsable()) 3697 return nullptr; 3698 3699 // Upper - Lower [- 1] 3700 if (TestIsStrictOp) 3701 Diff = SemaRef.BuildBinOp( 3702 S, DefaultLoc, BO_Sub, Diff.get(), 3703 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 3704 if (!Diff.isUsable()) 3705 return nullptr; 3706 3707 // Upper - Lower [- 1] + Step 3708 auto NewStep = tryBuildCapture(SemaRef, Step, Captures); 3709 if (!NewStep.isUsable()) 3710 return nullptr; 3711 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get()); 3712 if (!Diff.isUsable()) 3713 return nullptr; 3714 3715 // Parentheses (for dumping/debugging purposes only). 3716 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get()); 3717 if (!Diff.isUsable()) 3718 return nullptr; 3719 3720 // (Upper - Lower [- 1] + Step) / Step 3721 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get()); 3722 if (!Diff.isUsable()) 3723 return nullptr; 3724 3725 // OpenMP runtime requires 32-bit or 64-bit loop variables. 3726 QualType Type = Diff.get()->getType(); 3727 auto &C = SemaRef.Context; 3728 bool UseVarType = VarType->hasIntegerRepresentation() && 3729 C.getTypeSize(Type) > C.getTypeSize(VarType); 3730 if (!Type->isIntegerType() || UseVarType) { 3731 unsigned NewSize = 3732 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type); 3733 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation() 3734 : Type->hasSignedIntegerRepresentation(); 3735 Type = C.getIntTypeForBitwidth(NewSize, IsSigned); 3736 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) { 3737 Diff = SemaRef.PerformImplicitConversion( 3738 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true); 3739 if (!Diff.isUsable()) 3740 return nullptr; 3741 } 3742 } 3743 if (LimitedType) { 3744 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32; 3745 if (NewSize != C.getTypeSize(Type)) { 3746 if (NewSize < C.getTypeSize(Type)) { 3747 assert(NewSize == 64 && "incorrect loop var size"); 3748 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var) 3749 << InitSrcRange << ConditionSrcRange; 3750 } 3751 QualType NewType = C.getIntTypeForBitwidth( 3752 NewSize, Type->hasSignedIntegerRepresentation() || 3753 C.getTypeSize(Type) < NewSize); 3754 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) { 3755 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType, 3756 Sema::AA_Converting, true); 3757 if (!Diff.isUsable()) 3758 return nullptr; 3759 } 3760 } 3761 } 3762 3763 return Diff.get(); 3764 } 3765 3766 Expr *OpenMPIterationSpaceChecker::BuildPreCond( 3767 Scope *S, Expr *Cond, 3768 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const { 3769 // Try to build LB <op> UB, where <op> is <, >, <=, or >=. 3770 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 3771 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 3772 3773 auto NewLB = tryBuildCapture(SemaRef, LB, Captures); 3774 auto NewUB = tryBuildCapture(SemaRef, UB, Captures); 3775 if (!NewLB.isUsable() || !NewUB.isUsable()) 3776 return nullptr; 3777 3778 auto CondExpr = SemaRef.BuildBinOp( 3779 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE) 3780 : (TestIsStrictOp ? BO_GT : BO_GE), 3781 NewLB.get(), NewUB.get()); 3782 if (CondExpr.isUsable()) { 3783 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(), 3784 SemaRef.Context.BoolTy)) 3785 CondExpr = SemaRef.PerformImplicitConversion( 3786 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting, 3787 /*AllowExplicit=*/true); 3788 } 3789 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 3790 // Otherwise use original loop conditon and evaluate it in runtime. 3791 return CondExpr.isUsable() ? CondExpr.get() : Cond; 3792 } 3793 3794 /// \brief Build reference expression to the counter be used for codegen. 3795 DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar( 3796 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const { 3797 auto *VD = dyn_cast<VarDecl>(LCDecl); 3798 if (!VD) { 3799 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl); 3800 auto *Ref = buildDeclRefExpr( 3801 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc); 3802 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false); 3803 // If the loop control decl is explicitly marked as private, do not mark it 3804 // as captured again. 3805 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr) 3806 Captures.insert(std::make_pair(LCRef, Ref)); 3807 return Ref; 3808 } 3809 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(), 3810 DefaultLoc); 3811 } 3812 3813 Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const { 3814 if (LCDecl && !LCDecl->isInvalidDecl()) { 3815 auto Type = LCDecl->getType().getNonReferenceType(); 3816 auto *PrivateVar = 3817 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(), 3818 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr); 3819 if (PrivateVar->isInvalidDecl()) 3820 return nullptr; 3821 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc); 3822 } 3823 return nullptr; 3824 } 3825 3826 /// \brief Build initialization of the counter to be used for codegen. 3827 Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; } 3828 3829 /// \brief Build step of the counter be used for codegen. 3830 Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; } 3831 3832 /// \brief Iteration space of a single for loop. 3833 struct LoopIterationSpace final { 3834 /// \brief Condition of the loop. 3835 Expr *PreCond = nullptr; 3836 /// \brief This expression calculates the number of iterations in the loop. 3837 /// It is always possible to calculate it before starting the loop. 3838 Expr *NumIterations = nullptr; 3839 /// \brief The loop counter variable. 3840 Expr *CounterVar = nullptr; 3841 /// \brief Private loop counter variable. 3842 Expr *PrivateCounterVar = nullptr; 3843 /// \brief This is initializer for the initial value of #CounterVar. 3844 Expr *CounterInit = nullptr; 3845 /// \brief This is step for the #CounterVar used to generate its update: 3846 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration. 3847 Expr *CounterStep = nullptr; 3848 /// \brief Should step be subtracted? 3849 bool Subtract = false; 3850 /// \brief Source range of the loop init. 3851 SourceRange InitSrcRange; 3852 /// \brief Source range of the loop condition. 3853 SourceRange CondSrcRange; 3854 /// \brief Source range of the loop increment. 3855 SourceRange IncSrcRange; 3856 }; 3857 3858 } // namespace 3859 3860 void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) { 3861 assert(getLangOpts().OpenMP && "OpenMP is not active."); 3862 assert(Init && "Expected loop in canonical form."); 3863 unsigned AssociatedLoops = DSAStack->getAssociatedLoops(); 3864 if (AssociatedLoops > 0 && 3865 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) { 3866 OpenMPIterationSpaceChecker ISC(*this, ForLoc); 3867 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) { 3868 if (auto *D = ISC.GetLoopDecl()) { 3869 auto *VD = dyn_cast<VarDecl>(D); 3870 if (!VD) { 3871 if (auto *Private = IsOpenMPCapturedDecl(D)) 3872 VD = Private; 3873 else { 3874 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(), 3875 /*WithInit=*/false); 3876 VD = cast<VarDecl>(Ref->getDecl()); 3877 } 3878 } 3879 DSAStack->addLoopControlVariable(D, VD); 3880 } 3881 } 3882 DSAStack->setAssociatedLoops(AssociatedLoops - 1); 3883 } 3884 } 3885 3886 /// \brief Called on a for stmt to check and extract its iteration space 3887 /// for further processing (such as collapsing). 3888 static bool CheckOpenMPIterationSpace( 3889 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA, 3890 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount, 3891 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr, 3892 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 3893 LoopIterationSpace &ResultIterSpace, 3894 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 3895 // OpenMP [2.6, Canonical Loop Form] 3896 // for (init-expr; test-expr; incr-expr) structured-block 3897 auto *For = dyn_cast_or_null<ForStmt>(S); 3898 if (!For) { 3899 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for) 3900 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr) 3901 << getOpenMPDirectiveName(DKind) << NestedLoopCount 3902 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount; 3903 if (NestedLoopCount > 1) { 3904 if (CollapseLoopCountExpr && OrderedLoopCountExpr) 3905 SemaRef.Diag(DSA.getConstructLoc(), 3906 diag::note_omp_collapse_ordered_expr) 3907 << 2 << CollapseLoopCountExpr->getSourceRange() 3908 << OrderedLoopCountExpr->getSourceRange(); 3909 else if (CollapseLoopCountExpr) 3910 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 3911 diag::note_omp_collapse_ordered_expr) 3912 << 0 << CollapseLoopCountExpr->getSourceRange(); 3913 else 3914 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 3915 diag::note_omp_collapse_ordered_expr) 3916 << 1 << OrderedLoopCountExpr->getSourceRange(); 3917 } 3918 return true; 3919 } 3920 assert(For->getBody()); 3921 3922 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc()); 3923 3924 // Check init. 3925 auto Init = For->getInit(); 3926 if (ISC.CheckInit(Init)) 3927 return true; 3928 3929 bool HasErrors = false; 3930 3931 // Check loop variable's type. 3932 if (auto *LCDecl = ISC.GetLoopDecl()) { 3933 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr(); 3934 3935 // OpenMP [2.6, Canonical Loop Form] 3936 // Var is one of the following: 3937 // A variable of signed or unsigned integer type. 3938 // For C++, a variable of a random access iterator type. 3939 // For C, a variable of a pointer type. 3940 auto VarType = LCDecl->getType().getNonReferenceType(); 3941 if (!VarType->isDependentType() && !VarType->isIntegerType() && 3942 !VarType->isPointerType() && 3943 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) { 3944 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type) 3945 << SemaRef.getLangOpts().CPlusPlus; 3946 HasErrors = true; 3947 } 3948 3949 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in 3950 // a Construct 3951 // The loop iteration variable(s) in the associated for-loop(s) of a for or 3952 // parallel for construct is (are) private. 3953 // The loop iteration variable in the associated for-loop of a simd 3954 // construct with just one associated for-loop is linear with a 3955 // constant-linear-step that is the increment of the associated for-loop. 3956 // Exclude loop var from the list of variables with implicitly defined data 3957 // sharing attributes. 3958 VarsWithImplicitDSA.erase(LCDecl); 3959 3960 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 3961 // in a Construct, C/C++]. 3962 // The loop iteration variable in the associated for-loop of a simd 3963 // construct with just one associated for-loop may be listed in a linear 3964 // clause with a constant-linear-step that is the increment of the 3965 // associated for-loop. 3966 // The loop iteration variable(s) in the associated for-loop(s) of a for or 3967 // parallel for construct may be listed in a private or lastprivate clause. 3968 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false); 3969 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is 3970 // declared in the loop and it is predetermined as a private. 3971 auto PredeterminedCKind = 3972 isOpenMPSimdDirective(DKind) 3973 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate) 3974 : OMPC_private; 3975 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 3976 DVar.CKind != PredeterminedCKind) || 3977 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop || 3978 isOpenMPDistributeDirective(DKind)) && 3979 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown && 3980 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) && 3981 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 3982 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa) 3983 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind) 3984 << getOpenMPClauseName(PredeterminedCKind); 3985 if (DVar.RefExpr == nullptr) 3986 DVar.CKind = PredeterminedCKind; 3987 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true); 3988 HasErrors = true; 3989 } else if (LoopDeclRefExpr != nullptr) { 3990 // Make the loop iteration variable private (for worksharing constructs), 3991 // linear (for simd directives with the only one associated loop) or 3992 // lastprivate (for simd directives with several collapsed or ordered 3993 // loops). 3994 if (DVar.CKind == OMPC_unknown) 3995 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate, 3996 [](OpenMPDirectiveKind) -> bool { return true; }, 3997 /*FromParent=*/false); 3998 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind); 3999 } 4000 4001 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars"); 4002 4003 // Check test-expr. 4004 HasErrors |= ISC.CheckCond(For->getCond()); 4005 4006 // Check incr-expr. 4007 HasErrors |= ISC.CheckInc(For->getInc()); 4008 } 4009 4010 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors) 4011 return HasErrors; 4012 4013 // Build the loop's iteration space representation. 4014 ResultIterSpace.PreCond = 4015 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures); 4016 ResultIterSpace.NumIterations = ISC.BuildNumIterations( 4017 DSA.getCurScope(), 4018 (isOpenMPWorksharingDirective(DKind) || 4019 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)), 4020 Captures); 4021 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA); 4022 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar(); 4023 ResultIterSpace.CounterInit = ISC.BuildCounterInit(); 4024 ResultIterSpace.CounterStep = ISC.BuildCounterStep(); 4025 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange(); 4026 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange(); 4027 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange(); 4028 ResultIterSpace.Subtract = ISC.ShouldSubtractStep(); 4029 4030 HasErrors |= (ResultIterSpace.PreCond == nullptr || 4031 ResultIterSpace.NumIterations == nullptr || 4032 ResultIterSpace.CounterVar == nullptr || 4033 ResultIterSpace.PrivateCounterVar == nullptr || 4034 ResultIterSpace.CounterInit == nullptr || 4035 ResultIterSpace.CounterStep == nullptr); 4036 4037 return HasErrors; 4038 } 4039 4040 /// \brief Build 'VarRef = Start. 4041 static ExprResult 4042 BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef, 4043 ExprResult Start, 4044 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4045 // Build 'VarRef = Start. 4046 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures); 4047 if (!NewStart.isUsable()) 4048 return ExprError(); 4049 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(), 4050 VarRef.get()->getType())) { 4051 NewStart = SemaRef.PerformImplicitConversion( 4052 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting, 4053 /*AllowExplicit=*/true); 4054 if (!NewStart.isUsable()) 4055 return ExprError(); 4056 } 4057 4058 auto Init = 4059 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 4060 return Init; 4061 } 4062 4063 /// \brief Build 'VarRef = Start + Iter * Step'. 4064 static ExprResult 4065 BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc, 4066 ExprResult VarRef, ExprResult Start, ExprResult Iter, 4067 ExprResult Step, bool Subtract, 4068 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) { 4069 // Add parentheses (for debugging purposes only). 4070 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get()); 4071 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() || 4072 !Step.isUsable()) 4073 return ExprError(); 4074 4075 ExprResult NewStep = Step; 4076 if (Captures) 4077 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures); 4078 if (NewStep.isInvalid()) 4079 return ExprError(); 4080 ExprResult Update = 4081 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get()); 4082 if (!Update.isUsable()) 4083 return ExprError(); 4084 4085 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or 4086 // 'VarRef = Start (+|-) Iter * Step'. 4087 ExprResult NewStart = Start; 4088 if (Captures) 4089 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures); 4090 if (NewStart.isInvalid()) 4091 return ExprError(); 4092 4093 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'. 4094 ExprResult SavedUpdate = Update; 4095 ExprResult UpdateVal; 4096 if (VarRef.get()->getType()->isOverloadableType() || 4097 NewStart.get()->getType()->isOverloadableType() || 4098 Update.get()->getType()->isOverloadableType()) { 4099 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics(); 4100 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 4101 Update = 4102 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get()); 4103 if (Update.isUsable()) { 4104 UpdateVal = 4105 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign, 4106 VarRef.get(), SavedUpdate.get()); 4107 if (UpdateVal.isUsable()) { 4108 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(), 4109 UpdateVal.get()); 4110 } 4111 } 4112 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress); 4113 } 4114 4115 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'. 4116 if (!Update.isUsable() || !UpdateVal.isUsable()) { 4117 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add, 4118 NewStart.get(), SavedUpdate.get()); 4119 if (!Update.isUsable()) 4120 return ExprError(); 4121 4122 if (!SemaRef.Context.hasSameType(Update.get()->getType(), 4123 VarRef.get()->getType())) { 4124 Update = SemaRef.PerformImplicitConversion( 4125 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true); 4126 if (!Update.isUsable()) 4127 return ExprError(); 4128 } 4129 4130 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get()); 4131 } 4132 return Update; 4133 } 4134 4135 /// \brief Convert integer expression \a E to make it have at least \a Bits 4136 /// bits. 4137 static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) { 4138 if (E == nullptr) 4139 return ExprError(); 4140 auto &C = SemaRef.Context; 4141 QualType OldType = E->getType(); 4142 unsigned HasBits = C.getTypeSize(OldType); 4143 if (HasBits >= Bits) 4144 return ExprResult(E); 4145 // OK to convert to signed, because new type has more bits than old. 4146 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true); 4147 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting, 4148 true); 4149 } 4150 4151 /// \brief Check if the given expression \a E is a constant integer that fits 4152 /// into \a Bits bits. 4153 static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) { 4154 if (E == nullptr) 4155 return false; 4156 llvm::APSInt Result; 4157 if (E->isIntegerConstantExpr(Result, SemaRef.Context)) 4158 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits); 4159 return false; 4160 } 4161 4162 /// Build preinits statement for the given declarations. 4163 static Stmt *buildPreInits(ASTContext &Context, 4164 SmallVectorImpl<Decl *> &PreInits) { 4165 if (!PreInits.empty()) { 4166 return new (Context) DeclStmt( 4167 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()), 4168 SourceLocation(), SourceLocation()); 4169 } 4170 return nullptr; 4171 } 4172 4173 /// Build preinits statement for the given declarations. 4174 static Stmt *buildPreInits(ASTContext &Context, 4175 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) { 4176 if (!Captures.empty()) { 4177 SmallVector<Decl *, 16> PreInits; 4178 for (auto &Pair : Captures) 4179 PreInits.push_back(Pair.second->getDecl()); 4180 return buildPreInits(Context, PreInits); 4181 } 4182 return nullptr; 4183 } 4184 4185 /// Build postupdate expression for the given list of postupdates expressions. 4186 static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) { 4187 Expr *PostUpdate = nullptr; 4188 if (!PostUpdates.empty()) { 4189 for (auto *E : PostUpdates) { 4190 Expr *ConvE = S.BuildCStyleCastExpr( 4191 E->getExprLoc(), 4192 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy), 4193 E->getExprLoc(), E) 4194 .get(); 4195 PostUpdate = PostUpdate 4196 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma, 4197 PostUpdate, ConvE) 4198 .get() 4199 : ConvE; 4200 } 4201 } 4202 return PostUpdate; 4203 } 4204 4205 /// \brief Called on a for stmt to check itself and nested loops (if any). 4206 /// \return Returns 0 if one of the collapsed stmts is not canonical for loop, 4207 /// number of collapsed loops otherwise. 4208 static unsigned 4209 CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr, 4210 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef, 4211 DSAStackTy &DSA, 4212 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA, 4213 OMPLoopDirective::HelperExprs &Built) { 4214 unsigned NestedLoopCount = 1; 4215 if (CollapseLoopCountExpr) { 4216 // Found 'collapse' clause - calculate collapse number. 4217 llvm::APSInt Result; 4218 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) 4219 NestedLoopCount = Result.getLimitedValue(); 4220 } 4221 if (OrderedLoopCountExpr) { 4222 // Found 'ordered' clause - calculate collapse number. 4223 llvm::APSInt Result; 4224 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) { 4225 if (Result.getLimitedValue() < NestedLoopCount) { 4226 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(), 4227 diag::err_omp_wrong_ordered_loop_count) 4228 << OrderedLoopCountExpr->getSourceRange(); 4229 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(), 4230 diag::note_collapse_loop_count) 4231 << CollapseLoopCountExpr->getSourceRange(); 4232 } 4233 NestedLoopCount = Result.getLimitedValue(); 4234 } 4235 } 4236 // This is helper routine for loop directives (e.g., 'for', 'simd', 4237 // 'for simd', etc.). 4238 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 4239 SmallVector<LoopIterationSpace, 4> IterSpaces; 4240 IterSpaces.resize(NestedLoopCount); 4241 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true); 4242 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) { 4243 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt, 4244 NestedLoopCount, CollapseLoopCountExpr, 4245 OrderedLoopCountExpr, VarsWithImplicitDSA, 4246 IterSpaces[Cnt], Captures)) 4247 return 0; 4248 // Move on to the next nested for loop, or to the loop body. 4249 // OpenMP [2.8.1, simd construct, Restrictions] 4250 // All loops associated with the construct must be perfectly nested; that 4251 // is, there must be no intervening code nor any OpenMP directive between 4252 // any two loops. 4253 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers(); 4254 } 4255 4256 Built.clear(/* size */ NestedLoopCount); 4257 4258 if (SemaRef.CurContext->isDependentContext()) 4259 return NestedLoopCount; 4260 4261 // An example of what is generated for the following code: 4262 // 4263 // #pragma omp simd collapse(2) ordered(2) 4264 // for (i = 0; i < NI; ++i) 4265 // for (k = 0; k < NK; ++k) 4266 // for (j = J0; j < NJ; j+=2) { 4267 // <loop body> 4268 // } 4269 // 4270 // We generate the code below. 4271 // Note: the loop body may be outlined in CodeGen. 4272 // Note: some counters may be C++ classes, operator- is used to find number of 4273 // iterations and operator+= to calculate counter value. 4274 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32 4275 // or i64 is currently supported). 4276 // 4277 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2)) 4278 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) { 4279 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2); 4280 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2; 4281 // // similar updates for vars in clauses (e.g. 'linear') 4282 // <loop body (using local i and j)> 4283 // } 4284 // i = NI; // assign final values of counters 4285 // j = NJ; 4286 // 4287 4288 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are 4289 // the iteration counts of the collapsed for loops. 4290 // Precondition tests if there is at least one iteration (all conditions are 4291 // true). 4292 auto PreCond = ExprResult(IterSpaces[0].PreCond); 4293 auto N0 = IterSpaces[0].NumIterations; 4294 ExprResult LastIteration32 = WidenIterationCount( 4295 32 /* Bits */, SemaRef 4296 .PerformImplicitConversion( 4297 N0->IgnoreImpCasts(), N0->getType(), 4298 Sema::AA_Converting, /*AllowExplicit=*/true) 4299 .get(), 4300 SemaRef); 4301 ExprResult LastIteration64 = WidenIterationCount( 4302 64 /* Bits */, SemaRef 4303 .PerformImplicitConversion( 4304 N0->IgnoreImpCasts(), N0->getType(), 4305 Sema::AA_Converting, /*AllowExplicit=*/true) 4306 .get(), 4307 SemaRef); 4308 4309 if (!LastIteration32.isUsable() || !LastIteration64.isUsable()) 4310 return NestedLoopCount; 4311 4312 auto &C = SemaRef.Context; 4313 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32; 4314 4315 Scope *CurScope = DSA.getCurScope(); 4316 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) { 4317 if (PreCond.isUsable()) { 4318 PreCond = 4319 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd, 4320 PreCond.get(), IterSpaces[Cnt].PreCond); 4321 } 4322 auto N = IterSpaces[Cnt].NumIterations; 4323 SourceLocation Loc = N->getExprLoc(); 4324 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32; 4325 if (LastIteration32.isUsable()) 4326 LastIteration32 = SemaRef.BuildBinOp( 4327 CurScope, Loc, BO_Mul, LastIteration32.get(), 4328 SemaRef 4329 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 4330 Sema::AA_Converting, 4331 /*AllowExplicit=*/true) 4332 .get()); 4333 if (LastIteration64.isUsable()) 4334 LastIteration64 = SemaRef.BuildBinOp( 4335 CurScope, Loc, BO_Mul, LastIteration64.get(), 4336 SemaRef 4337 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(), 4338 Sema::AA_Converting, 4339 /*AllowExplicit=*/true) 4340 .get()); 4341 } 4342 4343 // Choose either the 32-bit or 64-bit version. 4344 ExprResult LastIteration = LastIteration64; 4345 if (LastIteration32.isUsable() && 4346 C.getTypeSize(LastIteration32.get()->getType()) == 32 && 4347 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 || 4348 FitsInto( 4349 32 /* Bits */, 4350 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(), 4351 LastIteration64.get(), SemaRef))) 4352 LastIteration = LastIteration32; 4353 QualType VType = LastIteration.get()->getType(); 4354 QualType RealVType = VType; 4355 QualType StrideVType = VType; 4356 if (isOpenMPTaskLoopDirective(DKind)) { 4357 VType = 4358 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0); 4359 StrideVType = 4360 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1); 4361 } 4362 4363 if (!LastIteration.isUsable()) 4364 return 0; 4365 4366 // Save the number of iterations. 4367 ExprResult NumIterations = LastIteration; 4368 { 4369 LastIteration = SemaRef.BuildBinOp( 4370 CurScope, LastIteration.get()->getExprLoc(), BO_Sub, 4371 LastIteration.get(), 4372 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4373 if (!LastIteration.isUsable()) 4374 return 0; 4375 } 4376 4377 // Calculate the last iteration number beforehand instead of doing this on 4378 // each iteration. Do not do this if the number of iterations may be kfold-ed. 4379 llvm::APSInt Result; 4380 bool IsConstant = 4381 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context); 4382 ExprResult CalcLastIteration; 4383 if (!IsConstant) { 4384 ExprResult SaveRef = 4385 tryBuildCapture(SemaRef, LastIteration.get(), Captures); 4386 LastIteration = SaveRef; 4387 4388 // Prepare SaveRef + 1. 4389 NumIterations = SemaRef.BuildBinOp( 4390 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(), 4391 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get()); 4392 if (!NumIterations.isUsable()) 4393 return 0; 4394 } 4395 4396 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin(); 4397 4398 // Build variables passed into runtime, necessary for worksharing directives. 4399 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB; 4400 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4401 isOpenMPDistributeDirective(DKind)) { 4402 // Lower bound variable, initialized with zero. 4403 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb"); 4404 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc); 4405 SemaRef.AddInitializerToDecl(LBDecl, 4406 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4407 /*DirectInit*/ false); 4408 4409 // Upper bound variable, initialized with last iteration number. 4410 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub"); 4411 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc); 4412 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(), 4413 /*DirectInit*/ false); 4414 4415 // A 32-bit variable-flag where runtime returns 1 for the last iteration. 4416 // This will be used to implement clause 'lastprivate'. 4417 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true); 4418 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last"); 4419 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc); 4420 SemaRef.AddInitializerToDecl(ILDecl, 4421 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4422 /*DirectInit*/ false); 4423 4424 // Stride variable returned by runtime (we initialize it to 1 by default). 4425 VarDecl *STDecl = 4426 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride"); 4427 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc); 4428 SemaRef.AddInitializerToDecl(STDecl, 4429 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(), 4430 /*DirectInit*/ false); 4431 4432 // Build expression: UB = min(UB, LastIteration) 4433 // It is necessary for CodeGen of directives with static scheduling. 4434 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT, 4435 UB.get(), LastIteration.get()); 4436 ExprResult CondOp = SemaRef.ActOnConditionalOp( 4437 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get()); 4438 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(), 4439 CondOp.get()); 4440 EUB = SemaRef.ActOnFinishFullExpr(EUB.get()); 4441 4442 // If we have a combined directive that combines 'distribute', 'for' or 4443 // 'simd' we need to be able to access the bounds of the schedule of the 4444 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained 4445 // by scheduling 'distribute' have to be passed to the schedule of 'for'. 4446 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4447 4448 // Lower bound variable, initialized with zero. 4449 VarDecl *CombLBDecl = 4450 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb"); 4451 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc); 4452 SemaRef.AddInitializerToDecl( 4453 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(), 4454 /*DirectInit*/ false); 4455 4456 // Upper bound variable, initialized with last iteration number. 4457 VarDecl *CombUBDecl = 4458 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub"); 4459 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc); 4460 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(), 4461 /*DirectInit*/ false); 4462 4463 ExprResult CombIsUBGreater = SemaRef.BuildBinOp( 4464 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get()); 4465 ExprResult CombCondOp = 4466 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(), 4467 LastIteration.get(), CombUB.get()); 4468 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(), 4469 CombCondOp.get()); 4470 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get()); 4471 4472 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl(); 4473 // We expect to have at least 2 more parameters than the 'parallel' 4474 // directive does - the lower and upper bounds of the previous schedule. 4475 assert(CD->getNumParams() >= 4 && 4476 "Unexpected number of parameters in loop combined directive"); 4477 4478 // Set the proper type for the bounds given what we learned from the 4479 // enclosed loops. 4480 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2); 4481 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3); 4482 4483 // Previous lower and upper bounds are obtained from the region 4484 // parameters. 4485 PrevLB = 4486 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc); 4487 PrevUB = 4488 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc); 4489 } 4490 } 4491 4492 // Build the iteration variable and its initialization before loop. 4493 ExprResult IV; 4494 ExprResult Init, CombInit; 4495 { 4496 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv"); 4497 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc); 4498 Expr *RHS = 4499 (isOpenMPWorksharingDirective(DKind) || 4500 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4501 ? LB.get() 4502 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 4503 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS); 4504 Init = SemaRef.ActOnFinishFullExpr(Init.get()); 4505 4506 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4507 Expr *CombRHS = 4508 (isOpenMPWorksharingDirective(DKind) || 4509 isOpenMPTaskLoopDirective(DKind) || 4510 isOpenMPDistributeDirective(DKind)) 4511 ? CombLB.get() 4512 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get(); 4513 CombInit = 4514 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS); 4515 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get()); 4516 } 4517 } 4518 4519 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops. 4520 SourceLocation CondLoc; 4521 ExprResult Cond = 4522 (isOpenMPWorksharingDirective(DKind) || 4523 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)) 4524 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()) 4525 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(), 4526 NumIterations.get()); 4527 ExprResult CombCond; 4528 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4529 CombCond = 4530 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get()); 4531 } 4532 // Loop increment (IV = IV + 1) 4533 SourceLocation IncLoc; 4534 ExprResult Inc = 4535 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(), 4536 SemaRef.ActOnIntegerConstant(IncLoc, 1).get()); 4537 if (!Inc.isUsable()) 4538 return 0; 4539 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get()); 4540 Inc = SemaRef.ActOnFinishFullExpr(Inc.get()); 4541 if (!Inc.isUsable()) 4542 return 0; 4543 4544 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST). 4545 // Used for directives with static scheduling. 4546 // In combined construct, add combined version that use CombLB and CombUB 4547 // base variables for the update 4548 ExprResult NextLB, NextUB, CombNextLB, CombNextUB; 4549 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) || 4550 isOpenMPDistributeDirective(DKind)) { 4551 // LB + ST 4552 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get()); 4553 if (!NextLB.isUsable()) 4554 return 0; 4555 // LB = LB + ST 4556 NextLB = 4557 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get()); 4558 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get()); 4559 if (!NextLB.isUsable()) 4560 return 0; 4561 // UB + ST 4562 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get()); 4563 if (!NextUB.isUsable()) 4564 return 0; 4565 // UB = UB + ST 4566 NextUB = 4567 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get()); 4568 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get()); 4569 if (!NextUB.isUsable()) 4570 return 0; 4571 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4572 CombNextLB = 4573 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get()); 4574 if (!NextLB.isUsable()) 4575 return 0; 4576 // LB = LB + ST 4577 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(), 4578 CombNextLB.get()); 4579 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get()); 4580 if (!CombNextLB.isUsable()) 4581 return 0; 4582 // UB + ST 4583 CombNextUB = 4584 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get()); 4585 if (!CombNextUB.isUsable()) 4586 return 0; 4587 // UB = UB + ST 4588 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(), 4589 CombNextUB.get()); 4590 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get()); 4591 if (!CombNextUB.isUsable()) 4592 return 0; 4593 } 4594 } 4595 4596 // Create increment expression for distribute loop when combined in a same 4597 // directive with for as IV = IV + ST; ensure upper bound expression based 4598 // on PrevUB instead of NumIterations - used to implement 'for' when found 4599 // in combination with 'distribute', like in 'distribute parallel for' 4600 SourceLocation DistIncLoc; 4601 ExprResult DistCond, DistInc, PrevEUB; 4602 if (isOpenMPLoopBoundSharingDirective(DKind)) { 4603 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get()); 4604 assert(DistCond.isUsable() && "distribute cond expr was not built"); 4605 4606 DistInc = 4607 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get()); 4608 assert(DistInc.isUsable() && "distribute inc expr was not built"); 4609 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(), 4610 DistInc.get()); 4611 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get()); 4612 assert(DistInc.isUsable() && "distribute inc expr was not built"); 4613 4614 // Build expression: UB = min(UB, prevUB) for #for in composite or combined 4615 // construct 4616 SourceLocation DistEUBLoc; 4617 ExprResult IsUBGreater = 4618 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get()); 4619 ExprResult CondOp = SemaRef.ActOnConditionalOp( 4620 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get()); 4621 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(), 4622 CondOp.get()); 4623 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get()); 4624 } 4625 4626 // Build updates and final values of the loop counters. 4627 bool HasErrors = false; 4628 Built.Counters.resize(NestedLoopCount); 4629 Built.Inits.resize(NestedLoopCount); 4630 Built.Updates.resize(NestedLoopCount); 4631 Built.Finals.resize(NestedLoopCount); 4632 SmallVector<Expr *, 4> LoopMultipliers; 4633 { 4634 ExprResult Div; 4635 // Go from inner nested loop to outer. 4636 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 4637 LoopIterationSpace &IS = IterSpaces[Cnt]; 4638 SourceLocation UpdLoc = IS.IncSrcRange.getBegin(); 4639 // Build: Iter = (IV / Div) % IS.NumIters 4640 // where Div is product of previous iterations' IS.NumIters. 4641 ExprResult Iter; 4642 if (Div.isUsable()) { 4643 Iter = 4644 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get()); 4645 } else { 4646 Iter = IV; 4647 assert((Cnt == (int)NestedLoopCount - 1) && 4648 "unusable div expected on first iteration only"); 4649 } 4650 4651 if (Cnt != 0 && Iter.isUsable()) 4652 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(), 4653 IS.NumIterations); 4654 if (!Iter.isUsable()) { 4655 HasErrors = true; 4656 break; 4657 } 4658 4659 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step 4660 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl()); 4661 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(), 4662 IS.CounterVar->getExprLoc(), 4663 /*RefersToCapture=*/true); 4664 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar, 4665 IS.CounterInit, Captures); 4666 if (!Init.isUsable()) { 4667 HasErrors = true; 4668 break; 4669 } 4670 ExprResult Update = BuildCounterUpdate( 4671 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter, 4672 IS.CounterStep, IS.Subtract, &Captures); 4673 if (!Update.isUsable()) { 4674 HasErrors = true; 4675 break; 4676 } 4677 4678 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step 4679 ExprResult Final = BuildCounterUpdate( 4680 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, 4681 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures); 4682 if (!Final.isUsable()) { 4683 HasErrors = true; 4684 break; 4685 } 4686 4687 // Build Div for the next iteration: Div <- Div * IS.NumIters 4688 if (Cnt != 0) { 4689 if (Div.isUnset()) 4690 Div = IS.NumIterations; 4691 else 4692 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(), 4693 IS.NumIterations); 4694 4695 // Add parentheses (for debugging purposes only). 4696 if (Div.isUsable()) 4697 Div = tryBuildCapture(SemaRef, Div.get(), Captures); 4698 if (!Div.isUsable()) { 4699 HasErrors = true; 4700 break; 4701 } 4702 LoopMultipliers.push_back(Div.get()); 4703 } 4704 if (!Update.isUsable() || !Final.isUsable()) { 4705 HasErrors = true; 4706 break; 4707 } 4708 // Save results 4709 Built.Counters[Cnt] = IS.CounterVar; 4710 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar; 4711 Built.Inits[Cnt] = Init.get(); 4712 Built.Updates[Cnt] = Update.get(); 4713 Built.Finals[Cnt] = Final.get(); 4714 } 4715 } 4716 4717 if (HasErrors) 4718 return 0; 4719 4720 // Save results 4721 Built.IterationVarRef = IV.get(); 4722 Built.LastIteration = LastIteration.get(); 4723 Built.NumIterations = NumIterations.get(); 4724 Built.CalcLastIteration = 4725 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get(); 4726 Built.PreCond = PreCond.get(); 4727 Built.PreInits = buildPreInits(C, Captures); 4728 Built.Cond = Cond.get(); 4729 Built.Init = Init.get(); 4730 Built.Inc = Inc.get(); 4731 Built.LB = LB.get(); 4732 Built.UB = UB.get(); 4733 Built.IL = IL.get(); 4734 Built.ST = ST.get(); 4735 Built.EUB = EUB.get(); 4736 Built.NLB = NextLB.get(); 4737 Built.NUB = NextUB.get(); 4738 Built.PrevLB = PrevLB.get(); 4739 Built.PrevUB = PrevUB.get(); 4740 Built.DistInc = DistInc.get(); 4741 Built.PrevEUB = PrevEUB.get(); 4742 Built.DistCombinedFields.LB = CombLB.get(); 4743 Built.DistCombinedFields.UB = CombUB.get(); 4744 Built.DistCombinedFields.EUB = CombEUB.get(); 4745 Built.DistCombinedFields.Init = CombInit.get(); 4746 Built.DistCombinedFields.Cond = CombCond.get(); 4747 Built.DistCombinedFields.NLB = CombNextLB.get(); 4748 Built.DistCombinedFields.NUB = CombNextUB.get(); 4749 4750 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get(); 4751 // Fill data for doacross depend clauses. 4752 for (auto Pair : DSA.getDoacrossDependClauses()) { 4753 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source) 4754 Pair.first->setCounterValue(CounterVal); 4755 else { 4756 if (NestedLoopCount != Pair.second.size() || 4757 NestedLoopCount != LoopMultipliers.size() + 1) { 4758 // Erroneous case - clause has some problems. 4759 Pair.first->setCounterValue(CounterVal); 4760 continue; 4761 } 4762 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink); 4763 auto I = Pair.second.rbegin(); 4764 auto IS = IterSpaces.rbegin(); 4765 auto ILM = LoopMultipliers.rbegin(); 4766 Expr *UpCounterVal = CounterVal; 4767 Expr *Multiplier = nullptr; 4768 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) { 4769 if (I->first) { 4770 assert(IS->CounterStep); 4771 Expr *NormalizedOffset = 4772 SemaRef 4773 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div, 4774 I->first, IS->CounterStep) 4775 .get(); 4776 if (Multiplier) { 4777 NormalizedOffset = 4778 SemaRef 4779 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul, 4780 NormalizedOffset, Multiplier) 4781 .get(); 4782 } 4783 assert(I->second == OO_Plus || I->second == OO_Minus); 4784 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub; 4785 UpCounterVal = SemaRef 4786 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK, 4787 UpCounterVal, NormalizedOffset) 4788 .get(); 4789 } 4790 Multiplier = *ILM; 4791 ++I; 4792 ++IS; 4793 ++ILM; 4794 } 4795 Pair.first->setCounterValue(UpCounterVal); 4796 } 4797 } 4798 4799 return NestedLoopCount; 4800 } 4801 4802 static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) { 4803 auto CollapseClauses = 4804 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses); 4805 if (CollapseClauses.begin() != CollapseClauses.end()) 4806 return (*CollapseClauses.begin())->getNumForLoops(); 4807 return nullptr; 4808 } 4809 4810 static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) { 4811 auto OrderedClauses = 4812 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses); 4813 if (OrderedClauses.begin() != OrderedClauses.end()) 4814 return (*OrderedClauses.begin())->getNumForLoops(); 4815 return nullptr; 4816 } 4817 4818 static bool checkSimdlenSafelenSpecified(Sema &S, 4819 const ArrayRef<OMPClause *> Clauses) { 4820 OMPSafelenClause *Safelen = nullptr; 4821 OMPSimdlenClause *Simdlen = nullptr; 4822 4823 for (auto *Clause : Clauses) { 4824 if (Clause->getClauseKind() == OMPC_safelen) 4825 Safelen = cast<OMPSafelenClause>(Clause); 4826 else if (Clause->getClauseKind() == OMPC_simdlen) 4827 Simdlen = cast<OMPSimdlenClause>(Clause); 4828 if (Safelen && Simdlen) 4829 break; 4830 } 4831 4832 if (Simdlen && Safelen) { 4833 llvm::APSInt SimdlenRes, SafelenRes; 4834 auto SimdlenLength = Simdlen->getSimdlen(); 4835 auto SafelenLength = Safelen->getSafelen(); 4836 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() || 4837 SimdlenLength->isInstantiationDependent() || 4838 SimdlenLength->containsUnexpandedParameterPack()) 4839 return false; 4840 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() || 4841 SafelenLength->isInstantiationDependent() || 4842 SafelenLength->containsUnexpandedParameterPack()) 4843 return false; 4844 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context); 4845 SafelenLength->EvaluateAsInt(SafelenRes, S.Context); 4846 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions] 4847 // If both simdlen and safelen clauses are specified, the value of the 4848 // simdlen parameter must be less than or equal to the value of the safelen 4849 // parameter. 4850 if (SimdlenRes > SafelenRes) { 4851 S.Diag(SimdlenLength->getExprLoc(), 4852 diag::err_omp_wrong_simdlen_safelen_values) 4853 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange(); 4854 return true; 4855 } 4856 } 4857 return false; 4858 } 4859 4860 StmtResult Sema::ActOnOpenMPSimdDirective( 4861 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4862 SourceLocation EndLoc, 4863 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4864 if (!AStmt) 4865 return StmtError(); 4866 4867 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4868 OMPLoopDirective::HelperExprs B; 4869 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4870 // define the nested loops number. 4871 unsigned NestedLoopCount = CheckOpenMPLoop( 4872 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 4873 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 4874 if (NestedLoopCount == 0) 4875 return StmtError(); 4876 4877 assert((CurContext->isDependentContext() || B.builtAll()) && 4878 "omp simd loop exprs were not built"); 4879 4880 if (!CurContext->isDependentContext()) { 4881 // Finalize the clauses that need pre-built expressions for CodeGen. 4882 for (auto C : Clauses) { 4883 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4884 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4885 B.NumIterations, *this, CurScope, 4886 DSAStack)) 4887 return StmtError(); 4888 } 4889 } 4890 4891 if (checkSimdlenSafelenSpecified(*this, Clauses)) 4892 return StmtError(); 4893 4894 getCurFunction()->setHasBranchProtectedScope(); 4895 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4896 Clauses, AStmt, B); 4897 } 4898 4899 StmtResult Sema::ActOnOpenMPForDirective( 4900 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4901 SourceLocation EndLoc, 4902 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4903 if (!AStmt) 4904 return StmtError(); 4905 4906 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4907 OMPLoopDirective::HelperExprs B; 4908 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4909 // define the nested loops number. 4910 unsigned NestedLoopCount = CheckOpenMPLoop( 4911 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses), 4912 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B); 4913 if (NestedLoopCount == 0) 4914 return StmtError(); 4915 4916 assert((CurContext->isDependentContext() || B.builtAll()) && 4917 "omp for loop exprs were not built"); 4918 4919 if (!CurContext->isDependentContext()) { 4920 // Finalize the clauses that need pre-built expressions for CodeGen. 4921 for (auto C : Clauses) { 4922 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4923 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4924 B.NumIterations, *this, CurScope, 4925 DSAStack)) 4926 return StmtError(); 4927 } 4928 } 4929 4930 getCurFunction()->setHasBranchProtectedScope(); 4931 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4932 Clauses, AStmt, B, DSAStack->isCancelRegion()); 4933 } 4934 4935 StmtResult Sema::ActOnOpenMPForSimdDirective( 4936 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 4937 SourceLocation EndLoc, 4938 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 4939 if (!AStmt) 4940 return StmtError(); 4941 4942 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4943 OMPLoopDirective::HelperExprs B; 4944 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 4945 // define the nested loops number. 4946 unsigned NestedLoopCount = 4947 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses), 4948 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 4949 VarsWithImplicitDSA, B); 4950 if (NestedLoopCount == 0) 4951 return StmtError(); 4952 4953 assert((CurContext->isDependentContext() || B.builtAll()) && 4954 "omp for simd loop exprs were not built"); 4955 4956 if (!CurContext->isDependentContext()) { 4957 // Finalize the clauses that need pre-built expressions for CodeGen. 4958 for (auto C : Clauses) { 4959 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 4960 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 4961 B.NumIterations, *this, CurScope, 4962 DSAStack)) 4963 return StmtError(); 4964 } 4965 } 4966 4967 if (checkSimdlenSafelenSpecified(*this, Clauses)) 4968 return StmtError(); 4969 4970 getCurFunction()->setHasBranchProtectedScope(); 4971 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount, 4972 Clauses, AStmt, B); 4973 } 4974 4975 StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses, 4976 Stmt *AStmt, 4977 SourceLocation StartLoc, 4978 SourceLocation EndLoc) { 4979 if (!AStmt) 4980 return StmtError(); 4981 4982 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 4983 auto BaseStmt = AStmt; 4984 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 4985 BaseStmt = CS->getCapturedStmt(); 4986 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 4987 auto S = C->children(); 4988 if (S.begin() == S.end()) 4989 return StmtError(); 4990 // All associated statements must be '#pragma omp section' except for 4991 // the first one. 4992 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 4993 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 4994 if (SectionStmt) 4995 Diag(SectionStmt->getLocStart(), 4996 diag::err_omp_sections_substmt_not_section); 4997 return StmtError(); 4998 } 4999 cast<OMPSectionDirective>(SectionStmt) 5000 ->setHasCancel(DSAStack->isCancelRegion()); 5001 } 5002 } else { 5003 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt); 5004 return StmtError(); 5005 } 5006 5007 getCurFunction()->setHasBranchProtectedScope(); 5008 5009 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5010 DSAStack->isCancelRegion()); 5011 } 5012 5013 StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt, 5014 SourceLocation StartLoc, 5015 SourceLocation EndLoc) { 5016 if (!AStmt) 5017 return StmtError(); 5018 5019 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5020 5021 getCurFunction()->setHasBranchProtectedScope(); 5022 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion()); 5023 5024 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt, 5025 DSAStack->isCancelRegion()); 5026 } 5027 5028 StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses, 5029 Stmt *AStmt, 5030 SourceLocation StartLoc, 5031 SourceLocation EndLoc) { 5032 if (!AStmt) 5033 return StmtError(); 5034 5035 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5036 5037 getCurFunction()->setHasBranchProtectedScope(); 5038 5039 // OpenMP [2.7.3, single Construct, Restrictions] 5040 // The copyprivate clause must not be used with the nowait clause. 5041 OMPClause *Nowait = nullptr; 5042 OMPClause *Copyprivate = nullptr; 5043 for (auto *Clause : Clauses) { 5044 if (Clause->getClauseKind() == OMPC_nowait) 5045 Nowait = Clause; 5046 else if (Clause->getClauseKind() == OMPC_copyprivate) 5047 Copyprivate = Clause; 5048 if (Copyprivate && Nowait) { 5049 Diag(Copyprivate->getLocStart(), 5050 diag::err_omp_single_copyprivate_with_nowait); 5051 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here); 5052 return StmtError(); 5053 } 5054 } 5055 5056 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5057 } 5058 5059 StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt, 5060 SourceLocation StartLoc, 5061 SourceLocation EndLoc) { 5062 if (!AStmt) 5063 return StmtError(); 5064 5065 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5066 5067 getCurFunction()->setHasBranchProtectedScope(); 5068 5069 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt); 5070 } 5071 5072 StmtResult Sema::ActOnOpenMPCriticalDirective( 5073 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses, 5074 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) { 5075 if (!AStmt) 5076 return StmtError(); 5077 5078 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5079 5080 bool ErrorFound = false; 5081 llvm::APSInt Hint; 5082 SourceLocation HintLoc; 5083 bool DependentHint = false; 5084 for (auto *C : Clauses) { 5085 if (C->getClauseKind() == OMPC_hint) { 5086 if (!DirName.getName()) { 5087 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name); 5088 ErrorFound = true; 5089 } 5090 Expr *E = cast<OMPHintClause>(C)->getHint(); 5091 if (E->isTypeDependent() || E->isValueDependent() || 5092 E->isInstantiationDependent()) 5093 DependentHint = true; 5094 else { 5095 Hint = E->EvaluateKnownConstInt(Context); 5096 HintLoc = C->getLocStart(); 5097 } 5098 } 5099 } 5100 if (ErrorFound) 5101 return StmtError(); 5102 auto Pair = DSAStack->getCriticalWithHint(DirName); 5103 if (Pair.first && DirName.getName() && !DependentHint) { 5104 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) { 5105 Diag(StartLoc, diag::err_omp_critical_with_hint); 5106 if (HintLoc.isValid()) { 5107 Diag(HintLoc, diag::note_omp_critical_hint_here) 5108 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false); 5109 } else 5110 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0; 5111 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) { 5112 Diag(C->getLocStart(), diag::note_omp_critical_hint_here) 5113 << 1 5114 << C->getHint()->EvaluateKnownConstInt(Context).toString( 5115 /*Radix=*/10, /*Signed=*/false); 5116 } else 5117 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1; 5118 } 5119 } 5120 5121 getCurFunction()->setHasBranchProtectedScope(); 5122 5123 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc, 5124 Clauses, AStmt); 5125 if (!Pair.first && DirName.getName() && !DependentHint) 5126 DSAStack->addCriticalWithHint(Dir, Hint); 5127 return Dir; 5128 } 5129 5130 StmtResult Sema::ActOnOpenMPParallelForDirective( 5131 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5132 SourceLocation EndLoc, 5133 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5134 if (!AStmt) 5135 return StmtError(); 5136 5137 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5138 // 1.2.2 OpenMP Language Terminology 5139 // Structured block - An executable statement with a single entry at the 5140 // top and a single exit at the bottom. 5141 // The point of exit cannot be a branch out of the structured block. 5142 // longjmp() and throw() must not violate the entry/exit criteria. 5143 CS->getCapturedDecl()->setNothrow(); 5144 5145 OMPLoopDirective::HelperExprs B; 5146 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5147 // define the nested loops number. 5148 unsigned NestedLoopCount = 5149 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses), 5150 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5151 VarsWithImplicitDSA, B); 5152 if (NestedLoopCount == 0) 5153 return StmtError(); 5154 5155 assert((CurContext->isDependentContext() || B.builtAll()) && 5156 "omp parallel for loop exprs were not built"); 5157 5158 if (!CurContext->isDependentContext()) { 5159 // Finalize the clauses that need pre-built expressions for CodeGen. 5160 for (auto C : Clauses) { 5161 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5162 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5163 B.NumIterations, *this, CurScope, 5164 DSAStack)) 5165 return StmtError(); 5166 } 5167 } 5168 5169 getCurFunction()->setHasBranchProtectedScope(); 5170 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc, 5171 NestedLoopCount, Clauses, AStmt, B, 5172 DSAStack->isCancelRegion()); 5173 } 5174 5175 StmtResult Sema::ActOnOpenMPParallelForSimdDirective( 5176 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 5177 SourceLocation EndLoc, 5178 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 5179 if (!AStmt) 5180 return StmtError(); 5181 5182 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 5183 // 1.2.2 OpenMP Language Terminology 5184 // Structured block - An executable statement with a single entry at the 5185 // top and a single exit at the bottom. 5186 // The point of exit cannot be a branch out of the structured block. 5187 // longjmp() and throw() must not violate the entry/exit criteria. 5188 CS->getCapturedDecl()->setNothrow(); 5189 5190 OMPLoopDirective::HelperExprs B; 5191 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 5192 // define the nested loops number. 5193 unsigned NestedLoopCount = 5194 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses), 5195 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 5196 VarsWithImplicitDSA, B); 5197 if (NestedLoopCount == 0) 5198 return StmtError(); 5199 5200 if (!CurContext->isDependentContext()) { 5201 // Finalize the clauses that need pre-built expressions for CodeGen. 5202 for (auto C : Clauses) { 5203 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 5204 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 5205 B.NumIterations, *this, CurScope, 5206 DSAStack)) 5207 return StmtError(); 5208 } 5209 } 5210 5211 if (checkSimdlenSafelenSpecified(*this, Clauses)) 5212 return StmtError(); 5213 5214 getCurFunction()->setHasBranchProtectedScope(); 5215 return OMPParallelForSimdDirective::Create( 5216 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 5217 } 5218 5219 StmtResult 5220 Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses, 5221 Stmt *AStmt, SourceLocation StartLoc, 5222 SourceLocation EndLoc) { 5223 if (!AStmt) 5224 return StmtError(); 5225 5226 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5227 auto BaseStmt = AStmt; 5228 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt)) 5229 BaseStmt = CS->getCapturedStmt(); 5230 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) { 5231 auto S = C->children(); 5232 if (S.begin() == S.end()) 5233 return StmtError(); 5234 // All associated statements must be '#pragma omp section' except for 5235 // the first one. 5236 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) { 5237 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) { 5238 if (SectionStmt) 5239 Diag(SectionStmt->getLocStart(), 5240 diag::err_omp_parallel_sections_substmt_not_section); 5241 return StmtError(); 5242 } 5243 cast<OMPSectionDirective>(SectionStmt) 5244 ->setHasCancel(DSAStack->isCancelRegion()); 5245 } 5246 } else { 5247 Diag(AStmt->getLocStart(), 5248 diag::err_omp_parallel_sections_not_compound_stmt); 5249 return StmtError(); 5250 } 5251 5252 getCurFunction()->setHasBranchProtectedScope(); 5253 5254 return OMPParallelSectionsDirective::Create( 5255 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion()); 5256 } 5257 5258 StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses, 5259 Stmt *AStmt, SourceLocation StartLoc, 5260 SourceLocation EndLoc) { 5261 if (!AStmt) 5262 return StmtError(); 5263 5264 auto *CS = cast<CapturedStmt>(AStmt); 5265 // 1.2.2 OpenMP Language Terminology 5266 // Structured block - An executable statement with a single entry at the 5267 // top and a single exit at the bottom. 5268 // The point of exit cannot be a branch out of the structured block. 5269 // longjmp() and throw() must not violate the entry/exit criteria. 5270 CS->getCapturedDecl()->setNothrow(); 5271 5272 getCurFunction()->setHasBranchProtectedScope(); 5273 5274 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 5275 DSAStack->isCancelRegion()); 5276 } 5277 5278 StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc, 5279 SourceLocation EndLoc) { 5280 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc); 5281 } 5282 5283 StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc, 5284 SourceLocation EndLoc) { 5285 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc); 5286 } 5287 5288 StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc, 5289 SourceLocation EndLoc) { 5290 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc); 5291 } 5292 5293 StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses, 5294 Stmt *AStmt, 5295 SourceLocation StartLoc, 5296 SourceLocation EndLoc) { 5297 if (!AStmt) 5298 return StmtError(); 5299 5300 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5301 5302 getCurFunction()->setHasBranchProtectedScope(); 5303 5304 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses, 5305 AStmt, 5306 DSAStack->getTaskgroupReductionRef()); 5307 } 5308 5309 StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses, 5310 SourceLocation StartLoc, 5311 SourceLocation EndLoc) { 5312 assert(Clauses.size() <= 1 && "Extra clauses in flush directive"); 5313 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses); 5314 } 5315 5316 StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses, 5317 Stmt *AStmt, 5318 SourceLocation StartLoc, 5319 SourceLocation EndLoc) { 5320 OMPClause *DependFound = nullptr; 5321 OMPClause *DependSourceClause = nullptr; 5322 OMPClause *DependSinkClause = nullptr; 5323 bool ErrorFound = false; 5324 OMPThreadsClause *TC = nullptr; 5325 OMPSIMDClause *SC = nullptr; 5326 for (auto *C : Clauses) { 5327 if (auto *DC = dyn_cast<OMPDependClause>(C)) { 5328 DependFound = C; 5329 if (DC->getDependencyKind() == OMPC_DEPEND_source) { 5330 if (DependSourceClause) { 5331 Diag(C->getLocStart(), diag::err_omp_more_one_clause) 5332 << getOpenMPDirectiveName(OMPD_ordered) 5333 << getOpenMPClauseName(OMPC_depend) << 2; 5334 ErrorFound = true; 5335 } else 5336 DependSourceClause = C; 5337 if (DependSinkClause) { 5338 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 5339 << 0; 5340 ErrorFound = true; 5341 } 5342 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) { 5343 if (DependSourceClause) { 5344 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed) 5345 << 1; 5346 ErrorFound = true; 5347 } 5348 DependSinkClause = C; 5349 } 5350 } else if (C->getClauseKind() == OMPC_threads) 5351 TC = cast<OMPThreadsClause>(C); 5352 else if (C->getClauseKind() == OMPC_simd) 5353 SC = cast<OMPSIMDClause>(C); 5354 } 5355 if (!ErrorFound && !SC && 5356 isOpenMPSimdDirective(DSAStack->getParentDirective())) { 5357 // OpenMP [2.8.1,simd Construct, Restrictions] 5358 // An ordered construct with the simd clause is the only OpenMP construct 5359 // that can appear in the simd region. 5360 Diag(StartLoc, diag::err_omp_prohibited_region_simd); 5361 ErrorFound = true; 5362 } else if (DependFound && (TC || SC)) { 5363 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd) 5364 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind()); 5365 ErrorFound = true; 5366 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) { 5367 Diag(DependFound->getLocStart(), 5368 diag::err_omp_ordered_directive_without_param); 5369 ErrorFound = true; 5370 } else if (TC || Clauses.empty()) { 5371 if (auto *Param = DSAStack->getParentOrderedRegionParam()) { 5372 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc; 5373 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param) 5374 << (TC != nullptr); 5375 Diag(Param->getLocStart(), diag::note_omp_ordered_param); 5376 ErrorFound = true; 5377 } 5378 } 5379 if ((!AStmt && !DependFound) || ErrorFound) 5380 return StmtError(); 5381 5382 if (AStmt) { 5383 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 5384 5385 getCurFunction()->setHasBranchProtectedScope(); 5386 } 5387 5388 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 5389 } 5390 5391 namespace { 5392 /// \brief Helper class for checking expression in 'omp atomic [update]' 5393 /// construct. 5394 class OpenMPAtomicUpdateChecker { 5395 /// \brief Error results for atomic update expressions. 5396 enum ExprAnalysisErrorCode { 5397 /// \brief A statement is not an expression statement. 5398 NotAnExpression, 5399 /// \brief Expression is not builtin binary or unary operation. 5400 NotABinaryOrUnaryExpression, 5401 /// \brief Unary operation is not post-/pre- increment/decrement operation. 5402 NotAnUnaryIncDecExpression, 5403 /// \brief An expression is not of scalar type. 5404 NotAScalarType, 5405 /// \brief A binary operation is not an assignment operation. 5406 NotAnAssignmentOp, 5407 /// \brief RHS part of the binary operation is not a binary expression. 5408 NotABinaryExpression, 5409 /// \brief RHS part is not additive/multiplicative/shift/biwise binary 5410 /// expression. 5411 NotABinaryOperator, 5412 /// \brief RHS binary operation does not have reference to the updated LHS 5413 /// part. 5414 NotAnUpdateExpression, 5415 /// \brief No errors is found. 5416 NoError 5417 }; 5418 /// \brief Reference to Sema. 5419 Sema &SemaRef; 5420 /// \brief A location for note diagnostics (when error is found). 5421 SourceLocation NoteLoc; 5422 /// \brief 'x' lvalue part of the source atomic expression. 5423 Expr *X; 5424 /// \brief 'expr' rvalue part of the source atomic expression. 5425 Expr *E; 5426 /// \brief Helper expression of the form 5427 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 5428 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 5429 Expr *UpdateExpr; 5430 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is 5431 /// important for non-associative operations. 5432 bool IsXLHSInRHSPart; 5433 BinaryOperatorKind Op; 5434 SourceLocation OpLoc; 5435 /// \brief true if the source expression is a postfix unary operation, false 5436 /// if it is a prefix unary operation. 5437 bool IsPostfixUpdate; 5438 5439 public: 5440 OpenMPAtomicUpdateChecker(Sema &SemaRef) 5441 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr), 5442 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {} 5443 /// \brief Check specified statement that it is suitable for 'atomic update' 5444 /// constructs and extract 'x', 'expr' and Operation from the original 5445 /// expression. If DiagId and NoteId == 0, then only check is performed 5446 /// without error notification. 5447 /// \param DiagId Diagnostic which should be emitted if error is found. 5448 /// \param NoteId Diagnostic note for the main error message. 5449 /// \return true if statement is not an update expression, false otherwise. 5450 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0); 5451 /// \brief Return the 'x' lvalue part of the source atomic expression. 5452 Expr *getX() const { return X; } 5453 /// \brief Return the 'expr' rvalue part of the source atomic expression. 5454 Expr *getExpr() const { return E; } 5455 /// \brief Return the update expression used in calculation of the updated 5456 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or 5457 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'. 5458 Expr *getUpdateExpr() const { return UpdateExpr; } 5459 /// \brief Return true if 'x' is LHS in RHS part of full update expression, 5460 /// false otherwise. 5461 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; } 5462 5463 /// \brief true if the source expression is a postfix unary operation, false 5464 /// if it is a prefix unary operation. 5465 bool isPostfixUpdate() const { return IsPostfixUpdate; } 5466 5467 private: 5468 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0, 5469 unsigned NoteId = 0); 5470 }; 5471 } // namespace 5472 5473 bool OpenMPAtomicUpdateChecker::checkBinaryOperation( 5474 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) { 5475 ExprAnalysisErrorCode ErrorFound = NoError; 5476 SourceLocation ErrorLoc, NoteLoc; 5477 SourceRange ErrorRange, NoteRange; 5478 // Allowed constructs are: 5479 // x = x binop expr; 5480 // x = expr binop x; 5481 if (AtomicBinOp->getOpcode() == BO_Assign) { 5482 X = AtomicBinOp->getLHS(); 5483 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>( 5484 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) { 5485 if (AtomicInnerBinOp->isMultiplicativeOp() || 5486 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() || 5487 AtomicInnerBinOp->isBitwiseOp()) { 5488 Op = AtomicInnerBinOp->getOpcode(); 5489 OpLoc = AtomicInnerBinOp->getOperatorLoc(); 5490 auto *LHS = AtomicInnerBinOp->getLHS(); 5491 auto *RHS = AtomicInnerBinOp->getRHS(); 5492 llvm::FoldingSetNodeID XId, LHSId, RHSId; 5493 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(), 5494 /*Canonical=*/true); 5495 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(), 5496 /*Canonical=*/true); 5497 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(), 5498 /*Canonical=*/true); 5499 if (XId == LHSId) { 5500 E = RHS; 5501 IsXLHSInRHSPart = true; 5502 } else if (XId == RHSId) { 5503 E = LHS; 5504 IsXLHSInRHSPart = false; 5505 } else { 5506 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 5507 ErrorRange = AtomicInnerBinOp->getSourceRange(); 5508 NoteLoc = X->getExprLoc(); 5509 NoteRange = X->getSourceRange(); 5510 ErrorFound = NotAnUpdateExpression; 5511 } 5512 } else { 5513 ErrorLoc = AtomicInnerBinOp->getExprLoc(); 5514 ErrorRange = AtomicInnerBinOp->getSourceRange(); 5515 NoteLoc = AtomicInnerBinOp->getOperatorLoc(); 5516 NoteRange = SourceRange(NoteLoc, NoteLoc); 5517 ErrorFound = NotABinaryOperator; 5518 } 5519 } else { 5520 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc(); 5521 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange(); 5522 ErrorFound = NotABinaryExpression; 5523 } 5524 } else { 5525 ErrorLoc = AtomicBinOp->getExprLoc(); 5526 ErrorRange = AtomicBinOp->getSourceRange(); 5527 NoteLoc = AtomicBinOp->getOperatorLoc(); 5528 NoteRange = SourceRange(NoteLoc, NoteLoc); 5529 ErrorFound = NotAnAssignmentOp; 5530 } 5531 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5532 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5533 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5534 return true; 5535 } else if (SemaRef.CurContext->isDependentContext()) 5536 E = X = UpdateExpr = nullptr; 5537 return ErrorFound != NoError; 5538 } 5539 5540 bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId, 5541 unsigned NoteId) { 5542 ExprAnalysisErrorCode ErrorFound = NoError; 5543 SourceLocation ErrorLoc, NoteLoc; 5544 SourceRange ErrorRange, NoteRange; 5545 // Allowed constructs are: 5546 // x++; 5547 // x--; 5548 // ++x; 5549 // --x; 5550 // x binop= expr; 5551 // x = x binop expr; 5552 // x = expr binop x; 5553 if (auto *AtomicBody = dyn_cast<Expr>(S)) { 5554 AtomicBody = AtomicBody->IgnoreParenImpCasts(); 5555 if (AtomicBody->getType()->isScalarType() || 5556 AtomicBody->isInstantiationDependent()) { 5557 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>( 5558 AtomicBody->IgnoreParenImpCasts())) { 5559 // Check for Compound Assignment Operation 5560 Op = BinaryOperator::getOpForCompoundAssignment( 5561 AtomicCompAssignOp->getOpcode()); 5562 OpLoc = AtomicCompAssignOp->getOperatorLoc(); 5563 E = AtomicCompAssignOp->getRHS(); 5564 X = AtomicCompAssignOp->getLHS()->IgnoreParens(); 5565 IsXLHSInRHSPart = true; 5566 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>( 5567 AtomicBody->IgnoreParenImpCasts())) { 5568 // Check for Binary Operation 5569 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId)) 5570 return true; 5571 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>( 5572 AtomicBody->IgnoreParenImpCasts())) { 5573 // Check for Unary Operation 5574 if (AtomicUnaryOp->isIncrementDecrementOp()) { 5575 IsPostfixUpdate = AtomicUnaryOp->isPostfix(); 5576 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub; 5577 OpLoc = AtomicUnaryOp->getOperatorLoc(); 5578 X = AtomicUnaryOp->getSubExpr()->IgnoreParens(); 5579 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get(); 5580 IsXLHSInRHSPart = true; 5581 } else { 5582 ErrorFound = NotAnUnaryIncDecExpression; 5583 ErrorLoc = AtomicUnaryOp->getExprLoc(); 5584 ErrorRange = AtomicUnaryOp->getSourceRange(); 5585 NoteLoc = AtomicUnaryOp->getOperatorLoc(); 5586 NoteRange = SourceRange(NoteLoc, NoteLoc); 5587 } 5588 } else if (!AtomicBody->isInstantiationDependent()) { 5589 ErrorFound = NotABinaryOrUnaryExpression; 5590 NoteLoc = ErrorLoc = AtomicBody->getExprLoc(); 5591 NoteRange = ErrorRange = AtomicBody->getSourceRange(); 5592 } 5593 } else { 5594 ErrorFound = NotAScalarType; 5595 NoteLoc = ErrorLoc = AtomicBody->getLocStart(); 5596 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5597 } 5598 } else { 5599 ErrorFound = NotAnExpression; 5600 NoteLoc = ErrorLoc = S->getLocStart(); 5601 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5602 } 5603 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) { 5604 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange; 5605 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange; 5606 return true; 5607 } else if (SemaRef.CurContext->isDependentContext()) 5608 E = X = UpdateExpr = nullptr; 5609 if (ErrorFound == NoError && E && X) { 5610 // Build an update expression of form 'OpaqueValueExpr(x) binop 5611 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop 5612 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression. 5613 auto *OVEX = new (SemaRef.getASTContext()) 5614 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue); 5615 auto *OVEExpr = new (SemaRef.getASTContext()) 5616 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue); 5617 auto Update = 5618 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr, 5619 IsXLHSInRHSPart ? OVEExpr : OVEX); 5620 if (Update.isInvalid()) 5621 return true; 5622 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(), 5623 Sema::AA_Casting); 5624 if (Update.isInvalid()) 5625 return true; 5626 UpdateExpr = Update.get(); 5627 } 5628 return ErrorFound != NoError; 5629 } 5630 5631 StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses, 5632 Stmt *AStmt, 5633 SourceLocation StartLoc, 5634 SourceLocation EndLoc) { 5635 if (!AStmt) 5636 return StmtError(); 5637 5638 auto *CS = cast<CapturedStmt>(AStmt); 5639 // 1.2.2 OpenMP Language Terminology 5640 // Structured block - An executable statement with a single entry at the 5641 // top and a single exit at the bottom. 5642 // The point of exit cannot be a branch out of the structured block. 5643 // longjmp() and throw() must not violate the entry/exit criteria. 5644 OpenMPClauseKind AtomicKind = OMPC_unknown; 5645 SourceLocation AtomicKindLoc; 5646 for (auto *C : Clauses) { 5647 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write || 5648 C->getClauseKind() == OMPC_update || 5649 C->getClauseKind() == OMPC_capture) { 5650 if (AtomicKind != OMPC_unknown) { 5651 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses) 5652 << SourceRange(C->getLocStart(), C->getLocEnd()); 5653 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause) 5654 << getOpenMPClauseName(AtomicKind); 5655 } else { 5656 AtomicKind = C->getClauseKind(); 5657 AtomicKindLoc = C->getLocStart(); 5658 } 5659 } 5660 } 5661 5662 auto Body = CS->getCapturedStmt(); 5663 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body)) 5664 Body = EWC->getSubExpr(); 5665 5666 Expr *X = nullptr; 5667 Expr *V = nullptr; 5668 Expr *E = nullptr; 5669 Expr *UE = nullptr; 5670 bool IsXLHSInRHSPart = false; 5671 bool IsPostfixUpdate = false; 5672 // OpenMP [2.12.6, atomic Construct] 5673 // In the next expressions: 5674 // * x and v (as applicable) are both l-value expressions with scalar type. 5675 // * During the execution of an atomic region, multiple syntactic 5676 // occurrences of x must designate the same storage location. 5677 // * Neither of v and expr (as applicable) may access the storage location 5678 // designated by x. 5679 // * Neither of x and expr (as applicable) may access the storage location 5680 // designated by v. 5681 // * expr is an expression with scalar type. 5682 // * binop is one of +, *, -, /, &, ^, |, <<, or >>. 5683 // * binop, binop=, ++, and -- are not overloaded operators. 5684 // * The expression x binop expr must be numerically equivalent to x binop 5685 // (expr). This requirement is satisfied if the operators in expr have 5686 // precedence greater than binop, or by using parentheses around expr or 5687 // subexpressions of expr. 5688 // * The expression expr binop x must be numerically equivalent to (expr) 5689 // binop x. This requirement is satisfied if the operators in expr have 5690 // precedence equal to or greater than binop, or by using parentheses around 5691 // expr or subexpressions of expr. 5692 // * For forms that allow multiple occurrences of x, the number of times 5693 // that x is evaluated is unspecified. 5694 if (AtomicKind == OMPC_read) { 5695 enum { 5696 NotAnExpression, 5697 NotAnAssignmentOp, 5698 NotAScalarType, 5699 NotAnLValue, 5700 NoError 5701 } ErrorFound = NoError; 5702 SourceLocation ErrorLoc, NoteLoc; 5703 SourceRange ErrorRange, NoteRange; 5704 // If clause is read: 5705 // v = x; 5706 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5707 auto *AtomicBinOp = 5708 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5709 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5710 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 5711 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts(); 5712 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 5713 (V->isInstantiationDependent() || V->getType()->isScalarType())) { 5714 if (!X->isLValue() || !V->isLValue()) { 5715 auto NotLValueExpr = X->isLValue() ? V : X; 5716 ErrorFound = NotAnLValue; 5717 ErrorLoc = AtomicBinOp->getExprLoc(); 5718 ErrorRange = AtomicBinOp->getSourceRange(); 5719 NoteLoc = NotLValueExpr->getExprLoc(); 5720 NoteRange = NotLValueExpr->getSourceRange(); 5721 } 5722 } else if (!X->isInstantiationDependent() || 5723 !V->isInstantiationDependent()) { 5724 auto NotScalarExpr = 5725 (X->isInstantiationDependent() || X->getType()->isScalarType()) 5726 ? V 5727 : X; 5728 ErrorFound = NotAScalarType; 5729 ErrorLoc = AtomicBinOp->getExprLoc(); 5730 ErrorRange = AtomicBinOp->getSourceRange(); 5731 NoteLoc = NotScalarExpr->getExprLoc(); 5732 NoteRange = NotScalarExpr->getSourceRange(); 5733 } 5734 } else if (!AtomicBody->isInstantiationDependent()) { 5735 ErrorFound = NotAnAssignmentOp; 5736 ErrorLoc = AtomicBody->getExprLoc(); 5737 ErrorRange = AtomicBody->getSourceRange(); 5738 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5739 : AtomicBody->getExprLoc(); 5740 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5741 : AtomicBody->getSourceRange(); 5742 } 5743 } else { 5744 ErrorFound = NotAnExpression; 5745 NoteLoc = ErrorLoc = Body->getLocStart(); 5746 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5747 } 5748 if (ErrorFound != NoError) { 5749 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement) 5750 << ErrorRange; 5751 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 5752 << NoteRange; 5753 return StmtError(); 5754 } else if (CurContext->isDependentContext()) 5755 V = X = nullptr; 5756 } else if (AtomicKind == OMPC_write) { 5757 enum { 5758 NotAnExpression, 5759 NotAnAssignmentOp, 5760 NotAScalarType, 5761 NotAnLValue, 5762 NoError 5763 } ErrorFound = NoError; 5764 SourceLocation ErrorLoc, NoteLoc; 5765 SourceRange ErrorRange, NoteRange; 5766 // If clause is write: 5767 // x = expr; 5768 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5769 auto *AtomicBinOp = 5770 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5771 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5772 X = AtomicBinOp->getLHS(); 5773 E = AtomicBinOp->getRHS(); 5774 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) && 5775 (E->isInstantiationDependent() || E->getType()->isScalarType())) { 5776 if (!X->isLValue()) { 5777 ErrorFound = NotAnLValue; 5778 ErrorLoc = AtomicBinOp->getExprLoc(); 5779 ErrorRange = AtomicBinOp->getSourceRange(); 5780 NoteLoc = X->getExprLoc(); 5781 NoteRange = X->getSourceRange(); 5782 } 5783 } else if (!X->isInstantiationDependent() || 5784 !E->isInstantiationDependent()) { 5785 auto NotScalarExpr = 5786 (X->isInstantiationDependent() || X->getType()->isScalarType()) 5787 ? E 5788 : X; 5789 ErrorFound = NotAScalarType; 5790 ErrorLoc = AtomicBinOp->getExprLoc(); 5791 ErrorRange = AtomicBinOp->getSourceRange(); 5792 NoteLoc = NotScalarExpr->getExprLoc(); 5793 NoteRange = NotScalarExpr->getSourceRange(); 5794 } 5795 } else if (!AtomicBody->isInstantiationDependent()) { 5796 ErrorFound = NotAnAssignmentOp; 5797 ErrorLoc = AtomicBody->getExprLoc(); 5798 ErrorRange = AtomicBody->getSourceRange(); 5799 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5800 : AtomicBody->getExprLoc(); 5801 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5802 : AtomicBody->getSourceRange(); 5803 } 5804 } else { 5805 ErrorFound = NotAnExpression; 5806 NoteLoc = ErrorLoc = Body->getLocStart(); 5807 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc); 5808 } 5809 if (ErrorFound != NoError) { 5810 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement) 5811 << ErrorRange; 5812 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound 5813 << NoteRange; 5814 return StmtError(); 5815 } else if (CurContext->isDependentContext()) 5816 E = X = nullptr; 5817 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) { 5818 // If clause is update: 5819 // x++; 5820 // x--; 5821 // ++x; 5822 // --x; 5823 // x binop= expr; 5824 // x = x binop expr; 5825 // x = expr binop x; 5826 OpenMPAtomicUpdateChecker Checker(*this); 5827 if (Checker.checkStatement( 5828 Body, (AtomicKind == OMPC_update) 5829 ? diag::err_omp_atomic_update_not_expression_statement 5830 : diag::err_omp_atomic_not_expression_statement, 5831 diag::note_omp_atomic_update)) 5832 return StmtError(); 5833 if (!CurContext->isDependentContext()) { 5834 E = Checker.getExpr(); 5835 X = Checker.getX(); 5836 UE = Checker.getUpdateExpr(); 5837 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5838 } 5839 } else if (AtomicKind == OMPC_capture) { 5840 enum { 5841 NotAnAssignmentOp, 5842 NotACompoundStatement, 5843 NotTwoSubstatements, 5844 NotASpecificExpression, 5845 NoError 5846 } ErrorFound = NoError; 5847 SourceLocation ErrorLoc, NoteLoc; 5848 SourceRange ErrorRange, NoteRange; 5849 if (auto *AtomicBody = dyn_cast<Expr>(Body)) { 5850 // If clause is a capture: 5851 // v = x++; 5852 // v = x--; 5853 // v = ++x; 5854 // v = --x; 5855 // v = x binop= expr; 5856 // v = x = x binop expr; 5857 // v = x = expr binop x; 5858 auto *AtomicBinOp = 5859 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts()); 5860 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) { 5861 V = AtomicBinOp->getLHS(); 5862 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts(); 5863 OpenMPAtomicUpdateChecker Checker(*this); 5864 if (Checker.checkStatement( 5865 Body, diag::err_omp_atomic_capture_not_expression_statement, 5866 diag::note_omp_atomic_update)) 5867 return StmtError(); 5868 E = Checker.getExpr(); 5869 X = Checker.getX(); 5870 UE = Checker.getUpdateExpr(); 5871 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5872 IsPostfixUpdate = Checker.isPostfixUpdate(); 5873 } else if (!AtomicBody->isInstantiationDependent()) { 5874 ErrorLoc = AtomicBody->getExprLoc(); 5875 ErrorRange = AtomicBody->getSourceRange(); 5876 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc() 5877 : AtomicBody->getExprLoc(); 5878 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange() 5879 : AtomicBody->getSourceRange(); 5880 ErrorFound = NotAnAssignmentOp; 5881 } 5882 if (ErrorFound != NoError) { 5883 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement) 5884 << ErrorRange; 5885 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 5886 return StmtError(); 5887 } else if (CurContext->isDependentContext()) { 5888 UE = V = E = X = nullptr; 5889 } 5890 } else { 5891 // If clause is a capture: 5892 // { v = x; x = expr; } 5893 // { v = x; x++; } 5894 // { v = x; x--; } 5895 // { v = x; ++x; } 5896 // { v = x; --x; } 5897 // { v = x; x binop= expr; } 5898 // { v = x; x = x binop expr; } 5899 // { v = x; x = expr binop x; } 5900 // { x++; v = x; } 5901 // { x--; v = x; } 5902 // { ++x; v = x; } 5903 // { --x; v = x; } 5904 // { x binop= expr; v = x; } 5905 // { x = x binop expr; v = x; } 5906 // { x = expr binop x; v = x; } 5907 if (auto *CS = dyn_cast<CompoundStmt>(Body)) { 5908 // Check that this is { expr1; expr2; } 5909 if (CS->size() == 2) { 5910 auto *First = CS->body_front(); 5911 auto *Second = CS->body_back(); 5912 if (auto *EWC = dyn_cast<ExprWithCleanups>(First)) 5913 First = EWC->getSubExpr()->IgnoreParenImpCasts(); 5914 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second)) 5915 Second = EWC->getSubExpr()->IgnoreParenImpCasts(); 5916 // Need to find what subexpression is 'v' and what is 'x'. 5917 OpenMPAtomicUpdateChecker Checker(*this); 5918 bool IsUpdateExprFound = !Checker.checkStatement(Second); 5919 BinaryOperator *BinOp = nullptr; 5920 if (IsUpdateExprFound) { 5921 BinOp = dyn_cast<BinaryOperator>(First); 5922 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 5923 } 5924 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 5925 // { v = x; x++; } 5926 // { v = x; x--; } 5927 // { v = x; ++x; } 5928 // { v = x; --x; } 5929 // { v = x; x binop= expr; } 5930 // { v = x; x = x binop expr; } 5931 // { v = x; x = expr binop x; } 5932 // Check that the first expression has form v = x. 5933 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 5934 llvm::FoldingSetNodeID XId, PossibleXId; 5935 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 5936 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 5937 IsUpdateExprFound = XId == PossibleXId; 5938 if (IsUpdateExprFound) { 5939 V = BinOp->getLHS(); 5940 X = Checker.getX(); 5941 E = Checker.getExpr(); 5942 UE = Checker.getUpdateExpr(); 5943 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5944 IsPostfixUpdate = true; 5945 } 5946 } 5947 if (!IsUpdateExprFound) { 5948 IsUpdateExprFound = !Checker.checkStatement(First); 5949 BinOp = nullptr; 5950 if (IsUpdateExprFound) { 5951 BinOp = dyn_cast<BinaryOperator>(Second); 5952 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign; 5953 } 5954 if (IsUpdateExprFound && !CurContext->isDependentContext()) { 5955 // { x++; v = x; } 5956 // { x--; v = x; } 5957 // { ++x; v = x; } 5958 // { --x; v = x; } 5959 // { x binop= expr; v = x; } 5960 // { x = x binop expr; v = x; } 5961 // { x = expr binop x; v = x; } 5962 // Check that the second expression has form v = x. 5963 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts(); 5964 llvm::FoldingSetNodeID XId, PossibleXId; 5965 Checker.getX()->Profile(XId, Context, /*Canonical=*/true); 5966 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true); 5967 IsUpdateExprFound = XId == PossibleXId; 5968 if (IsUpdateExprFound) { 5969 V = BinOp->getLHS(); 5970 X = Checker.getX(); 5971 E = Checker.getExpr(); 5972 UE = Checker.getUpdateExpr(); 5973 IsXLHSInRHSPart = Checker.isXLHSInRHSPart(); 5974 IsPostfixUpdate = false; 5975 } 5976 } 5977 } 5978 if (!IsUpdateExprFound) { 5979 // { v = x; x = expr; } 5980 auto *FirstExpr = dyn_cast<Expr>(First); 5981 auto *SecondExpr = dyn_cast<Expr>(Second); 5982 if (!FirstExpr || !SecondExpr || 5983 !(FirstExpr->isInstantiationDependent() || 5984 SecondExpr->isInstantiationDependent())) { 5985 auto *FirstBinOp = dyn_cast<BinaryOperator>(First); 5986 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) { 5987 ErrorFound = NotAnAssignmentOp; 5988 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc() 5989 : First->getLocStart(); 5990 NoteRange = ErrorRange = FirstBinOp 5991 ? FirstBinOp->getSourceRange() 5992 : SourceRange(ErrorLoc, ErrorLoc); 5993 } else { 5994 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second); 5995 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) { 5996 ErrorFound = NotAnAssignmentOp; 5997 NoteLoc = ErrorLoc = SecondBinOp 5998 ? SecondBinOp->getOperatorLoc() 5999 : Second->getLocStart(); 6000 NoteRange = ErrorRange = 6001 SecondBinOp ? SecondBinOp->getSourceRange() 6002 : SourceRange(ErrorLoc, ErrorLoc); 6003 } else { 6004 auto *PossibleXRHSInFirst = 6005 FirstBinOp->getRHS()->IgnoreParenImpCasts(); 6006 auto *PossibleXLHSInSecond = 6007 SecondBinOp->getLHS()->IgnoreParenImpCasts(); 6008 llvm::FoldingSetNodeID X1Id, X2Id; 6009 PossibleXRHSInFirst->Profile(X1Id, Context, 6010 /*Canonical=*/true); 6011 PossibleXLHSInSecond->Profile(X2Id, Context, 6012 /*Canonical=*/true); 6013 IsUpdateExprFound = X1Id == X2Id; 6014 if (IsUpdateExprFound) { 6015 V = FirstBinOp->getLHS(); 6016 X = SecondBinOp->getLHS(); 6017 E = SecondBinOp->getRHS(); 6018 UE = nullptr; 6019 IsXLHSInRHSPart = false; 6020 IsPostfixUpdate = true; 6021 } else { 6022 ErrorFound = NotASpecificExpression; 6023 ErrorLoc = FirstBinOp->getExprLoc(); 6024 ErrorRange = FirstBinOp->getSourceRange(); 6025 NoteLoc = SecondBinOp->getLHS()->getExprLoc(); 6026 NoteRange = SecondBinOp->getRHS()->getSourceRange(); 6027 } 6028 } 6029 } 6030 } 6031 } 6032 } else { 6033 NoteLoc = ErrorLoc = Body->getLocStart(); 6034 NoteRange = ErrorRange = 6035 SourceRange(Body->getLocStart(), Body->getLocStart()); 6036 ErrorFound = NotTwoSubstatements; 6037 } 6038 } else { 6039 NoteLoc = ErrorLoc = Body->getLocStart(); 6040 NoteRange = ErrorRange = 6041 SourceRange(Body->getLocStart(), Body->getLocStart()); 6042 ErrorFound = NotACompoundStatement; 6043 } 6044 if (ErrorFound != NoError) { 6045 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement) 6046 << ErrorRange; 6047 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange; 6048 return StmtError(); 6049 } else if (CurContext->isDependentContext()) { 6050 UE = V = E = X = nullptr; 6051 } 6052 } 6053 } 6054 6055 getCurFunction()->setHasBranchProtectedScope(); 6056 6057 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt, 6058 X, V, E, UE, IsXLHSInRHSPart, 6059 IsPostfixUpdate); 6060 } 6061 6062 StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses, 6063 Stmt *AStmt, 6064 SourceLocation StartLoc, 6065 SourceLocation EndLoc) { 6066 if (!AStmt) 6067 return StmtError(); 6068 6069 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6070 // 1.2.2 OpenMP Language Terminology 6071 // Structured block - An executable statement with a single entry at the 6072 // top and a single exit at the bottom. 6073 // The point of exit cannot be a branch out of the structured block. 6074 // longjmp() and throw() must not violate the entry/exit criteria. 6075 CS->getCapturedDecl()->setNothrow(); 6076 6077 // OpenMP [2.16, Nesting of Regions] 6078 // If specified, a teams construct must be contained within a target 6079 // construct. That target construct must contain no statements or directives 6080 // outside of the teams construct. 6081 if (DSAStack->hasInnerTeamsRegion()) { 6082 auto S = AStmt->IgnoreContainers(/*IgnoreCaptured*/ true); 6083 bool OMPTeamsFound = true; 6084 if (auto *CS = dyn_cast<CompoundStmt>(S)) { 6085 auto I = CS->body_begin(); 6086 while (I != CS->body_end()) { 6087 auto *OED = dyn_cast<OMPExecutableDirective>(*I); 6088 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) { 6089 OMPTeamsFound = false; 6090 break; 6091 } 6092 ++I; 6093 } 6094 assert(I != CS->body_end() && "Not found statement"); 6095 S = *I; 6096 } else { 6097 auto *OED = dyn_cast<OMPExecutableDirective>(S); 6098 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind()); 6099 } 6100 if (!OMPTeamsFound) { 6101 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams); 6102 Diag(DSAStack->getInnerTeamsRegionLoc(), 6103 diag::note_omp_nested_teams_construct_here); 6104 Diag(S->getLocStart(), diag::note_omp_nested_statement_here) 6105 << isa<OMPExecutableDirective>(S); 6106 return StmtError(); 6107 } 6108 } 6109 6110 getCurFunction()->setHasBranchProtectedScope(); 6111 6112 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6113 } 6114 6115 StmtResult 6116 Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses, 6117 Stmt *AStmt, SourceLocation StartLoc, 6118 SourceLocation EndLoc) { 6119 if (!AStmt) 6120 return StmtError(); 6121 6122 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6123 // 1.2.2 OpenMP Language Terminology 6124 // Structured block - An executable statement with a single entry at the 6125 // top and a single exit at the bottom. 6126 // The point of exit cannot be a branch out of the structured block. 6127 // longjmp() and throw() must not violate the entry/exit criteria. 6128 CS->getCapturedDecl()->setNothrow(); 6129 6130 getCurFunction()->setHasBranchProtectedScope(); 6131 6132 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, 6133 AStmt); 6134 } 6135 6136 StmtResult Sema::ActOnOpenMPTargetParallelForDirective( 6137 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6138 SourceLocation EndLoc, 6139 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6140 if (!AStmt) 6141 return StmtError(); 6142 6143 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6144 // 1.2.2 OpenMP Language Terminology 6145 // Structured block - An executable statement with a single entry at the 6146 // top and a single exit at the bottom. 6147 // The point of exit cannot be a branch out of the structured block. 6148 // longjmp() and throw() must not violate the entry/exit criteria. 6149 CS->getCapturedDecl()->setNothrow(); 6150 6151 OMPLoopDirective::HelperExprs B; 6152 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6153 // define the nested loops number. 6154 unsigned NestedLoopCount = 6155 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses), 6156 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6157 VarsWithImplicitDSA, B); 6158 if (NestedLoopCount == 0) 6159 return StmtError(); 6160 6161 assert((CurContext->isDependentContext() || B.builtAll()) && 6162 "omp target parallel for loop exprs were not built"); 6163 6164 if (!CurContext->isDependentContext()) { 6165 // Finalize the clauses that need pre-built expressions for CodeGen. 6166 for (auto C : Clauses) { 6167 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6168 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6169 B.NumIterations, *this, CurScope, 6170 DSAStack)) 6171 return StmtError(); 6172 } 6173 } 6174 6175 getCurFunction()->setHasBranchProtectedScope(); 6176 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc, 6177 NestedLoopCount, Clauses, AStmt, 6178 B, DSAStack->isCancelRegion()); 6179 } 6180 6181 /// Check for existence of a map clause in the list of clauses. 6182 static bool hasClauses(ArrayRef<OMPClause *> Clauses, 6183 const OpenMPClauseKind K) { 6184 return llvm::any_of( 6185 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; }); 6186 } 6187 6188 template <typename... Params> 6189 static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K, 6190 const Params... ClauseTypes) { 6191 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...); 6192 } 6193 6194 StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses, 6195 Stmt *AStmt, 6196 SourceLocation StartLoc, 6197 SourceLocation EndLoc) { 6198 if (!AStmt) 6199 return StmtError(); 6200 6201 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6202 6203 // OpenMP [2.10.1, Restrictions, p. 97] 6204 // At least one map clause must appear on the directive. 6205 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) { 6206 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 6207 << "'map' or 'use_device_ptr'" 6208 << getOpenMPDirectiveName(OMPD_target_data); 6209 return StmtError(); 6210 } 6211 6212 getCurFunction()->setHasBranchProtectedScope(); 6213 6214 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses, 6215 AStmt); 6216 } 6217 6218 StmtResult 6219 Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses, 6220 SourceLocation StartLoc, 6221 SourceLocation EndLoc) { 6222 // OpenMP [2.10.2, Restrictions, p. 99] 6223 // At least one map clause must appear on the directive. 6224 if (!hasClauses(Clauses, OMPC_map)) { 6225 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 6226 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data); 6227 return StmtError(); 6228 } 6229 6230 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, 6231 Clauses); 6232 } 6233 6234 StmtResult 6235 Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses, 6236 SourceLocation StartLoc, 6237 SourceLocation EndLoc) { 6238 // OpenMP [2.10.3, Restrictions, p. 102] 6239 // At least one map clause must appear on the directive. 6240 if (!hasClauses(Clauses, OMPC_map)) { 6241 Diag(StartLoc, diag::err_omp_no_clause_for_directive) 6242 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data); 6243 return StmtError(); 6244 } 6245 6246 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses); 6247 } 6248 6249 StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses, 6250 SourceLocation StartLoc, 6251 SourceLocation EndLoc) { 6252 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) { 6253 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required); 6254 return StmtError(); 6255 } 6256 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses); 6257 } 6258 6259 StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses, 6260 Stmt *AStmt, SourceLocation StartLoc, 6261 SourceLocation EndLoc) { 6262 if (!AStmt) 6263 return StmtError(); 6264 6265 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6266 // 1.2.2 OpenMP Language Terminology 6267 // Structured block - An executable statement with a single entry at the 6268 // top and a single exit at the bottom. 6269 // The point of exit cannot be a branch out of the structured block. 6270 // longjmp() and throw() must not violate the entry/exit criteria. 6271 CS->getCapturedDecl()->setNothrow(); 6272 6273 getCurFunction()->setHasBranchProtectedScope(); 6274 6275 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt); 6276 } 6277 6278 StmtResult 6279 Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc, 6280 SourceLocation EndLoc, 6281 OpenMPDirectiveKind CancelRegion) { 6282 if (DSAStack->isParentNowaitRegion()) { 6283 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0; 6284 return StmtError(); 6285 } 6286 if (DSAStack->isParentOrderedRegion()) { 6287 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0; 6288 return StmtError(); 6289 } 6290 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc, 6291 CancelRegion); 6292 } 6293 6294 StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses, 6295 SourceLocation StartLoc, 6296 SourceLocation EndLoc, 6297 OpenMPDirectiveKind CancelRegion) { 6298 if (DSAStack->isParentNowaitRegion()) { 6299 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1; 6300 return StmtError(); 6301 } 6302 if (DSAStack->isParentOrderedRegion()) { 6303 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1; 6304 return StmtError(); 6305 } 6306 DSAStack->setParentCancelRegion(/*Cancel=*/true); 6307 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses, 6308 CancelRegion); 6309 } 6310 6311 static bool checkGrainsizeNumTasksClauses(Sema &S, 6312 ArrayRef<OMPClause *> Clauses) { 6313 OMPClause *PrevClause = nullptr; 6314 bool ErrorFound = false; 6315 for (auto *C : Clauses) { 6316 if (C->getClauseKind() == OMPC_grainsize || 6317 C->getClauseKind() == OMPC_num_tasks) { 6318 if (!PrevClause) 6319 PrevClause = C; 6320 else if (PrevClause->getClauseKind() != C->getClauseKind()) { 6321 S.Diag(C->getLocStart(), 6322 diag::err_omp_grainsize_num_tasks_mutually_exclusive) 6323 << getOpenMPClauseName(C->getClauseKind()) 6324 << getOpenMPClauseName(PrevClause->getClauseKind()); 6325 S.Diag(PrevClause->getLocStart(), 6326 diag::note_omp_previous_grainsize_num_tasks) 6327 << getOpenMPClauseName(PrevClause->getClauseKind()); 6328 ErrorFound = true; 6329 } 6330 } 6331 } 6332 return ErrorFound; 6333 } 6334 6335 static bool checkReductionClauseWithNogroup(Sema &S, 6336 ArrayRef<OMPClause *> Clauses) { 6337 OMPClause *ReductionClause = nullptr; 6338 OMPClause *NogroupClause = nullptr; 6339 for (auto *C : Clauses) { 6340 if (C->getClauseKind() == OMPC_reduction) { 6341 ReductionClause = C; 6342 if (NogroupClause) 6343 break; 6344 continue; 6345 } 6346 if (C->getClauseKind() == OMPC_nogroup) { 6347 NogroupClause = C; 6348 if (ReductionClause) 6349 break; 6350 continue; 6351 } 6352 } 6353 if (ReductionClause && NogroupClause) { 6354 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup) 6355 << SourceRange(NogroupClause->getLocStart(), 6356 NogroupClause->getLocEnd()); 6357 return true; 6358 } 6359 return false; 6360 } 6361 6362 StmtResult Sema::ActOnOpenMPTaskLoopDirective( 6363 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6364 SourceLocation EndLoc, 6365 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6366 if (!AStmt) 6367 return StmtError(); 6368 6369 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6370 OMPLoopDirective::HelperExprs B; 6371 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6372 // define the nested loops number. 6373 unsigned NestedLoopCount = 6374 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses), 6375 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 6376 VarsWithImplicitDSA, B); 6377 if (NestedLoopCount == 0) 6378 return StmtError(); 6379 6380 assert((CurContext->isDependentContext() || B.builtAll()) && 6381 "omp for loop exprs were not built"); 6382 6383 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6384 // The grainsize clause and num_tasks clause are mutually exclusive and may 6385 // not appear on the same taskloop directive. 6386 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 6387 return StmtError(); 6388 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6389 // If a reduction clause is present on the taskloop directive, the nogroup 6390 // clause must not be specified. 6391 if (checkReductionClauseWithNogroup(*this, Clauses)) 6392 return StmtError(); 6393 6394 getCurFunction()->setHasBranchProtectedScope(); 6395 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc, 6396 NestedLoopCount, Clauses, AStmt, B); 6397 } 6398 6399 StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective( 6400 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6401 SourceLocation EndLoc, 6402 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6403 if (!AStmt) 6404 return StmtError(); 6405 6406 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6407 OMPLoopDirective::HelperExprs B; 6408 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6409 // define the nested loops number. 6410 unsigned NestedLoopCount = 6411 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses), 6412 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack, 6413 VarsWithImplicitDSA, B); 6414 if (NestedLoopCount == 0) 6415 return StmtError(); 6416 6417 assert((CurContext->isDependentContext() || B.builtAll()) && 6418 "omp for loop exprs were not built"); 6419 6420 if (!CurContext->isDependentContext()) { 6421 // Finalize the clauses that need pre-built expressions for CodeGen. 6422 for (auto C : Clauses) { 6423 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6424 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6425 B.NumIterations, *this, CurScope, 6426 DSAStack)) 6427 return StmtError(); 6428 } 6429 } 6430 6431 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6432 // The grainsize clause and num_tasks clause are mutually exclusive and may 6433 // not appear on the same taskloop directive. 6434 if (checkGrainsizeNumTasksClauses(*this, Clauses)) 6435 return StmtError(); 6436 // OpenMP, [2.9.2 taskloop Construct, Restrictions] 6437 // If a reduction clause is present on the taskloop directive, the nogroup 6438 // clause must not be specified. 6439 if (checkReductionClauseWithNogroup(*this, Clauses)) 6440 return StmtError(); 6441 6442 getCurFunction()->setHasBranchProtectedScope(); 6443 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc, 6444 NestedLoopCount, Clauses, AStmt, B); 6445 } 6446 6447 StmtResult Sema::ActOnOpenMPDistributeDirective( 6448 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6449 SourceLocation EndLoc, 6450 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6451 if (!AStmt) 6452 return StmtError(); 6453 6454 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected"); 6455 OMPLoopDirective::HelperExprs B; 6456 // In presence of clause 'collapse' with number of loops, it will 6457 // define the nested loops number. 6458 unsigned NestedLoopCount = 6459 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses), 6460 nullptr /*ordered not a clause on distribute*/, AStmt, 6461 *this, *DSAStack, VarsWithImplicitDSA, B); 6462 if (NestedLoopCount == 0) 6463 return StmtError(); 6464 6465 assert((CurContext->isDependentContext() || B.builtAll()) && 6466 "omp for loop exprs were not built"); 6467 6468 getCurFunction()->setHasBranchProtectedScope(); 6469 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc, 6470 NestedLoopCount, Clauses, AStmt, B); 6471 } 6472 6473 StmtResult Sema::ActOnOpenMPDistributeParallelForDirective( 6474 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6475 SourceLocation EndLoc, 6476 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6477 if (!AStmt) 6478 return StmtError(); 6479 6480 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6481 // 1.2.2 OpenMP Language Terminology 6482 // Structured block - An executable statement with a single entry at the 6483 // top and a single exit at the bottom. 6484 // The point of exit cannot be a branch out of the structured block. 6485 // longjmp() and throw() must not violate the entry/exit criteria. 6486 CS->getCapturedDecl()->setNothrow(); 6487 6488 OMPLoopDirective::HelperExprs B; 6489 // In presence of clause 'collapse' with number of loops, it will 6490 // define the nested loops number. 6491 unsigned NestedLoopCount = CheckOpenMPLoop( 6492 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses), 6493 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6494 VarsWithImplicitDSA, B); 6495 if (NestedLoopCount == 0) 6496 return StmtError(); 6497 6498 assert((CurContext->isDependentContext() || B.builtAll()) && 6499 "omp for loop exprs were not built"); 6500 6501 getCurFunction()->setHasBranchProtectedScope(); 6502 return OMPDistributeParallelForDirective::Create( 6503 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6504 } 6505 6506 StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective( 6507 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6508 SourceLocation EndLoc, 6509 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6510 if (!AStmt) 6511 return StmtError(); 6512 6513 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6514 // 1.2.2 OpenMP Language Terminology 6515 // Structured block - An executable statement with a single entry at the 6516 // top and a single exit at the bottom. 6517 // The point of exit cannot be a branch out of the structured block. 6518 // longjmp() and throw() must not violate the entry/exit criteria. 6519 CS->getCapturedDecl()->setNothrow(); 6520 6521 OMPLoopDirective::HelperExprs B; 6522 // In presence of clause 'collapse' with number of loops, it will 6523 // define the nested loops number. 6524 unsigned NestedLoopCount = CheckOpenMPLoop( 6525 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 6526 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6527 VarsWithImplicitDSA, B); 6528 if (NestedLoopCount == 0) 6529 return StmtError(); 6530 6531 assert((CurContext->isDependentContext() || B.builtAll()) && 6532 "omp for loop exprs were not built"); 6533 6534 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6535 return StmtError(); 6536 6537 getCurFunction()->setHasBranchProtectedScope(); 6538 return OMPDistributeParallelForSimdDirective::Create( 6539 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6540 } 6541 6542 StmtResult Sema::ActOnOpenMPDistributeSimdDirective( 6543 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6544 SourceLocation EndLoc, 6545 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6546 if (!AStmt) 6547 return StmtError(); 6548 6549 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6550 // 1.2.2 OpenMP Language Terminology 6551 // Structured block - An executable statement with a single entry at the 6552 // top and a single exit at the bottom. 6553 // The point of exit cannot be a branch out of the structured block. 6554 // longjmp() and throw() must not violate the entry/exit criteria. 6555 CS->getCapturedDecl()->setNothrow(); 6556 6557 OMPLoopDirective::HelperExprs B; 6558 // In presence of clause 'collapse' with number of loops, it will 6559 // define the nested loops number. 6560 unsigned NestedLoopCount = 6561 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses), 6562 nullptr /*ordered not a clause on distribute*/, AStmt, 6563 *this, *DSAStack, VarsWithImplicitDSA, B); 6564 if (NestedLoopCount == 0) 6565 return StmtError(); 6566 6567 assert((CurContext->isDependentContext() || B.builtAll()) && 6568 "omp for loop exprs were not built"); 6569 6570 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6571 return StmtError(); 6572 6573 getCurFunction()->setHasBranchProtectedScope(); 6574 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc, 6575 NestedLoopCount, Clauses, AStmt, B); 6576 } 6577 6578 StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective( 6579 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6580 SourceLocation EndLoc, 6581 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6582 if (!AStmt) 6583 return StmtError(); 6584 6585 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6586 // 1.2.2 OpenMP Language Terminology 6587 // Structured block - An executable statement with a single entry at the 6588 // top and a single exit at the bottom. 6589 // The point of exit cannot be a branch out of the structured block. 6590 // longjmp() and throw() must not violate the entry/exit criteria. 6591 CS->getCapturedDecl()->setNothrow(); 6592 6593 OMPLoopDirective::HelperExprs B; 6594 // In presence of clause 'collapse' or 'ordered' with number of loops, it will 6595 // define the nested loops number. 6596 unsigned NestedLoopCount = CheckOpenMPLoop( 6597 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses), 6598 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6599 VarsWithImplicitDSA, B); 6600 if (NestedLoopCount == 0) 6601 return StmtError(); 6602 6603 assert((CurContext->isDependentContext() || B.builtAll()) && 6604 "omp target parallel for simd loop exprs were not built"); 6605 6606 if (!CurContext->isDependentContext()) { 6607 // Finalize the clauses that need pre-built expressions for CodeGen. 6608 for (auto C : Clauses) { 6609 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6610 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6611 B.NumIterations, *this, CurScope, 6612 DSAStack)) 6613 return StmtError(); 6614 } 6615 } 6616 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6617 return StmtError(); 6618 6619 getCurFunction()->setHasBranchProtectedScope(); 6620 return OMPTargetParallelForSimdDirective::Create( 6621 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6622 } 6623 6624 StmtResult Sema::ActOnOpenMPTargetSimdDirective( 6625 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6626 SourceLocation EndLoc, 6627 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6628 if (!AStmt) 6629 return StmtError(); 6630 6631 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6632 // 1.2.2 OpenMP Language Terminology 6633 // Structured block - An executable statement with a single entry at the 6634 // top and a single exit at the bottom. 6635 // The point of exit cannot be a branch out of the structured block. 6636 // longjmp() and throw() must not violate the entry/exit criteria. 6637 CS->getCapturedDecl()->setNothrow(); 6638 6639 OMPLoopDirective::HelperExprs B; 6640 // In presence of clause 'collapse' with number of loops, it will define the 6641 // nested loops number. 6642 unsigned NestedLoopCount = 6643 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses), 6644 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack, 6645 VarsWithImplicitDSA, B); 6646 if (NestedLoopCount == 0) 6647 return StmtError(); 6648 6649 assert((CurContext->isDependentContext() || B.builtAll()) && 6650 "omp target simd loop exprs were not built"); 6651 6652 if (!CurContext->isDependentContext()) { 6653 // Finalize the clauses that need pre-built expressions for CodeGen. 6654 for (auto C : Clauses) { 6655 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6656 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6657 B.NumIterations, *this, CurScope, 6658 DSAStack)) 6659 return StmtError(); 6660 } 6661 } 6662 6663 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6664 return StmtError(); 6665 6666 getCurFunction()->setHasBranchProtectedScope(); 6667 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc, 6668 NestedLoopCount, Clauses, AStmt, B); 6669 } 6670 6671 StmtResult Sema::ActOnOpenMPTeamsDistributeDirective( 6672 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6673 SourceLocation EndLoc, 6674 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6675 if (!AStmt) 6676 return StmtError(); 6677 6678 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6679 // 1.2.2 OpenMP Language Terminology 6680 // Structured block - An executable statement with a single entry at the 6681 // top and a single exit at the bottom. 6682 // The point of exit cannot be a branch out of the structured block. 6683 // longjmp() and throw() must not violate the entry/exit criteria. 6684 CS->getCapturedDecl()->setNothrow(); 6685 6686 OMPLoopDirective::HelperExprs B; 6687 // In presence of clause 'collapse' with number of loops, it will 6688 // define the nested loops number. 6689 unsigned NestedLoopCount = 6690 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses), 6691 nullptr /*ordered not a clause on distribute*/, AStmt, 6692 *this, *DSAStack, VarsWithImplicitDSA, B); 6693 if (NestedLoopCount == 0) 6694 return StmtError(); 6695 6696 assert((CurContext->isDependentContext() || B.builtAll()) && 6697 "omp teams distribute loop exprs were not built"); 6698 6699 getCurFunction()->setHasBranchProtectedScope(); 6700 return OMPTeamsDistributeDirective::Create( 6701 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6702 } 6703 6704 StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective( 6705 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6706 SourceLocation EndLoc, 6707 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6708 if (!AStmt) 6709 return StmtError(); 6710 6711 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6712 // 1.2.2 OpenMP Language Terminology 6713 // Structured block - An executable statement with a single entry at the 6714 // top and a single exit at the bottom. 6715 // The point of exit cannot be a branch out of the structured block. 6716 // longjmp() and throw() must not violate the entry/exit criteria. 6717 CS->getCapturedDecl()->setNothrow(); 6718 6719 OMPLoopDirective::HelperExprs B; 6720 // In presence of clause 'collapse' with number of loops, it will 6721 // define the nested loops number. 6722 unsigned NestedLoopCount = CheckOpenMPLoop( 6723 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses), 6724 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6725 VarsWithImplicitDSA, B); 6726 6727 if (NestedLoopCount == 0) 6728 return StmtError(); 6729 6730 assert((CurContext->isDependentContext() || B.builtAll()) && 6731 "omp teams distribute simd loop exprs were not built"); 6732 6733 if (!CurContext->isDependentContext()) { 6734 // Finalize the clauses that need pre-built expressions for CodeGen. 6735 for (auto C : Clauses) { 6736 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6737 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6738 B.NumIterations, *this, CurScope, 6739 DSAStack)) 6740 return StmtError(); 6741 } 6742 } 6743 6744 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6745 return StmtError(); 6746 6747 getCurFunction()->setHasBranchProtectedScope(); 6748 return OMPTeamsDistributeSimdDirective::Create( 6749 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6750 } 6751 6752 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective( 6753 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6754 SourceLocation EndLoc, 6755 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6756 if (!AStmt) 6757 return StmtError(); 6758 6759 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6760 // 1.2.2 OpenMP Language Terminology 6761 // Structured block - An executable statement with a single entry at the 6762 // top and a single exit at the bottom. 6763 // The point of exit cannot be a branch out of the structured block. 6764 // longjmp() and throw() must not violate the entry/exit criteria. 6765 CS->getCapturedDecl()->setNothrow(); 6766 6767 OMPLoopDirective::HelperExprs B; 6768 // In presence of clause 'collapse' with number of loops, it will 6769 // define the nested loops number. 6770 auto NestedLoopCount = CheckOpenMPLoop( 6771 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses), 6772 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6773 VarsWithImplicitDSA, B); 6774 6775 if (NestedLoopCount == 0) 6776 return StmtError(); 6777 6778 assert((CurContext->isDependentContext() || B.builtAll()) && 6779 "omp for loop exprs were not built"); 6780 6781 if (!CurContext->isDependentContext()) { 6782 // Finalize the clauses that need pre-built expressions for CodeGen. 6783 for (auto C : Clauses) { 6784 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6785 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6786 B.NumIterations, *this, CurScope, 6787 DSAStack)) 6788 return StmtError(); 6789 } 6790 } 6791 6792 if (checkSimdlenSafelenSpecified(*this, Clauses)) 6793 return StmtError(); 6794 6795 getCurFunction()->setHasBranchProtectedScope(); 6796 return OMPTeamsDistributeParallelForSimdDirective::Create( 6797 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6798 } 6799 6800 StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective( 6801 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6802 SourceLocation EndLoc, 6803 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6804 if (!AStmt) 6805 return StmtError(); 6806 6807 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6808 // 1.2.2 OpenMP Language Terminology 6809 // Structured block - An executable statement with a single entry at the 6810 // top and a single exit at the bottom. 6811 // The point of exit cannot be a branch out of the structured block. 6812 // longjmp() and throw() must not violate the entry/exit criteria. 6813 CS->getCapturedDecl()->setNothrow(); 6814 6815 OMPLoopDirective::HelperExprs B; 6816 // In presence of clause 'collapse' with number of loops, it will 6817 // define the nested loops number. 6818 unsigned NestedLoopCount = CheckOpenMPLoop( 6819 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses), 6820 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6821 VarsWithImplicitDSA, B); 6822 6823 if (NestedLoopCount == 0) 6824 return StmtError(); 6825 6826 assert((CurContext->isDependentContext() || B.builtAll()) && 6827 "omp for loop exprs were not built"); 6828 6829 if (!CurContext->isDependentContext()) { 6830 // Finalize the clauses that need pre-built expressions for CodeGen. 6831 for (auto C : Clauses) { 6832 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6833 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6834 B.NumIterations, *this, CurScope, 6835 DSAStack)) 6836 return StmtError(); 6837 } 6838 } 6839 6840 getCurFunction()->setHasBranchProtectedScope(); 6841 return OMPTeamsDistributeParallelForDirective::Create( 6842 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6843 } 6844 6845 StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses, 6846 Stmt *AStmt, 6847 SourceLocation StartLoc, 6848 SourceLocation EndLoc) { 6849 if (!AStmt) 6850 return StmtError(); 6851 6852 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6853 // 1.2.2 OpenMP Language Terminology 6854 // Structured block - An executable statement with a single entry at the 6855 // top and a single exit at the bottom. 6856 // The point of exit cannot be a branch out of the structured block. 6857 // longjmp() and throw() must not violate the entry/exit criteria. 6858 CS->getCapturedDecl()->setNothrow(); 6859 6860 getCurFunction()->setHasBranchProtectedScope(); 6861 6862 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, 6863 AStmt); 6864 } 6865 6866 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective( 6867 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6868 SourceLocation EndLoc, 6869 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6870 if (!AStmt) 6871 return StmtError(); 6872 6873 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6874 // 1.2.2 OpenMP Language Terminology 6875 // Structured block - An executable statement with a single entry at the 6876 // top and a single exit at the bottom. 6877 // The point of exit cannot be a branch out of the structured block. 6878 // longjmp() and throw() must not violate the entry/exit criteria. 6879 CS->getCapturedDecl()->setNothrow(); 6880 6881 OMPLoopDirective::HelperExprs B; 6882 // In presence of clause 'collapse' with number of loops, it will 6883 // define the nested loops number. 6884 auto NestedLoopCount = CheckOpenMPLoop( 6885 OMPD_target_teams_distribute, 6886 getCollapseNumberExpr(Clauses), 6887 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6888 VarsWithImplicitDSA, B); 6889 if (NestedLoopCount == 0) 6890 return StmtError(); 6891 6892 assert((CurContext->isDependentContext() || B.builtAll()) && 6893 "omp target teams distribute loop exprs were not built"); 6894 6895 getCurFunction()->setHasBranchProtectedScope(); 6896 return OMPTargetTeamsDistributeDirective::Create( 6897 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6898 } 6899 6900 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective( 6901 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6902 SourceLocation EndLoc, 6903 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6904 if (!AStmt) 6905 return StmtError(); 6906 6907 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6908 // 1.2.2 OpenMP Language Terminology 6909 // Structured block - An executable statement with a single entry at the 6910 // top and a single exit at the bottom. 6911 // The point of exit cannot be a branch out of the structured block. 6912 // longjmp() and throw() must not violate the entry/exit criteria. 6913 CS->getCapturedDecl()->setNothrow(); 6914 6915 OMPLoopDirective::HelperExprs B; 6916 // In presence of clause 'collapse' with number of loops, it will 6917 // define the nested loops number. 6918 auto NestedLoopCount = CheckOpenMPLoop( 6919 OMPD_target_teams_distribute_parallel_for, 6920 getCollapseNumberExpr(Clauses), 6921 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6922 VarsWithImplicitDSA, B); 6923 if (NestedLoopCount == 0) 6924 return StmtError(); 6925 6926 assert((CurContext->isDependentContext() || B.builtAll()) && 6927 "omp target teams distribute parallel for loop exprs were not built"); 6928 6929 if (!CurContext->isDependentContext()) { 6930 // Finalize the clauses that need pre-built expressions for CodeGen. 6931 for (auto C : Clauses) { 6932 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6933 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6934 B.NumIterations, *this, CurScope, 6935 DSAStack)) 6936 return StmtError(); 6937 } 6938 } 6939 6940 getCurFunction()->setHasBranchProtectedScope(); 6941 return OMPTargetTeamsDistributeParallelForDirective::Create( 6942 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6943 } 6944 6945 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective( 6946 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6947 SourceLocation EndLoc, 6948 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6949 if (!AStmt) 6950 return StmtError(); 6951 6952 CapturedStmt *CS = cast<CapturedStmt>(AStmt); 6953 // 1.2.2 OpenMP Language Terminology 6954 // Structured block - An executable statement with a single entry at the 6955 // top and a single exit at the bottom. 6956 // The point of exit cannot be a branch out of the structured block. 6957 // longjmp() and throw() must not violate the entry/exit criteria. 6958 CS->getCapturedDecl()->setNothrow(); 6959 6960 OMPLoopDirective::HelperExprs B; 6961 // In presence of clause 'collapse' with number of loops, it will 6962 // define the nested loops number. 6963 auto NestedLoopCount = CheckOpenMPLoop( 6964 OMPD_target_teams_distribute_parallel_for_simd, 6965 getCollapseNumberExpr(Clauses), 6966 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 6967 VarsWithImplicitDSA, B); 6968 if (NestedLoopCount == 0) 6969 return StmtError(); 6970 6971 assert((CurContext->isDependentContext() || B.builtAll()) && 6972 "omp target teams distribute parallel for simd loop exprs were not " 6973 "built"); 6974 6975 if (!CurContext->isDependentContext()) { 6976 // Finalize the clauses that need pre-built expressions for CodeGen. 6977 for (auto C : Clauses) { 6978 if (auto *LC = dyn_cast<OMPLinearClause>(C)) 6979 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef), 6980 B.NumIterations, *this, CurScope, 6981 DSAStack)) 6982 return StmtError(); 6983 } 6984 } 6985 6986 getCurFunction()->setHasBranchProtectedScope(); 6987 return OMPTargetTeamsDistributeParallelForSimdDirective::Create( 6988 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 6989 } 6990 6991 StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective( 6992 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc, 6993 SourceLocation EndLoc, 6994 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) { 6995 if (!AStmt) 6996 return StmtError(); 6997 6998 auto *CS = cast<CapturedStmt>(AStmt); 6999 // 1.2.2 OpenMP Language Terminology 7000 // Structured block - An executable statement with a single entry at the 7001 // top and a single exit at the bottom. 7002 // The point of exit cannot be a branch out of the structured block. 7003 // longjmp() and throw() must not violate the entry/exit criteria. 7004 CS->getCapturedDecl()->setNothrow(); 7005 7006 OMPLoopDirective::HelperExprs B; 7007 // In presence of clause 'collapse' with number of loops, it will 7008 // define the nested loops number. 7009 auto NestedLoopCount = CheckOpenMPLoop( 7010 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses), 7011 nullptr /*ordered not a clause on distribute*/, AStmt, *this, *DSAStack, 7012 VarsWithImplicitDSA, B); 7013 if (NestedLoopCount == 0) 7014 return StmtError(); 7015 7016 assert((CurContext->isDependentContext() || B.builtAll()) && 7017 "omp target teams distribute simd loop exprs were not built"); 7018 7019 getCurFunction()->setHasBranchProtectedScope(); 7020 return OMPTargetTeamsDistributeSimdDirective::Create( 7021 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B); 7022 } 7023 7024 OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr, 7025 SourceLocation StartLoc, 7026 SourceLocation LParenLoc, 7027 SourceLocation EndLoc) { 7028 OMPClause *Res = nullptr; 7029 switch (Kind) { 7030 case OMPC_final: 7031 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc); 7032 break; 7033 case OMPC_num_threads: 7034 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc); 7035 break; 7036 case OMPC_safelen: 7037 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc); 7038 break; 7039 case OMPC_simdlen: 7040 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc); 7041 break; 7042 case OMPC_collapse: 7043 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc); 7044 break; 7045 case OMPC_ordered: 7046 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr); 7047 break; 7048 case OMPC_device: 7049 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc); 7050 break; 7051 case OMPC_num_teams: 7052 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc); 7053 break; 7054 case OMPC_thread_limit: 7055 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc); 7056 break; 7057 case OMPC_priority: 7058 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc); 7059 break; 7060 case OMPC_grainsize: 7061 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc); 7062 break; 7063 case OMPC_num_tasks: 7064 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc); 7065 break; 7066 case OMPC_hint: 7067 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc); 7068 break; 7069 case OMPC_if: 7070 case OMPC_default: 7071 case OMPC_proc_bind: 7072 case OMPC_schedule: 7073 case OMPC_private: 7074 case OMPC_firstprivate: 7075 case OMPC_lastprivate: 7076 case OMPC_shared: 7077 case OMPC_reduction: 7078 case OMPC_task_reduction: 7079 case OMPC_in_reduction: 7080 case OMPC_linear: 7081 case OMPC_aligned: 7082 case OMPC_copyin: 7083 case OMPC_copyprivate: 7084 case OMPC_nowait: 7085 case OMPC_untied: 7086 case OMPC_mergeable: 7087 case OMPC_threadprivate: 7088 case OMPC_flush: 7089 case OMPC_read: 7090 case OMPC_write: 7091 case OMPC_update: 7092 case OMPC_capture: 7093 case OMPC_seq_cst: 7094 case OMPC_depend: 7095 case OMPC_threads: 7096 case OMPC_simd: 7097 case OMPC_map: 7098 case OMPC_nogroup: 7099 case OMPC_dist_schedule: 7100 case OMPC_defaultmap: 7101 case OMPC_unknown: 7102 case OMPC_uniform: 7103 case OMPC_to: 7104 case OMPC_from: 7105 case OMPC_use_device_ptr: 7106 case OMPC_is_device_ptr: 7107 llvm_unreachable("Clause is not allowed."); 7108 } 7109 return Res; 7110 } 7111 7112 // An OpenMP directive such as 'target parallel' has two captured regions: 7113 // for the 'target' and 'parallel' respectively. This function returns 7114 // the region in which to capture expressions associated with a clause. 7115 // A return value of OMPD_unknown signifies that the expression should not 7116 // be captured. 7117 static OpenMPDirectiveKind getOpenMPCaptureRegionForClause( 7118 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, 7119 OpenMPDirectiveKind NameModifier = OMPD_unknown) { 7120 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 7121 7122 switch (CKind) { 7123 case OMPC_if: 7124 switch (DKind) { 7125 case OMPD_target_parallel: 7126 // If this clause applies to the nested 'parallel' region, capture within 7127 // the 'target' region, otherwise do not capture. 7128 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel) 7129 CaptureRegion = OMPD_target; 7130 break; 7131 case OMPD_cancel: 7132 case OMPD_parallel: 7133 case OMPD_parallel_sections: 7134 case OMPD_parallel_for: 7135 case OMPD_parallel_for_simd: 7136 case OMPD_target: 7137 case OMPD_target_simd: 7138 case OMPD_target_parallel_for: 7139 case OMPD_target_parallel_for_simd: 7140 case OMPD_target_teams: 7141 case OMPD_target_teams_distribute: 7142 case OMPD_target_teams_distribute_simd: 7143 case OMPD_target_teams_distribute_parallel_for: 7144 case OMPD_target_teams_distribute_parallel_for_simd: 7145 case OMPD_teams_distribute_parallel_for: 7146 case OMPD_teams_distribute_parallel_for_simd: 7147 case OMPD_distribute_parallel_for: 7148 case OMPD_distribute_parallel_for_simd: 7149 case OMPD_task: 7150 case OMPD_taskloop: 7151 case OMPD_taskloop_simd: 7152 case OMPD_target_data: 7153 case OMPD_target_enter_data: 7154 case OMPD_target_exit_data: 7155 case OMPD_target_update: 7156 // Do not capture if-clause expressions. 7157 break; 7158 case OMPD_threadprivate: 7159 case OMPD_taskyield: 7160 case OMPD_barrier: 7161 case OMPD_taskwait: 7162 case OMPD_cancellation_point: 7163 case OMPD_flush: 7164 case OMPD_declare_reduction: 7165 case OMPD_declare_simd: 7166 case OMPD_declare_target: 7167 case OMPD_end_declare_target: 7168 case OMPD_teams: 7169 case OMPD_simd: 7170 case OMPD_for: 7171 case OMPD_for_simd: 7172 case OMPD_sections: 7173 case OMPD_section: 7174 case OMPD_single: 7175 case OMPD_master: 7176 case OMPD_critical: 7177 case OMPD_taskgroup: 7178 case OMPD_distribute: 7179 case OMPD_ordered: 7180 case OMPD_atomic: 7181 case OMPD_distribute_simd: 7182 case OMPD_teams_distribute: 7183 case OMPD_teams_distribute_simd: 7184 llvm_unreachable("Unexpected OpenMP directive with if-clause"); 7185 case OMPD_unknown: 7186 llvm_unreachable("Unknown OpenMP directive"); 7187 } 7188 break; 7189 case OMPC_num_threads: 7190 switch (DKind) { 7191 case OMPD_target_parallel: 7192 CaptureRegion = OMPD_target; 7193 break; 7194 case OMPD_cancel: 7195 case OMPD_parallel: 7196 case OMPD_parallel_sections: 7197 case OMPD_parallel_for: 7198 case OMPD_parallel_for_simd: 7199 case OMPD_target: 7200 case OMPD_target_simd: 7201 case OMPD_target_parallel_for: 7202 case OMPD_target_parallel_for_simd: 7203 case OMPD_target_teams: 7204 case OMPD_target_teams_distribute: 7205 case OMPD_target_teams_distribute_simd: 7206 case OMPD_target_teams_distribute_parallel_for: 7207 case OMPD_target_teams_distribute_parallel_for_simd: 7208 case OMPD_teams_distribute_parallel_for: 7209 case OMPD_teams_distribute_parallel_for_simd: 7210 case OMPD_distribute_parallel_for: 7211 case OMPD_distribute_parallel_for_simd: 7212 case OMPD_task: 7213 case OMPD_taskloop: 7214 case OMPD_taskloop_simd: 7215 case OMPD_target_data: 7216 case OMPD_target_enter_data: 7217 case OMPD_target_exit_data: 7218 case OMPD_target_update: 7219 // Do not capture num_threads-clause expressions. 7220 break; 7221 case OMPD_threadprivate: 7222 case OMPD_taskyield: 7223 case OMPD_barrier: 7224 case OMPD_taskwait: 7225 case OMPD_cancellation_point: 7226 case OMPD_flush: 7227 case OMPD_declare_reduction: 7228 case OMPD_declare_simd: 7229 case OMPD_declare_target: 7230 case OMPD_end_declare_target: 7231 case OMPD_teams: 7232 case OMPD_simd: 7233 case OMPD_for: 7234 case OMPD_for_simd: 7235 case OMPD_sections: 7236 case OMPD_section: 7237 case OMPD_single: 7238 case OMPD_master: 7239 case OMPD_critical: 7240 case OMPD_taskgroup: 7241 case OMPD_distribute: 7242 case OMPD_ordered: 7243 case OMPD_atomic: 7244 case OMPD_distribute_simd: 7245 case OMPD_teams_distribute: 7246 case OMPD_teams_distribute_simd: 7247 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause"); 7248 case OMPD_unknown: 7249 llvm_unreachable("Unknown OpenMP directive"); 7250 } 7251 break; 7252 case OMPC_num_teams: 7253 switch (DKind) { 7254 case OMPD_target_teams: 7255 CaptureRegion = OMPD_target; 7256 break; 7257 case OMPD_cancel: 7258 case OMPD_parallel: 7259 case OMPD_parallel_sections: 7260 case OMPD_parallel_for: 7261 case OMPD_parallel_for_simd: 7262 case OMPD_target: 7263 case OMPD_target_simd: 7264 case OMPD_target_parallel: 7265 case OMPD_target_parallel_for: 7266 case OMPD_target_parallel_for_simd: 7267 case OMPD_target_teams_distribute: 7268 case OMPD_target_teams_distribute_simd: 7269 case OMPD_target_teams_distribute_parallel_for: 7270 case OMPD_target_teams_distribute_parallel_for_simd: 7271 case OMPD_teams_distribute_parallel_for: 7272 case OMPD_teams_distribute_parallel_for_simd: 7273 case OMPD_distribute_parallel_for: 7274 case OMPD_distribute_parallel_for_simd: 7275 case OMPD_task: 7276 case OMPD_taskloop: 7277 case OMPD_taskloop_simd: 7278 case OMPD_target_data: 7279 case OMPD_target_enter_data: 7280 case OMPD_target_exit_data: 7281 case OMPD_target_update: 7282 case OMPD_teams: 7283 case OMPD_teams_distribute: 7284 case OMPD_teams_distribute_simd: 7285 // Do not capture num_teams-clause expressions. 7286 break; 7287 case OMPD_threadprivate: 7288 case OMPD_taskyield: 7289 case OMPD_barrier: 7290 case OMPD_taskwait: 7291 case OMPD_cancellation_point: 7292 case OMPD_flush: 7293 case OMPD_declare_reduction: 7294 case OMPD_declare_simd: 7295 case OMPD_declare_target: 7296 case OMPD_end_declare_target: 7297 case OMPD_simd: 7298 case OMPD_for: 7299 case OMPD_for_simd: 7300 case OMPD_sections: 7301 case OMPD_section: 7302 case OMPD_single: 7303 case OMPD_master: 7304 case OMPD_critical: 7305 case OMPD_taskgroup: 7306 case OMPD_distribute: 7307 case OMPD_ordered: 7308 case OMPD_atomic: 7309 case OMPD_distribute_simd: 7310 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause"); 7311 case OMPD_unknown: 7312 llvm_unreachable("Unknown OpenMP directive"); 7313 } 7314 break; 7315 case OMPC_thread_limit: 7316 switch (DKind) { 7317 case OMPD_target_teams: 7318 CaptureRegion = OMPD_target; 7319 break; 7320 case OMPD_cancel: 7321 case OMPD_parallel: 7322 case OMPD_parallel_sections: 7323 case OMPD_parallel_for: 7324 case OMPD_parallel_for_simd: 7325 case OMPD_target: 7326 case OMPD_target_simd: 7327 case OMPD_target_parallel: 7328 case OMPD_target_parallel_for: 7329 case OMPD_target_parallel_for_simd: 7330 case OMPD_target_teams_distribute: 7331 case OMPD_target_teams_distribute_simd: 7332 case OMPD_target_teams_distribute_parallel_for: 7333 case OMPD_target_teams_distribute_parallel_for_simd: 7334 case OMPD_teams_distribute_parallel_for: 7335 case OMPD_teams_distribute_parallel_for_simd: 7336 case OMPD_distribute_parallel_for: 7337 case OMPD_distribute_parallel_for_simd: 7338 case OMPD_task: 7339 case OMPD_taskloop: 7340 case OMPD_taskloop_simd: 7341 case OMPD_target_data: 7342 case OMPD_target_enter_data: 7343 case OMPD_target_exit_data: 7344 case OMPD_target_update: 7345 case OMPD_teams: 7346 case OMPD_teams_distribute: 7347 case OMPD_teams_distribute_simd: 7348 // Do not capture thread_limit-clause expressions. 7349 break; 7350 case OMPD_threadprivate: 7351 case OMPD_taskyield: 7352 case OMPD_barrier: 7353 case OMPD_taskwait: 7354 case OMPD_cancellation_point: 7355 case OMPD_flush: 7356 case OMPD_declare_reduction: 7357 case OMPD_declare_simd: 7358 case OMPD_declare_target: 7359 case OMPD_end_declare_target: 7360 case OMPD_simd: 7361 case OMPD_for: 7362 case OMPD_for_simd: 7363 case OMPD_sections: 7364 case OMPD_section: 7365 case OMPD_single: 7366 case OMPD_master: 7367 case OMPD_critical: 7368 case OMPD_taskgroup: 7369 case OMPD_distribute: 7370 case OMPD_ordered: 7371 case OMPD_atomic: 7372 case OMPD_distribute_simd: 7373 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause"); 7374 case OMPD_unknown: 7375 llvm_unreachable("Unknown OpenMP directive"); 7376 } 7377 break; 7378 case OMPC_schedule: 7379 case OMPC_dist_schedule: 7380 case OMPC_firstprivate: 7381 case OMPC_lastprivate: 7382 case OMPC_reduction: 7383 case OMPC_task_reduction: 7384 case OMPC_in_reduction: 7385 case OMPC_linear: 7386 case OMPC_default: 7387 case OMPC_proc_bind: 7388 case OMPC_final: 7389 case OMPC_safelen: 7390 case OMPC_simdlen: 7391 case OMPC_collapse: 7392 case OMPC_private: 7393 case OMPC_shared: 7394 case OMPC_aligned: 7395 case OMPC_copyin: 7396 case OMPC_copyprivate: 7397 case OMPC_ordered: 7398 case OMPC_nowait: 7399 case OMPC_untied: 7400 case OMPC_mergeable: 7401 case OMPC_threadprivate: 7402 case OMPC_flush: 7403 case OMPC_read: 7404 case OMPC_write: 7405 case OMPC_update: 7406 case OMPC_capture: 7407 case OMPC_seq_cst: 7408 case OMPC_depend: 7409 case OMPC_device: 7410 case OMPC_threads: 7411 case OMPC_simd: 7412 case OMPC_map: 7413 case OMPC_priority: 7414 case OMPC_grainsize: 7415 case OMPC_nogroup: 7416 case OMPC_num_tasks: 7417 case OMPC_hint: 7418 case OMPC_defaultmap: 7419 case OMPC_unknown: 7420 case OMPC_uniform: 7421 case OMPC_to: 7422 case OMPC_from: 7423 case OMPC_use_device_ptr: 7424 case OMPC_is_device_ptr: 7425 llvm_unreachable("Unexpected OpenMP clause."); 7426 } 7427 return CaptureRegion; 7428 } 7429 7430 OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier, 7431 Expr *Condition, SourceLocation StartLoc, 7432 SourceLocation LParenLoc, 7433 SourceLocation NameModifierLoc, 7434 SourceLocation ColonLoc, 7435 SourceLocation EndLoc) { 7436 Expr *ValExpr = Condition; 7437 Stmt *HelperValStmt = nullptr; 7438 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 7439 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 7440 !Condition->isInstantiationDependent() && 7441 !Condition->containsUnexpandedParameterPack()) { 7442 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 7443 if (Val.isInvalid()) 7444 return nullptr; 7445 7446 ValExpr = MakeFullExpr(Val.get()).get(); 7447 7448 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 7449 CaptureRegion = 7450 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier); 7451 if (CaptureRegion != OMPD_unknown) { 7452 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7453 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7454 HelperValStmt = buildPreInits(Context, Captures); 7455 } 7456 } 7457 7458 return new (Context) 7459 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc, 7460 LParenLoc, NameModifierLoc, ColonLoc, EndLoc); 7461 } 7462 7463 OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition, 7464 SourceLocation StartLoc, 7465 SourceLocation LParenLoc, 7466 SourceLocation EndLoc) { 7467 Expr *ValExpr = Condition; 7468 if (!Condition->isValueDependent() && !Condition->isTypeDependent() && 7469 !Condition->isInstantiationDependent() && 7470 !Condition->containsUnexpandedParameterPack()) { 7471 ExprResult Val = CheckBooleanCondition(StartLoc, Condition); 7472 if (Val.isInvalid()) 7473 return nullptr; 7474 7475 ValExpr = MakeFullExpr(Val.get()).get(); 7476 } 7477 7478 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc); 7479 } 7480 ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc, 7481 Expr *Op) { 7482 if (!Op) 7483 return ExprError(); 7484 7485 class IntConvertDiagnoser : public ICEConvertDiagnoser { 7486 public: 7487 IntConvertDiagnoser() 7488 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {} 7489 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc, 7490 QualType T) override { 7491 return S.Diag(Loc, diag::err_omp_not_integral) << T; 7492 } 7493 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc, 7494 QualType T) override { 7495 return S.Diag(Loc, diag::err_omp_incomplete_type) << T; 7496 } 7497 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc, 7498 QualType T, 7499 QualType ConvTy) override { 7500 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy; 7501 } 7502 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv, 7503 QualType ConvTy) override { 7504 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 7505 << ConvTy->isEnumeralType() << ConvTy; 7506 } 7507 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc, 7508 QualType T) override { 7509 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T; 7510 } 7511 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv, 7512 QualType ConvTy) override { 7513 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here) 7514 << ConvTy->isEnumeralType() << ConvTy; 7515 } 7516 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType, 7517 QualType) override { 7518 llvm_unreachable("conversion functions are permitted"); 7519 } 7520 } ConvertDiagnoser; 7521 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser); 7522 } 7523 7524 static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, 7525 OpenMPClauseKind CKind, 7526 bool StrictlyPositive) { 7527 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() && 7528 !ValExpr->isInstantiationDependent()) { 7529 SourceLocation Loc = ValExpr->getExprLoc(); 7530 ExprResult Value = 7531 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr); 7532 if (Value.isInvalid()) 7533 return false; 7534 7535 ValExpr = Value.get(); 7536 // The expression must evaluate to a non-negative integer value. 7537 llvm::APSInt Result; 7538 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) && 7539 Result.isSigned() && 7540 !((!StrictlyPositive && Result.isNonNegative()) || 7541 (StrictlyPositive && Result.isStrictlyPositive()))) { 7542 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause) 7543 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 7544 << ValExpr->getSourceRange(); 7545 return false; 7546 } 7547 } 7548 return true; 7549 } 7550 7551 OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads, 7552 SourceLocation StartLoc, 7553 SourceLocation LParenLoc, 7554 SourceLocation EndLoc) { 7555 Expr *ValExpr = NumThreads; 7556 Stmt *HelperValStmt = nullptr; 7557 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 7558 7559 // OpenMP [2.5, Restrictions] 7560 // The num_threads expression must evaluate to a positive integer value. 7561 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads, 7562 /*StrictlyPositive=*/true)) 7563 return nullptr; 7564 7565 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 7566 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads); 7567 if (CaptureRegion != OMPD_unknown) { 7568 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7569 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7570 HelperValStmt = buildPreInits(Context, Captures); 7571 } 7572 7573 return new (Context) OMPNumThreadsClause( 7574 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 7575 } 7576 7577 ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E, 7578 OpenMPClauseKind CKind, 7579 bool StrictlyPositive) { 7580 if (!E) 7581 return ExprError(); 7582 if (E->isValueDependent() || E->isTypeDependent() || 7583 E->isInstantiationDependent() || E->containsUnexpandedParameterPack()) 7584 return E; 7585 llvm::APSInt Result; 7586 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result); 7587 if (ICE.isInvalid()) 7588 return ExprError(); 7589 if ((StrictlyPositive && !Result.isStrictlyPositive()) || 7590 (!StrictlyPositive && !Result.isNonNegative())) { 7591 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause) 7592 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0) 7593 << E->getSourceRange(); 7594 return ExprError(); 7595 } 7596 if (CKind == OMPC_aligned && !Result.isPowerOf2()) { 7597 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two) 7598 << E->getSourceRange(); 7599 return ExprError(); 7600 } 7601 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1) 7602 DSAStack->setAssociatedLoops(Result.getExtValue()); 7603 else if (CKind == OMPC_ordered) 7604 DSAStack->setAssociatedLoops(Result.getExtValue()); 7605 return ICE; 7606 } 7607 7608 OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc, 7609 SourceLocation LParenLoc, 7610 SourceLocation EndLoc) { 7611 // OpenMP [2.8.1, simd construct, Description] 7612 // The parameter of the safelen clause must be a constant 7613 // positive integer expression. 7614 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen); 7615 if (Safelen.isInvalid()) 7616 return nullptr; 7617 return new (Context) 7618 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc); 7619 } 7620 7621 OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc, 7622 SourceLocation LParenLoc, 7623 SourceLocation EndLoc) { 7624 // OpenMP [2.8.1, simd construct, Description] 7625 // The parameter of the simdlen clause must be a constant 7626 // positive integer expression. 7627 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen); 7628 if (Simdlen.isInvalid()) 7629 return nullptr; 7630 return new (Context) 7631 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc); 7632 } 7633 7634 OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops, 7635 SourceLocation StartLoc, 7636 SourceLocation LParenLoc, 7637 SourceLocation EndLoc) { 7638 // OpenMP [2.7.1, loop construct, Description] 7639 // OpenMP [2.8.1, simd construct, Description] 7640 // OpenMP [2.9.6, distribute construct, Description] 7641 // The parameter of the collapse clause must be a constant 7642 // positive integer expression. 7643 ExprResult NumForLoopsResult = 7644 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse); 7645 if (NumForLoopsResult.isInvalid()) 7646 return nullptr; 7647 return new (Context) 7648 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc); 7649 } 7650 7651 OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc, 7652 SourceLocation EndLoc, 7653 SourceLocation LParenLoc, 7654 Expr *NumForLoops) { 7655 // OpenMP [2.7.1, loop construct, Description] 7656 // OpenMP [2.8.1, simd construct, Description] 7657 // OpenMP [2.9.6, distribute construct, Description] 7658 // The parameter of the ordered clause must be a constant 7659 // positive integer expression if any. 7660 if (NumForLoops && LParenLoc.isValid()) { 7661 ExprResult NumForLoopsResult = 7662 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered); 7663 if (NumForLoopsResult.isInvalid()) 7664 return nullptr; 7665 NumForLoops = NumForLoopsResult.get(); 7666 } else 7667 NumForLoops = nullptr; 7668 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops); 7669 return new (Context) 7670 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc); 7671 } 7672 7673 OMPClause *Sema::ActOnOpenMPSimpleClause( 7674 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc, 7675 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) { 7676 OMPClause *Res = nullptr; 7677 switch (Kind) { 7678 case OMPC_default: 7679 Res = 7680 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument), 7681 ArgumentLoc, StartLoc, LParenLoc, EndLoc); 7682 break; 7683 case OMPC_proc_bind: 7684 Res = ActOnOpenMPProcBindClause( 7685 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc, 7686 LParenLoc, EndLoc); 7687 break; 7688 case OMPC_if: 7689 case OMPC_final: 7690 case OMPC_num_threads: 7691 case OMPC_safelen: 7692 case OMPC_simdlen: 7693 case OMPC_collapse: 7694 case OMPC_schedule: 7695 case OMPC_private: 7696 case OMPC_firstprivate: 7697 case OMPC_lastprivate: 7698 case OMPC_shared: 7699 case OMPC_reduction: 7700 case OMPC_task_reduction: 7701 case OMPC_in_reduction: 7702 case OMPC_linear: 7703 case OMPC_aligned: 7704 case OMPC_copyin: 7705 case OMPC_copyprivate: 7706 case OMPC_ordered: 7707 case OMPC_nowait: 7708 case OMPC_untied: 7709 case OMPC_mergeable: 7710 case OMPC_threadprivate: 7711 case OMPC_flush: 7712 case OMPC_read: 7713 case OMPC_write: 7714 case OMPC_update: 7715 case OMPC_capture: 7716 case OMPC_seq_cst: 7717 case OMPC_depend: 7718 case OMPC_device: 7719 case OMPC_threads: 7720 case OMPC_simd: 7721 case OMPC_map: 7722 case OMPC_num_teams: 7723 case OMPC_thread_limit: 7724 case OMPC_priority: 7725 case OMPC_grainsize: 7726 case OMPC_nogroup: 7727 case OMPC_num_tasks: 7728 case OMPC_hint: 7729 case OMPC_dist_schedule: 7730 case OMPC_defaultmap: 7731 case OMPC_unknown: 7732 case OMPC_uniform: 7733 case OMPC_to: 7734 case OMPC_from: 7735 case OMPC_use_device_ptr: 7736 case OMPC_is_device_ptr: 7737 llvm_unreachable("Clause is not allowed."); 7738 } 7739 return Res; 7740 } 7741 7742 static std::string 7743 getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last, 7744 ArrayRef<unsigned> Exclude = llvm::None) { 7745 std::string Values; 7746 unsigned Bound = Last >= 2 ? Last - 2 : 0; 7747 unsigned Skipped = Exclude.size(); 7748 auto S = Exclude.begin(), E = Exclude.end(); 7749 for (unsigned i = First; i < Last; ++i) { 7750 if (std::find(S, E, i) != E) { 7751 --Skipped; 7752 continue; 7753 } 7754 Values += "'"; 7755 Values += getOpenMPSimpleClauseTypeName(K, i); 7756 Values += "'"; 7757 if (i == Bound - Skipped) 7758 Values += " or "; 7759 else if (i != Bound + 1 - Skipped) 7760 Values += ", "; 7761 } 7762 return Values; 7763 } 7764 7765 OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind, 7766 SourceLocation KindKwLoc, 7767 SourceLocation StartLoc, 7768 SourceLocation LParenLoc, 7769 SourceLocation EndLoc) { 7770 if (Kind == OMPC_DEFAULT_unknown) { 7771 static_assert(OMPC_DEFAULT_unknown > 0, 7772 "OMPC_DEFAULT_unknown not greater than 0"); 7773 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 7774 << getListOfPossibleValues(OMPC_default, /*First=*/0, 7775 /*Last=*/OMPC_DEFAULT_unknown) 7776 << getOpenMPClauseName(OMPC_default); 7777 return nullptr; 7778 } 7779 switch (Kind) { 7780 case OMPC_DEFAULT_none: 7781 DSAStack->setDefaultDSANone(KindKwLoc); 7782 break; 7783 case OMPC_DEFAULT_shared: 7784 DSAStack->setDefaultDSAShared(KindKwLoc); 7785 break; 7786 case OMPC_DEFAULT_unknown: 7787 llvm_unreachable("Clause kind is not allowed."); 7788 break; 7789 } 7790 return new (Context) 7791 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 7792 } 7793 7794 OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind, 7795 SourceLocation KindKwLoc, 7796 SourceLocation StartLoc, 7797 SourceLocation LParenLoc, 7798 SourceLocation EndLoc) { 7799 if (Kind == OMPC_PROC_BIND_unknown) { 7800 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value) 7801 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0, 7802 /*Last=*/OMPC_PROC_BIND_unknown) 7803 << getOpenMPClauseName(OMPC_proc_bind); 7804 return nullptr; 7805 } 7806 return new (Context) 7807 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc); 7808 } 7809 7810 OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause( 7811 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr, 7812 SourceLocation StartLoc, SourceLocation LParenLoc, 7813 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc, 7814 SourceLocation EndLoc) { 7815 OMPClause *Res = nullptr; 7816 switch (Kind) { 7817 case OMPC_schedule: 7818 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements }; 7819 assert(Argument.size() == NumberOfElements && 7820 ArgumentLoc.size() == NumberOfElements); 7821 Res = ActOnOpenMPScheduleClause( 7822 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]), 7823 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]), 7824 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr, 7825 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2], 7826 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc); 7827 break; 7828 case OMPC_if: 7829 assert(Argument.size() == 1 && ArgumentLoc.size() == 1); 7830 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()), 7831 Expr, StartLoc, LParenLoc, ArgumentLoc.back(), 7832 DelimLoc, EndLoc); 7833 break; 7834 case OMPC_dist_schedule: 7835 Res = ActOnOpenMPDistScheduleClause( 7836 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr, 7837 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc); 7838 break; 7839 case OMPC_defaultmap: 7840 enum { Modifier, DefaultmapKind }; 7841 Res = ActOnOpenMPDefaultmapClause( 7842 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]), 7843 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]), 7844 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind], 7845 EndLoc); 7846 break; 7847 case OMPC_final: 7848 case OMPC_num_threads: 7849 case OMPC_safelen: 7850 case OMPC_simdlen: 7851 case OMPC_collapse: 7852 case OMPC_default: 7853 case OMPC_proc_bind: 7854 case OMPC_private: 7855 case OMPC_firstprivate: 7856 case OMPC_lastprivate: 7857 case OMPC_shared: 7858 case OMPC_reduction: 7859 case OMPC_task_reduction: 7860 case OMPC_in_reduction: 7861 case OMPC_linear: 7862 case OMPC_aligned: 7863 case OMPC_copyin: 7864 case OMPC_copyprivate: 7865 case OMPC_ordered: 7866 case OMPC_nowait: 7867 case OMPC_untied: 7868 case OMPC_mergeable: 7869 case OMPC_threadprivate: 7870 case OMPC_flush: 7871 case OMPC_read: 7872 case OMPC_write: 7873 case OMPC_update: 7874 case OMPC_capture: 7875 case OMPC_seq_cst: 7876 case OMPC_depend: 7877 case OMPC_device: 7878 case OMPC_threads: 7879 case OMPC_simd: 7880 case OMPC_map: 7881 case OMPC_num_teams: 7882 case OMPC_thread_limit: 7883 case OMPC_priority: 7884 case OMPC_grainsize: 7885 case OMPC_nogroup: 7886 case OMPC_num_tasks: 7887 case OMPC_hint: 7888 case OMPC_unknown: 7889 case OMPC_uniform: 7890 case OMPC_to: 7891 case OMPC_from: 7892 case OMPC_use_device_ptr: 7893 case OMPC_is_device_ptr: 7894 llvm_unreachable("Clause is not allowed."); 7895 } 7896 return Res; 7897 } 7898 7899 static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1, 7900 OpenMPScheduleClauseModifier M2, 7901 SourceLocation M1Loc, SourceLocation M2Loc) { 7902 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) { 7903 SmallVector<unsigned, 2> Excluded; 7904 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown) 7905 Excluded.push_back(M2); 7906 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) 7907 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic); 7908 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic) 7909 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic); 7910 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value) 7911 << getListOfPossibleValues(OMPC_schedule, 7912 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1, 7913 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 7914 Excluded) 7915 << getOpenMPClauseName(OMPC_schedule); 7916 return true; 7917 } 7918 return false; 7919 } 7920 7921 OMPClause *Sema::ActOnOpenMPScheduleClause( 7922 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2, 7923 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 7924 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc, 7925 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) { 7926 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) || 7927 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc)) 7928 return nullptr; 7929 // OpenMP, 2.7.1, Loop Construct, Restrictions 7930 // Either the monotonic modifier or the nonmonotonic modifier can be specified 7931 // but not both. 7932 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) || 7933 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic && 7934 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) || 7935 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic && 7936 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) { 7937 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier) 7938 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2) 7939 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1); 7940 return nullptr; 7941 } 7942 if (Kind == OMPC_SCHEDULE_unknown) { 7943 std::string Values; 7944 if (M1Loc.isInvalid() && M2Loc.isInvalid()) { 7945 unsigned Exclude[] = {OMPC_SCHEDULE_unknown}; 7946 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 7947 /*Last=*/OMPC_SCHEDULE_MODIFIER_last, 7948 Exclude); 7949 } else { 7950 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0, 7951 /*Last=*/OMPC_SCHEDULE_unknown); 7952 } 7953 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 7954 << Values << getOpenMPClauseName(OMPC_schedule); 7955 return nullptr; 7956 } 7957 // OpenMP, 2.7.1, Loop Construct, Restrictions 7958 // The nonmonotonic modifier can only be specified with schedule(dynamic) or 7959 // schedule(guided). 7960 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic || 7961 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) && 7962 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) { 7963 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc, 7964 diag::err_omp_schedule_nonmonotonic_static); 7965 return nullptr; 7966 } 7967 Expr *ValExpr = ChunkSize; 7968 Stmt *HelperValStmt = nullptr; 7969 if (ChunkSize) { 7970 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 7971 !ChunkSize->isInstantiationDependent() && 7972 !ChunkSize->containsUnexpandedParameterPack()) { 7973 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 7974 ExprResult Val = 7975 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 7976 if (Val.isInvalid()) 7977 return nullptr; 7978 7979 ValExpr = Val.get(); 7980 7981 // OpenMP [2.7.1, Restrictions] 7982 // chunk_size must be a loop invariant integer expression with a positive 7983 // value. 7984 llvm::APSInt Result; 7985 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 7986 if (Result.isSigned() && !Result.isStrictlyPositive()) { 7987 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 7988 << "schedule" << 1 << ChunkSize->getSourceRange(); 7989 return nullptr; 7990 } 7991 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 7992 !CurContext->isDependentContext()) { 7993 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 7994 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 7995 HelperValStmt = buildPreInits(Context, Captures); 7996 } 7997 } 7998 } 7999 8000 return new (Context) 8001 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind, 8002 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc); 8003 } 8004 8005 OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind, 8006 SourceLocation StartLoc, 8007 SourceLocation EndLoc) { 8008 OMPClause *Res = nullptr; 8009 switch (Kind) { 8010 case OMPC_ordered: 8011 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc); 8012 break; 8013 case OMPC_nowait: 8014 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc); 8015 break; 8016 case OMPC_untied: 8017 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc); 8018 break; 8019 case OMPC_mergeable: 8020 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc); 8021 break; 8022 case OMPC_read: 8023 Res = ActOnOpenMPReadClause(StartLoc, EndLoc); 8024 break; 8025 case OMPC_write: 8026 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc); 8027 break; 8028 case OMPC_update: 8029 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc); 8030 break; 8031 case OMPC_capture: 8032 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc); 8033 break; 8034 case OMPC_seq_cst: 8035 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc); 8036 break; 8037 case OMPC_threads: 8038 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc); 8039 break; 8040 case OMPC_simd: 8041 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc); 8042 break; 8043 case OMPC_nogroup: 8044 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc); 8045 break; 8046 case OMPC_if: 8047 case OMPC_final: 8048 case OMPC_num_threads: 8049 case OMPC_safelen: 8050 case OMPC_simdlen: 8051 case OMPC_collapse: 8052 case OMPC_schedule: 8053 case OMPC_private: 8054 case OMPC_firstprivate: 8055 case OMPC_lastprivate: 8056 case OMPC_shared: 8057 case OMPC_reduction: 8058 case OMPC_task_reduction: 8059 case OMPC_in_reduction: 8060 case OMPC_linear: 8061 case OMPC_aligned: 8062 case OMPC_copyin: 8063 case OMPC_copyprivate: 8064 case OMPC_default: 8065 case OMPC_proc_bind: 8066 case OMPC_threadprivate: 8067 case OMPC_flush: 8068 case OMPC_depend: 8069 case OMPC_device: 8070 case OMPC_map: 8071 case OMPC_num_teams: 8072 case OMPC_thread_limit: 8073 case OMPC_priority: 8074 case OMPC_grainsize: 8075 case OMPC_num_tasks: 8076 case OMPC_hint: 8077 case OMPC_dist_schedule: 8078 case OMPC_defaultmap: 8079 case OMPC_unknown: 8080 case OMPC_uniform: 8081 case OMPC_to: 8082 case OMPC_from: 8083 case OMPC_use_device_ptr: 8084 case OMPC_is_device_ptr: 8085 llvm_unreachable("Clause is not allowed."); 8086 } 8087 return Res; 8088 } 8089 8090 OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc, 8091 SourceLocation EndLoc) { 8092 DSAStack->setNowaitRegion(); 8093 return new (Context) OMPNowaitClause(StartLoc, EndLoc); 8094 } 8095 8096 OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc, 8097 SourceLocation EndLoc) { 8098 return new (Context) OMPUntiedClause(StartLoc, EndLoc); 8099 } 8100 8101 OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc, 8102 SourceLocation EndLoc) { 8103 return new (Context) OMPMergeableClause(StartLoc, EndLoc); 8104 } 8105 8106 OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc, 8107 SourceLocation EndLoc) { 8108 return new (Context) OMPReadClause(StartLoc, EndLoc); 8109 } 8110 8111 OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc, 8112 SourceLocation EndLoc) { 8113 return new (Context) OMPWriteClause(StartLoc, EndLoc); 8114 } 8115 8116 OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc, 8117 SourceLocation EndLoc) { 8118 return new (Context) OMPUpdateClause(StartLoc, EndLoc); 8119 } 8120 8121 OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc, 8122 SourceLocation EndLoc) { 8123 return new (Context) OMPCaptureClause(StartLoc, EndLoc); 8124 } 8125 8126 OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc, 8127 SourceLocation EndLoc) { 8128 return new (Context) OMPSeqCstClause(StartLoc, EndLoc); 8129 } 8130 8131 OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc, 8132 SourceLocation EndLoc) { 8133 return new (Context) OMPThreadsClause(StartLoc, EndLoc); 8134 } 8135 8136 OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc, 8137 SourceLocation EndLoc) { 8138 return new (Context) OMPSIMDClause(StartLoc, EndLoc); 8139 } 8140 8141 OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc, 8142 SourceLocation EndLoc) { 8143 return new (Context) OMPNogroupClause(StartLoc, EndLoc); 8144 } 8145 8146 OMPClause *Sema::ActOnOpenMPVarListClause( 8147 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr, 8148 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, 8149 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec, 8150 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind, 8151 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier, 8152 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 8153 SourceLocation DepLinMapLoc) { 8154 OMPClause *Res = nullptr; 8155 switch (Kind) { 8156 case OMPC_private: 8157 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc); 8158 break; 8159 case OMPC_firstprivate: 8160 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 8161 break; 8162 case OMPC_lastprivate: 8163 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 8164 break; 8165 case OMPC_shared: 8166 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc); 8167 break; 8168 case OMPC_reduction: 8169 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 8170 EndLoc, ReductionIdScopeSpec, ReductionId); 8171 break; 8172 case OMPC_task_reduction: 8173 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 8174 EndLoc, ReductionIdScopeSpec, 8175 ReductionId); 8176 break; 8177 case OMPC_in_reduction: 8178 Res = 8179 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc, 8180 EndLoc, ReductionIdScopeSpec, ReductionId); 8181 break; 8182 case OMPC_linear: 8183 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc, 8184 LinKind, DepLinMapLoc, ColonLoc, EndLoc); 8185 break; 8186 case OMPC_aligned: 8187 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc, 8188 ColonLoc, EndLoc); 8189 break; 8190 case OMPC_copyin: 8191 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc); 8192 break; 8193 case OMPC_copyprivate: 8194 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc); 8195 break; 8196 case OMPC_flush: 8197 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc); 8198 break; 8199 case OMPC_depend: 8200 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList, 8201 StartLoc, LParenLoc, EndLoc); 8202 break; 8203 case OMPC_map: 8204 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit, 8205 DepLinMapLoc, ColonLoc, VarList, StartLoc, 8206 LParenLoc, EndLoc); 8207 break; 8208 case OMPC_to: 8209 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc); 8210 break; 8211 case OMPC_from: 8212 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc); 8213 break; 8214 case OMPC_use_device_ptr: 8215 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 8216 break; 8217 case OMPC_is_device_ptr: 8218 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc); 8219 break; 8220 case OMPC_if: 8221 case OMPC_final: 8222 case OMPC_num_threads: 8223 case OMPC_safelen: 8224 case OMPC_simdlen: 8225 case OMPC_collapse: 8226 case OMPC_default: 8227 case OMPC_proc_bind: 8228 case OMPC_schedule: 8229 case OMPC_ordered: 8230 case OMPC_nowait: 8231 case OMPC_untied: 8232 case OMPC_mergeable: 8233 case OMPC_threadprivate: 8234 case OMPC_read: 8235 case OMPC_write: 8236 case OMPC_update: 8237 case OMPC_capture: 8238 case OMPC_seq_cst: 8239 case OMPC_device: 8240 case OMPC_threads: 8241 case OMPC_simd: 8242 case OMPC_num_teams: 8243 case OMPC_thread_limit: 8244 case OMPC_priority: 8245 case OMPC_grainsize: 8246 case OMPC_nogroup: 8247 case OMPC_num_tasks: 8248 case OMPC_hint: 8249 case OMPC_dist_schedule: 8250 case OMPC_defaultmap: 8251 case OMPC_unknown: 8252 case OMPC_uniform: 8253 llvm_unreachable("Clause is not allowed."); 8254 } 8255 return Res; 8256 } 8257 8258 ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK, 8259 ExprObjectKind OK, SourceLocation Loc) { 8260 ExprResult Res = BuildDeclRefExpr( 8261 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc); 8262 if (!Res.isUsable()) 8263 return ExprError(); 8264 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) { 8265 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get()); 8266 if (!Res.isUsable()) 8267 return ExprError(); 8268 } 8269 if (VK != VK_LValue && Res.get()->isGLValue()) { 8270 Res = DefaultLvalueConversion(Res.get()); 8271 if (!Res.isUsable()) 8272 return ExprError(); 8273 } 8274 return Res; 8275 } 8276 8277 static std::pair<ValueDecl *, bool> 8278 getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc, 8279 SourceRange &ERange, bool AllowArraySection = false) { 8280 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() || 8281 RefExpr->containsUnexpandedParameterPack()) 8282 return std::make_pair(nullptr, true); 8283 8284 // OpenMP [3.1, C/C++] 8285 // A list item is a variable name. 8286 // OpenMP [2.9.3.3, Restrictions, p.1] 8287 // A variable that is part of another variable (as an array or 8288 // structure element) cannot appear in a private clause. 8289 RefExpr = RefExpr->IgnoreParens(); 8290 enum { 8291 NoArrayExpr = -1, 8292 ArraySubscript = 0, 8293 OMPArraySection = 1 8294 } IsArrayExpr = NoArrayExpr; 8295 if (AllowArraySection) { 8296 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) { 8297 auto *Base = ASE->getBase()->IgnoreParenImpCasts(); 8298 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 8299 Base = TempASE->getBase()->IgnoreParenImpCasts(); 8300 RefExpr = Base; 8301 IsArrayExpr = ArraySubscript; 8302 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) { 8303 auto *Base = OASE->getBase()->IgnoreParenImpCasts(); 8304 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) 8305 Base = TempOASE->getBase()->IgnoreParenImpCasts(); 8306 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) 8307 Base = TempASE->getBase()->IgnoreParenImpCasts(); 8308 RefExpr = Base; 8309 IsArrayExpr = OMPArraySection; 8310 } 8311 } 8312 ELoc = RefExpr->getExprLoc(); 8313 ERange = RefExpr->getSourceRange(); 8314 RefExpr = RefExpr->IgnoreParenImpCasts(); 8315 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr); 8316 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr); 8317 if ((!DE || !isa<VarDecl>(DE->getDecl())) && 8318 (S.getCurrentThisType().isNull() || !ME || 8319 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) || 8320 !isa<FieldDecl>(ME->getMemberDecl()))) { 8321 if (IsArrayExpr != NoArrayExpr) 8322 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr 8323 << ERange; 8324 else { 8325 S.Diag(ELoc, 8326 AllowArraySection 8327 ? diag::err_omp_expected_var_name_member_expr_or_array_item 8328 : diag::err_omp_expected_var_name_member_expr) 8329 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange; 8330 } 8331 return std::make_pair(nullptr, false); 8332 } 8333 return std::make_pair( 8334 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false); 8335 } 8336 8337 OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList, 8338 SourceLocation StartLoc, 8339 SourceLocation LParenLoc, 8340 SourceLocation EndLoc) { 8341 SmallVector<Expr *, 8> Vars; 8342 SmallVector<Expr *, 8> PrivateCopies; 8343 for (auto &RefExpr : VarList) { 8344 assert(RefExpr && "NULL expr in OpenMP private clause."); 8345 SourceLocation ELoc; 8346 SourceRange ERange; 8347 Expr *SimpleRefExpr = RefExpr; 8348 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8349 if (Res.second) { 8350 // It will be analyzed later. 8351 Vars.push_back(RefExpr); 8352 PrivateCopies.push_back(nullptr); 8353 } 8354 ValueDecl *D = Res.first; 8355 if (!D) 8356 continue; 8357 8358 QualType Type = D->getType(); 8359 auto *VD = dyn_cast<VarDecl>(D); 8360 8361 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8362 // A variable that appears in a private clause must not have an incomplete 8363 // type or a reference type. 8364 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type)) 8365 continue; 8366 Type = Type.getNonReferenceType(); 8367 8368 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8369 // in a Construct] 8370 // Variables with the predetermined data-sharing attributes may not be 8371 // listed in data-sharing attributes clauses, except for the cases 8372 // listed below. For these exceptions only, listing a predetermined 8373 // variable in a data-sharing attribute clause is allowed and overrides 8374 // the variable's predetermined data-sharing attributes. 8375 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8376 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) { 8377 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 8378 << getOpenMPClauseName(OMPC_private); 8379 ReportOriginalDSA(*this, DSAStack, D, DVar); 8380 continue; 8381 } 8382 8383 auto CurrDir = DSAStack->getCurrentDirective(); 8384 // Variably modified types are not supported for tasks. 8385 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 8386 isOpenMPTaskingDirective(CurrDir)) { 8387 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 8388 << getOpenMPClauseName(OMPC_private) << Type 8389 << getOpenMPDirectiveName(CurrDir); 8390 bool IsDecl = 8391 !VD || 8392 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8393 Diag(D->getLocation(), 8394 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8395 << D; 8396 continue; 8397 } 8398 8399 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 8400 // A list item cannot appear in both a map clause and a data-sharing 8401 // attribute clause on the same construct 8402 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || 8403 CurrDir == OMPD_target_teams || 8404 CurrDir == OMPD_target_teams_distribute || 8405 CurrDir == OMPD_target_teams_distribute_parallel_for || 8406 CurrDir == OMPD_target_teams_distribute_parallel_for_simd || 8407 CurrDir == OMPD_target_teams_distribute_simd || 8408 CurrDir == OMPD_target_parallel_for_simd || 8409 CurrDir == OMPD_target_parallel_for) { 8410 OpenMPClauseKind ConflictKind; 8411 if (DSAStack->checkMappableExprComponentListsForDecl( 8412 VD, /*CurrentRegionOnly=*/true, 8413 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 8414 OpenMPClauseKind WhereFoundClauseKind) -> bool { 8415 ConflictKind = WhereFoundClauseKind; 8416 return true; 8417 })) { 8418 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 8419 << getOpenMPClauseName(OMPC_private) 8420 << getOpenMPClauseName(ConflictKind) 8421 << getOpenMPDirectiveName(CurrDir); 8422 ReportOriginalDSA(*this, DSAStack, D, DVar); 8423 continue; 8424 } 8425 } 8426 8427 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1] 8428 // A variable of class type (or array thereof) that appears in a private 8429 // clause requires an accessible, unambiguous default constructor for the 8430 // class type. 8431 // Generate helper private variable and initialize it with the default 8432 // value. The address of the original variable is replaced by the address of 8433 // the new private variable in CodeGen. This new variable is not added to 8434 // IdResolver, so the code in the OpenMP region uses original variable for 8435 // proper diagnostics. 8436 Type = Type.getUnqualifiedType(); 8437 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 8438 D->hasAttrs() ? &D->getAttrs() : nullptr); 8439 ActOnUninitializedDecl(VDPrivate); 8440 if (VDPrivate->isInvalidDecl()) 8441 continue; 8442 auto VDPrivateRefExpr = buildDeclRefExpr( 8443 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 8444 8445 DeclRefExpr *Ref = nullptr; 8446 if (!VD && !CurContext->isDependentContext()) 8447 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 8448 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref); 8449 Vars.push_back((VD || CurContext->isDependentContext()) 8450 ? RefExpr->IgnoreParens() 8451 : Ref); 8452 PrivateCopies.push_back(VDPrivateRefExpr); 8453 } 8454 8455 if (Vars.empty()) 8456 return nullptr; 8457 8458 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 8459 PrivateCopies); 8460 } 8461 8462 namespace { 8463 class DiagsUninitializedSeveretyRAII { 8464 private: 8465 DiagnosticsEngine &Diags; 8466 SourceLocation SavedLoc; 8467 bool IsIgnored; 8468 8469 public: 8470 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc, 8471 bool IsIgnored) 8472 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) { 8473 if (!IsIgnored) { 8474 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init, 8475 /*Map*/ diag::Severity::Ignored, Loc); 8476 } 8477 } 8478 ~DiagsUninitializedSeveretyRAII() { 8479 if (!IsIgnored) 8480 Diags.popMappings(SavedLoc); 8481 } 8482 }; 8483 } 8484 8485 OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList, 8486 SourceLocation StartLoc, 8487 SourceLocation LParenLoc, 8488 SourceLocation EndLoc) { 8489 SmallVector<Expr *, 8> Vars; 8490 SmallVector<Expr *, 8> PrivateCopies; 8491 SmallVector<Expr *, 8> Inits; 8492 SmallVector<Decl *, 4> ExprCaptures; 8493 bool IsImplicitClause = 8494 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid(); 8495 auto ImplicitClauseLoc = DSAStack->getConstructLoc(); 8496 8497 for (auto &RefExpr : VarList) { 8498 assert(RefExpr && "NULL expr in OpenMP firstprivate clause."); 8499 SourceLocation ELoc; 8500 SourceRange ERange; 8501 Expr *SimpleRefExpr = RefExpr; 8502 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8503 if (Res.second) { 8504 // It will be analyzed later. 8505 Vars.push_back(RefExpr); 8506 PrivateCopies.push_back(nullptr); 8507 Inits.push_back(nullptr); 8508 } 8509 ValueDecl *D = Res.first; 8510 if (!D) 8511 continue; 8512 8513 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc; 8514 QualType Type = D->getType(); 8515 auto *VD = dyn_cast<VarDecl>(D); 8516 8517 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 8518 // A variable that appears in a private clause must not have an incomplete 8519 // type or a reference type. 8520 if (RequireCompleteType(ELoc, Type, 8521 diag::err_omp_firstprivate_incomplete_type)) 8522 continue; 8523 Type = Type.getNonReferenceType(); 8524 8525 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1] 8526 // A variable of class type (or array thereof) that appears in a private 8527 // clause requires an accessible, unambiguous copy constructor for the 8528 // class type. 8529 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 8530 8531 // If an implicit firstprivate variable found it was checked already. 8532 DSAStackTy::DSAVarData TopDVar; 8533 if (!IsImplicitClause) { 8534 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8535 TopDVar = DVar; 8536 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8537 bool IsConstant = ElemType.isConstant(Context); 8538 // OpenMP [2.4.13, Data-sharing Attribute Clauses] 8539 // A list item that specifies a given variable may not appear in more 8540 // than one clause on the same directive, except that a variable may be 8541 // specified in both firstprivate and lastprivate clauses. 8542 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 8543 // A list item may appear in a firstprivate or lastprivate clause but not 8544 // both. 8545 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate && 8546 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_lastprivate) && 8547 DVar.RefExpr) { 8548 Diag(ELoc, diag::err_omp_wrong_dsa) 8549 << getOpenMPClauseName(DVar.CKind) 8550 << getOpenMPClauseName(OMPC_firstprivate); 8551 ReportOriginalDSA(*this, DSAStack, D, DVar); 8552 continue; 8553 } 8554 8555 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8556 // in a Construct] 8557 // Variables with the predetermined data-sharing attributes may not be 8558 // listed in data-sharing attributes clauses, except for the cases 8559 // listed below. For these exceptions only, listing a predetermined 8560 // variable in a data-sharing attribute clause is allowed and overrides 8561 // the variable's predetermined data-sharing attributes. 8562 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8563 // in a Construct, C/C++, p.2] 8564 // Variables with const-qualified type having no mutable member may be 8565 // listed in a firstprivate clause, even if they are static data members. 8566 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr && 8567 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) { 8568 Diag(ELoc, diag::err_omp_wrong_dsa) 8569 << getOpenMPClauseName(DVar.CKind) 8570 << getOpenMPClauseName(OMPC_firstprivate); 8571 ReportOriginalDSA(*this, DSAStack, D, DVar); 8572 continue; 8573 } 8574 8575 // OpenMP [2.9.3.4, Restrictions, p.2] 8576 // A list item that is private within a parallel region must not appear 8577 // in a firstprivate clause on a worksharing construct if any of the 8578 // worksharing regions arising from the worksharing construct ever bind 8579 // to any of the parallel regions arising from the parallel construct. 8580 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 8581 // A list item that is private within a teams region must not appear in a 8582 // firstprivate clause on a distribute construct if any of the distribute 8583 // regions arising from the distribute construct ever bind to any of the 8584 // teams regions arising from the teams construct. 8585 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3] 8586 // A list item that appears in a reduction clause of a teams construct 8587 // must not appear in a firstprivate clause on a distribute construct if 8588 // any of the distribute regions arising from the distribute construct 8589 // ever bind to any of the teams regions arising from the teams construct. 8590 if ((isOpenMPWorksharingDirective(CurrDir) || 8591 isOpenMPDistributeDirective(CurrDir)) && 8592 !isOpenMPParallelDirective(CurrDir) && 8593 !isOpenMPTeamsDirective(CurrDir)) { 8594 DVar = DSAStack->getImplicitDSA(D, true); 8595 if (DVar.CKind != OMPC_shared && 8596 (isOpenMPParallelDirective(DVar.DKind) || 8597 isOpenMPTeamsDirective(DVar.DKind) || 8598 DVar.DKind == OMPD_unknown)) { 8599 Diag(ELoc, diag::err_omp_required_access) 8600 << getOpenMPClauseName(OMPC_firstprivate) 8601 << getOpenMPClauseName(OMPC_shared); 8602 ReportOriginalDSA(*this, DSAStack, D, DVar); 8603 continue; 8604 } 8605 } 8606 // OpenMP [2.9.3.4, Restrictions, p.3] 8607 // A list item that appears in a reduction clause of a parallel construct 8608 // must not appear in a firstprivate clause on a worksharing or task 8609 // construct if any of the worksharing or task regions arising from the 8610 // worksharing or task construct ever bind to any of the parallel regions 8611 // arising from the parallel construct. 8612 // OpenMP [2.9.3.4, Restrictions, p.4] 8613 // A list item that appears in a reduction clause in worksharing 8614 // construct must not appear in a firstprivate clause in a task construct 8615 // encountered during execution of any of the worksharing regions arising 8616 // from the worksharing construct. 8617 if (isOpenMPTaskingDirective(CurrDir)) { 8618 DVar = DSAStack->hasInnermostDSA( 8619 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; }, 8620 [](OpenMPDirectiveKind K) -> bool { 8621 return isOpenMPParallelDirective(K) || 8622 isOpenMPWorksharingDirective(K) || 8623 isOpenMPTeamsDirective(K); 8624 }, 8625 /*FromParent=*/true); 8626 if (DVar.CKind == OMPC_reduction && 8627 (isOpenMPParallelDirective(DVar.DKind) || 8628 isOpenMPWorksharingDirective(DVar.DKind) || 8629 isOpenMPTeamsDirective(DVar.DKind))) { 8630 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate) 8631 << getOpenMPDirectiveName(DVar.DKind); 8632 ReportOriginalDSA(*this, DSAStack, D, DVar); 8633 continue; 8634 } 8635 } 8636 8637 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 8638 // A list item cannot appear in both a map clause and a data-sharing 8639 // attribute clause on the same construct 8640 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel || 8641 CurrDir == OMPD_target_teams || 8642 CurrDir == OMPD_target_teams_distribute || 8643 CurrDir == OMPD_target_teams_distribute_parallel_for || 8644 CurrDir == OMPD_target_teams_distribute_parallel_for_simd || 8645 CurrDir == OMPD_target_teams_distribute_simd || 8646 CurrDir == OMPD_target_parallel_for_simd || 8647 CurrDir == OMPD_target_parallel_for) { 8648 OpenMPClauseKind ConflictKind; 8649 if (DSAStack->checkMappableExprComponentListsForDecl( 8650 VD, /*CurrentRegionOnly=*/true, 8651 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef, 8652 OpenMPClauseKind WhereFoundClauseKind) -> bool { 8653 ConflictKind = WhereFoundClauseKind; 8654 return true; 8655 })) { 8656 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 8657 << getOpenMPClauseName(OMPC_firstprivate) 8658 << getOpenMPClauseName(ConflictKind) 8659 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8660 ReportOriginalDSA(*this, DSAStack, D, DVar); 8661 continue; 8662 } 8663 } 8664 } 8665 8666 // Variably modified types are not supported for tasks. 8667 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() && 8668 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) { 8669 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 8670 << getOpenMPClauseName(OMPC_firstprivate) << Type 8671 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 8672 bool IsDecl = 8673 !VD || 8674 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 8675 Diag(D->getLocation(), 8676 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 8677 << D; 8678 continue; 8679 } 8680 8681 Type = Type.getUnqualifiedType(); 8682 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 8683 D->hasAttrs() ? &D->getAttrs() : nullptr); 8684 // Generate helper private variable and initialize it with the value of the 8685 // original variable. The address of the original variable is replaced by 8686 // the address of the new private variable in the CodeGen. This new variable 8687 // is not added to IdResolver, so the code in the OpenMP region uses 8688 // original variable for proper diagnostics and variable capturing. 8689 Expr *VDInitRefExpr = nullptr; 8690 // For arrays generate initializer for single element and replace it by the 8691 // original array element in CodeGen. 8692 if (Type->isArrayType()) { 8693 auto VDInit = 8694 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName()); 8695 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc); 8696 auto Init = DefaultLvalueConversion(VDInitRefExpr).get(); 8697 ElemType = ElemType.getUnqualifiedType(); 8698 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, 8699 ".firstprivate.temp"); 8700 InitializedEntity Entity = 8701 InitializedEntity::InitializeVariable(VDInitTemp); 8702 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc); 8703 8704 InitializationSequence InitSeq(*this, Entity, Kind, Init); 8705 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init); 8706 if (Result.isInvalid()) 8707 VDPrivate->setInvalidDecl(); 8708 else 8709 VDPrivate->setInit(Result.getAs<Expr>()); 8710 // Remove temp variable declaration. 8711 Context.Deallocate(VDInitTemp); 8712 } else { 8713 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type, 8714 ".firstprivate.temp"); 8715 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 8716 RefExpr->getExprLoc()); 8717 AddInitializerToDecl(VDPrivate, 8718 DefaultLvalueConversion(VDInitRefExpr).get(), 8719 /*DirectInit=*/false); 8720 } 8721 if (VDPrivate->isInvalidDecl()) { 8722 if (IsImplicitClause) { 8723 Diag(RefExpr->getExprLoc(), 8724 diag::note_omp_task_predetermined_firstprivate_here); 8725 } 8726 continue; 8727 } 8728 CurContext->addDecl(VDPrivate); 8729 auto VDPrivateRefExpr = buildDeclRefExpr( 8730 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), 8731 RefExpr->getExprLoc()); 8732 DeclRefExpr *Ref = nullptr; 8733 if (!VD && !CurContext->isDependentContext()) { 8734 if (TopDVar.CKind == OMPC_lastprivate) 8735 Ref = TopDVar.PrivateCopy; 8736 else { 8737 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 8738 if (!IsOpenMPCapturedDecl(D)) 8739 ExprCaptures.push_back(Ref->getDecl()); 8740 } 8741 } 8742 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 8743 Vars.push_back((VD || CurContext->isDependentContext()) 8744 ? RefExpr->IgnoreParens() 8745 : Ref); 8746 PrivateCopies.push_back(VDPrivateRefExpr); 8747 Inits.push_back(VDInitRefExpr); 8748 } 8749 8750 if (Vars.empty()) 8751 return nullptr; 8752 8753 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 8754 Vars, PrivateCopies, Inits, 8755 buildPreInits(Context, ExprCaptures)); 8756 } 8757 8758 OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList, 8759 SourceLocation StartLoc, 8760 SourceLocation LParenLoc, 8761 SourceLocation EndLoc) { 8762 SmallVector<Expr *, 8> Vars; 8763 SmallVector<Expr *, 8> SrcExprs; 8764 SmallVector<Expr *, 8> DstExprs; 8765 SmallVector<Expr *, 8> AssignmentOps; 8766 SmallVector<Decl *, 4> ExprCaptures; 8767 SmallVector<Expr *, 4> ExprPostUpdates; 8768 for (auto &RefExpr : VarList) { 8769 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 8770 SourceLocation ELoc; 8771 SourceRange ERange; 8772 Expr *SimpleRefExpr = RefExpr; 8773 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8774 if (Res.second) { 8775 // It will be analyzed later. 8776 Vars.push_back(RefExpr); 8777 SrcExprs.push_back(nullptr); 8778 DstExprs.push_back(nullptr); 8779 AssignmentOps.push_back(nullptr); 8780 } 8781 ValueDecl *D = Res.first; 8782 if (!D) 8783 continue; 8784 8785 QualType Type = D->getType(); 8786 auto *VD = dyn_cast<VarDecl>(D); 8787 8788 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2] 8789 // A variable that appears in a lastprivate clause must not have an 8790 // incomplete type or a reference type. 8791 if (RequireCompleteType(ELoc, Type, 8792 diag::err_omp_lastprivate_incomplete_type)) 8793 continue; 8794 Type = Type.getNonReferenceType(); 8795 8796 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective(); 8797 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 8798 // in a Construct] 8799 // Variables with the predetermined data-sharing attributes may not be 8800 // listed in data-sharing attributes clauses, except for the cases 8801 // listed below. 8802 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3] 8803 // A list item may appear in a firstprivate or lastprivate clause but not 8804 // both. 8805 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8806 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate && 8807 (CurrDir == OMPD_distribute || DVar.CKind != OMPC_firstprivate) && 8808 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) { 8809 Diag(ELoc, diag::err_omp_wrong_dsa) 8810 << getOpenMPClauseName(DVar.CKind) 8811 << getOpenMPClauseName(OMPC_lastprivate); 8812 ReportOriginalDSA(*this, DSAStack, D, DVar); 8813 continue; 8814 } 8815 8816 // OpenMP [2.14.3.5, Restrictions, p.2] 8817 // A list item that is private within a parallel region, or that appears in 8818 // the reduction clause of a parallel construct, must not appear in a 8819 // lastprivate clause on a worksharing construct if any of the corresponding 8820 // worksharing regions ever binds to any of the corresponding parallel 8821 // regions. 8822 DSAStackTy::DSAVarData TopDVar = DVar; 8823 if (isOpenMPWorksharingDirective(CurrDir) && 8824 !isOpenMPParallelDirective(CurrDir) && 8825 !isOpenMPTeamsDirective(CurrDir)) { 8826 DVar = DSAStack->getImplicitDSA(D, true); 8827 if (DVar.CKind != OMPC_shared) { 8828 Diag(ELoc, diag::err_omp_required_access) 8829 << getOpenMPClauseName(OMPC_lastprivate) 8830 << getOpenMPClauseName(OMPC_shared); 8831 ReportOriginalDSA(*this, DSAStack, D, DVar); 8832 continue; 8833 } 8834 } 8835 8836 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2] 8837 // A variable of class type (or array thereof) that appears in a 8838 // lastprivate clause requires an accessible, unambiguous default 8839 // constructor for the class type, unless the list item is also specified 8840 // in a firstprivate clause. 8841 // A variable of class type (or array thereof) that appears in a 8842 // lastprivate clause requires an accessible, unambiguous copy assignment 8843 // operator for the class type. 8844 Type = Context.getBaseElementType(Type).getNonReferenceType(); 8845 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(), 8846 Type.getUnqualifiedType(), ".lastprivate.src", 8847 D->hasAttrs() ? &D->getAttrs() : nullptr); 8848 auto *PseudoSrcExpr = 8849 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc); 8850 auto *DstVD = 8851 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst", 8852 D->hasAttrs() ? &D->getAttrs() : nullptr); 8853 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 8854 // For arrays generate assignment operation for single element and replace 8855 // it by the original array element in CodeGen. 8856 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign, 8857 PseudoDstExpr, PseudoSrcExpr); 8858 if (AssignmentOp.isInvalid()) 8859 continue; 8860 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 8861 /*DiscardedValue=*/true); 8862 if (AssignmentOp.isInvalid()) 8863 continue; 8864 8865 DeclRefExpr *Ref = nullptr; 8866 if (!VD && !CurContext->isDependentContext()) { 8867 if (TopDVar.CKind == OMPC_firstprivate) 8868 Ref = TopDVar.PrivateCopy; 8869 else { 8870 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 8871 if (!IsOpenMPCapturedDecl(D)) 8872 ExprCaptures.push_back(Ref->getDecl()); 8873 } 8874 if (TopDVar.CKind == OMPC_firstprivate || 8875 (!IsOpenMPCapturedDecl(D) && 8876 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) { 8877 ExprResult RefRes = DefaultLvalueConversion(Ref); 8878 if (!RefRes.isUsable()) 8879 continue; 8880 ExprResult PostUpdateRes = 8881 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 8882 RefRes.get()); 8883 if (!PostUpdateRes.isUsable()) 8884 continue; 8885 ExprPostUpdates.push_back( 8886 IgnoredValueConversions(PostUpdateRes.get()).get()); 8887 } 8888 } 8889 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref); 8890 Vars.push_back((VD || CurContext->isDependentContext()) 8891 ? RefExpr->IgnoreParens() 8892 : Ref); 8893 SrcExprs.push_back(PseudoSrcExpr); 8894 DstExprs.push_back(PseudoDstExpr); 8895 AssignmentOps.push_back(AssignmentOp.get()); 8896 } 8897 8898 if (Vars.empty()) 8899 return nullptr; 8900 8901 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 8902 Vars, SrcExprs, DstExprs, AssignmentOps, 8903 buildPreInits(Context, ExprCaptures), 8904 buildPostUpdate(*this, ExprPostUpdates)); 8905 } 8906 8907 OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList, 8908 SourceLocation StartLoc, 8909 SourceLocation LParenLoc, 8910 SourceLocation EndLoc) { 8911 SmallVector<Expr *, 8> Vars; 8912 for (auto &RefExpr : VarList) { 8913 assert(RefExpr && "NULL expr in OpenMP lastprivate clause."); 8914 SourceLocation ELoc; 8915 SourceRange ERange; 8916 Expr *SimpleRefExpr = RefExpr; 8917 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 8918 if (Res.second) { 8919 // It will be analyzed later. 8920 Vars.push_back(RefExpr); 8921 } 8922 ValueDecl *D = Res.first; 8923 if (!D) 8924 continue; 8925 8926 auto *VD = dyn_cast<VarDecl>(D); 8927 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced 8928 // in a Construct] 8929 // Variables with the predetermined data-sharing attributes may not be 8930 // listed in data-sharing attributes clauses, except for the cases 8931 // listed below. For these exceptions only, listing a predetermined 8932 // variable in a data-sharing attribute clause is allowed and overrides 8933 // the variable's predetermined data-sharing attributes. 8934 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 8935 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared && 8936 DVar.RefExpr) { 8937 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 8938 << getOpenMPClauseName(OMPC_shared); 8939 ReportOriginalDSA(*this, DSAStack, D, DVar); 8940 continue; 8941 } 8942 8943 DeclRefExpr *Ref = nullptr; 8944 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext()) 8945 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 8946 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref); 8947 Vars.push_back((VD || !Ref || CurContext->isDependentContext()) 8948 ? RefExpr->IgnoreParens() 8949 : Ref); 8950 } 8951 8952 if (Vars.empty()) 8953 return nullptr; 8954 8955 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars); 8956 } 8957 8958 namespace { 8959 class DSARefChecker : public StmtVisitor<DSARefChecker, bool> { 8960 DSAStackTy *Stack; 8961 8962 public: 8963 bool VisitDeclRefExpr(DeclRefExpr *E) { 8964 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) { 8965 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false); 8966 if (DVar.CKind == OMPC_shared && !DVar.RefExpr) 8967 return false; 8968 if (DVar.CKind != OMPC_unknown) 8969 return true; 8970 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA( 8971 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; }, 8972 /*FromParent=*/true); 8973 if (DVarPrivate.CKind != OMPC_unknown) 8974 return true; 8975 return false; 8976 } 8977 return false; 8978 } 8979 bool VisitStmt(Stmt *S) { 8980 for (auto Child : S->children()) { 8981 if (Child && Visit(Child)) 8982 return true; 8983 } 8984 return false; 8985 } 8986 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {} 8987 }; 8988 } // namespace 8989 8990 namespace { 8991 // Transform MemberExpression for specified FieldDecl of current class to 8992 // DeclRefExpr to specified OMPCapturedExprDecl. 8993 class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> { 8994 typedef TreeTransform<TransformExprToCaptures> BaseTransform; 8995 ValueDecl *Field; 8996 DeclRefExpr *CapturedExpr; 8997 8998 public: 8999 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl) 9000 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {} 9001 9002 ExprResult TransformMemberExpr(MemberExpr *E) { 9003 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) && 9004 E->getMemberDecl() == Field) { 9005 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false); 9006 return CapturedExpr; 9007 } 9008 return BaseTransform::TransformMemberExpr(E); 9009 } 9010 DeclRefExpr *getCapturedExpr() { return CapturedExpr; } 9011 }; 9012 } // namespace 9013 9014 template <typename T> 9015 static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups, 9016 const llvm::function_ref<T(ValueDecl *)> &Gen) { 9017 for (auto &Set : Lookups) { 9018 for (auto *D : Set) { 9019 if (auto Res = Gen(cast<ValueDecl>(D))) 9020 return Res; 9021 } 9022 } 9023 return T(); 9024 } 9025 9026 static ExprResult 9027 buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range, 9028 Scope *S, CXXScopeSpec &ReductionIdScopeSpec, 9029 const DeclarationNameInfo &ReductionId, QualType Ty, 9030 CXXCastPath &BasePath, Expr *UnresolvedReduction) { 9031 if (ReductionIdScopeSpec.isInvalid()) 9032 return ExprError(); 9033 SmallVector<UnresolvedSet<8>, 4> Lookups; 9034 if (S) { 9035 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName); 9036 Lookup.suppressDiagnostics(); 9037 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) { 9038 auto *D = Lookup.getRepresentativeDecl(); 9039 do { 9040 S = S->getParent(); 9041 } while (S && !S->isDeclScope(D)); 9042 if (S) 9043 S = S->getParent(); 9044 Lookups.push_back(UnresolvedSet<8>()); 9045 Lookups.back().append(Lookup.begin(), Lookup.end()); 9046 Lookup.clear(); 9047 } 9048 } else if (auto *ULE = 9049 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) { 9050 Lookups.push_back(UnresolvedSet<8>()); 9051 Decl *PrevD = nullptr; 9052 for (auto *D : ULE->decls()) { 9053 if (D == PrevD) 9054 Lookups.push_back(UnresolvedSet<8>()); 9055 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D)) 9056 Lookups.back().addDecl(DRD); 9057 PrevD = D; 9058 } 9059 } 9060 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() || 9061 Ty->isInstantiationDependentType() || 9062 Ty->containsUnexpandedParameterPack() || 9063 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool { 9064 return !D->isInvalidDecl() && 9065 (D->getType()->isDependentType() || 9066 D->getType()->isInstantiationDependentType() || 9067 D->getType()->containsUnexpandedParameterPack()); 9068 })) { 9069 UnresolvedSet<8> ResSet; 9070 for (auto &Set : Lookups) { 9071 ResSet.append(Set.begin(), Set.end()); 9072 // The last item marks the end of all declarations at the specified scope. 9073 ResSet.addDecl(Set[Set.size() - 1]); 9074 } 9075 return UnresolvedLookupExpr::Create( 9076 SemaRef.Context, /*NamingClass=*/nullptr, 9077 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId, 9078 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end()); 9079 } 9080 if (auto *VD = filterLookupForUDR<ValueDecl *>( 9081 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * { 9082 if (!D->isInvalidDecl() && 9083 SemaRef.Context.hasSameType(D->getType(), Ty)) 9084 return D; 9085 return nullptr; 9086 })) 9087 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 9088 if (auto *VD = filterLookupForUDR<ValueDecl *>( 9089 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * { 9090 if (!D->isInvalidDecl() && 9091 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) && 9092 !Ty.isMoreQualifiedThan(D->getType())) 9093 return D; 9094 return nullptr; 9095 })) { 9096 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true, 9097 /*DetectVirtual=*/false); 9098 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) { 9099 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType( 9100 VD->getType().getUnqualifiedType()))) { 9101 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(), 9102 /*DiagID=*/0) != 9103 Sema::AR_inaccessible) { 9104 SemaRef.BuildBasePathArray(Paths, BasePath); 9105 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc); 9106 } 9107 } 9108 } 9109 } 9110 if (ReductionIdScopeSpec.isSet()) { 9111 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range; 9112 return ExprError(); 9113 } 9114 return ExprEmpty(); 9115 } 9116 9117 namespace { 9118 /// Data for the reduction-based clauses. 9119 struct ReductionData { 9120 /// List of original reduction items. 9121 SmallVector<Expr *, 8> Vars; 9122 /// List of private copies of the reduction items. 9123 SmallVector<Expr *, 8> Privates; 9124 /// LHS expressions for the reduction_op expressions. 9125 SmallVector<Expr *, 8> LHSs; 9126 /// RHS expressions for the reduction_op expressions. 9127 SmallVector<Expr *, 8> RHSs; 9128 /// Reduction operation expression. 9129 SmallVector<Expr *, 8> ReductionOps; 9130 /// Taskgroup descriptors for the corresponding reduction items in 9131 /// in_reduction clauses. 9132 SmallVector<Expr *, 8> TaskgroupDescriptors; 9133 /// List of captures for clause. 9134 SmallVector<Decl *, 4> ExprCaptures; 9135 /// List of postupdate expressions. 9136 SmallVector<Expr *, 4> ExprPostUpdates; 9137 ReductionData() = delete; 9138 /// Reserves required memory for the reduction data. 9139 ReductionData(unsigned Size) { 9140 Vars.reserve(Size); 9141 Privates.reserve(Size); 9142 LHSs.reserve(Size); 9143 RHSs.reserve(Size); 9144 ReductionOps.reserve(Size); 9145 TaskgroupDescriptors.reserve(Size); 9146 ExprCaptures.reserve(Size); 9147 ExprPostUpdates.reserve(Size); 9148 } 9149 /// Stores reduction item and reduction operation only (required for dependent 9150 /// reduction item). 9151 void push(Expr *Item, Expr *ReductionOp) { 9152 Vars.emplace_back(Item); 9153 Privates.emplace_back(nullptr); 9154 LHSs.emplace_back(nullptr); 9155 RHSs.emplace_back(nullptr); 9156 ReductionOps.emplace_back(ReductionOp); 9157 TaskgroupDescriptors.emplace_back(nullptr); 9158 } 9159 /// Stores reduction data. 9160 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp, 9161 Expr *TaskgroupDescriptor) { 9162 Vars.emplace_back(Item); 9163 Privates.emplace_back(Private); 9164 LHSs.emplace_back(LHS); 9165 RHSs.emplace_back(RHS); 9166 ReductionOps.emplace_back(ReductionOp); 9167 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor); 9168 } 9169 }; 9170 } // namespace 9171 9172 static bool ActOnOMPReductionKindClause( 9173 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind, 9174 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 9175 SourceLocation ColonLoc, SourceLocation EndLoc, 9176 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 9177 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) { 9178 auto DN = ReductionId.getName(); 9179 auto OOK = DN.getCXXOverloadedOperator(); 9180 BinaryOperatorKind BOK = BO_Comma; 9181 9182 ASTContext &Context = S.Context; 9183 // OpenMP [2.14.3.6, reduction clause] 9184 // C 9185 // reduction-identifier is either an identifier or one of the following 9186 // operators: +, -, *, &, |, ^, && and || 9187 // C++ 9188 // reduction-identifier is either an id-expression or one of the following 9189 // operators: +, -, *, &, |, ^, && and || 9190 switch (OOK) { 9191 case OO_Plus: 9192 case OO_Minus: 9193 BOK = BO_Add; 9194 break; 9195 case OO_Star: 9196 BOK = BO_Mul; 9197 break; 9198 case OO_Amp: 9199 BOK = BO_And; 9200 break; 9201 case OO_Pipe: 9202 BOK = BO_Or; 9203 break; 9204 case OO_Caret: 9205 BOK = BO_Xor; 9206 break; 9207 case OO_AmpAmp: 9208 BOK = BO_LAnd; 9209 break; 9210 case OO_PipePipe: 9211 BOK = BO_LOr; 9212 break; 9213 case OO_New: 9214 case OO_Delete: 9215 case OO_Array_New: 9216 case OO_Array_Delete: 9217 case OO_Slash: 9218 case OO_Percent: 9219 case OO_Tilde: 9220 case OO_Exclaim: 9221 case OO_Equal: 9222 case OO_Less: 9223 case OO_Greater: 9224 case OO_LessEqual: 9225 case OO_GreaterEqual: 9226 case OO_PlusEqual: 9227 case OO_MinusEqual: 9228 case OO_StarEqual: 9229 case OO_SlashEqual: 9230 case OO_PercentEqual: 9231 case OO_CaretEqual: 9232 case OO_AmpEqual: 9233 case OO_PipeEqual: 9234 case OO_LessLess: 9235 case OO_GreaterGreater: 9236 case OO_LessLessEqual: 9237 case OO_GreaterGreaterEqual: 9238 case OO_EqualEqual: 9239 case OO_ExclaimEqual: 9240 case OO_PlusPlus: 9241 case OO_MinusMinus: 9242 case OO_Comma: 9243 case OO_ArrowStar: 9244 case OO_Arrow: 9245 case OO_Call: 9246 case OO_Subscript: 9247 case OO_Conditional: 9248 case OO_Coawait: 9249 case NUM_OVERLOADED_OPERATORS: 9250 llvm_unreachable("Unexpected reduction identifier"); 9251 case OO_None: 9252 if (auto *II = DN.getAsIdentifierInfo()) { 9253 if (II->isStr("max")) 9254 BOK = BO_GT; 9255 else if (II->isStr("min")) 9256 BOK = BO_LT; 9257 } 9258 break; 9259 } 9260 SourceRange ReductionIdRange; 9261 if (ReductionIdScopeSpec.isValid()) 9262 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc()); 9263 else 9264 ReductionIdRange.setBegin(ReductionId.getBeginLoc()); 9265 ReductionIdRange.setEnd(ReductionId.getEndLoc()); 9266 9267 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end(); 9268 bool FirstIter = true; 9269 for (auto RefExpr : VarList) { 9270 assert(RefExpr && "nullptr expr in OpenMP reduction clause."); 9271 // OpenMP [2.1, C/C++] 9272 // A list item is a variable or array section, subject to the restrictions 9273 // specified in Section 2.4 on page 42 and in each of the sections 9274 // describing clauses and directives for which a list appears. 9275 // OpenMP [2.14.3.3, Restrictions, p.1] 9276 // A variable that is part of another variable (as an array or 9277 // structure element) cannot appear in a private clause. 9278 if (!FirstIter && IR != ER) 9279 ++IR; 9280 FirstIter = false; 9281 SourceLocation ELoc; 9282 SourceRange ERange; 9283 Expr *SimpleRefExpr = RefExpr; 9284 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange, 9285 /*AllowArraySection=*/true); 9286 if (Res.second) { 9287 // Try to find 'declare reduction' corresponding construct before using 9288 // builtin/overloaded operators. 9289 QualType Type = Context.DependentTy; 9290 CXXCastPath BasePath; 9291 ExprResult DeclareReductionRef = buildDeclareReductionRef( 9292 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 9293 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 9294 Expr *ReductionOp = nullptr; 9295 if (S.CurContext->isDependentContext() && 9296 (DeclareReductionRef.isUnset() || 9297 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) 9298 ReductionOp = DeclareReductionRef.get(); 9299 // It will be analyzed later. 9300 RD.push(RefExpr, ReductionOp); 9301 } 9302 ValueDecl *D = Res.first; 9303 if (!D) 9304 continue; 9305 9306 Expr *TaskgroupDescriptor = nullptr; 9307 QualType Type; 9308 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens()); 9309 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens()); 9310 if (ASE) 9311 Type = ASE->getType().getNonReferenceType(); 9312 else if (OASE) { 9313 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase()); 9314 if (auto *ATy = BaseType->getAsArrayTypeUnsafe()) 9315 Type = ATy->getElementType(); 9316 else 9317 Type = BaseType->getPointeeType(); 9318 Type = Type.getNonReferenceType(); 9319 } else 9320 Type = Context.getBaseElementType(D->getType().getNonReferenceType()); 9321 auto *VD = dyn_cast<VarDecl>(D); 9322 9323 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3] 9324 // A variable that appears in a private clause must not have an incomplete 9325 // type or a reference type. 9326 if (S.RequireCompleteType(ELoc, Type, 9327 diag::err_omp_reduction_incomplete_type)) 9328 continue; 9329 // OpenMP [2.14.3.6, reduction clause, Restrictions] 9330 // A list item that appears in a reduction clause must not be 9331 // const-qualified. 9332 if (Type.getNonReferenceType().isConstant(Context)) { 9333 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange; 9334 if (!ASE && !OASE) { 9335 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 9336 VarDecl::DeclarationOnly; 9337 S.Diag(D->getLocation(), 9338 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9339 << D; 9340 } 9341 continue; 9342 } 9343 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4] 9344 // If a list-item is a reference type then it must bind to the same object 9345 // for all threads of the team. 9346 if (!ASE && !OASE && VD) { 9347 VarDecl *VDDef = VD->getDefinition(); 9348 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) { 9349 DSARefChecker Check(Stack); 9350 if (Check.Visit(VDDef->getInit())) { 9351 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg) 9352 << getOpenMPClauseName(ClauseKind) << ERange; 9353 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef; 9354 continue; 9355 } 9356 } 9357 } 9358 9359 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced 9360 // in a Construct] 9361 // Variables with the predetermined data-sharing attributes may not be 9362 // listed in data-sharing attributes clauses, except for the cases 9363 // listed below. For these exceptions only, listing a predetermined 9364 // variable in a data-sharing attribute clause is allowed and overrides 9365 // the variable's predetermined data-sharing attributes. 9366 // OpenMP [2.14.3.6, Restrictions, p.3] 9367 // Any number of reduction clauses can be specified on the directive, 9368 // but a list item can appear only once in the reduction clauses for that 9369 // directive. 9370 DSAStackTy::DSAVarData DVar; 9371 DVar = Stack->getTopDSA(D, false); 9372 if (DVar.CKind == OMPC_reduction) { 9373 S.Diag(ELoc, diag::err_omp_once_referenced) 9374 << getOpenMPClauseName(ClauseKind); 9375 if (DVar.RefExpr) 9376 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced); 9377 continue; 9378 } else if (DVar.CKind != OMPC_unknown) { 9379 S.Diag(ELoc, diag::err_omp_wrong_dsa) 9380 << getOpenMPClauseName(DVar.CKind) 9381 << getOpenMPClauseName(OMPC_reduction); 9382 ReportOriginalDSA(S, Stack, D, DVar); 9383 continue; 9384 } 9385 9386 // OpenMP [2.14.3.6, Restrictions, p.1] 9387 // A list item that appears in a reduction clause of a worksharing 9388 // construct must be shared in the parallel regions to which any of the 9389 // worksharing regions arising from the worksharing construct bind. 9390 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective(); 9391 if (isOpenMPWorksharingDirective(CurrDir) && 9392 !isOpenMPParallelDirective(CurrDir) && 9393 !isOpenMPTeamsDirective(CurrDir)) { 9394 DVar = Stack->getImplicitDSA(D, true); 9395 if (DVar.CKind != OMPC_shared) { 9396 S.Diag(ELoc, diag::err_omp_required_access) 9397 << getOpenMPClauseName(OMPC_reduction) 9398 << getOpenMPClauseName(OMPC_shared); 9399 ReportOriginalDSA(S, Stack, D, DVar); 9400 continue; 9401 } 9402 } 9403 9404 // Try to find 'declare reduction' corresponding construct before using 9405 // builtin/overloaded operators. 9406 CXXCastPath BasePath; 9407 ExprResult DeclareReductionRef = buildDeclareReductionRef( 9408 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec, 9409 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR); 9410 if (DeclareReductionRef.isInvalid()) 9411 continue; 9412 if (S.CurContext->isDependentContext() && 9413 (DeclareReductionRef.isUnset() || 9414 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) { 9415 RD.push(RefExpr, DeclareReductionRef.get()); 9416 continue; 9417 } 9418 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) { 9419 // Not allowed reduction identifier is found. 9420 S.Diag(ReductionId.getLocStart(), 9421 diag::err_omp_unknown_reduction_identifier) 9422 << Type << ReductionIdRange; 9423 continue; 9424 } 9425 9426 // OpenMP [2.14.3.6, reduction clause, Restrictions] 9427 // The type of a list item that appears in a reduction clause must be valid 9428 // for the reduction-identifier. For a max or min reduction in C, the type 9429 // of the list item must be an allowed arithmetic data type: char, int, 9430 // float, double, or _Bool, possibly modified with long, short, signed, or 9431 // unsigned. For a max or min reduction in C++, the type of the list item 9432 // must be an allowed arithmetic data type: char, wchar_t, int, float, 9433 // double, or bool, possibly modified with long, short, signed, or unsigned. 9434 if (DeclareReductionRef.isUnset()) { 9435 if ((BOK == BO_GT || BOK == BO_LT) && 9436 !(Type->isScalarType() || 9437 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) { 9438 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg) 9439 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus; 9440 if (!ASE && !OASE) { 9441 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 9442 VarDecl::DeclarationOnly; 9443 S.Diag(D->getLocation(), 9444 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9445 << D; 9446 } 9447 continue; 9448 } 9449 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) && 9450 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) { 9451 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg) 9452 << getOpenMPClauseName(ClauseKind); 9453 if (!ASE && !OASE) { 9454 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 9455 VarDecl::DeclarationOnly; 9456 S.Diag(D->getLocation(), 9457 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9458 << D; 9459 } 9460 continue; 9461 } 9462 } 9463 9464 Type = Type.getNonLValueExprType(Context).getUnqualifiedType(); 9465 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs", 9466 D->hasAttrs() ? &D->getAttrs() : nullptr); 9467 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(), 9468 D->hasAttrs() ? &D->getAttrs() : nullptr); 9469 auto PrivateTy = Type; 9470 if (OASE || 9471 (!ASE && 9472 D->getType().getNonReferenceType()->isVariablyModifiedType())) { 9473 // For arrays/array sections only: 9474 // Create pseudo array type for private copy. The size for this array will 9475 // be generated during codegen. 9476 // For array subscripts or single variables Private Ty is the same as Type 9477 // (type of the variable or single array element). 9478 PrivateTy = Context.getVariableArrayType( 9479 Type, 9480 new (Context) OpaqueValueExpr(SourceLocation(), Context.getSizeType(), 9481 VK_RValue), 9482 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange()); 9483 } else if (!ASE && !OASE && 9484 Context.getAsArrayType(D->getType().getNonReferenceType())) 9485 PrivateTy = D->getType().getNonReferenceType(); 9486 // Private copy. 9487 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(), 9488 D->hasAttrs() ? &D->getAttrs() : nullptr); 9489 // Add initializer for private variable. 9490 Expr *Init = nullptr; 9491 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc); 9492 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc); 9493 if (DeclareReductionRef.isUsable()) { 9494 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>(); 9495 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl()); 9496 if (DRD->getInitializer()) { 9497 Init = DRDRef; 9498 RHSVD->setInit(DRDRef); 9499 RHSVD->setInitStyle(VarDecl::CallInit); 9500 } 9501 } else { 9502 switch (BOK) { 9503 case BO_Add: 9504 case BO_Xor: 9505 case BO_Or: 9506 case BO_LOr: 9507 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'. 9508 if (Type->isScalarType() || Type->isAnyComplexType()) 9509 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get(); 9510 break; 9511 case BO_Mul: 9512 case BO_LAnd: 9513 if (Type->isScalarType() || Type->isAnyComplexType()) { 9514 // '*' and '&&' reduction ops - initializer is '1'. 9515 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get(); 9516 } 9517 break; 9518 case BO_And: { 9519 // '&' reduction op - initializer is '~0'. 9520 QualType OrigType = Type; 9521 if (auto *ComplexTy = OrigType->getAs<ComplexType>()) 9522 Type = ComplexTy->getElementType(); 9523 if (Type->isRealFloatingType()) { 9524 llvm::APFloat InitValue = 9525 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type), 9526 /*isIEEE=*/true); 9527 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 9528 Type, ELoc); 9529 } else if (Type->isScalarType()) { 9530 auto Size = Context.getTypeSize(Type); 9531 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0); 9532 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size); 9533 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 9534 } 9535 if (Init && OrigType->isAnyComplexType()) { 9536 // Init = 0xFFFF + 0xFFFFi; 9537 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType); 9538 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get(); 9539 } 9540 Type = OrigType; 9541 break; 9542 } 9543 case BO_LT: 9544 case BO_GT: { 9545 // 'min' reduction op - initializer is 'Largest representable number in 9546 // the reduction list item type'. 9547 // 'max' reduction op - initializer is 'Least representable number in 9548 // the reduction list item type'. 9549 if (Type->isIntegerType() || Type->isPointerType()) { 9550 bool IsSigned = Type->hasSignedIntegerRepresentation(); 9551 auto Size = Context.getTypeSize(Type); 9552 QualType IntTy = 9553 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned); 9554 llvm::APInt InitValue = 9555 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size) 9556 : llvm::APInt::getMinValue(Size) 9557 : IsSigned ? llvm::APInt::getSignedMaxValue(Size) 9558 : llvm::APInt::getMaxValue(Size); 9559 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc); 9560 if (Type->isPointerType()) { 9561 // Cast to pointer type. 9562 auto CastExpr = S.BuildCStyleCastExpr( 9563 SourceLocation(), Context.getTrivialTypeSourceInfo(Type, ELoc), 9564 SourceLocation(), Init); 9565 if (CastExpr.isInvalid()) 9566 continue; 9567 Init = CastExpr.get(); 9568 } 9569 } else if (Type->isRealFloatingType()) { 9570 llvm::APFloat InitValue = llvm::APFloat::getLargest( 9571 Context.getFloatTypeSemantics(Type), BOK != BO_LT); 9572 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true, 9573 Type, ELoc); 9574 } 9575 break; 9576 } 9577 case BO_PtrMemD: 9578 case BO_PtrMemI: 9579 case BO_MulAssign: 9580 case BO_Div: 9581 case BO_Rem: 9582 case BO_Sub: 9583 case BO_Shl: 9584 case BO_Shr: 9585 case BO_LE: 9586 case BO_GE: 9587 case BO_EQ: 9588 case BO_NE: 9589 case BO_AndAssign: 9590 case BO_XorAssign: 9591 case BO_OrAssign: 9592 case BO_Assign: 9593 case BO_AddAssign: 9594 case BO_SubAssign: 9595 case BO_DivAssign: 9596 case BO_RemAssign: 9597 case BO_ShlAssign: 9598 case BO_ShrAssign: 9599 case BO_Comma: 9600 llvm_unreachable("Unexpected reduction operation"); 9601 } 9602 } 9603 if (Init && DeclareReductionRef.isUnset()) 9604 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false); 9605 else if (!Init) 9606 S.ActOnUninitializedDecl(RHSVD); 9607 if (RHSVD->isInvalidDecl()) 9608 continue; 9609 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) { 9610 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible) 9611 << Type << ReductionIdRange; 9612 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) == 9613 VarDecl::DeclarationOnly; 9614 S.Diag(D->getLocation(), 9615 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9616 << D; 9617 continue; 9618 } 9619 // Store initializer for single element in private copy. Will be used during 9620 // codegen. 9621 PrivateVD->setInit(RHSVD->getInit()); 9622 PrivateVD->setInitStyle(RHSVD->getInitStyle()); 9623 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc); 9624 ExprResult ReductionOp; 9625 if (DeclareReductionRef.isUsable()) { 9626 QualType RedTy = DeclareReductionRef.get()->getType(); 9627 QualType PtrRedTy = Context.getPointerType(RedTy); 9628 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE); 9629 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE); 9630 if (!BasePath.empty()) { 9631 LHS = S.DefaultLvalueConversion(LHS.get()); 9632 RHS = S.DefaultLvalueConversion(RHS.get()); 9633 LHS = ImplicitCastExpr::Create(Context, PtrRedTy, 9634 CK_UncheckedDerivedToBase, LHS.get(), 9635 &BasePath, LHS.get()->getValueKind()); 9636 RHS = ImplicitCastExpr::Create(Context, PtrRedTy, 9637 CK_UncheckedDerivedToBase, RHS.get(), 9638 &BasePath, RHS.get()->getValueKind()); 9639 } 9640 FunctionProtoType::ExtProtoInfo EPI; 9641 QualType Params[] = {PtrRedTy, PtrRedTy}; 9642 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI); 9643 auto *OVE = new (Context) OpaqueValueExpr( 9644 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary, 9645 S.DefaultLvalueConversion(DeclareReductionRef.get()).get()); 9646 Expr *Args[] = {LHS.get(), RHS.get()}; 9647 ReductionOp = new (Context) 9648 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc); 9649 } else { 9650 ReductionOp = S.BuildBinOp( 9651 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE); 9652 if (ReductionOp.isUsable()) { 9653 if (BOK != BO_LT && BOK != BO_GT) { 9654 ReductionOp = 9655 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(), 9656 BO_Assign, LHSDRE, ReductionOp.get()); 9657 } else { 9658 auto *ConditionalOp = new (Context) ConditionalOperator( 9659 ReductionOp.get(), SourceLocation(), LHSDRE, SourceLocation(), 9660 RHSDRE, Type, VK_LValue, OK_Ordinary); 9661 ReductionOp = 9662 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(), 9663 BO_Assign, LHSDRE, ConditionalOp); 9664 } 9665 if (ReductionOp.isUsable()) 9666 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get()); 9667 } 9668 if (!ReductionOp.isUsable()) 9669 continue; 9670 } 9671 9672 // OpenMP [2.15.4.6, Restrictions, p.2] 9673 // A list item that appears in an in_reduction clause of a task construct 9674 // must appear in a task_reduction clause of a construct associated with a 9675 // taskgroup region that includes the participating task in its taskgroup 9676 // set. The construct associated with the innermost region that meets this 9677 // condition must specify the same reduction-identifier as the in_reduction 9678 // clause. 9679 if (ClauseKind == OMPC_in_reduction) { 9680 SourceRange ParentSR; 9681 BinaryOperatorKind ParentBOK; 9682 const Expr *ParentReductionOp; 9683 Expr *ParentBOKTD, *ParentReductionOpTD; 9684 DSAStackTy::DSAVarData ParentBOKDSA = 9685 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK, 9686 ParentBOKTD); 9687 DSAStackTy::DSAVarData ParentReductionOpDSA = 9688 Stack->getTopMostTaskgroupReductionData( 9689 D, ParentSR, ParentReductionOp, ParentReductionOpTD); 9690 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown; 9691 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown; 9692 if (!IsParentBOK && !IsParentReductionOp) { 9693 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction); 9694 continue; 9695 } 9696 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) || 9697 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK || 9698 IsParentReductionOp) { 9699 bool EmitError = true; 9700 if (IsParentReductionOp && DeclareReductionRef.isUsable()) { 9701 llvm::FoldingSetNodeID RedId, ParentRedId; 9702 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true); 9703 DeclareReductionRef.get()->Profile(RedId, Context, 9704 /*Canonical=*/true); 9705 EmitError = RedId != ParentRedId; 9706 } 9707 if (EmitError) { 9708 S.Diag(ReductionId.getLocStart(), 9709 diag::err_omp_reduction_identifier_mismatch) 9710 << ReductionIdRange << RefExpr->getSourceRange(); 9711 S.Diag(ParentSR.getBegin(), 9712 diag::note_omp_previous_reduction_identifier) 9713 << ParentSR 9714 << (IsParentBOK ? ParentBOKDSA.RefExpr 9715 : ParentReductionOpDSA.RefExpr) 9716 ->getSourceRange(); 9717 continue; 9718 } 9719 } 9720 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD; 9721 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined."); 9722 } 9723 9724 DeclRefExpr *Ref = nullptr; 9725 Expr *VarsExpr = RefExpr->IgnoreParens(); 9726 if (!VD && !S.CurContext->isDependentContext()) { 9727 if (ASE || OASE) { 9728 TransformExprToCaptures RebuildToCapture(S, D); 9729 VarsExpr = 9730 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get(); 9731 Ref = RebuildToCapture.getCapturedExpr(); 9732 } else { 9733 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false); 9734 } 9735 if (!S.IsOpenMPCapturedDecl(D)) { 9736 RD.ExprCaptures.emplace_back(Ref->getDecl()); 9737 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 9738 ExprResult RefRes = S.DefaultLvalueConversion(Ref); 9739 if (!RefRes.isUsable()) 9740 continue; 9741 ExprResult PostUpdateRes = 9742 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr, 9743 RefRes.get()); 9744 if (!PostUpdateRes.isUsable()) 9745 continue; 9746 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) || 9747 Stack->getCurrentDirective() == OMPD_taskgroup) { 9748 S.Diag(RefExpr->getExprLoc(), 9749 diag::err_omp_reduction_non_addressable_expression) 9750 << RefExpr->getSourceRange(); 9751 continue; 9752 } 9753 RD.ExprPostUpdates.emplace_back( 9754 S.IgnoredValueConversions(PostUpdateRes.get()).get()); 9755 } 9756 } 9757 } 9758 // All reduction items are still marked as reduction (to do not increase 9759 // code base size). 9760 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref); 9761 if (CurrDir == OMPD_taskgroup) { 9762 if (DeclareReductionRef.isUsable()) 9763 Stack->addTaskgroupReductionData(D, ReductionIdRange, 9764 DeclareReductionRef.get()); 9765 else 9766 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK); 9767 } 9768 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(), 9769 TaskgroupDescriptor); 9770 } 9771 return RD.Vars.empty(); 9772 } 9773 9774 OMPClause *Sema::ActOnOpenMPReductionClause( 9775 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 9776 SourceLocation ColonLoc, SourceLocation EndLoc, 9777 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 9778 ArrayRef<Expr *> UnresolvedReductions) { 9779 ReductionData RD(VarList.size()); 9780 9781 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList, 9782 StartLoc, LParenLoc, ColonLoc, EndLoc, 9783 ReductionIdScopeSpec, ReductionId, 9784 UnresolvedReductions, RD)) 9785 return nullptr; 9786 9787 return OMPReductionClause::Create( 9788 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 9789 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 9790 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 9791 buildPreInits(Context, RD.ExprCaptures), 9792 buildPostUpdate(*this, RD.ExprPostUpdates)); 9793 } 9794 9795 OMPClause *Sema::ActOnOpenMPTaskReductionClause( 9796 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 9797 SourceLocation ColonLoc, SourceLocation EndLoc, 9798 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 9799 ArrayRef<Expr *> UnresolvedReductions) { 9800 ReductionData RD(VarList.size()); 9801 9802 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, 9803 VarList, StartLoc, LParenLoc, ColonLoc, 9804 EndLoc, ReductionIdScopeSpec, ReductionId, 9805 UnresolvedReductions, RD)) 9806 return nullptr; 9807 9808 return OMPTaskReductionClause::Create( 9809 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 9810 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 9811 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, 9812 buildPreInits(Context, RD.ExprCaptures), 9813 buildPostUpdate(*this, RD.ExprPostUpdates)); 9814 } 9815 9816 OMPClause *Sema::ActOnOpenMPInReductionClause( 9817 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc, 9818 SourceLocation ColonLoc, SourceLocation EndLoc, 9819 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId, 9820 ArrayRef<Expr *> UnresolvedReductions) { 9821 ReductionData RD(VarList.size()); 9822 9823 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList, 9824 StartLoc, LParenLoc, ColonLoc, EndLoc, 9825 ReductionIdScopeSpec, ReductionId, 9826 UnresolvedReductions, RD)) 9827 return nullptr; 9828 9829 return OMPInReductionClause::Create( 9830 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars, 9831 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId, 9832 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors, 9833 buildPreInits(Context, RD.ExprCaptures), 9834 buildPostUpdate(*this, RD.ExprPostUpdates)); 9835 } 9836 9837 bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind, 9838 SourceLocation LinLoc) { 9839 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) || 9840 LinKind == OMPC_LINEAR_unknown) { 9841 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus; 9842 return true; 9843 } 9844 return false; 9845 } 9846 9847 bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc, 9848 OpenMPLinearClauseKind LinKind, 9849 QualType Type) { 9850 auto *VD = dyn_cast_or_null<VarDecl>(D); 9851 // A variable must not have an incomplete type or a reference type. 9852 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type)) 9853 return true; 9854 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) && 9855 !Type->isReferenceType()) { 9856 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference) 9857 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind); 9858 return true; 9859 } 9860 Type = Type.getNonReferenceType(); 9861 9862 // A list item must not be const-qualified. 9863 if (Type.isConstant(Context)) { 9864 Diag(ELoc, diag::err_omp_const_variable) 9865 << getOpenMPClauseName(OMPC_linear); 9866 if (D) { 9867 bool IsDecl = 9868 !VD || 9869 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9870 Diag(D->getLocation(), 9871 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9872 << D; 9873 } 9874 return true; 9875 } 9876 9877 // A list item must be of integral or pointer type. 9878 Type = Type.getUnqualifiedType().getCanonicalType(); 9879 const auto *Ty = Type.getTypePtrOrNull(); 9880 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) && 9881 !Ty->isPointerType())) { 9882 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type; 9883 if (D) { 9884 bool IsDecl = 9885 !VD || 9886 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 9887 Diag(D->getLocation(), 9888 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 9889 << D; 9890 } 9891 return true; 9892 } 9893 return false; 9894 } 9895 9896 OMPClause *Sema::ActOnOpenMPLinearClause( 9897 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc, 9898 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind, 9899 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 9900 SmallVector<Expr *, 8> Vars; 9901 SmallVector<Expr *, 8> Privates; 9902 SmallVector<Expr *, 8> Inits; 9903 SmallVector<Decl *, 4> ExprCaptures; 9904 SmallVector<Expr *, 4> ExprPostUpdates; 9905 if (CheckOpenMPLinearModifier(LinKind, LinLoc)) 9906 LinKind = OMPC_LINEAR_val; 9907 for (auto &RefExpr : VarList) { 9908 assert(RefExpr && "NULL expr in OpenMP linear clause."); 9909 SourceLocation ELoc; 9910 SourceRange ERange; 9911 Expr *SimpleRefExpr = RefExpr; 9912 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 9913 /*AllowArraySection=*/false); 9914 if (Res.second) { 9915 // It will be analyzed later. 9916 Vars.push_back(RefExpr); 9917 Privates.push_back(nullptr); 9918 Inits.push_back(nullptr); 9919 } 9920 ValueDecl *D = Res.first; 9921 if (!D) 9922 continue; 9923 9924 QualType Type = D->getType(); 9925 auto *VD = dyn_cast<VarDecl>(D); 9926 9927 // OpenMP [2.14.3.7, linear clause] 9928 // A list-item cannot appear in more than one linear clause. 9929 // A list-item that appears in a linear clause cannot appear in any 9930 // other data-sharing attribute clause. 9931 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false); 9932 if (DVar.RefExpr) { 9933 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind) 9934 << getOpenMPClauseName(OMPC_linear); 9935 ReportOriginalDSA(*this, DSAStack, D, DVar); 9936 continue; 9937 } 9938 9939 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type)) 9940 continue; 9941 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 9942 9943 // Build private copy of original var. 9944 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(), 9945 D->hasAttrs() ? &D->getAttrs() : nullptr); 9946 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc); 9947 // Build var to save initial value. 9948 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start"); 9949 Expr *InitExpr; 9950 DeclRefExpr *Ref = nullptr; 9951 if (!VD && !CurContext->isDependentContext()) { 9952 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false); 9953 if (!IsOpenMPCapturedDecl(D)) { 9954 ExprCaptures.push_back(Ref->getDecl()); 9955 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) { 9956 ExprResult RefRes = DefaultLvalueConversion(Ref); 9957 if (!RefRes.isUsable()) 9958 continue; 9959 ExprResult PostUpdateRes = 9960 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 9961 SimpleRefExpr, RefRes.get()); 9962 if (!PostUpdateRes.isUsable()) 9963 continue; 9964 ExprPostUpdates.push_back( 9965 IgnoredValueConversions(PostUpdateRes.get()).get()); 9966 } 9967 } 9968 } 9969 if (LinKind == OMPC_LINEAR_uval) 9970 InitExpr = VD ? VD->getInit() : SimpleRefExpr; 9971 else 9972 InitExpr = VD ? SimpleRefExpr : Ref; 9973 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(), 9974 /*DirectInit=*/false); 9975 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc); 9976 9977 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref); 9978 Vars.push_back((VD || CurContext->isDependentContext()) 9979 ? RefExpr->IgnoreParens() 9980 : Ref); 9981 Privates.push_back(PrivateRef); 9982 Inits.push_back(InitRef); 9983 } 9984 9985 if (Vars.empty()) 9986 return nullptr; 9987 9988 Expr *StepExpr = Step; 9989 Expr *CalcStepExpr = nullptr; 9990 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() && 9991 !Step->isInstantiationDependent() && 9992 !Step->containsUnexpandedParameterPack()) { 9993 SourceLocation StepLoc = Step->getLocStart(); 9994 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step); 9995 if (Val.isInvalid()) 9996 return nullptr; 9997 StepExpr = Val.get(); 9998 9999 // Build var to save the step value. 10000 VarDecl *SaveVar = 10001 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step"); 10002 ExprResult SaveRef = 10003 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc); 10004 ExprResult CalcStep = 10005 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr); 10006 CalcStep = ActOnFinishFullExpr(CalcStep.get()); 10007 10008 // Warn about zero linear step (it would be probably better specified as 10009 // making corresponding variables 'const'). 10010 llvm::APSInt Result; 10011 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context); 10012 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive()) 10013 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0] 10014 << (Vars.size() > 1); 10015 if (!IsConstant && CalcStep.isUsable()) { 10016 // Calculate the step beforehand instead of doing this on each iteration. 10017 // (This is not used if the number of iterations may be kfold-ed). 10018 CalcStepExpr = CalcStep.get(); 10019 } 10020 } 10021 10022 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc, 10023 ColonLoc, EndLoc, Vars, Privates, Inits, 10024 StepExpr, CalcStepExpr, 10025 buildPreInits(Context, ExprCaptures), 10026 buildPostUpdate(*this, ExprPostUpdates)); 10027 } 10028 10029 static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV, 10030 Expr *NumIterations, Sema &SemaRef, 10031 Scope *S, DSAStackTy *Stack) { 10032 // Walk the vars and build update/final expressions for the CodeGen. 10033 SmallVector<Expr *, 8> Updates; 10034 SmallVector<Expr *, 8> Finals; 10035 Expr *Step = Clause.getStep(); 10036 Expr *CalcStep = Clause.getCalcStep(); 10037 // OpenMP [2.14.3.7, linear clause] 10038 // If linear-step is not specified it is assumed to be 1. 10039 if (Step == nullptr) 10040 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(); 10041 else if (CalcStep) { 10042 Step = cast<BinaryOperator>(CalcStep)->getLHS(); 10043 } 10044 bool HasErrors = false; 10045 auto CurInit = Clause.inits().begin(); 10046 auto CurPrivate = Clause.privates().begin(); 10047 auto LinKind = Clause.getModifier(); 10048 for (auto &RefExpr : Clause.varlists()) { 10049 SourceLocation ELoc; 10050 SourceRange ERange; 10051 Expr *SimpleRefExpr = RefExpr; 10052 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange, 10053 /*AllowArraySection=*/false); 10054 ValueDecl *D = Res.first; 10055 if (Res.second || !D) { 10056 Updates.push_back(nullptr); 10057 Finals.push_back(nullptr); 10058 HasErrors = true; 10059 continue; 10060 } 10061 auto &&Info = Stack->isLoopControlVariable(D); 10062 Expr *InitExpr = *CurInit; 10063 10064 // Build privatized reference to the current linear var. 10065 auto *DE = cast<DeclRefExpr>(SimpleRefExpr); 10066 Expr *CapturedRef; 10067 if (LinKind == OMPC_LINEAR_uval) 10068 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit(); 10069 else 10070 CapturedRef = 10071 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()), 10072 DE->getType().getUnqualifiedType(), DE->getExprLoc(), 10073 /*RefersToCapture=*/true); 10074 10075 // Build update: Var = InitExpr + IV * Step 10076 ExprResult Update; 10077 if (!Info.first) { 10078 Update = 10079 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, 10080 InitExpr, IV, Step, /* Subtract */ false); 10081 } else 10082 Update = *CurPrivate; 10083 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(), 10084 /*DiscardedValue=*/true); 10085 10086 // Build final: Var = InitExpr + NumIterations * Step 10087 ExprResult Final; 10088 if (!Info.first) { 10089 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef, 10090 InitExpr, NumIterations, Step, 10091 /* Subtract */ false); 10092 } else 10093 Final = *CurPrivate; 10094 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(), 10095 /*DiscardedValue=*/true); 10096 10097 if (!Update.isUsable() || !Final.isUsable()) { 10098 Updates.push_back(nullptr); 10099 Finals.push_back(nullptr); 10100 HasErrors = true; 10101 } else { 10102 Updates.push_back(Update.get()); 10103 Finals.push_back(Final.get()); 10104 } 10105 ++CurInit; 10106 ++CurPrivate; 10107 } 10108 Clause.setUpdates(Updates); 10109 Clause.setFinals(Finals); 10110 return HasErrors; 10111 } 10112 10113 OMPClause *Sema::ActOnOpenMPAlignedClause( 10114 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc, 10115 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) { 10116 10117 SmallVector<Expr *, 8> Vars; 10118 for (auto &RefExpr : VarList) { 10119 assert(RefExpr && "NULL expr in OpenMP linear clause."); 10120 SourceLocation ELoc; 10121 SourceRange ERange; 10122 Expr *SimpleRefExpr = RefExpr; 10123 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 10124 /*AllowArraySection=*/false); 10125 if (Res.second) { 10126 // It will be analyzed later. 10127 Vars.push_back(RefExpr); 10128 } 10129 ValueDecl *D = Res.first; 10130 if (!D) 10131 continue; 10132 10133 QualType QType = D->getType(); 10134 auto *VD = dyn_cast<VarDecl>(D); 10135 10136 // OpenMP [2.8.1, simd construct, Restrictions] 10137 // The type of list items appearing in the aligned clause must be 10138 // array, pointer, reference to array, or reference to pointer. 10139 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType(); 10140 const Type *Ty = QType.getTypePtrOrNull(); 10141 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) { 10142 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr) 10143 << QType << getLangOpts().CPlusPlus << ERange; 10144 bool IsDecl = 10145 !VD || 10146 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10147 Diag(D->getLocation(), 10148 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10149 << D; 10150 continue; 10151 } 10152 10153 // OpenMP [2.8.1, simd construct, Restrictions] 10154 // A list-item cannot appear in more than one aligned clause. 10155 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) { 10156 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange; 10157 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa) 10158 << getOpenMPClauseName(OMPC_aligned); 10159 continue; 10160 } 10161 10162 DeclRefExpr *Ref = nullptr; 10163 if (!VD && IsOpenMPCapturedDecl(D)) 10164 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 10165 Vars.push_back(DefaultFunctionArrayConversion( 10166 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref) 10167 .get()); 10168 } 10169 10170 // OpenMP [2.8.1, simd construct, Description] 10171 // The parameter of the aligned clause, alignment, must be a constant 10172 // positive integer expression. 10173 // If no optional parameter is specified, implementation-defined default 10174 // alignments for SIMD instructions on the target platforms are assumed. 10175 if (Alignment != nullptr) { 10176 ExprResult AlignResult = 10177 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned); 10178 if (AlignResult.isInvalid()) 10179 return nullptr; 10180 Alignment = AlignResult.get(); 10181 } 10182 if (Vars.empty()) 10183 return nullptr; 10184 10185 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc, 10186 EndLoc, Vars, Alignment); 10187 } 10188 10189 OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList, 10190 SourceLocation StartLoc, 10191 SourceLocation LParenLoc, 10192 SourceLocation EndLoc) { 10193 SmallVector<Expr *, 8> Vars; 10194 SmallVector<Expr *, 8> SrcExprs; 10195 SmallVector<Expr *, 8> DstExprs; 10196 SmallVector<Expr *, 8> AssignmentOps; 10197 for (auto &RefExpr : VarList) { 10198 assert(RefExpr && "NULL expr in OpenMP copyin clause."); 10199 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 10200 // It will be analyzed later. 10201 Vars.push_back(RefExpr); 10202 SrcExprs.push_back(nullptr); 10203 DstExprs.push_back(nullptr); 10204 AssignmentOps.push_back(nullptr); 10205 continue; 10206 } 10207 10208 SourceLocation ELoc = RefExpr->getExprLoc(); 10209 // OpenMP [2.1, C/C++] 10210 // A list item is a variable name. 10211 // OpenMP [2.14.4.1, Restrictions, p.1] 10212 // A list item that appears in a copyin clause must be threadprivate. 10213 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr); 10214 if (!DE || !isa<VarDecl>(DE->getDecl())) { 10215 Diag(ELoc, diag::err_omp_expected_var_name_member_expr) 10216 << 0 << RefExpr->getSourceRange(); 10217 continue; 10218 } 10219 10220 Decl *D = DE->getDecl(); 10221 VarDecl *VD = cast<VarDecl>(D); 10222 10223 QualType Type = VD->getType(); 10224 if (Type->isDependentType() || Type->isInstantiationDependentType()) { 10225 // It will be analyzed later. 10226 Vars.push_back(DE); 10227 SrcExprs.push_back(nullptr); 10228 DstExprs.push_back(nullptr); 10229 AssignmentOps.push_back(nullptr); 10230 continue; 10231 } 10232 10233 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1] 10234 // A list item that appears in a copyin clause must be threadprivate. 10235 if (!DSAStack->isThreadPrivate(VD)) { 10236 Diag(ELoc, diag::err_omp_required_access) 10237 << getOpenMPClauseName(OMPC_copyin) 10238 << getOpenMPDirectiveName(OMPD_threadprivate); 10239 continue; 10240 } 10241 10242 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 10243 // A variable of class type (or array thereof) that appears in a 10244 // copyin clause requires an accessible, unambiguous copy assignment 10245 // operator for the class type. 10246 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType(); 10247 auto *SrcVD = 10248 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(), 10249 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr); 10250 auto *PseudoSrcExpr = buildDeclRefExpr( 10251 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc()); 10252 auto *DstVD = 10253 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst", 10254 VD->hasAttrs() ? &VD->getAttrs() : nullptr); 10255 auto *PseudoDstExpr = 10256 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc()); 10257 // For arrays generate assignment operation for single element and replace 10258 // it by the original array element in CodeGen. 10259 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, 10260 PseudoDstExpr, PseudoSrcExpr); 10261 if (AssignmentOp.isInvalid()) 10262 continue; 10263 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(), 10264 /*DiscardedValue=*/true); 10265 if (AssignmentOp.isInvalid()) 10266 continue; 10267 10268 DSAStack->addDSA(VD, DE, OMPC_copyin); 10269 Vars.push_back(DE); 10270 SrcExprs.push_back(PseudoSrcExpr); 10271 DstExprs.push_back(PseudoDstExpr); 10272 AssignmentOps.push_back(AssignmentOp.get()); 10273 } 10274 10275 if (Vars.empty()) 10276 return nullptr; 10277 10278 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars, 10279 SrcExprs, DstExprs, AssignmentOps); 10280 } 10281 10282 OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList, 10283 SourceLocation StartLoc, 10284 SourceLocation LParenLoc, 10285 SourceLocation EndLoc) { 10286 SmallVector<Expr *, 8> Vars; 10287 SmallVector<Expr *, 8> SrcExprs; 10288 SmallVector<Expr *, 8> DstExprs; 10289 SmallVector<Expr *, 8> AssignmentOps; 10290 for (auto &RefExpr : VarList) { 10291 assert(RefExpr && "NULL expr in OpenMP linear clause."); 10292 SourceLocation ELoc; 10293 SourceRange ERange; 10294 Expr *SimpleRefExpr = RefExpr; 10295 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange, 10296 /*AllowArraySection=*/false); 10297 if (Res.second) { 10298 // It will be analyzed later. 10299 Vars.push_back(RefExpr); 10300 SrcExprs.push_back(nullptr); 10301 DstExprs.push_back(nullptr); 10302 AssignmentOps.push_back(nullptr); 10303 } 10304 ValueDecl *D = Res.first; 10305 if (!D) 10306 continue; 10307 10308 QualType Type = D->getType(); 10309 auto *VD = dyn_cast<VarDecl>(D); 10310 10311 // OpenMP [2.14.4.2, Restrictions, p.2] 10312 // A list item that appears in a copyprivate clause may not appear in a 10313 // private or firstprivate clause on the single construct. 10314 if (!VD || !DSAStack->isThreadPrivate(VD)) { 10315 auto DVar = DSAStack->getTopDSA(D, false); 10316 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate && 10317 DVar.RefExpr) { 10318 Diag(ELoc, diag::err_omp_wrong_dsa) 10319 << getOpenMPClauseName(DVar.CKind) 10320 << getOpenMPClauseName(OMPC_copyprivate); 10321 ReportOriginalDSA(*this, DSAStack, D, DVar); 10322 continue; 10323 } 10324 10325 // OpenMP [2.11.4.2, Restrictions, p.1] 10326 // All list items that appear in a copyprivate clause must be either 10327 // threadprivate or private in the enclosing context. 10328 if (DVar.CKind == OMPC_unknown) { 10329 DVar = DSAStack->getImplicitDSA(D, false); 10330 if (DVar.CKind == OMPC_shared) { 10331 Diag(ELoc, diag::err_omp_required_access) 10332 << getOpenMPClauseName(OMPC_copyprivate) 10333 << "threadprivate or private in the enclosing context"; 10334 ReportOriginalDSA(*this, DSAStack, D, DVar); 10335 continue; 10336 } 10337 } 10338 } 10339 10340 // Variably modified types are not supported. 10341 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) { 10342 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported) 10343 << getOpenMPClauseName(OMPC_copyprivate) << Type 10344 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 10345 bool IsDecl = 10346 !VD || 10347 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly; 10348 Diag(D->getLocation(), 10349 IsDecl ? diag::note_previous_decl : diag::note_defined_here) 10350 << D; 10351 continue; 10352 } 10353 10354 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2] 10355 // A variable of class type (or array thereof) that appears in a 10356 // copyin clause requires an accessible, unambiguous copy assignment 10357 // operator for the class type. 10358 Type = Context.getBaseElementType(Type.getNonReferenceType()) 10359 .getUnqualifiedType(); 10360 auto *SrcVD = 10361 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src", 10362 D->hasAttrs() ? &D->getAttrs() : nullptr); 10363 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc); 10364 auto *DstVD = 10365 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst", 10366 D->hasAttrs() ? &D->getAttrs() : nullptr); 10367 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc); 10368 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, 10369 PseudoDstExpr, PseudoSrcExpr); 10370 if (AssignmentOp.isInvalid()) 10371 continue; 10372 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc, 10373 /*DiscardedValue=*/true); 10374 if (AssignmentOp.isInvalid()) 10375 continue; 10376 10377 // No need to mark vars as copyprivate, they are already threadprivate or 10378 // implicitly private. 10379 assert(VD || IsOpenMPCapturedDecl(D)); 10380 Vars.push_back( 10381 VD ? RefExpr->IgnoreParens() 10382 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false)); 10383 SrcExprs.push_back(PseudoSrcExpr); 10384 DstExprs.push_back(PseudoDstExpr); 10385 AssignmentOps.push_back(AssignmentOp.get()); 10386 } 10387 10388 if (Vars.empty()) 10389 return nullptr; 10390 10391 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10392 Vars, SrcExprs, DstExprs, AssignmentOps); 10393 } 10394 10395 OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList, 10396 SourceLocation StartLoc, 10397 SourceLocation LParenLoc, 10398 SourceLocation EndLoc) { 10399 if (VarList.empty()) 10400 return nullptr; 10401 10402 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList); 10403 } 10404 10405 OMPClause * 10406 Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind, 10407 SourceLocation DepLoc, SourceLocation ColonLoc, 10408 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 10409 SourceLocation LParenLoc, SourceLocation EndLoc) { 10410 if (DSAStack->getCurrentDirective() == OMPD_ordered && 10411 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) { 10412 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 10413 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend); 10414 return nullptr; 10415 } 10416 if (DSAStack->getCurrentDirective() != OMPD_ordered && 10417 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source || 10418 DepKind == OMPC_DEPEND_sink)) { 10419 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink}; 10420 Diag(DepLoc, diag::err_omp_unexpected_clause_value) 10421 << getListOfPossibleValues(OMPC_depend, /*First=*/0, 10422 /*Last=*/OMPC_DEPEND_unknown, Except) 10423 << getOpenMPClauseName(OMPC_depend); 10424 return nullptr; 10425 } 10426 SmallVector<Expr *, 8> Vars; 10427 DSAStackTy::OperatorOffsetTy OpsOffs; 10428 llvm::APSInt DepCounter(/*BitWidth=*/32); 10429 llvm::APSInt TotalDepCount(/*BitWidth=*/32); 10430 if (DepKind == OMPC_DEPEND_sink) { 10431 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) { 10432 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context); 10433 TotalDepCount.setIsUnsigned(/*Val=*/true); 10434 } 10435 } 10436 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) || 10437 DSAStack->getParentOrderedRegionParam()) { 10438 for (auto &RefExpr : VarList) { 10439 assert(RefExpr && "NULL expr in OpenMP shared clause."); 10440 if (isa<DependentScopeDeclRefExpr>(RefExpr)) { 10441 // It will be analyzed later. 10442 Vars.push_back(RefExpr); 10443 continue; 10444 } 10445 10446 SourceLocation ELoc = RefExpr->getExprLoc(); 10447 auto *SimpleExpr = RefExpr->IgnoreParenCasts(); 10448 if (DepKind == OMPC_DEPEND_sink) { 10449 if (DepCounter >= TotalDepCount) { 10450 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr); 10451 continue; 10452 } 10453 ++DepCounter; 10454 // OpenMP [2.13.9, Summary] 10455 // depend(dependence-type : vec), where dependence-type is: 10456 // 'sink' and where vec is the iteration vector, which has the form: 10457 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn] 10458 // where n is the value specified by the ordered clause in the loop 10459 // directive, xi denotes the loop iteration variable of the i-th nested 10460 // loop associated with the loop directive, and di is a constant 10461 // non-negative integer. 10462 if (CurContext->isDependentContext()) { 10463 // It will be analyzed later. 10464 Vars.push_back(RefExpr); 10465 continue; 10466 } 10467 SimpleExpr = SimpleExpr->IgnoreImplicit(); 10468 OverloadedOperatorKind OOK = OO_None; 10469 SourceLocation OOLoc; 10470 Expr *LHS = SimpleExpr; 10471 Expr *RHS = nullptr; 10472 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) { 10473 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode()); 10474 OOLoc = BO->getOperatorLoc(); 10475 LHS = BO->getLHS()->IgnoreParenImpCasts(); 10476 RHS = BO->getRHS()->IgnoreParenImpCasts(); 10477 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) { 10478 OOK = OCE->getOperator(); 10479 OOLoc = OCE->getOperatorLoc(); 10480 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 10481 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts(); 10482 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) { 10483 OOK = MCE->getMethodDecl() 10484 ->getNameInfo() 10485 .getName() 10486 .getCXXOverloadedOperator(); 10487 OOLoc = MCE->getCallee()->getExprLoc(); 10488 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts(); 10489 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts(); 10490 } 10491 SourceLocation ELoc; 10492 SourceRange ERange; 10493 auto Res = getPrivateItem(*this, LHS, ELoc, ERange, 10494 /*AllowArraySection=*/false); 10495 if (Res.second) { 10496 // It will be analyzed later. 10497 Vars.push_back(RefExpr); 10498 } 10499 ValueDecl *D = Res.first; 10500 if (!D) 10501 continue; 10502 10503 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) { 10504 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus); 10505 continue; 10506 } 10507 if (RHS) { 10508 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause( 10509 RHS, OMPC_depend, /*StrictlyPositive=*/false); 10510 if (RHSRes.isInvalid()) 10511 continue; 10512 } 10513 if (!CurContext->isDependentContext() && 10514 DSAStack->getParentOrderedRegionParam() && 10515 DepCounter != DSAStack->isParentLoopControlVariable(D).first) { 10516 ValueDecl* VD = DSAStack->getParentLoopControlVariable( 10517 DepCounter.getZExtValue()); 10518 if (VD) { 10519 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) 10520 << 1 << VD; 10521 } else { 10522 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0; 10523 } 10524 continue; 10525 } 10526 OpsOffs.push_back({RHS, OOK}); 10527 } else { 10528 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr); 10529 if (!RefExpr->IgnoreParenImpCasts()->isLValue() || 10530 (ASE && 10531 !ASE->getBase() 10532 ->getType() 10533 .getNonReferenceType() 10534 ->isPointerType() && 10535 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) { 10536 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 10537 << RefExpr->getSourceRange(); 10538 continue; 10539 } 10540 bool Suppress = getDiagnostics().getSuppressAllDiagnostics(); 10541 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true); 10542 ExprResult Res = CreateBuiltinUnaryOp(SourceLocation(), UO_AddrOf, 10543 RefExpr->IgnoreParenImpCasts()); 10544 getDiagnostics().setSuppressAllDiagnostics(Suppress); 10545 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) { 10546 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item) 10547 << RefExpr->getSourceRange(); 10548 continue; 10549 } 10550 } 10551 Vars.push_back(RefExpr->IgnoreParenImpCasts()); 10552 } 10553 10554 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink && 10555 TotalDepCount > VarList.size() && 10556 DSAStack->getParentOrderedRegionParam() && 10557 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) { 10558 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1 10559 << DSAStack->getParentLoopControlVariable(VarList.size() + 1); 10560 } 10561 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink && 10562 Vars.empty()) 10563 return nullptr; 10564 } 10565 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc, 10566 DepKind, DepLoc, ColonLoc, Vars); 10567 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) 10568 DSAStack->addDoacrossDependClause(C, OpsOffs); 10569 return C; 10570 } 10571 10572 OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc, 10573 SourceLocation LParenLoc, 10574 SourceLocation EndLoc) { 10575 Expr *ValExpr = Device; 10576 10577 // OpenMP [2.9.1, Restrictions] 10578 // The device expression must evaluate to a non-negative integer value. 10579 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device, 10580 /*StrictlyPositive=*/false)) 10581 return nullptr; 10582 10583 return new (Context) OMPDeviceClause(ValExpr, StartLoc, LParenLoc, EndLoc); 10584 } 10585 10586 static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef, 10587 DSAStackTy *Stack, QualType QTy) { 10588 NamedDecl *ND; 10589 if (QTy->isIncompleteType(&ND)) { 10590 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR; 10591 return false; 10592 } 10593 return true; 10594 } 10595 10596 /// \brief Return true if it can be proven that the provided array expression 10597 /// (array section or array subscript) does NOT specify the whole size of the 10598 /// array whose base type is \a BaseQTy. 10599 static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef, 10600 const Expr *E, 10601 QualType BaseQTy) { 10602 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 10603 10604 // If this is an array subscript, it refers to the whole size if the size of 10605 // the dimension is constant and equals 1. Also, an array section assumes the 10606 // format of an array subscript if no colon is used. 10607 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) { 10608 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 10609 return ATy->getSize().getSExtValue() != 1; 10610 // Size can't be evaluated statically. 10611 return false; 10612 } 10613 10614 assert(OASE && "Expecting array section if not an array subscript."); 10615 auto *LowerBound = OASE->getLowerBound(); 10616 auto *Length = OASE->getLength(); 10617 10618 // If there is a lower bound that does not evaluates to zero, we are not 10619 // covering the whole dimension. 10620 if (LowerBound) { 10621 llvm::APSInt ConstLowerBound; 10622 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext())) 10623 return false; // Can't get the integer value as a constant. 10624 if (ConstLowerBound.getSExtValue()) 10625 return true; 10626 } 10627 10628 // If we don't have a length we covering the whole dimension. 10629 if (!Length) 10630 return false; 10631 10632 // If the base is a pointer, we don't have a way to get the size of the 10633 // pointee. 10634 if (BaseQTy->isPointerType()) 10635 return false; 10636 10637 // We can only check if the length is the same as the size of the dimension 10638 // if we have a constant array. 10639 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()); 10640 if (!CATy) 10641 return false; 10642 10643 llvm::APSInt ConstLength; 10644 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 10645 return false; // Can't get the integer value as a constant. 10646 10647 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue(); 10648 } 10649 10650 // Return true if it can be proven that the provided array expression (array 10651 // section or array subscript) does NOT specify a single element of the array 10652 // whose base type is \a BaseQTy. 10653 static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef, 10654 const Expr *E, 10655 QualType BaseQTy) { 10656 auto *OASE = dyn_cast<OMPArraySectionExpr>(E); 10657 10658 // An array subscript always refer to a single element. Also, an array section 10659 // assumes the format of an array subscript if no colon is used. 10660 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) 10661 return false; 10662 10663 assert(OASE && "Expecting array section if not an array subscript."); 10664 auto *Length = OASE->getLength(); 10665 10666 // If we don't have a length we have to check if the array has unitary size 10667 // for this dimension. Also, we should always expect a length if the base type 10668 // is pointer. 10669 if (!Length) { 10670 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr())) 10671 return ATy->getSize().getSExtValue() != 1; 10672 // We cannot assume anything. 10673 return false; 10674 } 10675 10676 // Check if the length evaluates to 1. 10677 llvm::APSInt ConstLength; 10678 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext())) 10679 return false; // Can't get the integer value as a constant. 10680 10681 return ConstLength.getSExtValue() != 1; 10682 } 10683 10684 // Return the expression of the base of the mappable expression or null if it 10685 // cannot be determined and do all the necessary checks to see if the expression 10686 // is valid as a standalone mappable expression. In the process, record all the 10687 // components of the expression. 10688 static Expr *CheckMapClauseExpressionBase( 10689 Sema &SemaRef, Expr *E, 10690 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents, 10691 OpenMPClauseKind CKind) { 10692 SourceLocation ELoc = E->getExprLoc(); 10693 SourceRange ERange = E->getSourceRange(); 10694 10695 // The base of elements of list in a map clause have to be either: 10696 // - a reference to variable or field. 10697 // - a member expression. 10698 // - an array expression. 10699 // 10700 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the 10701 // reference to 'r'. 10702 // 10703 // If we have: 10704 // 10705 // struct SS { 10706 // Bla S; 10707 // foo() { 10708 // #pragma omp target map (S.Arr[:12]); 10709 // } 10710 // } 10711 // 10712 // We want to retrieve the member expression 'this->S'; 10713 10714 Expr *RelevantExpr = nullptr; 10715 10716 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2] 10717 // If a list item is an array section, it must specify contiguous storage. 10718 // 10719 // For this restriction it is sufficient that we make sure only references 10720 // to variables or fields and array expressions, and that no array sections 10721 // exist except in the rightmost expression (unless they cover the whole 10722 // dimension of the array). E.g. these would be invalid: 10723 // 10724 // r.ArrS[3:5].Arr[6:7] 10725 // 10726 // r.ArrS[3:5].x 10727 // 10728 // but these would be valid: 10729 // r.ArrS[3].Arr[6:7] 10730 // 10731 // r.ArrS[3].x 10732 10733 bool AllowUnitySizeArraySection = true; 10734 bool AllowWholeSizeArraySection = true; 10735 10736 while (!RelevantExpr) { 10737 E = E->IgnoreParenImpCasts(); 10738 10739 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) { 10740 if (!isa<VarDecl>(CurE->getDecl())) 10741 break; 10742 10743 RelevantExpr = CurE; 10744 10745 // If we got a reference to a declaration, we should not expect any array 10746 // section before that. 10747 AllowUnitySizeArraySection = false; 10748 AllowWholeSizeArraySection = false; 10749 10750 // Record the component. 10751 CurComponents.push_back(OMPClauseMappableExprCommon::MappableComponent( 10752 CurE, CurE->getDecl())); 10753 continue; 10754 } 10755 10756 if (auto *CurE = dyn_cast<MemberExpr>(E)) { 10757 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts(); 10758 10759 if (isa<CXXThisExpr>(BaseE)) 10760 // We found a base expression: this->Val. 10761 RelevantExpr = CurE; 10762 else 10763 E = BaseE; 10764 10765 if (!isa<FieldDecl>(CurE->getMemberDecl())) { 10766 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field) 10767 << CurE->getSourceRange(); 10768 break; 10769 } 10770 10771 auto *FD = cast<FieldDecl>(CurE->getMemberDecl()); 10772 10773 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3] 10774 // A bit-field cannot appear in a map clause. 10775 // 10776 if (FD->isBitField()) { 10777 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause) 10778 << CurE->getSourceRange() << getOpenMPClauseName(CKind); 10779 break; 10780 } 10781 10782 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 10783 // If the type of a list item is a reference to a type T then the type 10784 // will be considered to be T for all purposes of this clause. 10785 QualType CurType = BaseE->getType().getNonReferenceType(); 10786 10787 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2] 10788 // A list item cannot be a variable that is a member of a structure with 10789 // a union type. 10790 // 10791 if (auto *RT = CurType->getAs<RecordType>()) 10792 if (RT->isUnionType()) { 10793 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed) 10794 << CurE->getSourceRange(); 10795 break; 10796 } 10797 10798 // If we got a member expression, we should not expect any array section 10799 // before that: 10800 // 10801 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7] 10802 // If a list item is an element of a structure, only the rightmost symbol 10803 // of the variable reference can be an array section. 10804 // 10805 AllowUnitySizeArraySection = false; 10806 AllowWholeSizeArraySection = false; 10807 10808 // Record the component. 10809 CurComponents.push_back( 10810 OMPClauseMappableExprCommon::MappableComponent(CurE, FD)); 10811 continue; 10812 } 10813 10814 if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) { 10815 E = CurE->getBase()->IgnoreParenImpCasts(); 10816 10817 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) { 10818 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 10819 << 0 << CurE->getSourceRange(); 10820 break; 10821 } 10822 10823 // If we got an array subscript that express the whole dimension we 10824 // can have any array expressions before. If it only expressing part of 10825 // the dimension, we can only have unitary-size array expressions. 10826 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, 10827 E->getType())) 10828 AllowWholeSizeArraySection = false; 10829 10830 // Record the component - we don't have any declaration associated. 10831 CurComponents.push_back( 10832 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 10833 continue; 10834 } 10835 10836 if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) { 10837 E = CurE->getBase()->IgnoreParenImpCasts(); 10838 10839 auto CurType = 10840 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 10841 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 10844 // will be considered to be T for all purposes of this clause. 10845 if (CurType->isReferenceType()) 10846 CurType = CurType->getPointeeType(); 10847 10848 bool IsPointer = CurType->isAnyPointerType(); 10849 10850 if (!IsPointer && !CurType->isArrayType()) { 10851 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name) 10852 << 0 << CurE->getSourceRange(); 10853 break; 10854 } 10855 10856 bool NotWhole = 10857 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType); 10858 bool NotUnity = 10859 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType); 10860 10861 if (AllowWholeSizeArraySection) { 10862 // Any array section is currently allowed. Allowing a whole size array 10863 // section implies allowing a unity array section as well. 10864 // 10865 // If this array section refers to the whole dimension we can still 10866 // accept other array sections before this one, except if the base is a 10867 // pointer. Otherwise, only unitary sections are accepted. 10868 if (NotWhole || IsPointer) 10869 AllowWholeSizeArraySection = false; 10870 } else if (AllowUnitySizeArraySection && NotUnity) { 10871 // A unity or whole array section is not allowed and that is not 10872 // compatible with the properties of the current array section. 10873 SemaRef.Diag( 10874 ELoc, diag::err_array_section_does_not_specify_contiguous_storage) 10875 << CurE->getSourceRange(); 10876 break; 10877 } 10878 10879 // Record the component - we don't have any declaration associated. 10880 CurComponents.push_back( 10881 OMPClauseMappableExprCommon::MappableComponent(CurE, nullptr)); 10882 continue; 10883 } 10884 10885 // If nothing else worked, this is not a valid map clause expression. 10886 SemaRef.Diag(ELoc, 10887 diag::err_omp_expected_named_var_member_or_array_expression) 10888 << ERange; 10889 break; 10890 } 10891 10892 return RelevantExpr; 10893 } 10894 10895 // Return true if expression E associated with value VD has conflicts with other 10896 // map information. 10897 static bool CheckMapConflicts( 10898 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E, 10899 bool CurrentRegionOnly, 10900 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents, 10901 OpenMPClauseKind CKind) { 10902 assert(VD && E); 10903 SourceLocation ELoc = E->getExprLoc(); 10904 SourceRange ERange = E->getSourceRange(); 10905 10906 // In order to easily check the conflicts we need to match each component of 10907 // the expression under test with the components of the expressions that are 10908 // already in the stack. 10909 10910 assert(!CurComponents.empty() && "Map clause expression with no components!"); 10911 assert(CurComponents.back().getAssociatedDeclaration() == VD && 10912 "Map clause expression with unexpected base!"); 10913 10914 // Variables to help detecting enclosing problems in data environment nests. 10915 bool IsEnclosedByDataEnvironmentExpr = false; 10916 const Expr *EnclosingExpr = nullptr; 10917 10918 bool FoundError = DSAS->checkMappableExprComponentListsForDecl( 10919 VD, CurrentRegionOnly, 10920 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef 10921 StackComponents, 10922 OpenMPClauseKind) -> bool { 10923 10924 assert(!StackComponents.empty() && 10925 "Map clause expression with no components!"); 10926 assert(StackComponents.back().getAssociatedDeclaration() == VD && 10927 "Map clause expression with unexpected base!"); 10928 10929 // The whole expression in the stack. 10930 auto *RE = StackComponents.front().getAssociatedExpression(); 10931 10932 // Expressions must start from the same base. Here we detect at which 10933 // point both expressions diverge from each other and see if we can 10934 // detect if the memory referred to both expressions is contiguous and 10935 // do not overlap. 10936 auto CI = CurComponents.rbegin(); 10937 auto CE = CurComponents.rend(); 10938 auto SI = StackComponents.rbegin(); 10939 auto SE = StackComponents.rend(); 10940 for (; CI != CE && SI != SE; ++CI, ++SI) { 10941 10942 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3] 10943 // At most one list item can be an array item derived from a given 10944 // variable in map clauses of the same construct. 10945 if (CurrentRegionOnly && 10946 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) || 10947 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) && 10948 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) || 10949 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) { 10950 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(), 10951 diag::err_omp_multiple_array_items_in_map_clause) 10952 << CI->getAssociatedExpression()->getSourceRange(); 10953 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(), 10954 diag::note_used_here) 10955 << SI->getAssociatedExpression()->getSourceRange(); 10956 return true; 10957 } 10958 10959 // Do both expressions have the same kind? 10960 if (CI->getAssociatedExpression()->getStmtClass() != 10961 SI->getAssociatedExpression()->getStmtClass()) 10962 break; 10963 10964 // Are we dealing with different variables/fields? 10965 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration()) 10966 break; 10967 } 10968 // Check if the extra components of the expressions in the enclosing 10969 // data environment are redundant for the current base declaration. 10970 // If they are, the maps completely overlap, which is legal. 10971 for (; SI != SE; ++SI) { 10972 QualType Type; 10973 if (auto *ASE = 10974 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) { 10975 Type = ASE->getBase()->IgnoreParenImpCasts()->getType(); 10976 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>( 10977 SI->getAssociatedExpression())) { 10978 auto *E = OASE->getBase()->IgnoreParenImpCasts(); 10979 Type = 10980 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType(); 10981 } 10982 if (Type.isNull() || Type->isAnyPointerType() || 10983 CheckArrayExpressionDoesNotReferToWholeSize( 10984 SemaRef, SI->getAssociatedExpression(), Type)) 10985 break; 10986 } 10987 10988 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 10989 // List items of map clauses in the same construct must not share 10990 // original storage. 10991 // 10992 // If the expressions are exactly the same or one is a subset of the 10993 // other, it means they are sharing storage. 10994 if (CI == CE && SI == SE) { 10995 if (CurrentRegionOnly) { 10996 if (CKind == OMPC_map) 10997 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 10998 else { 10999 assert(CKind == OMPC_to || CKind == OMPC_from); 11000 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 11001 << ERange; 11002 } 11003 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 11004 << RE->getSourceRange(); 11005 return true; 11006 } else { 11007 // If we find the same expression in the enclosing data environment, 11008 // that is legal. 11009 IsEnclosedByDataEnvironmentExpr = true; 11010 return false; 11011 } 11012 } 11013 11014 QualType DerivedType = 11015 std::prev(CI)->getAssociatedDeclaration()->getType(); 11016 SourceLocation DerivedLoc = 11017 std::prev(CI)->getAssociatedExpression()->getExprLoc(); 11018 11019 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 11020 // If the type of a list item is a reference to a type T then the type 11021 // will be considered to be T for all purposes of this clause. 11022 DerivedType = DerivedType.getNonReferenceType(); 11023 11024 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1] 11025 // A variable for which the type is pointer and an array section 11026 // derived from that variable must not appear as list items of map 11027 // clauses of the same construct. 11028 // 11029 // Also, cover one of the cases in: 11030 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 11031 // If any part of the original storage of a list item has corresponding 11032 // storage in the device data environment, all of the original storage 11033 // must have corresponding storage in the device data environment. 11034 // 11035 if (DerivedType->isAnyPointerType()) { 11036 if (CI == CE || SI == SE) { 11037 SemaRef.Diag( 11038 DerivedLoc, 11039 diag::err_omp_pointer_mapped_along_with_derived_section) 11040 << DerivedLoc; 11041 } else { 11042 assert(CI != CE && SI != SE); 11043 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced) 11044 << DerivedLoc; 11045 } 11046 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 11047 << RE->getSourceRange(); 11048 return true; 11049 } 11050 11051 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4] 11052 // List items of map clauses in the same construct must not share 11053 // original storage. 11054 // 11055 // An expression is a subset of the other. 11056 if (CurrentRegionOnly && (CI == CE || SI == SE)) { 11057 if (CKind == OMPC_map) 11058 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange; 11059 else { 11060 assert(CKind == OMPC_to || CKind == OMPC_from); 11061 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update) 11062 << ERange; 11063 } 11064 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here) 11065 << RE->getSourceRange(); 11066 return true; 11067 } 11068 11069 // The current expression uses the same base as other expression in the 11070 // data environment but does not contain it completely. 11071 if (!CurrentRegionOnly && SI != SE) 11072 EnclosingExpr = RE; 11073 11074 // The current expression is a subset of the expression in the data 11075 // environment. 11076 IsEnclosedByDataEnvironmentExpr |= 11077 (!CurrentRegionOnly && CI != CE && SI == SE); 11078 11079 return false; 11080 }); 11081 11082 if (CurrentRegionOnly) 11083 return FoundError; 11084 11085 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5] 11086 // If any part of the original storage of a list item has corresponding 11087 // storage in the device data environment, all of the original storage must 11088 // have corresponding storage in the device data environment. 11089 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6] 11090 // If a list item is an element of a structure, and a different element of 11091 // the structure has a corresponding list item in the device data environment 11092 // prior to a task encountering the construct associated with the map clause, 11093 // then the list item must also have a corresponding list item in the device 11094 // data environment prior to the task encountering the construct. 11095 // 11096 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) { 11097 SemaRef.Diag(ELoc, 11098 diag::err_omp_original_storage_is_shared_and_does_not_contain) 11099 << ERange; 11100 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here) 11101 << EnclosingExpr->getSourceRange(); 11102 return true; 11103 } 11104 11105 return FoundError; 11106 } 11107 11108 namespace { 11109 // Utility struct that gathers all the related lists associated with a mappable 11110 // expression. 11111 struct MappableVarListInfo final { 11112 // The list of expressions. 11113 ArrayRef<Expr *> VarList; 11114 // The list of processed expressions. 11115 SmallVector<Expr *, 16> ProcessedVarList; 11116 // The mappble components for each expression. 11117 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents; 11118 // The base declaration of the variable. 11119 SmallVector<ValueDecl *, 16> VarBaseDeclarations; 11120 11121 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) { 11122 // We have a list of components and base declarations for each entry in the 11123 // variable list. 11124 VarComponents.reserve(VarList.size()); 11125 VarBaseDeclarations.reserve(VarList.size()); 11126 } 11127 }; 11128 } 11129 11130 // Check the validity of the provided variable list for the provided clause kind 11131 // \a CKind. In the check process the valid expressions, and mappable expression 11132 // components and variables are extracted and used to fill \a Vars, 11133 // \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and 11134 // \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'. 11135 static void 11136 checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS, 11137 OpenMPClauseKind CKind, MappableVarListInfo &MVLI, 11138 SourceLocation StartLoc, 11139 OpenMPMapClauseKind MapType = OMPC_MAP_unknown, 11140 bool IsMapTypeImplicit = false) { 11141 // We only expect mappable expressions in 'to', 'from', and 'map' clauses. 11142 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) && 11143 "Unexpected clause kind with mappable expressions!"); 11144 11145 // Keep track of the mappable components and base declarations in this clause. 11146 // Each entry in the list is going to have a list of components associated. We 11147 // record each set of the components so that we can build the clause later on. 11148 // In the end we should have the same amount of declarations and component 11149 // lists. 11150 11151 for (auto &RE : MVLI.VarList) { 11152 assert(RE && "Null expr in omp to/from/map clause"); 11153 SourceLocation ELoc = RE->getExprLoc(); 11154 11155 auto *VE = RE->IgnoreParenLValueCasts(); 11156 11157 if (VE->isValueDependent() || VE->isTypeDependent() || 11158 VE->isInstantiationDependent() || 11159 VE->containsUnexpandedParameterPack()) { 11160 // We can only analyze this information once the missing information is 11161 // resolved. 11162 MVLI.ProcessedVarList.push_back(RE); 11163 continue; 11164 } 11165 11166 auto *SimpleExpr = RE->IgnoreParenCasts(); 11167 11168 if (!RE->IgnoreParenImpCasts()->isLValue()) { 11169 SemaRef.Diag(ELoc, 11170 diag::err_omp_expected_named_var_member_or_array_expression) 11171 << RE->getSourceRange(); 11172 continue; 11173 } 11174 11175 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents; 11176 ValueDecl *CurDeclaration = nullptr; 11177 11178 // Obtain the array or member expression bases if required. Also, fill the 11179 // components array with all the components identified in the process. 11180 auto *BE = 11181 CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents, CKind); 11182 if (!BE) 11183 continue; 11184 11185 assert(!CurComponents.empty() && 11186 "Invalid mappable expression information."); 11187 11188 // For the following checks, we rely on the base declaration which is 11189 // expected to be associated with the last component. The declaration is 11190 // expected to be a variable or a field (if 'this' is being mapped). 11191 CurDeclaration = CurComponents.back().getAssociatedDeclaration(); 11192 assert(CurDeclaration && "Null decl on map clause."); 11193 assert( 11194 CurDeclaration->isCanonicalDecl() && 11195 "Expecting components to have associated only canonical declarations."); 11196 11197 auto *VD = dyn_cast<VarDecl>(CurDeclaration); 11198 auto *FD = dyn_cast<FieldDecl>(CurDeclaration); 11199 11200 assert((VD || FD) && "Only variables or fields are expected here!"); 11201 (void)FD; 11202 11203 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10] 11204 // threadprivate variables cannot appear in a map clause. 11205 // OpenMP 4.5 [2.10.5, target update Construct] 11206 // threadprivate variables cannot appear in a from clause. 11207 if (VD && DSAS->isThreadPrivate(VD)) { 11208 auto DVar = DSAS->getTopDSA(VD, false); 11209 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause) 11210 << getOpenMPClauseName(CKind); 11211 ReportOriginalDSA(SemaRef, DSAS, VD, DVar); 11212 continue; 11213 } 11214 11215 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 11216 // A list item cannot appear in both a map clause and a data-sharing 11217 // attribute clause on the same construct. 11218 11219 // Check conflicts with other map clause expressions. We check the conflicts 11220 // with the current construct separately from the enclosing data 11221 // environment, because the restrictions are different. We only have to 11222 // check conflicts across regions for the map clauses. 11223 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 11224 /*CurrentRegionOnly=*/true, CurComponents, CKind)) 11225 break; 11226 if (CKind == OMPC_map && 11227 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr, 11228 /*CurrentRegionOnly=*/false, CurComponents, CKind)) 11229 break; 11230 11231 // OpenMP 4.5 [2.10.5, target update Construct] 11232 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1] 11233 // If the type of a list item is a reference to a type T then the type will 11234 // be considered to be T for all purposes of this clause. 11235 QualType Type = CurDeclaration->getType().getNonReferenceType(); 11236 11237 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4] 11238 // A list item in a to or from clause must have a mappable type. 11239 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9] 11240 // A list item must have a mappable type. 11241 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef, 11242 DSAS, Type)) 11243 continue; 11244 11245 if (CKind == OMPC_map) { 11246 // target enter data 11247 // OpenMP [2.10.2, Restrictions, p. 99] 11248 // A map-type must be specified in all map clauses and must be either 11249 // to or alloc. 11250 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective(); 11251 if (DKind == OMPD_target_enter_data && 11252 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) { 11253 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 11254 << (IsMapTypeImplicit ? 1 : 0) 11255 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 11256 << getOpenMPDirectiveName(DKind); 11257 continue; 11258 } 11259 11260 // target exit_data 11261 // OpenMP [2.10.3, Restrictions, p. 102] 11262 // A map-type must be specified in all map clauses and must be either 11263 // from, release, or delete. 11264 if (DKind == OMPD_target_exit_data && 11265 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release || 11266 MapType == OMPC_MAP_delete)) { 11267 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive) 11268 << (IsMapTypeImplicit ? 1 : 0) 11269 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType) 11270 << getOpenMPDirectiveName(DKind); 11271 continue; 11272 } 11273 11274 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3] 11275 // A list item cannot appear in both a map clause and a data-sharing 11276 // attribute clause on the same construct 11277 if ((DKind == OMPD_target || DKind == OMPD_target_teams || 11278 DKind == OMPD_target_teams_distribute || 11279 DKind == OMPD_target_teams_distribute_parallel_for || 11280 DKind == OMPD_target_teams_distribute_parallel_for_simd || 11281 DKind == OMPD_target_teams_distribute_simd) && VD) { 11282 auto DVar = DSAS->getTopDSA(VD, false); 11283 if (isOpenMPPrivate(DVar.CKind)) { 11284 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 11285 << getOpenMPClauseName(DVar.CKind) 11286 << getOpenMPClauseName(OMPC_map) 11287 << getOpenMPDirectiveName(DSAS->getCurrentDirective()); 11288 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar); 11289 continue; 11290 } 11291 } 11292 } 11293 11294 // Save the current expression. 11295 MVLI.ProcessedVarList.push_back(RE); 11296 11297 // Store the components in the stack so that they can be used to check 11298 // against other clauses later on. 11299 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents, 11300 /*WhereFoundClauseKind=*/OMPC_map); 11301 11302 // Save the components and declaration to create the clause. For purposes of 11303 // the clause creation, any component list that has has base 'this' uses 11304 // null as base declaration. 11305 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 11306 MVLI.VarComponents.back().append(CurComponents.begin(), 11307 CurComponents.end()); 11308 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr 11309 : CurDeclaration); 11310 } 11311 } 11312 11313 OMPClause * 11314 Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier, 11315 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, 11316 SourceLocation MapLoc, SourceLocation ColonLoc, 11317 ArrayRef<Expr *> VarList, SourceLocation StartLoc, 11318 SourceLocation LParenLoc, SourceLocation EndLoc) { 11319 MappableVarListInfo MVLI(VarList); 11320 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc, 11321 MapType, IsMapTypeImplicit); 11322 11323 // We need to produce a map clause even if we don't have variables so that 11324 // other diagnostics related with non-existing map clauses are accurate. 11325 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11326 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11327 MVLI.VarComponents, MapTypeModifier, MapType, 11328 IsMapTypeImplicit, MapLoc); 11329 } 11330 11331 QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc, 11332 TypeResult ParsedType) { 11333 assert(ParsedType.isUsable()); 11334 11335 QualType ReductionType = GetTypeFromParser(ParsedType.get()); 11336 if (ReductionType.isNull()) 11337 return QualType(); 11338 11339 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++ 11340 // A type name in a declare reduction directive cannot be a function type, an 11341 // array type, a reference type, or a type qualified with const, volatile or 11342 // restrict. 11343 if (ReductionType.hasQualifiers()) { 11344 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0; 11345 return QualType(); 11346 } 11347 11348 if (ReductionType->isFunctionType()) { 11349 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1; 11350 return QualType(); 11351 } 11352 if (ReductionType->isReferenceType()) { 11353 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2; 11354 return QualType(); 11355 } 11356 if (ReductionType->isArrayType()) { 11357 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3; 11358 return QualType(); 11359 } 11360 return ReductionType; 11361 } 11362 11363 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart( 11364 Scope *S, DeclContext *DC, DeclarationName Name, 11365 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes, 11366 AccessSpecifier AS, Decl *PrevDeclInScope) { 11367 SmallVector<Decl *, 8> Decls; 11368 Decls.reserve(ReductionTypes.size()); 11369 11370 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName, 11371 ForRedeclaration); 11372 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions 11373 // A reduction-identifier may not be re-declared in the current scope for the 11374 // same type or for a type that is compatible according to the base language 11375 // rules. 11376 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes; 11377 OMPDeclareReductionDecl *PrevDRD = nullptr; 11378 bool InCompoundScope = true; 11379 if (S != nullptr) { 11380 // Find previous declaration with the same name not referenced in other 11381 // declarations. 11382 FunctionScopeInfo *ParentFn = getEnclosingFunction(); 11383 InCompoundScope = 11384 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty(); 11385 LookupName(Lookup, S); 11386 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false, 11387 /*AllowInlineNamespace=*/false); 11388 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious; 11389 auto Filter = Lookup.makeFilter(); 11390 while (Filter.hasNext()) { 11391 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next()); 11392 if (InCompoundScope) { 11393 auto I = UsedAsPrevious.find(PrevDecl); 11394 if (I == UsedAsPrevious.end()) 11395 UsedAsPrevious[PrevDecl] = false; 11396 if (auto *D = PrevDecl->getPrevDeclInScope()) 11397 UsedAsPrevious[D] = true; 11398 } 11399 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] = 11400 PrevDecl->getLocation(); 11401 } 11402 Filter.done(); 11403 if (InCompoundScope) { 11404 for (auto &PrevData : UsedAsPrevious) { 11405 if (!PrevData.second) { 11406 PrevDRD = PrevData.first; 11407 break; 11408 } 11409 } 11410 } 11411 } else if (PrevDeclInScope != nullptr) { 11412 auto *PrevDRDInScope = PrevDRD = 11413 cast<OMPDeclareReductionDecl>(PrevDeclInScope); 11414 do { 11415 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] = 11416 PrevDRDInScope->getLocation(); 11417 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope(); 11418 } while (PrevDRDInScope != nullptr); 11419 } 11420 for (auto &TyData : ReductionTypes) { 11421 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType()); 11422 bool Invalid = false; 11423 if (I != PreviousRedeclTypes.end()) { 11424 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition) 11425 << TyData.first; 11426 Diag(I->second, diag::note_previous_definition); 11427 Invalid = true; 11428 } 11429 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second; 11430 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second, 11431 Name, TyData.first, PrevDRD); 11432 DC->addDecl(DRD); 11433 DRD->setAccess(AS); 11434 Decls.push_back(DRD); 11435 if (Invalid) 11436 DRD->setInvalidDecl(); 11437 else 11438 PrevDRD = DRD; 11439 } 11440 11441 return DeclGroupPtrTy::make( 11442 DeclGroupRef::Create(Context, Decls.begin(), Decls.size())); 11443 } 11444 11445 void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) { 11446 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11447 11448 // Enter new function scope. 11449 PushFunctionScope(); 11450 getCurFunction()->setHasBranchProtectedScope(); 11451 getCurFunction()->setHasOMPDeclareReductionCombiner(); 11452 11453 if (S != nullptr) 11454 PushDeclContext(S, DRD); 11455 else 11456 CurContext = DRD; 11457 11458 PushExpressionEvaluationContext( 11459 ExpressionEvaluationContext::PotentiallyEvaluated); 11460 11461 QualType ReductionType = DRD->getType(); 11462 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will 11463 // be replaced by '*omp_parm' during codegen. This required because 'omp_in' 11464 // uses semantics of argument handles by value, but it should be passed by 11465 // reference. C lang does not support references, so pass all parameters as 11466 // pointers. 11467 // Create 'T omp_in;' variable. 11468 auto *OmpInParm = 11469 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in"); 11470 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will 11471 // be replaced by '*omp_parm' during codegen. This required because 'omp_out' 11472 // uses semantics of argument handles by value, but it should be passed by 11473 // reference. C lang does not support references, so pass all parameters as 11474 // pointers. 11475 // Create 'T omp_out;' variable. 11476 auto *OmpOutParm = 11477 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out"); 11478 if (S != nullptr) { 11479 PushOnScopeChains(OmpInParm, S); 11480 PushOnScopeChains(OmpOutParm, S); 11481 } else { 11482 DRD->addDecl(OmpInParm); 11483 DRD->addDecl(OmpOutParm); 11484 } 11485 } 11486 11487 void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) { 11488 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11489 DiscardCleanupsInEvaluationContext(); 11490 PopExpressionEvaluationContext(); 11491 11492 PopDeclContext(); 11493 PopFunctionScopeInfo(); 11494 11495 if (Combiner != nullptr) 11496 DRD->setCombiner(Combiner); 11497 else 11498 DRD->setInvalidDecl(); 11499 } 11500 11501 VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) { 11502 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11503 11504 // Enter new function scope. 11505 PushFunctionScope(); 11506 getCurFunction()->setHasBranchProtectedScope(); 11507 11508 if (S != nullptr) 11509 PushDeclContext(S, DRD); 11510 else 11511 CurContext = DRD; 11512 11513 PushExpressionEvaluationContext( 11514 ExpressionEvaluationContext::PotentiallyEvaluated); 11515 11516 QualType ReductionType = DRD->getType(); 11517 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will 11518 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv' 11519 // uses semantics of argument handles by value, but it should be passed by 11520 // reference. C lang does not support references, so pass all parameters as 11521 // pointers. 11522 // Create 'T omp_priv;' variable. 11523 auto *OmpPrivParm = 11524 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv"); 11525 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will 11526 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig' 11527 // uses semantics of argument handles by value, but it should be passed by 11528 // reference. C lang does not support references, so pass all parameters as 11529 // pointers. 11530 // Create 'T omp_orig;' variable. 11531 auto *OmpOrigParm = 11532 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig"); 11533 if (S != nullptr) { 11534 PushOnScopeChains(OmpPrivParm, S); 11535 PushOnScopeChains(OmpOrigParm, S); 11536 } else { 11537 DRD->addDecl(OmpPrivParm); 11538 DRD->addDecl(OmpOrigParm); 11539 } 11540 return OmpPrivParm; 11541 } 11542 11543 void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer, 11544 VarDecl *OmpPrivParm) { 11545 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11546 DiscardCleanupsInEvaluationContext(); 11547 PopExpressionEvaluationContext(); 11548 11549 PopDeclContext(); 11550 PopFunctionScopeInfo(); 11551 11552 if (Initializer != nullptr) { 11553 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit); 11554 } else if (OmpPrivParm->hasInit()) { 11555 DRD->setInitializer(OmpPrivParm->getInit(), 11556 OmpPrivParm->isDirectInit() 11557 ? OMPDeclareReductionDecl::DirectInit 11558 : OMPDeclareReductionDecl::CopyInit); 11559 } else { 11560 DRD->setInvalidDecl(); 11561 } 11562 } 11563 11564 Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd( 11565 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) { 11566 for (auto *D : DeclReductions.get()) { 11567 if (IsValid) { 11568 auto *DRD = cast<OMPDeclareReductionDecl>(D); 11569 if (S != nullptr) 11570 PushOnScopeChains(DRD, S, /*AddToContext=*/false); 11571 } else 11572 D->setInvalidDecl(); 11573 } 11574 return DeclReductions; 11575 } 11576 11577 OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams, 11578 SourceLocation StartLoc, 11579 SourceLocation LParenLoc, 11580 SourceLocation EndLoc) { 11581 Expr *ValExpr = NumTeams; 11582 Stmt *HelperValStmt = nullptr; 11583 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 11584 11585 // OpenMP [teams Constrcut, Restrictions] 11586 // The num_teams expression must evaluate to a positive integer value. 11587 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams, 11588 /*StrictlyPositive=*/true)) 11589 return nullptr; 11590 11591 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 11592 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams); 11593 if (CaptureRegion != OMPD_unknown) { 11594 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11595 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11596 HelperValStmt = buildPreInits(Context, Captures); 11597 } 11598 11599 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion, 11600 StartLoc, LParenLoc, EndLoc); 11601 } 11602 11603 OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit, 11604 SourceLocation StartLoc, 11605 SourceLocation LParenLoc, 11606 SourceLocation EndLoc) { 11607 Expr *ValExpr = ThreadLimit; 11608 Stmt *HelperValStmt = nullptr; 11609 OpenMPDirectiveKind CaptureRegion = OMPD_unknown; 11610 11611 // OpenMP [teams Constrcut, Restrictions] 11612 // The thread_limit expression must evaluate to a positive integer value. 11613 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit, 11614 /*StrictlyPositive=*/true)) 11615 return nullptr; 11616 11617 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective(); 11618 CaptureRegion = getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit); 11619 if (CaptureRegion != OMPD_unknown) { 11620 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11621 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11622 HelperValStmt = buildPreInits(Context, Captures); 11623 } 11624 11625 return new (Context) OMPThreadLimitClause( 11626 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc); 11627 } 11628 11629 OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority, 11630 SourceLocation StartLoc, 11631 SourceLocation LParenLoc, 11632 SourceLocation EndLoc) { 11633 Expr *ValExpr = Priority; 11634 11635 // OpenMP [2.9.1, task Constrcut] 11636 // The priority-value is a non-negative numerical scalar expression. 11637 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority, 11638 /*StrictlyPositive=*/false)) 11639 return nullptr; 11640 11641 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11642 } 11643 11644 OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize, 11645 SourceLocation StartLoc, 11646 SourceLocation LParenLoc, 11647 SourceLocation EndLoc) { 11648 Expr *ValExpr = Grainsize; 11649 11650 // OpenMP [2.9.2, taskloop Constrcut] 11651 // The parameter of the grainsize clause must be a positive integer 11652 // expression. 11653 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize, 11654 /*StrictlyPositive=*/true)) 11655 return nullptr; 11656 11657 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11658 } 11659 11660 OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks, 11661 SourceLocation StartLoc, 11662 SourceLocation LParenLoc, 11663 SourceLocation EndLoc) { 11664 Expr *ValExpr = NumTasks; 11665 11666 // OpenMP [2.9.2, taskloop Constrcut] 11667 // The parameter of the num_tasks clause must be a positive integer 11668 // expression. 11669 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks, 11670 /*StrictlyPositive=*/true)) 11671 return nullptr; 11672 11673 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc); 11674 } 11675 11676 OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc, 11677 SourceLocation LParenLoc, 11678 SourceLocation EndLoc) { 11679 // OpenMP [2.13.2, critical construct, Description] 11680 // ... where hint-expression is an integer constant expression that evaluates 11681 // to a valid lock hint. 11682 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint); 11683 if (HintExpr.isInvalid()) 11684 return nullptr; 11685 return new (Context) 11686 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc); 11687 } 11688 11689 OMPClause *Sema::ActOnOpenMPDistScheduleClause( 11690 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc, 11691 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc, 11692 SourceLocation EndLoc) { 11693 if (Kind == OMPC_DIST_SCHEDULE_unknown) { 11694 std::string Values; 11695 Values += "'"; 11696 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0); 11697 Values += "'"; 11698 Diag(KindLoc, diag::err_omp_unexpected_clause_value) 11699 << Values << getOpenMPClauseName(OMPC_dist_schedule); 11700 return nullptr; 11701 } 11702 Expr *ValExpr = ChunkSize; 11703 Stmt *HelperValStmt = nullptr; 11704 if (ChunkSize) { 11705 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() && 11706 !ChunkSize->isInstantiationDependent() && 11707 !ChunkSize->containsUnexpandedParameterPack()) { 11708 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart(); 11709 ExprResult Val = 11710 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize); 11711 if (Val.isInvalid()) 11712 return nullptr; 11713 11714 ValExpr = Val.get(); 11715 11716 // OpenMP [2.7.1, Restrictions] 11717 // chunk_size must be a loop invariant integer expression with a positive 11718 // value. 11719 llvm::APSInt Result; 11720 if (ValExpr->isIntegerConstantExpr(Result, Context)) { 11721 if (Result.isSigned() && !Result.isStrictlyPositive()) { 11722 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause) 11723 << "dist_schedule" << ChunkSize->getSourceRange(); 11724 return nullptr; 11725 } 11726 } else if (isParallelOrTaskRegion(DSAStack->getCurrentDirective()) && 11727 !CurContext->isDependentContext()) { 11728 llvm::MapVector<Expr *, DeclRefExpr *> Captures; 11729 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get(); 11730 HelperValStmt = buildPreInits(Context, Captures); 11731 } 11732 } 11733 } 11734 11735 return new (Context) 11736 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, 11737 Kind, ValExpr, HelperValStmt); 11738 } 11739 11740 OMPClause *Sema::ActOnOpenMPDefaultmapClause( 11741 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind, 11742 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, 11743 SourceLocation KindLoc, SourceLocation EndLoc) { 11744 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)' 11745 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) { 11746 std::string Value; 11747 SourceLocation Loc; 11748 Value += "'"; 11749 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) { 11750 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 11751 OMPC_DEFAULTMAP_MODIFIER_tofrom); 11752 Loc = MLoc; 11753 } else { 11754 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap, 11755 OMPC_DEFAULTMAP_scalar); 11756 Loc = KindLoc; 11757 } 11758 Value += "'"; 11759 Diag(Loc, diag::err_omp_unexpected_clause_value) 11760 << Value << getOpenMPClauseName(OMPC_defaultmap); 11761 return nullptr; 11762 } 11763 11764 return new (Context) 11765 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M); 11766 } 11767 11768 bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) { 11769 DeclContext *CurLexicalContext = getCurLexicalContext(); 11770 if (!CurLexicalContext->isFileContext() && 11771 !CurLexicalContext->isExternCContext() && 11772 !CurLexicalContext->isExternCXXContext()) { 11773 Diag(Loc, diag::err_omp_region_not_file_context); 11774 return false; 11775 } 11776 if (IsInOpenMPDeclareTargetContext) { 11777 Diag(Loc, diag::err_omp_enclosed_declare_target); 11778 return false; 11779 } 11780 11781 IsInOpenMPDeclareTargetContext = true; 11782 return true; 11783 } 11784 11785 void Sema::ActOnFinishOpenMPDeclareTargetDirective() { 11786 assert(IsInOpenMPDeclareTargetContext && 11787 "Unexpected ActOnFinishOpenMPDeclareTargetDirective"); 11788 11789 IsInOpenMPDeclareTargetContext = false; 11790 } 11791 11792 void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope, 11793 CXXScopeSpec &ScopeSpec, 11794 const DeclarationNameInfo &Id, 11795 OMPDeclareTargetDeclAttr::MapTypeTy MT, 11796 NamedDeclSetType &SameDirectiveDecls) { 11797 LookupResult Lookup(*this, Id, LookupOrdinaryName); 11798 LookupParsedName(Lookup, CurScope, &ScopeSpec, true); 11799 11800 if (Lookup.isAmbiguous()) 11801 return; 11802 Lookup.suppressDiagnostics(); 11803 11804 if (!Lookup.isSingleResult()) { 11805 if (TypoCorrection Corrected = 11806 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, 11807 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this), 11808 CTK_ErrorRecovery)) { 11809 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest) 11810 << Id.getName()); 11811 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl()); 11812 return; 11813 } 11814 11815 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName(); 11816 return; 11817 } 11818 11819 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>(); 11820 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) { 11821 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl()))) 11822 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName(); 11823 11824 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) { 11825 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT); 11826 ND->addAttr(A); 11827 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11828 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A); 11829 checkDeclIsAllowedInOpenMPTarget(nullptr, ND); 11830 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) { 11831 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link) 11832 << Id.getName(); 11833 } 11834 } else 11835 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName(); 11836 } 11837 11838 static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR, 11839 Sema &SemaRef, Decl *D) { 11840 if (!D) 11841 return; 11842 Decl *LD = nullptr; 11843 if (isa<TagDecl>(D)) { 11844 LD = cast<TagDecl>(D)->getDefinition(); 11845 } else if (isa<VarDecl>(D)) { 11846 LD = cast<VarDecl>(D)->getDefinition(); 11847 11848 // If this is an implicit variable that is legal and we do not need to do 11849 // anything. 11850 if (cast<VarDecl>(D)->isImplicit()) { 11851 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11852 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11853 D->addAttr(A); 11854 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11855 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11856 return; 11857 } 11858 11859 } else if (isa<FunctionDecl>(D)) { 11860 const FunctionDecl *FD = nullptr; 11861 if (cast<FunctionDecl>(D)->hasBody(FD)) 11862 LD = const_cast<FunctionDecl *>(FD); 11863 11864 // If the definition is associated with the current declaration in the 11865 // target region (it can be e.g. a lambda) that is legal and we do not need 11866 // to do anything else. 11867 if (LD == D) { 11868 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11869 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11870 D->addAttr(A); 11871 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11872 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11873 return; 11874 } 11875 } 11876 if (!LD) 11877 LD = D; 11878 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() && 11879 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) { 11880 // Outlined declaration is not declared target. 11881 if (LD->isOutOfLine()) { 11882 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 11883 SemaRef.Diag(SL, diag::note_used_here) << SR; 11884 } else { 11885 DeclContext *DC = LD->getDeclContext(); 11886 while (DC) { 11887 if (isa<FunctionDecl>(DC) && 11888 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>()) 11889 break; 11890 DC = DC->getParent(); 11891 } 11892 if (DC) 11893 return; 11894 11895 // Is not declared in target context. 11896 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context); 11897 SemaRef.Diag(SL, diag::note_used_here) << SR; 11898 } 11899 // Mark decl as declared target to prevent further diagnostic. 11900 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11901 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To); 11902 D->addAttr(A); 11903 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener()) 11904 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11905 } 11906 } 11907 11908 static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR, 11909 Sema &SemaRef, DSAStackTy *Stack, 11910 ValueDecl *VD) { 11911 if (VD->hasAttr<OMPDeclareTargetDeclAttr>()) 11912 return true; 11913 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType())) 11914 return false; 11915 return true; 11916 } 11917 11918 void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D) { 11919 if (!D || D->isInvalidDecl()) 11920 return; 11921 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange(); 11922 SourceLocation SL = E ? E->getLocStart() : D->getLocation(); 11923 // 2.10.6: threadprivate variable cannot appear in a declare target directive. 11924 if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 11925 if (DSAStack->isThreadPrivate(VD)) { 11926 Diag(SL, diag::err_omp_threadprivate_in_target); 11927 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false)); 11928 return; 11929 } 11930 } 11931 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 11932 // Problem if any with var declared with incomplete type will be reported 11933 // as normal, so no need to check it here. 11934 if ((E || !VD->getType()->isIncompleteType()) && 11935 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) { 11936 // Mark decl as declared target to prevent further diagnostic. 11937 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) { 11938 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11939 Context, OMPDeclareTargetDeclAttr::MT_To); 11940 VD->addAttr(A); 11941 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11942 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A); 11943 } 11944 return; 11945 } 11946 } 11947 if (!E) { 11948 // Checking declaration inside declare target region. 11949 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() && 11950 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) { 11951 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit( 11952 Context, OMPDeclareTargetDeclAttr::MT_To); 11953 D->addAttr(A); 11954 if (ASTMutationListener *ML = Context.getASTMutationListener()) 11955 ML->DeclarationMarkedOpenMPDeclareTarget(D, A); 11956 } 11957 return; 11958 } 11959 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D); 11960 } 11961 11962 OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList, 11963 SourceLocation StartLoc, 11964 SourceLocation LParenLoc, 11965 SourceLocation EndLoc) { 11966 MappableVarListInfo MVLI(VarList); 11967 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc); 11968 if (MVLI.ProcessedVarList.empty()) 11969 return nullptr; 11970 11971 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11972 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11973 MVLI.VarComponents); 11974 } 11975 11976 OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList, 11977 SourceLocation StartLoc, 11978 SourceLocation LParenLoc, 11979 SourceLocation EndLoc) { 11980 MappableVarListInfo MVLI(VarList); 11981 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc); 11982 if (MVLI.ProcessedVarList.empty()) 11983 return nullptr; 11984 11985 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc, 11986 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations, 11987 MVLI.VarComponents); 11988 } 11989 11990 OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList, 11991 SourceLocation StartLoc, 11992 SourceLocation LParenLoc, 11993 SourceLocation EndLoc) { 11994 MappableVarListInfo MVLI(VarList); 11995 SmallVector<Expr *, 8> PrivateCopies; 11996 SmallVector<Expr *, 8> Inits; 11997 11998 for (auto &RefExpr : VarList) { 11999 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause."); 12000 SourceLocation ELoc; 12001 SourceRange ERange; 12002 Expr *SimpleRefExpr = RefExpr; 12003 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 12004 if (Res.second) { 12005 // It will be analyzed later. 12006 MVLI.ProcessedVarList.push_back(RefExpr); 12007 PrivateCopies.push_back(nullptr); 12008 Inits.push_back(nullptr); 12009 } 12010 ValueDecl *D = Res.first; 12011 if (!D) 12012 continue; 12013 12014 QualType Type = D->getType(); 12015 Type = Type.getNonReferenceType().getUnqualifiedType(); 12016 12017 auto *VD = dyn_cast<VarDecl>(D); 12018 12019 // Item should be a pointer or reference to pointer. 12020 if (!Type->isPointerType()) { 12021 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer) 12022 << 0 << RefExpr->getSourceRange(); 12023 continue; 12024 } 12025 12026 // Build the private variable and the expression that refers to it. 12027 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(), 12028 D->hasAttrs() ? &D->getAttrs() : nullptr); 12029 if (VDPrivate->isInvalidDecl()) 12030 continue; 12031 12032 CurContext->addDecl(VDPrivate); 12033 auto VDPrivateRefExpr = buildDeclRefExpr( 12034 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc); 12035 12036 // Add temporary variable to initialize the private copy of the pointer. 12037 auto *VDInit = 12038 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp"); 12039 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(), 12040 RefExpr->getExprLoc()); 12041 AddInitializerToDecl(VDPrivate, 12042 DefaultLvalueConversion(VDInitRefExpr).get(), 12043 /*DirectInit=*/false); 12044 12045 // If required, build a capture to implement the privatization initialized 12046 // with the current list item value. 12047 DeclRefExpr *Ref = nullptr; 12048 if (!VD) 12049 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true); 12050 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref); 12051 PrivateCopies.push_back(VDPrivateRefExpr); 12052 Inits.push_back(VDInitRefExpr); 12053 12054 // We need to add a data sharing attribute for this variable to make sure it 12055 // is correctly captured. A variable that shows up in a use_device_ptr has 12056 // similar properties of a first private variable. 12057 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref); 12058 12059 // Create a mappable component for the list item. List items in this clause 12060 // only need a component. 12061 MVLI.VarBaseDeclarations.push_back(D); 12062 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 12063 MVLI.VarComponents.back().push_back( 12064 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D)); 12065 } 12066 12067 if (MVLI.ProcessedVarList.empty()) 12068 return nullptr; 12069 12070 return OMPUseDevicePtrClause::Create( 12071 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 12072 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents); 12073 } 12074 12075 OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList, 12076 SourceLocation StartLoc, 12077 SourceLocation LParenLoc, 12078 SourceLocation EndLoc) { 12079 MappableVarListInfo MVLI(VarList); 12080 for (auto &RefExpr : VarList) { 12081 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause."); 12082 SourceLocation ELoc; 12083 SourceRange ERange; 12084 Expr *SimpleRefExpr = RefExpr; 12085 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange); 12086 if (Res.second) { 12087 // It will be analyzed later. 12088 MVLI.ProcessedVarList.push_back(RefExpr); 12089 } 12090 ValueDecl *D = Res.first; 12091 if (!D) 12092 continue; 12093 12094 QualType Type = D->getType(); 12095 // item should be a pointer or array or reference to pointer or array 12096 if (!Type.getNonReferenceType()->isPointerType() && 12097 !Type.getNonReferenceType()->isArrayType()) { 12098 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr) 12099 << 0 << RefExpr->getSourceRange(); 12100 continue; 12101 } 12102 12103 // Check if the declaration in the clause does not show up in any data 12104 // sharing attribute. 12105 auto DVar = DSAStack->getTopDSA(D, false); 12106 if (isOpenMPPrivate(DVar.CKind)) { 12107 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa) 12108 << getOpenMPClauseName(DVar.CKind) 12109 << getOpenMPClauseName(OMPC_is_device_ptr) 12110 << getOpenMPDirectiveName(DSAStack->getCurrentDirective()); 12111 ReportOriginalDSA(*this, DSAStack, D, DVar); 12112 continue; 12113 } 12114 12115 Expr *ConflictExpr; 12116 if (DSAStack->checkMappableExprComponentListsForDecl( 12117 D, /*CurrentRegionOnly=*/true, 12118 [&ConflictExpr]( 12119 OMPClauseMappableExprCommon::MappableExprComponentListRef R, 12120 OpenMPClauseKind) -> bool { 12121 ConflictExpr = R.front().getAssociatedExpression(); 12122 return true; 12123 })) { 12124 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange(); 12125 Diag(ConflictExpr->getExprLoc(), diag::note_used_here) 12126 << ConflictExpr->getSourceRange(); 12127 continue; 12128 } 12129 12130 // Store the components in the stack so that they can be used to check 12131 // against other clauses later on. 12132 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D); 12133 DSAStack->addMappableExpressionComponents( 12134 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr); 12135 12136 // Record the expression we've just processed. 12137 MVLI.ProcessedVarList.push_back(SimpleRefExpr); 12138 12139 // Create a mappable component for the list item. List items in this clause 12140 // only need a component. We use a null declaration to signal fields in 12141 // 'this'. 12142 assert((isa<DeclRefExpr>(SimpleRefExpr) || 12143 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) && 12144 "Unexpected device pointer expression!"); 12145 MVLI.VarBaseDeclarations.push_back( 12146 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr); 12147 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1); 12148 MVLI.VarComponents.back().push_back(MC); 12149 } 12150 12151 if (MVLI.ProcessedVarList.empty()) 12152 return nullptr; 12153 12154 return OMPIsDevicePtrClause::Create( 12155 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList, 12156 MVLI.VarBaseDeclarations, MVLI.VarComponents); 12157 } 12158