1 //===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===// 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 // 10 // This file implements decl-related attribute processing. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/DeclCXX.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/Mangle.h" 24 #include "clang/AST/RecursiveASTVisitor.h" 25 #include "clang/Basic/CharInfo.h" 26 #include "clang/Basic/SourceManager.h" 27 #include "clang/Basic/TargetInfo.h" 28 #include "clang/Lex/Preprocessor.h" 29 #include "clang/Sema/DeclSpec.h" 30 #include "clang/Sema/DelayedDiagnostic.h" 31 #include "clang/Sema/Initialization.h" 32 #include "clang/Sema/Lookup.h" 33 #include "clang/Sema/Scope.h" 34 #include "clang/Sema/SemaInternal.h" 35 #include "llvm/ADT/STLExtras.h" 36 #include "llvm/ADT/StringExtras.h" 37 #include "llvm/Support/MathExtras.h" 38 39 using namespace clang; 40 using namespace sema; 41 42 namespace AttributeLangSupport { 43 enum LANG { 44 C, 45 Cpp, 46 ObjC 47 }; 48 } // end namespace AttributeLangSupport 49 50 //===----------------------------------------------------------------------===// 51 // Helper functions 52 //===----------------------------------------------------------------------===// 53 54 /// isFunctionOrMethod - Return true if the given decl has function 55 /// type (function or function-typed variable) or an Objective-C 56 /// method. 57 static bool isFunctionOrMethod(const Decl *D) { 58 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D); 59 } 60 61 /// \brief Return true if the given decl has function type (function or 62 /// function-typed variable) or an Objective-C method or a block. 63 static bool isFunctionOrMethodOrBlock(const Decl *D) { 64 return isFunctionOrMethod(D) || isa<BlockDecl>(D); 65 } 66 67 /// Return true if the given decl has a declarator that should have 68 /// been processed by Sema::GetTypeForDeclarator. 69 static bool hasDeclarator(const Decl *D) { 70 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl. 71 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) || 72 isa<ObjCPropertyDecl>(D); 73 } 74 75 /// hasFunctionProto - Return true if the given decl has a argument 76 /// information. This decl should have already passed 77 /// isFunctionOrMethod or isFunctionOrMethodOrBlock. 78 static bool hasFunctionProto(const Decl *D) { 79 if (const FunctionType *FnTy = D->getFunctionType()) 80 return isa<FunctionProtoType>(FnTy); 81 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D); 82 } 83 84 /// getFunctionOrMethodNumParams - Return number of function or method 85 /// parameters. It is an error to call this on a K&R function (use 86 /// hasFunctionProto first). 87 static unsigned getFunctionOrMethodNumParams(const Decl *D) { 88 if (const FunctionType *FnTy = D->getFunctionType()) 89 return cast<FunctionProtoType>(FnTy)->getNumParams(); 90 if (const auto *BD = dyn_cast<BlockDecl>(D)) 91 return BD->getNumParams(); 92 return cast<ObjCMethodDecl>(D)->param_size(); 93 } 94 95 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) { 96 if (const FunctionType *FnTy = D->getFunctionType()) 97 return cast<FunctionProtoType>(FnTy)->getParamType(Idx); 98 if (const auto *BD = dyn_cast<BlockDecl>(D)) 99 return BD->getParamDecl(Idx)->getType(); 100 101 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType(); 102 } 103 104 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) { 105 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 106 return FD->getParamDecl(Idx)->getSourceRange(); 107 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 108 return MD->parameters()[Idx]->getSourceRange(); 109 if (const auto *BD = dyn_cast<BlockDecl>(D)) 110 return BD->getParamDecl(Idx)->getSourceRange(); 111 return SourceRange(); 112 } 113 114 static QualType getFunctionOrMethodResultType(const Decl *D) { 115 if (const FunctionType *FnTy = D->getFunctionType()) 116 return cast<FunctionType>(FnTy)->getReturnType(); 117 return cast<ObjCMethodDecl>(D)->getReturnType(); 118 } 119 120 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) { 121 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 122 return FD->getReturnTypeSourceRange(); 123 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 124 return MD->getReturnTypeSourceRange(); 125 return SourceRange(); 126 } 127 128 static bool isFunctionOrMethodVariadic(const Decl *D) { 129 if (const FunctionType *FnTy = D->getFunctionType()) 130 return cast<FunctionProtoType>(FnTy)->isVariadic(); 131 if (const auto *BD = dyn_cast<BlockDecl>(D)) 132 return BD->isVariadic(); 133 return cast<ObjCMethodDecl>(D)->isVariadic(); 134 } 135 136 static bool isInstanceMethod(const Decl *D) { 137 if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(D)) 138 return MethodDecl->isInstance(); 139 return false; 140 } 141 142 static inline bool isNSStringType(QualType T, ASTContext &Ctx) { 143 const auto *PT = T->getAs<ObjCObjectPointerType>(); 144 if (!PT) 145 return false; 146 147 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface(); 148 if (!Cls) 149 return false; 150 151 IdentifierInfo* ClsName = Cls->getIdentifier(); 152 153 // FIXME: Should we walk the chain of classes? 154 return ClsName == &Ctx.Idents.get("NSString") || 155 ClsName == &Ctx.Idents.get("NSMutableString"); 156 } 157 158 static inline bool isCFStringType(QualType T, ASTContext &Ctx) { 159 const auto *PT = T->getAs<PointerType>(); 160 if (!PT) 161 return false; 162 163 const auto *RT = PT->getPointeeType()->getAs<RecordType>(); 164 if (!RT) 165 return false; 166 167 const RecordDecl *RD = RT->getDecl(); 168 if (RD->getTagKind() != TTK_Struct) 169 return false; 170 171 return RD->getIdentifier() == &Ctx.Idents.get("__CFString"); 172 } 173 174 static unsigned getNumAttributeArgs(const AttributeList &AL) { 175 // FIXME: Include the type in the argument list. 176 return AL.getNumArgs() + AL.hasParsedType(); 177 } 178 179 template <typename Compare> 180 static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &AL, 181 unsigned Num, unsigned Diag, 182 Compare Comp) { 183 if (Comp(getNumAttributeArgs(AL), Num)) { 184 S.Diag(AL.getLoc(), Diag) << AL.getName() << Num; 185 return false; 186 } 187 188 return true; 189 } 190 191 /// \brief Check if the attribute has exactly as many args as Num. May 192 /// output an error. 193 static bool checkAttributeNumArgs(Sema &S, const AttributeList &AL, 194 unsigned Num) { 195 return checkAttributeNumArgsImpl(S, AL, Num, 196 diag::err_attribute_wrong_number_arguments, 197 std::not_equal_to<unsigned>()); 198 } 199 200 /// \brief Check if the attribute has at least as many args as Num. May 201 /// output an error. 202 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &AL, 203 unsigned Num) { 204 return checkAttributeNumArgsImpl(S, AL, Num, 205 diag::err_attribute_too_few_arguments, 206 std::less<unsigned>()); 207 } 208 209 /// \brief Check if the attribute has at most as many args as Num. May 210 /// output an error. 211 static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &AL, 212 unsigned Num) { 213 return checkAttributeNumArgsImpl(S, AL, Num, 214 diag::err_attribute_too_many_arguments, 215 std::greater<unsigned>()); 216 } 217 218 /// \brief A helper function to provide Attribute Location for the Attr types 219 /// AND the AttributeList. 220 template <typename AttrInfo> 221 static typename std::enable_if<std::is_base_of<Attr, AttrInfo>::value, 222 SourceLocation>::type 223 getAttrLoc(const AttrInfo &AL) { 224 return AL.getLocation(); 225 } 226 static SourceLocation getAttrLoc(const AttributeList &AL) { 227 return AL.getLoc(); 228 } 229 230 /// \brief A helper function to provide Attribute Name for the Attr types 231 /// AND the AttributeList. 232 template <typename AttrInfo> 233 static typename std::enable_if<std::is_base_of<Attr, AttrInfo>::value, 234 const AttrInfo *>::type 235 getAttrName(const AttrInfo &AL) { 236 return &AL; 237 } 238 static const IdentifierInfo *getAttrName(const AttributeList &AL) { 239 return AL.getName(); 240 } 241 242 /// \brief If Expr is a valid integer constant, get the value of the integer 243 /// expression and return success or failure. May output an error. 244 template <typename AttrInfo> 245 static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr, 246 uint32_t &Val, unsigned Idx = UINT_MAX) { 247 llvm::APSInt I(32); 248 if (Expr->isTypeDependent() || Expr->isValueDependent() || 249 !Expr->isIntegerConstantExpr(I, S.Context)) { 250 if (Idx != UINT_MAX) 251 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type) 252 << getAttrName(AI) << Idx << AANT_ArgumentIntegerConstant 253 << Expr->getSourceRange(); 254 else 255 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type) 256 << getAttrName(AI) << AANT_ArgumentIntegerConstant 257 << Expr->getSourceRange(); 258 return false; 259 } 260 261 if (!I.isIntN(32)) { 262 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large) 263 << I.toString(10, false) << 32 << /* Unsigned */ 1; 264 return false; 265 } 266 267 Val = (uint32_t)I.getZExtValue(); 268 return true; 269 } 270 271 /// \brief Wrapper around checkUInt32Argument, with an extra check to be sure 272 /// that the result will fit into a regular (signed) int. All args have the same 273 /// purpose as they do in checkUInt32Argument. 274 template <typename AttrInfo> 275 static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr, 276 int &Val, unsigned Idx = UINT_MAX) { 277 uint32_t UVal; 278 if (!checkUInt32Argument(S, AI, Expr, UVal, Idx)) 279 return false; 280 281 if (UVal > (uint32_t)std::numeric_limits<int>::max()) { 282 llvm::APSInt I(32); // for toString 283 I = UVal; 284 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large) 285 << I.toString(10, false) << 32 << /* Unsigned */ 0; 286 return false; 287 } 288 289 Val = UVal; 290 return true; 291 } 292 293 /// \brief Diagnose mutually exclusive attributes when present on a given 294 /// declaration. Returns true if diagnosed. 295 template <typename AttrTy> 296 static bool checkAttrMutualExclusion(Sema &S, Decl *D, SourceRange Range, 297 IdentifierInfo *Ident) { 298 if (const auto *A = D->getAttr<AttrTy>()) { 299 S.Diag(Range.getBegin(), diag::err_attributes_are_not_compatible) << Ident 300 << A; 301 S.Diag(A->getLocation(), diag::note_conflicting_attribute); 302 return true; 303 } 304 return false; 305 } 306 307 /// \brief Check if IdxExpr is a valid parameter index for a function or 308 /// instance method D. May output an error. 309 /// 310 /// \returns true if IdxExpr is a valid index. 311 template <typename AttrInfo> 312 static bool checkFunctionOrMethodParameterIndex( 313 Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum, 314 const Expr *IdxExpr, uint64_t &Idx, bool AllowImplicitThis = false) { 315 assert(isFunctionOrMethodOrBlock(D)); 316 317 // In C++ the implicit 'this' function parameter also counts. 318 // Parameters are counted from one. 319 bool HP = hasFunctionProto(D); 320 bool HasImplicitThisParam = isInstanceMethod(D); 321 bool IV = HP && isFunctionOrMethodVariadic(D); 322 unsigned NumParams = 323 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam; 324 325 llvm::APSInt IdxInt; 326 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() || 327 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) { 328 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type) 329 << getAttrName(AI) << AttrArgNum << AANT_ArgumentIntegerConstant 330 << IdxExpr->getSourceRange(); 331 return false; 332 } 333 334 Idx = IdxInt.getLimitedValue(); 335 if (Idx < 1 || (!IV && Idx > NumParams)) { 336 S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds) 337 << getAttrName(AI) << AttrArgNum << IdxExpr->getSourceRange(); 338 return false; 339 } 340 Idx--; // Convert to zero-based. 341 if (HasImplicitThisParam && !AllowImplicitThis) { 342 if (Idx == 0) { 343 S.Diag(getAttrLoc(AI), 344 diag::err_attribute_invalid_implicit_this_argument) 345 << getAttrName(AI) << IdxExpr->getSourceRange(); 346 return false; 347 } 348 --Idx; 349 } 350 351 return true; 352 } 353 354 /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal. 355 /// If not emit an error and return false. If the argument is an identifier it 356 /// will emit an error with a fixit hint and treat it as if it was a string 357 /// literal. 358 bool Sema::checkStringLiteralArgumentAttr(const AttributeList &AL, 359 unsigned ArgNum, StringRef &Str, 360 SourceLocation *ArgLocation) { 361 // Look for identifiers. If we have one emit a hint to fix it to a literal. 362 if (AL.isArgIdent(ArgNum)) { 363 IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum); 364 Diag(Loc->Loc, diag::err_attribute_argument_type) 365 << AL.getName() << AANT_ArgumentString 366 << FixItHint::CreateInsertion(Loc->Loc, "\"") 367 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\""); 368 Str = Loc->Ident->getName(); 369 if (ArgLocation) 370 *ArgLocation = Loc->Loc; 371 return true; 372 } 373 374 // Now check for an actual string literal. 375 Expr *ArgExpr = AL.getArgAsExpr(ArgNum); 376 const auto *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts()); 377 if (ArgLocation) 378 *ArgLocation = ArgExpr->getLocStart(); 379 380 if (!Literal || !Literal->isAscii()) { 381 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type) 382 << AL.getName() << AANT_ArgumentString; 383 return false; 384 } 385 386 Str = Literal->getString(); 387 return true; 388 } 389 390 /// \brief Applies the given attribute to the Decl without performing any 391 /// additional semantic checking. 392 template <typename AttrType> 393 static void handleSimpleAttribute(Sema &S, Decl *D, const AttributeList &AL) { 394 D->addAttr(::new (S.Context) AttrType(AL.getRange(), S.Context, 395 AL.getAttributeSpellingListIndex())); 396 } 397 398 template <typename AttrType> 399 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D, 400 const AttributeList &AL) { 401 handleSimpleAttribute<AttrType>(S, D, AL); 402 } 403 404 /// \brief Applies the given attribute to the Decl so long as the Decl doesn't 405 /// already have one of the given incompatible attributes. 406 template <typename AttrType, typename IncompatibleAttrType, 407 typename... IncompatibleAttrTypes> 408 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D, 409 const AttributeList &AL) { 410 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, AL.getRange(), 411 AL.getName())) 412 return; 413 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D, 414 AL); 415 } 416 417 /// \brief Check if the passed-in expression is of type int or bool. 418 static bool isIntOrBool(Expr *Exp) { 419 QualType QT = Exp->getType(); 420 return QT->isBooleanType() || QT->isIntegerType(); 421 } 422 423 424 // Check to see if the type is a smart pointer of some kind. We assume 425 // it's a smart pointer if it defines both operator-> and operator*. 426 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) { 427 DeclContextLookupResult Res1 = RT->getDecl()->lookup( 428 S.Context.DeclarationNames.getCXXOperatorName(OO_Star)); 429 if (Res1.empty()) 430 return false; 431 432 DeclContextLookupResult Res2 = RT->getDecl()->lookup( 433 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow)); 434 if (Res2.empty()) 435 return false; 436 437 return true; 438 } 439 440 /// \brief Check if passed in Decl is a pointer type. 441 /// Note that this function may produce an error message. 442 /// \return true if the Decl is a pointer type; false otherwise 443 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D, 444 const AttributeList &AL) { 445 const auto *VD = cast<ValueDecl>(D); 446 QualType QT = VD->getType(); 447 if (QT->isAnyPointerType()) 448 return true; 449 450 if (const auto *RT = QT->getAs<RecordType>()) { 451 // If it's an incomplete type, it could be a smart pointer; skip it. 452 // (We don't want to force template instantiation if we can avoid it, 453 // since that would alter the order in which templates are instantiated.) 454 if (RT->isIncompleteType()) 455 return true; 456 457 if (threadSafetyCheckIsSmartPointer(S, RT)) 458 return true; 459 } 460 461 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) 462 << AL.getName() << QT; 463 return false; 464 } 465 466 /// \brief Checks that the passed in QualType either is of RecordType or points 467 /// to RecordType. Returns the relevant RecordType, null if it does not exit. 468 static const RecordType *getRecordType(QualType QT) { 469 if (const auto *RT = QT->getAs<RecordType>()) 470 return RT; 471 472 // Now check if we point to record type. 473 if (const auto *PT = QT->getAs<PointerType>()) 474 return PT->getPointeeType()->getAs<RecordType>(); 475 476 return nullptr; 477 } 478 479 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) { 480 const RecordType *RT = getRecordType(Ty); 481 482 if (!RT) 483 return false; 484 485 // Don't check for the capability if the class hasn't been defined yet. 486 if (RT->isIncompleteType()) 487 return true; 488 489 // Allow smart pointers to be used as capability objects. 490 // FIXME -- Check the type that the smart pointer points to. 491 if (threadSafetyCheckIsSmartPointer(S, RT)) 492 return true; 493 494 // Check if the record itself has a capability. 495 RecordDecl *RD = RT->getDecl(); 496 if (RD->hasAttr<CapabilityAttr>()) 497 return true; 498 499 // Else check if any base classes have a capability. 500 if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) { 501 CXXBasePaths BPaths(false, false); 502 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) { 503 const auto *Type = BS->getType()->getAs<RecordType>(); 504 return Type->getDecl()->hasAttr<CapabilityAttr>(); 505 }, BPaths)) 506 return true; 507 } 508 return false; 509 } 510 511 static bool checkTypedefTypeForCapability(QualType Ty) { 512 const auto *TD = Ty->getAs<TypedefType>(); 513 if (!TD) 514 return false; 515 516 TypedefNameDecl *TN = TD->getDecl(); 517 if (!TN) 518 return false; 519 520 return TN->hasAttr<CapabilityAttr>(); 521 } 522 523 static bool typeHasCapability(Sema &S, QualType Ty) { 524 if (checkTypedefTypeForCapability(Ty)) 525 return true; 526 527 if (checkRecordTypeForCapability(S, Ty)) 528 return true; 529 530 return false; 531 } 532 533 static bool isCapabilityExpr(Sema &S, const Expr *Ex) { 534 // Capability expressions are simple expressions involving the boolean logic 535 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once 536 // a DeclRefExpr is found, its type should be checked to determine whether it 537 // is a capability or not. 538 539 if (const auto *E = dyn_cast<CastExpr>(Ex)) 540 return isCapabilityExpr(S, E->getSubExpr()); 541 else if (const auto *E = dyn_cast<ParenExpr>(Ex)) 542 return isCapabilityExpr(S, E->getSubExpr()); 543 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) { 544 if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf || 545 E->getOpcode() == UO_Deref) 546 return isCapabilityExpr(S, E->getSubExpr()); 547 return false; 548 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) { 549 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr) 550 return isCapabilityExpr(S, E->getLHS()) && 551 isCapabilityExpr(S, E->getRHS()); 552 return false; 553 } 554 555 return typeHasCapability(S, Ex->getType()); 556 } 557 558 /// \brief Checks that all attribute arguments, starting from Sidx, resolve to 559 /// a capability object. 560 /// \param Sidx The attribute argument index to start checking with. 561 /// \param ParamIdxOk Whether an argument can be indexing into a function 562 /// parameter list. 563 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D, 564 const AttributeList &AL, 565 SmallVectorImpl<Expr *> &Args, 566 int Sidx = 0, 567 bool ParamIdxOk = false) { 568 for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) { 569 Expr *ArgExp = AL.getArgAsExpr(Idx); 570 571 if (ArgExp->isTypeDependent()) { 572 // FIXME -- need to check this again on template instantiation 573 Args.push_back(ArgExp); 574 continue; 575 } 576 577 if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) { 578 if (StrLit->getLength() == 0 || 579 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) { 580 // Pass empty strings to the analyzer without warnings. 581 // Treat "*" as the universal lock. 582 Args.push_back(ArgExp); 583 continue; 584 } 585 586 // We allow constant strings to be used as a placeholder for expressions 587 // that are not valid C++ syntax, but warn that they are ignored. 588 S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL.getName(); 589 Args.push_back(ArgExp); 590 continue; 591 } 592 593 QualType ArgTy = ArgExp->getType(); 594 595 // A pointer to member expression of the form &MyClass::mu is treated 596 // specially -- we need to look at the type of the member. 597 if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp)) 598 if (UOp->getOpcode() == UO_AddrOf) 599 if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr())) 600 if (DRE->getDecl()->isCXXInstanceMember()) 601 ArgTy = DRE->getDecl()->getType(); 602 603 // First see if we can just cast to record type, or pointer to record type. 604 const RecordType *RT = getRecordType(ArgTy); 605 606 // Now check if we index into a record type function param. 607 if(!RT && ParamIdxOk) { 608 const auto *FD = dyn_cast<FunctionDecl>(D); 609 const auto *IL = dyn_cast<IntegerLiteral>(ArgExp); 610 if(FD && IL) { 611 unsigned int NumParams = FD->getNumParams(); 612 llvm::APInt ArgValue = IL->getValue(); 613 uint64_t ParamIdxFromOne = ArgValue.getZExtValue(); 614 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1; 615 if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) { 616 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range) 617 << AL.getName() << Idx + 1 << NumParams; 618 continue; 619 } 620 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType(); 621 } 622 } 623 624 // If the type does not have a capability, see if the components of the 625 // expression have capabilities. This allows for writing C code where the 626 // capability may be on the type, and the expression is a capability 627 // boolean logic expression. Eg) requires_capability(A || B && !C) 628 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp)) 629 S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable) 630 << AL.getName() << ArgTy; 631 632 Args.push_back(ArgExp); 633 } 634 } 635 636 //===----------------------------------------------------------------------===// 637 // Attribute Implementations 638 //===----------------------------------------------------------------------===// 639 640 static void handlePtGuardedVarAttr(Sema &S, Decl *D, 641 const AttributeList &AL) { 642 if (!threadSafetyCheckIsPointer(S, D, AL)) 643 return; 644 645 D->addAttr(::new (S.Context) 646 PtGuardedVarAttr(AL.getRange(), S.Context, 647 AL.getAttributeSpellingListIndex())); 648 } 649 650 static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const AttributeList &AL, 651 Expr *&Arg) { 652 SmallVector<Expr *, 1> Args; 653 // check that all arguments are lockable objects 654 checkAttrArgsAreCapabilityObjs(S, D, AL, Args); 655 unsigned Size = Args.size(); 656 if (Size != 1) 657 return false; 658 659 Arg = Args[0]; 660 661 return true; 662 } 663 664 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &AL) { 665 Expr *Arg = nullptr; 666 if (!checkGuardedByAttrCommon(S, D, AL, Arg)) 667 return; 668 669 D->addAttr(::new (S.Context) GuardedByAttr( 670 AL.getRange(), S.Context, Arg, AL.getAttributeSpellingListIndex())); 671 } 672 673 static void handlePtGuardedByAttr(Sema &S, Decl *D, 674 const AttributeList &AL) { 675 Expr *Arg = nullptr; 676 if (!checkGuardedByAttrCommon(S, D, AL, Arg)) 677 return; 678 679 if (!threadSafetyCheckIsPointer(S, D, AL)) 680 return; 681 682 D->addAttr(::new (S.Context) PtGuardedByAttr( 683 AL.getRange(), S.Context, Arg, AL.getAttributeSpellingListIndex())); 684 } 685 686 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, 687 const AttributeList &AL, 688 SmallVectorImpl<Expr *> &Args) { 689 if (!checkAttributeAtLeastNumArgs(S, AL, 1)) 690 return false; 691 692 // Check that this attribute only applies to lockable types. 693 QualType QT = cast<ValueDecl>(D)->getType(); 694 if (!QT->isDependentType() && !typeHasCapability(S, QT)) { 695 S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) 696 << AL.getName(); 697 return false; 698 } 699 700 // Check that all arguments are lockable objects. 701 checkAttrArgsAreCapabilityObjs(S, D, AL, Args); 702 if (Args.empty()) 703 return false; 704 705 return true; 706 } 707 708 static void handleAcquiredAfterAttr(Sema &S, Decl *D, 709 const AttributeList &AL) { 710 SmallVector<Expr *, 1> Args; 711 if (!checkAcquireOrderAttrCommon(S, D, AL, Args)) 712 return; 713 714 Expr **StartArg = &Args[0]; 715 D->addAttr(::new (S.Context) AcquiredAfterAttr( 716 AL.getRange(), S.Context, StartArg, Args.size(), 717 AL.getAttributeSpellingListIndex())); 718 } 719 720 static void handleAcquiredBeforeAttr(Sema &S, Decl *D, 721 const AttributeList &AL) { 722 SmallVector<Expr *, 1> Args; 723 if (!checkAcquireOrderAttrCommon(S, D, AL, Args)) 724 return; 725 726 Expr **StartArg = &Args[0]; 727 D->addAttr(::new (S.Context) AcquiredBeforeAttr( 728 AL.getRange(), S.Context, StartArg, Args.size(), 729 AL.getAttributeSpellingListIndex())); 730 } 731 732 static bool checkLockFunAttrCommon(Sema &S, Decl *D, 733 const AttributeList &AL, 734 SmallVectorImpl<Expr *> &Args) { 735 // zero or more arguments ok 736 // check that all arguments are lockable objects 737 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true); 738 739 return true; 740 } 741 742 static void handleAssertSharedLockAttr(Sema &S, Decl *D, 743 const AttributeList &AL) { 744 SmallVector<Expr *, 1> Args; 745 if (!checkLockFunAttrCommon(S, D, AL, Args)) 746 return; 747 748 unsigned Size = Args.size(); 749 Expr **StartArg = Size == 0 ? nullptr : &Args[0]; 750 D->addAttr(::new (S.Context) 751 AssertSharedLockAttr(AL.getRange(), S.Context, StartArg, Size, 752 AL.getAttributeSpellingListIndex())); 753 } 754 755 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D, 756 const AttributeList &AL) { 757 SmallVector<Expr *, 1> Args; 758 if (!checkLockFunAttrCommon(S, D, AL, Args)) 759 return; 760 761 unsigned Size = Args.size(); 762 Expr **StartArg = Size == 0 ? nullptr : &Args[0]; 763 D->addAttr(::new (S.Context) AssertExclusiveLockAttr( 764 AL.getRange(), S.Context, StartArg, Size, 765 AL.getAttributeSpellingListIndex())); 766 } 767 768 /// \brief Checks to be sure that the given parameter number is in bounds, and is 769 /// an integral type. Will emit appropriate diagnostics if this returns 770 /// false. 771 /// 772 /// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used 773 /// to actually retrieve the argument, so it's base-0. 774 template <typename AttrInfo> 775 static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD, 776 const AttrInfo &AI, Expr *AttrArg, 777 unsigned FuncParamNo, unsigned AttrArgNo, 778 bool AllowDependentType = false) { 779 uint64_t Idx; 780 if (!checkFunctionOrMethodParameterIndex(S, FD, AI, FuncParamNo, AttrArg, 781 Idx)) 782 return false; 783 784 const ParmVarDecl *Param = FD->getParamDecl(Idx); 785 if (AllowDependentType && Param->getType()->isDependentType()) 786 return true; 787 if (!Param->getType()->isIntegerType() && !Param->getType()->isCharType()) { 788 SourceLocation SrcLoc = AttrArg->getLocStart(); 789 S.Diag(SrcLoc, diag::err_attribute_integers_only) 790 << getAttrName(AI) << Param->getSourceRange(); 791 return false; 792 } 793 return true; 794 } 795 796 /// \brief Checks to be sure that the given parameter number is in bounds, and is 797 /// an integral type. Will emit appropriate diagnostics if this returns false. 798 /// 799 /// FuncParamNo is expected to be from the user, so is base-1. AttrArgNo is used 800 /// to actually retrieve the argument, so it's base-0. 801 static bool checkParamIsIntegerType(Sema &S, const FunctionDecl *FD, 802 const AttributeList &AL, 803 unsigned FuncParamNo, unsigned AttrArgNo, 804 bool AllowDependentType = false) { 805 assert(AL.isArgExpr(AttrArgNo) && "Expected expression argument"); 806 return checkParamIsIntegerType(S, FD, AL, AL.getArgAsExpr(AttrArgNo), 807 FuncParamNo, AttrArgNo, AllowDependentType); 808 } 809 810 static void handleAllocSizeAttr(Sema &S, Decl *D, const AttributeList &AL) { 811 if (!checkAttributeAtLeastNumArgs(S, AL, 1) || 812 !checkAttributeAtMostNumArgs(S, AL, 2)) 813 return; 814 815 const auto *FD = cast<FunctionDecl>(D); 816 if (!FD->getReturnType()->isPointerType()) { 817 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) 818 << AL.getName(); 819 return; 820 } 821 822 const Expr *SizeExpr = AL.getArgAsExpr(0); 823 int SizeArgNo; 824 // Parameter indices are 1-indexed, hence Index=1 825 if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNo, /*Index=*/1)) 826 return; 827 828 if (!checkParamIsIntegerType(S, FD, AL, SizeArgNo, /*AttrArgNo=*/0)) 829 return; 830 831 // Args are 1-indexed, so 0 implies that the arg was not present 832 int NumberArgNo = 0; 833 if (AL.getNumArgs() == 2) { 834 const Expr *NumberExpr = AL.getArgAsExpr(1); 835 // Parameter indices are 1-based, hence Index=2 836 if (!checkPositiveIntArgument(S, AL, NumberExpr, NumberArgNo, 837 /*Index=*/2)) 838 return; 839 840 if (!checkParamIsIntegerType(S, FD, AL, NumberArgNo, /*AttrArgNo=*/1)) 841 return; 842 } 843 844 D->addAttr(::new (S.Context) 845 AllocSizeAttr(AL.getRange(), S.Context, SizeArgNo, NumberArgNo, 846 AL.getAttributeSpellingListIndex())); 847 } 848 849 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, 850 const AttributeList &AL, 851 SmallVectorImpl<Expr *> &Args) { 852 if (!checkAttributeAtLeastNumArgs(S, AL, 1)) 853 return false; 854 855 if (!isIntOrBool(AL.getArgAsExpr(0))) { 856 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 857 << AL.getName() << 1 << AANT_ArgumentIntOrBool; 858 return false; 859 } 860 861 // check that all arguments are lockable objects 862 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1); 863 864 return true; 865 } 866 867 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D, 868 const AttributeList &AL) { 869 SmallVector<Expr*, 2> Args; 870 if (!checkTryLockFunAttrCommon(S, D, AL, Args)) 871 return; 872 873 D->addAttr(::new (S.Context) SharedTrylockFunctionAttr( 874 AL.getRange(), S.Context, AL.getArgAsExpr(0), Args.data(), Args.size(), 875 AL.getAttributeSpellingListIndex())); 876 } 877 878 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D, 879 const AttributeList &AL) { 880 SmallVector<Expr*, 2> Args; 881 if (!checkTryLockFunAttrCommon(S, D, AL, Args)) 882 return; 883 884 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr( 885 AL.getRange(), S.Context, AL.getArgAsExpr(0), Args.data(), 886 Args.size(), AL.getAttributeSpellingListIndex())); 887 } 888 889 static void handleLockReturnedAttr(Sema &S, Decl *D, 890 const AttributeList &AL) { 891 // check that the argument is lockable object 892 SmallVector<Expr*, 1> Args; 893 checkAttrArgsAreCapabilityObjs(S, D, AL, Args); 894 unsigned Size = Args.size(); 895 if (Size == 0) 896 return; 897 898 D->addAttr(::new (S.Context) 899 LockReturnedAttr(AL.getRange(), S.Context, Args[0], 900 AL.getAttributeSpellingListIndex())); 901 } 902 903 static void handleLocksExcludedAttr(Sema &S, Decl *D, 904 const AttributeList &AL) { 905 if (!checkAttributeAtLeastNumArgs(S, AL, 1)) 906 return; 907 908 // check that all arguments are lockable objects 909 SmallVector<Expr*, 1> Args; 910 checkAttrArgsAreCapabilityObjs(S, D, AL, Args); 911 unsigned Size = Args.size(); 912 if (Size == 0) 913 return; 914 Expr **StartArg = &Args[0]; 915 916 D->addAttr(::new (S.Context) 917 LocksExcludedAttr(AL.getRange(), S.Context, StartArg, Size, 918 AL.getAttributeSpellingListIndex())); 919 } 920 921 static bool checkFunctionConditionAttr(Sema &S, Decl *D, 922 const AttributeList &AL, 923 Expr *&Cond, StringRef &Msg) { 924 Cond = AL.getArgAsExpr(0); 925 if (!Cond->isTypeDependent()) { 926 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond); 927 if (Converted.isInvalid()) 928 return false; 929 Cond = Converted.get(); 930 } 931 932 if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg)) 933 return false; 934 935 if (Msg.empty()) 936 Msg = "<no message provided>"; 937 938 SmallVector<PartialDiagnosticAt, 8> Diags; 939 if (isa<FunctionDecl>(D) && !Cond->isValueDependent() && 940 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D), 941 Diags)) { 942 S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) 943 << AL.getName(); 944 for (const PartialDiagnosticAt &PDiag : Diags) 945 S.Diag(PDiag.first, PDiag.second); 946 return false; 947 } 948 return true; 949 } 950 951 static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &AL) { 952 S.Diag(AL.getLoc(), diag::ext_clang_enable_if); 953 954 Expr *Cond; 955 StringRef Msg; 956 if (checkFunctionConditionAttr(S, D, AL, Cond, Msg)) 957 D->addAttr(::new (S.Context) 958 EnableIfAttr(AL.getRange(), S.Context, Cond, Msg, 959 AL.getAttributeSpellingListIndex())); 960 } 961 962 namespace { 963 /// Determines if a given Expr references any of the given function's 964 /// ParmVarDecls, or the function's implicit `this` parameter (if applicable). 965 class ArgumentDependenceChecker 966 : public RecursiveASTVisitor<ArgumentDependenceChecker> { 967 #ifndef NDEBUG 968 const CXXRecordDecl *ClassType; 969 #endif 970 llvm::SmallPtrSet<const ParmVarDecl *, 16> Parms; 971 bool Result; 972 973 public: 974 ArgumentDependenceChecker(const FunctionDecl *FD) { 975 #ifndef NDEBUG 976 if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 977 ClassType = MD->getParent(); 978 else 979 ClassType = nullptr; 980 #endif 981 Parms.insert(FD->param_begin(), FD->param_end()); 982 } 983 984 bool referencesArgs(Expr *E) { 985 Result = false; 986 TraverseStmt(E); 987 return Result; 988 } 989 990 bool VisitCXXThisExpr(CXXThisExpr *E) { 991 assert(E->getType()->getPointeeCXXRecordDecl() == ClassType && 992 "`this` doesn't refer to the enclosing class?"); 993 Result = true; 994 return false; 995 } 996 997 bool VisitDeclRefExpr(DeclRefExpr *DRE) { 998 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) 999 if (Parms.count(PVD)) { 1000 Result = true; 1001 return false; 1002 } 1003 return true; 1004 } 1005 }; 1006 } 1007 1008 static void handleDiagnoseIfAttr(Sema &S, Decl *D, const AttributeList &AL) { 1009 S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if); 1010 1011 Expr *Cond; 1012 StringRef Msg; 1013 if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg)) 1014 return; 1015 1016 StringRef DiagTypeStr; 1017 if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr)) 1018 return; 1019 1020 DiagnoseIfAttr::DiagnosticType DiagType; 1021 if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) { 1022 S.Diag(AL.getArgAsExpr(2)->getLocStart(), 1023 diag::err_diagnose_if_invalid_diagnostic_type); 1024 return; 1025 } 1026 1027 bool ArgDependent = false; 1028 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 1029 ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond); 1030 D->addAttr(::new (S.Context) DiagnoseIfAttr( 1031 AL.getRange(), S.Context, Cond, Msg, DiagType, ArgDependent, 1032 cast<NamedDecl>(D), AL.getAttributeSpellingListIndex())); 1033 } 1034 1035 static void handlePassObjectSizeAttr(Sema &S, Decl *D, 1036 const AttributeList &AL) { 1037 if (D->hasAttr<PassObjectSizeAttr>()) { 1038 S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter) 1039 << AL.getName(); 1040 return; 1041 } 1042 1043 Expr *E = AL.getArgAsExpr(0); 1044 uint32_t Type; 1045 if (!checkUInt32Argument(S, AL, E, Type, /*Idx=*/1)) 1046 return; 1047 1048 // pass_object_size's argument is passed in as the second argument of 1049 // __builtin_object_size. So, it has the same constraints as that second 1050 // argument; namely, it must be in the range [0, 3]. 1051 if (Type > 3) { 1052 S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range) 1053 << AL.getName() << 0 << 3 << E->getSourceRange(); 1054 return; 1055 } 1056 1057 // pass_object_size is only supported on constant pointer parameters; as a 1058 // kindness to users, we allow the parameter to be non-const for declarations. 1059 // At this point, we have no clue if `D` belongs to a function declaration or 1060 // definition, so we defer the constness check until later. 1061 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) { 1062 S.Diag(D->getLocStart(), diag::err_attribute_pointers_only) 1063 << AL.getName() << 1; 1064 return; 1065 } 1066 1067 D->addAttr(::new (S.Context) PassObjectSizeAttr( 1068 AL.getRange(), S.Context, (int)Type, AL.getAttributeSpellingListIndex())); 1069 } 1070 1071 static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &AL) { 1072 ConsumableAttr::ConsumedState DefaultState; 1073 1074 if (AL.isArgIdent(0)) { 1075 IdentifierLoc *IL = AL.getArgAsIdent(0); 1076 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(), 1077 DefaultState)) { 1078 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) 1079 << AL.getName() << IL->Ident; 1080 return; 1081 } 1082 } else { 1083 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 1084 << AL.getName() << AANT_ArgumentIdentifier; 1085 return; 1086 } 1087 1088 D->addAttr(::new (S.Context) 1089 ConsumableAttr(AL.getRange(), S.Context, DefaultState, 1090 AL.getAttributeSpellingListIndex())); 1091 } 1092 1093 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD, 1094 const AttributeList &AL) { 1095 ASTContext &CurrContext = S.getASTContext(); 1096 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType(); 1097 1098 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) { 1099 if (!RD->hasAttr<ConsumableAttr>()) { 1100 S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) << 1101 RD->getNameAsString(); 1102 1103 return false; 1104 } 1105 } 1106 1107 return true; 1108 } 1109 1110 static void handleCallableWhenAttr(Sema &S, Decl *D, 1111 const AttributeList &AL) { 1112 if (!checkAttributeAtLeastNumArgs(S, AL, 1)) 1113 return; 1114 1115 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL)) 1116 return; 1117 1118 SmallVector<CallableWhenAttr::ConsumedState, 3> States; 1119 for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) { 1120 CallableWhenAttr::ConsumedState CallableState; 1121 1122 StringRef StateString; 1123 SourceLocation Loc; 1124 if (AL.isArgIdent(ArgIndex)) { 1125 IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex); 1126 StateString = Ident->Ident->getName(); 1127 Loc = Ident->Loc; 1128 } else { 1129 if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc)) 1130 return; 1131 } 1132 1133 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString, 1134 CallableState)) { 1135 S.Diag(Loc, diag::warn_attribute_type_not_supported) 1136 << AL.getName() << StateString; 1137 return; 1138 } 1139 1140 States.push_back(CallableState); 1141 } 1142 1143 D->addAttr(::new (S.Context) 1144 CallableWhenAttr(AL.getRange(), S.Context, States.data(), 1145 States.size(), AL.getAttributeSpellingListIndex())); 1146 } 1147 1148 static void handleParamTypestateAttr(Sema &S, Decl *D, 1149 const AttributeList &AL) { 1150 ParamTypestateAttr::ConsumedState ParamState; 1151 1152 if (AL.isArgIdent(0)) { 1153 IdentifierLoc *Ident = AL.getArgAsIdent(0); 1154 StringRef StateString = Ident->Ident->getName(); 1155 1156 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString, 1157 ParamState)) { 1158 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) 1159 << AL.getName() << StateString; 1160 return; 1161 } 1162 } else { 1163 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) << 1164 AL.getName() << AANT_ArgumentIdentifier; 1165 return; 1166 } 1167 1168 // FIXME: This check is currently being done in the analysis. It can be 1169 // enabled here only after the parser propagates attributes at 1170 // template specialization definition, not declaration. 1171 //QualType ReturnType = cast<ParmVarDecl>(D)->getType(); 1172 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); 1173 // 1174 //if (!RD || !RD->hasAttr<ConsumableAttr>()) { 1175 // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) << 1176 // ReturnType.getAsString(); 1177 // return; 1178 //} 1179 1180 D->addAttr(::new (S.Context) 1181 ParamTypestateAttr(AL.getRange(), S.Context, ParamState, 1182 AL.getAttributeSpellingListIndex())); 1183 } 1184 1185 static void handleReturnTypestateAttr(Sema &S, Decl *D, 1186 const AttributeList &AL) { 1187 ReturnTypestateAttr::ConsumedState ReturnState; 1188 1189 if (AL.isArgIdent(0)) { 1190 IdentifierLoc *IL = AL.getArgAsIdent(0); 1191 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(), 1192 ReturnState)) { 1193 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) 1194 << AL.getName() << IL->Ident; 1195 return; 1196 } 1197 } else { 1198 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) << 1199 AL.getName() << AANT_ArgumentIdentifier; 1200 return; 1201 } 1202 1203 // FIXME: This check is currently being done in the analysis. It can be 1204 // enabled here only after the parser propagates attributes at 1205 // template specialization definition, not declaration. 1206 //QualType ReturnType; 1207 // 1208 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) { 1209 // ReturnType = Param->getType(); 1210 // 1211 //} else if (const CXXConstructorDecl *Constructor = 1212 // dyn_cast<CXXConstructorDecl>(D)) { 1213 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType(); 1214 // 1215 //} else { 1216 // 1217 // ReturnType = cast<FunctionDecl>(D)->getCallResultType(); 1218 //} 1219 // 1220 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); 1221 // 1222 //if (!RD || !RD->hasAttr<ConsumableAttr>()) { 1223 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) << 1224 // ReturnType.getAsString(); 1225 // return; 1226 //} 1227 1228 D->addAttr(::new (S.Context) 1229 ReturnTypestateAttr(AL.getRange(), S.Context, ReturnState, 1230 AL.getAttributeSpellingListIndex())); 1231 } 1232 1233 static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &AL) { 1234 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL)) 1235 return; 1236 1237 SetTypestateAttr::ConsumedState NewState; 1238 if (AL.isArgIdent(0)) { 1239 IdentifierLoc *Ident = AL.getArgAsIdent(0); 1240 StringRef Param = Ident->Ident->getName(); 1241 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) { 1242 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) 1243 << AL.getName() << Param; 1244 return; 1245 } 1246 } else { 1247 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) << 1248 AL.getName() << AANT_ArgumentIdentifier; 1249 return; 1250 } 1251 1252 D->addAttr(::new (S.Context) 1253 SetTypestateAttr(AL.getRange(), S.Context, NewState, 1254 AL.getAttributeSpellingListIndex())); 1255 } 1256 1257 static void handleTestTypestateAttr(Sema &S, Decl *D, 1258 const AttributeList &AL) { 1259 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL)) 1260 return; 1261 1262 TestTypestateAttr::ConsumedState TestState; 1263 if (AL.isArgIdent(0)) { 1264 IdentifierLoc *Ident = AL.getArgAsIdent(0); 1265 StringRef Param = Ident->Ident->getName(); 1266 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) { 1267 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) 1268 << AL.getName() << Param; 1269 return; 1270 } 1271 } else { 1272 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) << 1273 AL.getName() << AANT_ArgumentIdentifier; 1274 return; 1275 } 1276 1277 D->addAttr(::new (S.Context) 1278 TestTypestateAttr(AL.getRange(), S.Context, TestState, 1279 AL.getAttributeSpellingListIndex())); 1280 } 1281 1282 static void handleExtVectorTypeAttr(Sema &S, Decl *D, const AttributeList &AL) { 1283 // Remember this typedef decl, we will need it later for diagnostics. 1284 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D)); 1285 } 1286 1287 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &AL) { 1288 if (auto *TD = dyn_cast<TagDecl>(D)) 1289 TD->addAttr(::new (S.Context) PackedAttr(AL.getRange(), S.Context, 1290 AL.getAttributeSpellingListIndex())); 1291 else if (auto *FD = dyn_cast<FieldDecl>(D)) { 1292 bool BitfieldByteAligned = (!FD->getType()->isDependentType() && 1293 !FD->getType()->isIncompleteType() && 1294 FD->isBitField() && 1295 S.Context.getTypeAlign(FD->getType()) <= 8); 1296 1297 if (S.getASTContext().getTargetInfo().getTriple().isPS4()) { 1298 if (BitfieldByteAligned) 1299 // The PS4 target needs to maintain ABI backwards compatibility. 1300 S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type) 1301 << AL.getName() << FD->getType(); 1302 else 1303 FD->addAttr(::new (S.Context) PackedAttr( 1304 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); 1305 } else { 1306 // Report warning about changed offset in the newer compiler versions. 1307 if (BitfieldByteAligned) 1308 S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield); 1309 1310 FD->addAttr(::new (S.Context) PackedAttr( 1311 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); 1312 } 1313 1314 } else 1315 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL.getName(); 1316 } 1317 1318 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &AL) { 1319 // The IBOutlet/IBOutletCollection attributes only apply to instance 1320 // variables or properties of Objective-C classes. The outlet must also 1321 // have an object reference type. 1322 if (const auto *VD = dyn_cast<ObjCIvarDecl>(D)) { 1323 if (!VD->getType()->getAs<ObjCObjectPointerType>()) { 1324 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type) 1325 << AL.getName() << VD->getType() << 0; 1326 return false; 1327 } 1328 } 1329 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) { 1330 if (!PD->getType()->getAs<ObjCObjectPointerType>()) { 1331 S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type) 1332 << AL.getName() << PD->getType() << 1; 1333 return false; 1334 } 1335 } 1336 else { 1337 S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL.getName(); 1338 return false; 1339 } 1340 1341 return true; 1342 } 1343 1344 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &AL) { 1345 if (!checkIBOutletCommon(S, D, AL)) 1346 return; 1347 1348 D->addAttr(::new (S.Context) 1349 IBOutletAttr(AL.getRange(), S.Context, 1350 AL.getAttributeSpellingListIndex())); 1351 } 1352 1353 static void handleIBOutletCollection(Sema &S, Decl *D, 1354 const AttributeList &AL) { 1355 1356 // The iboutletcollection attribute can have zero or one arguments. 1357 if (AL.getNumArgs() > 1) { 1358 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) 1359 << AL.getName() << 1; 1360 return; 1361 } 1362 1363 if (!checkIBOutletCommon(S, D, AL)) 1364 return; 1365 1366 ParsedType PT; 1367 1368 if (AL.hasParsedType()) 1369 PT = AL.getTypeArg(); 1370 else { 1371 PT = S.getTypeName(S.Context.Idents.get("NSObject"), AL.getLoc(), 1372 S.getScopeForContext(D->getDeclContext()->getParent())); 1373 if (!PT) { 1374 S.Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject"; 1375 return; 1376 } 1377 } 1378 1379 TypeSourceInfo *QTLoc = nullptr; 1380 QualType QT = S.GetTypeFromParser(PT, &QTLoc); 1381 if (!QTLoc) 1382 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, AL.getLoc()); 1383 1384 // Diagnose use of non-object type in iboutletcollection attribute. 1385 // FIXME. Gnu attribute extension ignores use of builtin types in 1386 // attributes. So, __attribute__((iboutletcollection(char))) will be 1387 // treated as __attribute__((iboutletcollection())). 1388 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) { 1389 S.Diag(AL.getLoc(), 1390 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype 1391 : diag::err_iboutletcollection_type) << QT; 1392 return; 1393 } 1394 1395 D->addAttr(::new (S.Context) 1396 IBOutletCollectionAttr(AL.getRange(), S.Context, QTLoc, 1397 AL.getAttributeSpellingListIndex())); 1398 } 1399 1400 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) { 1401 if (RefOkay) { 1402 if (T->isReferenceType()) 1403 return true; 1404 } else { 1405 T = T.getNonReferenceType(); 1406 } 1407 1408 // The nonnull attribute, and other similar attributes, can be applied to a 1409 // transparent union that contains a pointer type. 1410 if (const RecordType *UT = T->getAsUnionType()) { 1411 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) { 1412 RecordDecl *UD = UT->getDecl(); 1413 for (const auto *I : UD->fields()) { 1414 QualType QT = I->getType(); 1415 if (QT->isAnyPointerType() || QT->isBlockPointerType()) 1416 return true; 1417 } 1418 } 1419 } 1420 1421 return T->isAnyPointerType() || T->isBlockPointerType(); 1422 } 1423 1424 static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &AL, 1425 SourceRange AttrParmRange, 1426 SourceRange TypeRange, 1427 bool isReturnValue = false) { 1428 if (!S.isValidPointerAttrType(T)) { 1429 if (isReturnValue) 1430 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) 1431 << AL.getName() << AttrParmRange << TypeRange; 1432 else 1433 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only) 1434 << AL.getName() << AttrParmRange << TypeRange << 0; 1435 return false; 1436 } 1437 return true; 1438 } 1439 1440 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &AL) { 1441 SmallVector<unsigned, 8> NonNullArgs; 1442 for (unsigned I = 0; I < AL.getNumArgs(); ++I) { 1443 Expr *Ex = AL.getArgAsExpr(I); 1444 uint64_t Idx; 1445 if (!checkFunctionOrMethodParameterIndex(S, D, AL, I + 1, Ex, Idx)) 1446 return; 1447 1448 // Is the function argument a pointer type? 1449 if (Idx < getFunctionOrMethodNumParams(D) && 1450 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), AL, 1451 Ex->getSourceRange(), 1452 getFunctionOrMethodParamRange(D, Idx))) 1453 continue; 1454 1455 NonNullArgs.push_back(Idx); 1456 } 1457 1458 // If no arguments were specified to __attribute__((nonnull)) then all pointer 1459 // arguments have a nonnull attribute; warn if there aren't any. Skip this 1460 // check if the attribute came from a macro expansion or a template 1461 // instantiation. 1462 if (NonNullArgs.empty() && AL.getLoc().isFileID() && 1463 !S.inTemplateInstantiation()) { 1464 bool AnyPointers = isFunctionOrMethodVariadic(D); 1465 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); 1466 I != E && !AnyPointers; ++I) { 1467 QualType T = getFunctionOrMethodParamType(D, I); 1468 if (T->isDependentType() || S.isValidPointerAttrType(T)) 1469 AnyPointers = true; 1470 } 1471 1472 if (!AnyPointers) 1473 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers); 1474 } 1475 1476 unsigned *Start = NonNullArgs.data(); 1477 unsigned Size = NonNullArgs.size(); 1478 llvm::array_pod_sort(Start, Start + Size); 1479 D->addAttr(::new (S.Context) 1480 NonNullAttr(AL.getRange(), S.Context, Start, Size, 1481 AL.getAttributeSpellingListIndex())); 1482 } 1483 1484 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D, 1485 const AttributeList &AL) { 1486 if (AL.getNumArgs() > 0) { 1487 if (D->getFunctionType()) { 1488 handleNonNullAttr(S, D, AL); 1489 } else { 1490 S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args) 1491 << D->getSourceRange(); 1492 } 1493 return; 1494 } 1495 1496 // Is the argument a pointer type? 1497 if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(), 1498 D->getSourceRange())) 1499 return; 1500 1501 D->addAttr(::new (S.Context) 1502 NonNullAttr(AL.getRange(), S.Context, nullptr, 0, 1503 AL.getAttributeSpellingListIndex())); 1504 } 1505 1506 static void handleReturnsNonNullAttr(Sema &S, Decl *D, 1507 const AttributeList &AL) { 1508 QualType ResultType = getFunctionOrMethodResultType(D); 1509 SourceRange SR = getFunctionOrMethodResultSourceRange(D); 1510 if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR, 1511 /* isReturnValue */ true)) 1512 return; 1513 1514 D->addAttr(::new (S.Context) 1515 ReturnsNonNullAttr(AL.getRange(), S.Context, 1516 AL.getAttributeSpellingListIndex())); 1517 } 1518 1519 static void handleNoEscapeAttr(Sema &S, Decl *D, const AttributeList &AL) { 1520 if (D->isInvalidDecl()) 1521 return; 1522 1523 // noescape only applies to pointer types. 1524 QualType T = cast<ParmVarDecl>(D)->getType(); 1525 if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) { 1526 S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only) 1527 << AL.getName() << AL.getRange() << 0; 1528 return; 1529 } 1530 1531 D->addAttr(::new (S.Context) NoEscapeAttr( 1532 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); 1533 } 1534 1535 static void handleAssumeAlignedAttr(Sema &S, Decl *D, 1536 const AttributeList &AL) { 1537 Expr *E = AL.getArgAsExpr(0), 1538 *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr; 1539 S.AddAssumeAlignedAttr(AL.getRange(), D, E, OE, 1540 AL.getAttributeSpellingListIndex()); 1541 } 1542 1543 static void handleAllocAlignAttr(Sema &S, Decl *D, 1544 const AttributeList &AL) { 1545 S.AddAllocAlignAttr(AL.getRange(), D, AL.getArgAsExpr(0), 1546 AL.getAttributeSpellingListIndex()); 1547 } 1548 1549 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, 1550 Expr *OE, unsigned SpellingListIndex) { 1551 QualType ResultType = getFunctionOrMethodResultType(D); 1552 SourceRange SR = getFunctionOrMethodResultSourceRange(D); 1553 1554 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex); 1555 SourceLocation AttrLoc = AttrRange.getBegin(); 1556 1557 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) { 1558 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only) 1559 << &TmpAttr << AttrRange << SR; 1560 return; 1561 } 1562 1563 if (!E->isValueDependent()) { 1564 llvm::APSInt I(64); 1565 if (!E->isIntegerConstantExpr(I, Context)) { 1566 if (OE) 1567 Diag(AttrLoc, diag::err_attribute_argument_n_type) 1568 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant 1569 << E->getSourceRange(); 1570 else 1571 Diag(AttrLoc, diag::err_attribute_argument_type) 1572 << &TmpAttr << AANT_ArgumentIntegerConstant 1573 << E->getSourceRange(); 1574 return; 1575 } 1576 1577 if (!I.isPowerOf2()) { 1578 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 1579 << E->getSourceRange(); 1580 return; 1581 } 1582 } 1583 1584 if (OE) { 1585 if (!OE->isValueDependent()) { 1586 llvm::APSInt I(64); 1587 if (!OE->isIntegerConstantExpr(I, Context)) { 1588 Diag(AttrLoc, diag::err_attribute_argument_n_type) 1589 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant 1590 << OE->getSourceRange(); 1591 return; 1592 } 1593 } 1594 } 1595 1596 D->addAttr(::new (Context) 1597 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex)); 1598 } 1599 1600 void Sema::AddAllocAlignAttr(SourceRange AttrRange, Decl *D, Expr *ParamExpr, 1601 unsigned SpellingListIndex) { 1602 QualType ResultType = getFunctionOrMethodResultType(D); 1603 1604 AllocAlignAttr TmpAttr(AttrRange, Context, 0, SpellingListIndex); 1605 SourceLocation AttrLoc = AttrRange.getBegin(); 1606 1607 if (!ResultType->isDependentType() && 1608 !isValidPointerAttrType(ResultType, /* RefOkay */ true)) { 1609 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only) 1610 << &TmpAttr << AttrRange << getFunctionOrMethodResultSourceRange(D); 1611 return; 1612 } 1613 1614 uint64_t IndexVal; 1615 const auto *FuncDecl = cast<FunctionDecl>(D); 1616 if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr, 1617 /*AttrArgNo=*/1, ParamExpr, 1618 IndexVal)) 1619 return; 1620 1621 QualType Ty = getFunctionOrMethodParamType(D, IndexVal); 1622 if (!Ty->isDependentType() && !Ty->isIntegralType(Context)) { 1623 Diag(ParamExpr->getLocStart(), diag::err_attribute_integers_only) 1624 << &TmpAttr << FuncDecl->getParamDecl(IndexVal)->getSourceRange(); 1625 return; 1626 } 1627 1628 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex 1629 // because that has corrected for the implicit this parameter, and is zero- 1630 // based. The attribute expects what the user wrote explicitly. 1631 llvm::APSInt Val; 1632 ParamExpr->EvaluateAsInt(Val, Context); 1633 1634 D->addAttr(::new (Context) AllocAlignAttr( 1635 AttrRange, Context, Val.getZExtValue(), SpellingListIndex)); 1636 } 1637 1638 /// Normalize the attribute, __foo__ becomes foo. 1639 /// Returns true if normalization was applied. 1640 static bool normalizeName(StringRef &AttrName) { 1641 if (AttrName.size() > 4 && AttrName.startswith("__") && 1642 AttrName.endswith("__")) { 1643 AttrName = AttrName.drop_front(2).drop_back(2); 1644 return true; 1645 } 1646 return false; 1647 } 1648 1649 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) { 1650 // This attribute must be applied to a function declaration. The first 1651 // argument to the attribute must be an identifier, the name of the resource, 1652 // for example: malloc. The following arguments must be argument indexes, the 1653 // arguments must be of integer type for Returns, otherwise of pointer type. 1654 // The difference between Holds and Takes is that a pointer may still be used 1655 // after being held. free() should be __attribute((ownership_takes)), whereas 1656 // a list append function may well be __attribute((ownership_holds)). 1657 1658 if (!AL.isArgIdent(0)) { 1659 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 1660 << AL.getName() << 1 << AANT_ArgumentIdentifier; 1661 return; 1662 } 1663 1664 // Figure out our Kind. 1665 OwnershipAttr::OwnershipKind K = 1666 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0, 1667 AL.getAttributeSpellingListIndex()).getOwnKind(); 1668 1669 // Check arguments. 1670 switch (K) { 1671 case OwnershipAttr::Takes: 1672 case OwnershipAttr::Holds: 1673 if (AL.getNumArgs() < 2) { 1674 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) 1675 << AL.getName() << 2; 1676 return; 1677 } 1678 break; 1679 case OwnershipAttr::Returns: 1680 if (AL.getNumArgs() > 2) { 1681 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) 1682 << AL.getName() << 1; 1683 return; 1684 } 1685 break; 1686 } 1687 1688 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident; 1689 1690 StringRef ModuleName = Module->getName(); 1691 if (normalizeName(ModuleName)) { 1692 Module = &S.PP.getIdentifierTable().get(ModuleName); 1693 } 1694 1695 SmallVector<unsigned, 8> OwnershipArgs; 1696 for (unsigned i = 1; i < AL.getNumArgs(); ++i) { 1697 Expr *Ex = AL.getArgAsExpr(i); 1698 uint64_t Idx; 1699 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx)) 1700 return; 1701 1702 // Is the function argument a pointer type? 1703 QualType T = getFunctionOrMethodParamType(D, Idx); 1704 int Err = -1; // No error 1705 switch (K) { 1706 case OwnershipAttr::Takes: 1707 case OwnershipAttr::Holds: 1708 if (!T->isAnyPointerType() && !T->isBlockPointerType()) 1709 Err = 0; 1710 break; 1711 case OwnershipAttr::Returns: 1712 if (!T->isIntegerType()) 1713 Err = 1; 1714 break; 1715 } 1716 if (-1 != Err) { 1717 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err 1718 << Ex->getSourceRange(); 1719 return; 1720 } 1721 1722 // Check we don't have a conflict with another ownership attribute. 1723 for (const auto *I : D->specific_attrs<OwnershipAttr>()) { 1724 // Cannot have two ownership attributes of different kinds for the same 1725 // index. 1726 if (I->getOwnKind() != K && I->args_end() != 1727 std::find(I->args_begin(), I->args_end(), Idx)) { 1728 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) 1729 << AL.getName() << I; 1730 return; 1731 } else if (K == OwnershipAttr::Returns && 1732 I->getOwnKind() == OwnershipAttr::Returns) { 1733 // A returns attribute conflicts with any other returns attribute using 1734 // a different index. Note, diagnostic reporting is 1-based, but stored 1735 // argument indexes are 0-based. 1736 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) { 1737 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch) 1738 << *(I->args_begin()) + 1; 1739 if (I->args_size()) 1740 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch) 1741 << (unsigned)Idx + 1 << Ex->getSourceRange(); 1742 return; 1743 } 1744 } 1745 } 1746 OwnershipArgs.push_back(Idx); 1747 } 1748 1749 unsigned* start = OwnershipArgs.data(); 1750 unsigned size = OwnershipArgs.size(); 1751 llvm::array_pod_sort(start, start + size); 1752 1753 D->addAttr(::new (S.Context) 1754 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size, 1755 AL.getAttributeSpellingListIndex())); 1756 } 1757 1758 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &AL) { 1759 // Check the attribute arguments. 1760 if (AL.getNumArgs() > 1) { 1761 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) 1762 << AL.getName() << 1; 1763 return; 1764 } 1765 1766 // gcc rejects 1767 // class c { 1768 // static int a __attribute__((weakref ("v2"))); 1769 // static int b() __attribute__((weakref ("f3"))); 1770 // }; 1771 // and ignores the attributes of 1772 // void f(void) { 1773 // static int a __attribute__((weakref ("v2"))); 1774 // } 1775 // we reject them 1776 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext(); 1777 if (!Ctx->isFileContext()) { 1778 S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context) 1779 << cast<NamedDecl>(D); 1780 return; 1781 } 1782 1783 // The GCC manual says 1784 // 1785 // At present, a declaration to which `weakref' is attached can only 1786 // be `static'. 1787 // 1788 // It also says 1789 // 1790 // Without a TARGET, 1791 // given as an argument to `weakref' or to `alias', `weakref' is 1792 // equivalent to `weak'. 1793 // 1794 // gcc 4.4.1 will accept 1795 // int a7 __attribute__((weakref)); 1796 // as 1797 // int a7 __attribute__((weak)); 1798 // This looks like a bug in gcc. We reject that for now. We should revisit 1799 // it if this behaviour is actually used. 1800 1801 // GCC rejects 1802 // static ((alias ("y"), weakref)). 1803 // Should we? How to check that weakref is before or after alias? 1804 1805 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead 1806 // of transforming it into an AliasAttr. The WeakRefAttr never uses the 1807 // StringRef parameter it was given anyway. 1808 StringRef Str; 1809 if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str)) 1810 // GCC will accept anything as the argument of weakref. Should we 1811 // check for an existing decl? 1812 D->addAttr(::new (S.Context) AliasAttr(AL.getRange(), S.Context, Str, 1813 AL.getAttributeSpellingListIndex())); 1814 1815 D->addAttr(::new (S.Context) 1816 WeakRefAttr(AL.getRange(), S.Context, 1817 AL.getAttributeSpellingListIndex())); 1818 } 1819 1820 static void handleIFuncAttr(Sema &S, Decl *D, const AttributeList &AL) { 1821 StringRef Str; 1822 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str)) 1823 return; 1824 1825 // Aliases should be on declarations, not definitions. 1826 const auto *FD = cast<FunctionDecl>(D); 1827 if (FD->isThisDeclarationADefinition()) { 1828 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1; 1829 return; 1830 } 1831 1832 D->addAttr(::new (S.Context) IFuncAttr(AL.getRange(), S.Context, Str, 1833 AL.getAttributeSpellingListIndex())); 1834 } 1835 1836 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &AL) { 1837 StringRef Str; 1838 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str)) 1839 return; 1840 1841 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 1842 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin); 1843 return; 1844 } 1845 if (S.Context.getTargetInfo().getTriple().isNVPTX()) { 1846 S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx); 1847 } 1848 1849 // Aliases should be on declarations, not definitions. 1850 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 1851 if (FD->isThisDeclarationADefinition()) { 1852 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0; 1853 return; 1854 } 1855 } else { 1856 const auto *VD = cast<VarDecl>(D); 1857 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) { 1858 S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0; 1859 return; 1860 } 1861 } 1862 1863 // FIXME: check if target symbol exists in current file 1864 1865 D->addAttr(::new (S.Context) AliasAttr(AL.getRange(), S.Context, Str, 1866 AL.getAttributeSpellingListIndex())); 1867 } 1868 1869 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &AL) { 1870 if (checkAttrMutualExclusion<HotAttr>(S, D, AL.getRange(), AL.getName())) 1871 return; 1872 1873 D->addAttr(::new (S.Context) ColdAttr(AL.getRange(), S.Context, 1874 AL.getAttributeSpellingListIndex())); 1875 } 1876 1877 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &AL) { 1878 if (checkAttrMutualExclusion<ColdAttr>(S, D, AL.getRange(), AL.getName())) 1879 return; 1880 1881 D->addAttr(::new (S.Context) HotAttr(AL.getRange(), S.Context, 1882 AL.getAttributeSpellingListIndex())); 1883 } 1884 1885 static void handleTLSModelAttr(Sema &S, Decl *D, 1886 const AttributeList &AL) { 1887 StringRef Model; 1888 SourceLocation LiteralLoc; 1889 // Check that it is a string. 1890 if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc)) 1891 return; 1892 1893 // Check that the value. 1894 if (Model != "global-dynamic" && Model != "local-dynamic" 1895 && Model != "initial-exec" && Model != "local-exec") { 1896 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg); 1897 return; 1898 } 1899 1900 D->addAttr(::new (S.Context) 1901 TLSModelAttr(AL.getRange(), S.Context, Model, 1902 AL.getAttributeSpellingListIndex())); 1903 } 1904 1905 static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &AL) { 1906 QualType ResultType = getFunctionOrMethodResultType(D); 1907 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) { 1908 D->addAttr(::new (S.Context) RestrictAttr( 1909 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); 1910 return; 1911 } 1912 1913 S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) 1914 << AL.getName() << getFunctionOrMethodResultSourceRange(D); 1915 } 1916 1917 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &AL) { 1918 if (S.LangOpts.CPlusPlus) { 1919 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang) 1920 << AL.getName() << AttributeLangSupport::Cpp; 1921 return; 1922 } 1923 1924 if (CommonAttr *CA = S.mergeCommonAttr(D, AL.getRange(), AL.getName(), 1925 AL.getAttributeSpellingListIndex())) 1926 D->addAttr(CA); 1927 } 1928 1929 static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &AL) { 1930 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, AL.getRange(), 1931 AL.getName())) 1932 return; 1933 1934 if (AL.isDeclspecAttribute()) { 1935 const auto &Triple = S.getASTContext().getTargetInfo().getTriple(); 1936 const auto &Arch = Triple.getArch(); 1937 if (Arch != llvm::Triple::x86 && 1938 (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) { 1939 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch) 1940 << AL.getName() << Triple.getArchName(); 1941 return; 1942 } 1943 } 1944 1945 D->addAttr(::new (S.Context) NakedAttr(AL.getRange(), S.Context, 1946 AL.getAttributeSpellingListIndex())); 1947 } 1948 1949 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &Attrs) { 1950 if (hasDeclarator(D)) return; 1951 1952 if (S.CheckNoReturnAttr(Attrs)) 1953 return; 1954 1955 if (!isa<ObjCMethodDecl>(D)) { 1956 S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type) 1957 << Attrs.getName() << ExpectedFunctionOrMethod; 1958 return; 1959 } 1960 1961 D->addAttr(::new (S.Context) NoReturnAttr( 1962 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex())); 1963 } 1964 1965 static void handleNoCallerSavedRegsAttr(Sema &S, Decl *D, 1966 const AttributeList &AL) { 1967 if (S.CheckNoCallerSavedRegsAttr(AL)) 1968 return; 1969 1970 D->addAttr(::new (S.Context) AnyX86NoCallerSavedRegistersAttr( 1971 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); 1972 } 1973 1974 bool Sema::CheckNoReturnAttr(const AttributeList &Attrs) { 1975 if (!checkAttributeNumArgs(*this, Attrs, 0)) { 1976 Attrs.setInvalid(); 1977 return true; 1978 } 1979 1980 return false; 1981 } 1982 1983 bool Sema::CheckNoCallerSavedRegsAttr(const AttributeList &AL) { 1984 // Check whether the attribute is valid on the current target. 1985 if (!AL.existsInTarget(Context.getTargetInfo())) { 1986 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) << AL.getName(); 1987 AL.setInvalid(); 1988 return true; 1989 } 1990 1991 if (!checkAttributeNumArgs(*this, AL, 0)) { 1992 AL.setInvalid(); 1993 return true; 1994 } 1995 1996 return false; 1997 } 1998 1999 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, 2000 const AttributeList &AL) { 2001 2002 // The checking path for 'noreturn' and 'analyzer_noreturn' are different 2003 // because 'analyzer_noreturn' does not impact the type. 2004 if (!isFunctionOrMethodOrBlock(D)) { 2005 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2006 if (!VD || (!VD->getType()->isBlockPointerType() && 2007 !VD->getType()->isFunctionPointerType())) { 2008 S.Diag(AL.getLoc(), 2009 AL.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type 2010 : diag::warn_attribute_wrong_decl_type) 2011 << AL.getName() << ExpectedFunctionMethodOrBlock; 2012 return; 2013 } 2014 } 2015 2016 D->addAttr(::new (S.Context) 2017 AnalyzerNoReturnAttr(AL.getRange(), S.Context, 2018 AL.getAttributeSpellingListIndex())); 2019 } 2020 2021 // PS3 PPU-specific. 2022 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &AL) { 2023 /* 2024 Returning a Vector Class in Registers 2025 2026 According to the PPU ABI specifications, a class with a single member of 2027 vector type is returned in memory when used as the return value of a function. 2028 This results in inefficient code when implementing vector classes. To return 2029 the value in a single vector register, add the vecreturn attribute to the 2030 class definition. This attribute is also applicable to struct types. 2031 2032 Example: 2033 2034 struct Vector 2035 { 2036 __vector float xyzw; 2037 } __attribute__((vecreturn)); 2038 2039 Vector Add(Vector lhs, Vector rhs) 2040 { 2041 Vector result; 2042 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw); 2043 return result; // This will be returned in a register 2044 } 2045 */ 2046 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) { 2047 S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A; 2048 return; 2049 } 2050 2051 const auto *R = cast<RecordDecl>(D); 2052 int count = 0; 2053 2054 if (!isa<CXXRecordDecl>(R)) { 2055 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member); 2056 return; 2057 } 2058 2059 if (!cast<CXXRecordDecl>(R)->isPOD()) { 2060 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record); 2061 return; 2062 } 2063 2064 for (const auto *I : R->fields()) { 2065 if ((count == 1) || !I->getType()->isVectorType()) { 2066 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member); 2067 return; 2068 } 2069 count++; 2070 } 2071 2072 D->addAttr(::new (S.Context) VecReturnAttr( 2073 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); 2074 } 2075 2076 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D, 2077 const AttributeList &AL) { 2078 if (isa<ParmVarDecl>(D)) { 2079 // [[carries_dependency]] can only be applied to a parameter if it is a 2080 // parameter of a function declaration or lambda. 2081 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) { 2082 S.Diag(AL.getLoc(), 2083 diag::err_carries_dependency_param_not_function_decl); 2084 return; 2085 } 2086 } 2087 2088 D->addAttr(::new (S.Context) CarriesDependencyAttr( 2089 AL.getRange(), S.Context, 2090 AL.getAttributeSpellingListIndex())); 2091 } 2092 2093 static void handleNotTailCalledAttr(Sema &S, Decl *D, 2094 const AttributeList &AL) { 2095 if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, AL.getRange(), 2096 AL.getName())) 2097 return; 2098 2099 D->addAttr(::new (S.Context) NotTailCalledAttr( 2100 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); 2101 } 2102 2103 static void handleDisableTailCallsAttr(Sema &S, Decl *D, 2104 const AttributeList &AL) { 2105 if (checkAttrMutualExclusion<NakedAttr>(S, D, AL.getRange(), 2106 AL.getName())) 2107 return; 2108 2109 D->addAttr(::new (S.Context) DisableTailCallsAttr( 2110 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); 2111 } 2112 2113 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &AL) { 2114 if (const auto *VD = dyn_cast<VarDecl>(D)) { 2115 if (VD->hasLocalStorage()) { 2116 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL.getName(); 2117 return; 2118 } 2119 } else if (!isFunctionOrMethod(D)) { 2120 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 2121 << AL.getName() << ExpectedVariableOrFunction; 2122 return; 2123 } 2124 2125 D->addAttr(::new (S.Context) 2126 UsedAttr(AL.getRange(), S.Context, 2127 AL.getAttributeSpellingListIndex())); 2128 } 2129 2130 static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &AL) { 2131 bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName(); 2132 2133 if (IsCXX17Attr && isa<VarDecl>(D)) { 2134 // The C++17 spelling of this attribute cannot be applied to a static data 2135 // member per [dcl.attr.unused]p2. 2136 if (cast<VarDecl>(D)->isStaticDataMember()) { 2137 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 2138 << AL.getName() << ExpectedForMaybeUnused; 2139 return; 2140 } 2141 } 2142 2143 // If this is spelled as the standard C++17 attribute, but not in C++17, warn 2144 // about using it as an extension. 2145 if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr) 2146 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL.getName(); 2147 2148 D->addAttr(::new (S.Context) UnusedAttr( 2149 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); 2150 } 2151 2152 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &AL) { 2153 uint32_t priority = ConstructorAttr::DefaultPriority; 2154 if (AL.getNumArgs() && 2155 !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority)) 2156 return; 2157 2158 D->addAttr(::new (S.Context) 2159 ConstructorAttr(AL.getRange(), S.Context, priority, 2160 AL.getAttributeSpellingListIndex())); 2161 } 2162 2163 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &AL) { 2164 uint32_t priority = DestructorAttr::DefaultPriority; 2165 if (AL.getNumArgs() && 2166 !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority)) 2167 return; 2168 2169 D->addAttr(::new (S.Context) 2170 DestructorAttr(AL.getRange(), S.Context, priority, 2171 AL.getAttributeSpellingListIndex())); 2172 } 2173 2174 template <typename AttrTy> 2175 static void handleAttrWithMessage(Sema &S, Decl *D, 2176 const AttributeList &AL) { 2177 // Handle the case where the attribute has a text message. 2178 StringRef Str; 2179 if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str)) 2180 return; 2181 2182 D->addAttr(::new (S.Context) AttrTy(AL.getRange(), S.Context, Str, 2183 AL.getAttributeSpellingListIndex())); 2184 } 2185 2186 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D, 2187 const AttributeList &AL) { 2188 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) { 2189 S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition) 2190 << AL.getName() << AL.getRange(); 2191 return; 2192 } 2193 2194 D->addAttr(::new (S.Context) 2195 ObjCExplicitProtocolImplAttr(AL.getRange(), S.Context, 2196 AL.getAttributeSpellingListIndex())); 2197 } 2198 2199 static bool checkAvailabilityAttr(Sema &S, SourceRange Range, 2200 IdentifierInfo *Platform, 2201 VersionTuple Introduced, 2202 VersionTuple Deprecated, 2203 VersionTuple Obsoleted) { 2204 StringRef PlatformName 2205 = AvailabilityAttr::getPrettyPlatformName(Platform->getName()); 2206 if (PlatformName.empty()) 2207 PlatformName = Platform->getName(); 2208 2209 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all 2210 // of these steps are needed). 2211 if (!Introduced.empty() && !Deprecated.empty() && 2212 !(Introduced <= Deprecated)) { 2213 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 2214 << 1 << PlatformName << Deprecated.getAsString() 2215 << 0 << Introduced.getAsString(); 2216 return true; 2217 } 2218 2219 if (!Introduced.empty() && !Obsoleted.empty() && 2220 !(Introduced <= Obsoleted)) { 2221 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 2222 << 2 << PlatformName << Obsoleted.getAsString() 2223 << 0 << Introduced.getAsString(); 2224 return true; 2225 } 2226 2227 if (!Deprecated.empty() && !Obsoleted.empty() && 2228 !(Deprecated <= Obsoleted)) { 2229 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 2230 << 2 << PlatformName << Obsoleted.getAsString() 2231 << 1 << Deprecated.getAsString(); 2232 return true; 2233 } 2234 2235 return false; 2236 } 2237 2238 /// \brief Check whether the two versions match. 2239 /// 2240 /// If either version tuple is empty, then they are assumed to match. If 2241 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y. 2242 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y, 2243 bool BeforeIsOkay) { 2244 if (X.empty() || Y.empty()) 2245 return true; 2246 2247 if (X == Y) 2248 return true; 2249 2250 if (BeforeIsOkay && X < Y) 2251 return true; 2252 2253 return false; 2254 } 2255 2256 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range, 2257 IdentifierInfo *Platform, 2258 bool Implicit, 2259 VersionTuple Introduced, 2260 VersionTuple Deprecated, 2261 VersionTuple Obsoleted, 2262 bool IsUnavailable, 2263 StringRef Message, 2264 bool IsStrict, 2265 StringRef Replacement, 2266 AvailabilityMergeKind AMK, 2267 unsigned AttrSpellingListIndex) { 2268 VersionTuple MergedIntroduced = Introduced; 2269 VersionTuple MergedDeprecated = Deprecated; 2270 VersionTuple MergedObsoleted = Obsoleted; 2271 bool FoundAny = false; 2272 bool OverrideOrImpl = false; 2273 switch (AMK) { 2274 case AMK_None: 2275 case AMK_Redeclaration: 2276 OverrideOrImpl = false; 2277 break; 2278 2279 case AMK_Override: 2280 case AMK_ProtocolImplementation: 2281 OverrideOrImpl = true; 2282 break; 2283 } 2284 2285 if (D->hasAttrs()) { 2286 AttrVec &Attrs = D->getAttrs(); 2287 for (unsigned i = 0, e = Attrs.size(); i != e;) { 2288 const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]); 2289 if (!OldAA) { 2290 ++i; 2291 continue; 2292 } 2293 2294 IdentifierInfo *OldPlatform = OldAA->getPlatform(); 2295 if (OldPlatform != Platform) { 2296 ++i; 2297 continue; 2298 } 2299 2300 // If there is an existing availability attribute for this platform that 2301 // is explicit and the new one is implicit use the explicit one and 2302 // discard the new implicit attribute. 2303 if (!OldAA->isImplicit() && Implicit) { 2304 return nullptr; 2305 } 2306 2307 // If there is an existing attribute for this platform that is implicit 2308 // and the new attribute is explicit then erase the old one and 2309 // continue processing the attributes. 2310 if (!Implicit && OldAA->isImplicit()) { 2311 Attrs.erase(Attrs.begin() + i); 2312 --e; 2313 continue; 2314 } 2315 2316 FoundAny = true; 2317 VersionTuple OldIntroduced = OldAA->getIntroduced(); 2318 VersionTuple OldDeprecated = OldAA->getDeprecated(); 2319 VersionTuple OldObsoleted = OldAA->getObsoleted(); 2320 bool OldIsUnavailable = OldAA->getUnavailable(); 2321 2322 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) || 2323 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) || 2324 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) || 2325 !(OldIsUnavailable == IsUnavailable || 2326 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) { 2327 if (OverrideOrImpl) { 2328 int Which = -1; 2329 VersionTuple FirstVersion; 2330 VersionTuple SecondVersion; 2331 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) { 2332 Which = 0; 2333 FirstVersion = OldIntroduced; 2334 SecondVersion = Introduced; 2335 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) { 2336 Which = 1; 2337 FirstVersion = Deprecated; 2338 SecondVersion = OldDeprecated; 2339 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) { 2340 Which = 2; 2341 FirstVersion = Obsoleted; 2342 SecondVersion = OldObsoleted; 2343 } 2344 2345 if (Which == -1) { 2346 Diag(OldAA->getLocation(), 2347 diag::warn_mismatched_availability_override_unavail) 2348 << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) 2349 << (AMK == AMK_Override); 2350 } else { 2351 Diag(OldAA->getLocation(), 2352 diag::warn_mismatched_availability_override) 2353 << Which 2354 << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) 2355 << FirstVersion.getAsString() << SecondVersion.getAsString() 2356 << (AMK == AMK_Override); 2357 } 2358 if (AMK == AMK_Override) 2359 Diag(Range.getBegin(), diag::note_overridden_method); 2360 else 2361 Diag(Range.getBegin(), diag::note_protocol_method); 2362 } else { 2363 Diag(OldAA->getLocation(), diag::warn_mismatched_availability); 2364 Diag(Range.getBegin(), diag::note_previous_attribute); 2365 } 2366 2367 Attrs.erase(Attrs.begin() + i); 2368 --e; 2369 continue; 2370 } 2371 2372 VersionTuple MergedIntroduced2 = MergedIntroduced; 2373 VersionTuple MergedDeprecated2 = MergedDeprecated; 2374 VersionTuple MergedObsoleted2 = MergedObsoleted; 2375 2376 if (MergedIntroduced2.empty()) 2377 MergedIntroduced2 = OldIntroduced; 2378 if (MergedDeprecated2.empty()) 2379 MergedDeprecated2 = OldDeprecated; 2380 if (MergedObsoleted2.empty()) 2381 MergedObsoleted2 = OldObsoleted; 2382 2383 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform, 2384 MergedIntroduced2, MergedDeprecated2, 2385 MergedObsoleted2)) { 2386 Attrs.erase(Attrs.begin() + i); 2387 --e; 2388 continue; 2389 } 2390 2391 MergedIntroduced = MergedIntroduced2; 2392 MergedDeprecated = MergedDeprecated2; 2393 MergedObsoleted = MergedObsoleted2; 2394 ++i; 2395 } 2396 } 2397 2398 if (FoundAny && 2399 MergedIntroduced == Introduced && 2400 MergedDeprecated == Deprecated && 2401 MergedObsoleted == Obsoleted) 2402 return nullptr; 2403 2404 // Only create a new attribute if !OverrideOrImpl, but we want to do 2405 // the checking. 2406 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced, 2407 MergedDeprecated, MergedObsoleted) && 2408 !OverrideOrImpl) { 2409 auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform, 2410 Introduced, Deprecated, 2411 Obsoleted, IsUnavailable, Message, 2412 IsStrict, Replacement, 2413 AttrSpellingListIndex); 2414 Avail->setImplicit(Implicit); 2415 return Avail; 2416 } 2417 return nullptr; 2418 } 2419 2420 static void handleAvailabilityAttr(Sema &S, Decl *D, 2421 const AttributeList &AL) { 2422 if (!checkAttributeNumArgs(S, AL, 1)) 2423 return; 2424 IdentifierLoc *Platform = AL.getArgAsIdent(0); 2425 unsigned Index = AL.getAttributeSpellingListIndex(); 2426 2427 IdentifierInfo *II = Platform->Ident; 2428 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty()) 2429 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform) 2430 << Platform->Ident; 2431 2432 auto *ND = dyn_cast<NamedDecl>(D); 2433 if (!ND) // We warned about this already, so just return. 2434 return; 2435 2436 AvailabilityChange Introduced = AL.getAvailabilityIntroduced(); 2437 AvailabilityChange Deprecated = AL.getAvailabilityDeprecated(); 2438 AvailabilityChange Obsoleted = AL.getAvailabilityObsoleted(); 2439 bool IsUnavailable = AL.getUnavailableLoc().isValid(); 2440 bool IsStrict = AL.getStrictLoc().isValid(); 2441 StringRef Str; 2442 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getMessageExpr())) 2443 Str = SE->getString(); 2444 StringRef Replacement; 2445 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getReplacementExpr())) 2446 Replacement = SE->getString(); 2447 2448 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, AL.getRange(), II, 2449 false/*Implicit*/, 2450 Introduced.Version, 2451 Deprecated.Version, 2452 Obsoleted.Version, 2453 IsUnavailable, Str, 2454 IsStrict, Replacement, 2455 Sema::AMK_None, 2456 Index); 2457 if (NewAttr) 2458 D->addAttr(NewAttr); 2459 2460 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning 2461 // matches before the start of the watchOS platform. 2462 if (S.Context.getTargetInfo().getTriple().isWatchOS()) { 2463 IdentifierInfo *NewII = nullptr; 2464 if (II->getName() == "ios") 2465 NewII = &S.Context.Idents.get("watchos"); 2466 else if (II->getName() == "ios_app_extension") 2467 NewII = &S.Context.Idents.get("watchos_app_extension"); 2468 2469 if (NewII) { 2470 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple { 2471 if (Version.empty()) 2472 return Version; 2473 auto Major = Version.getMajor(); 2474 auto NewMajor = Major >= 9 ? Major - 7 : 0; 2475 if (NewMajor >= 2) { 2476 if (Version.getMinor().hasValue()) { 2477 if (Version.getSubminor().hasValue()) 2478 return VersionTuple(NewMajor, Version.getMinor().getValue(), 2479 Version.getSubminor().getValue()); 2480 else 2481 return VersionTuple(NewMajor, Version.getMinor().getValue()); 2482 } 2483 } 2484 2485 return VersionTuple(2, 0); 2486 }; 2487 2488 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version); 2489 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version); 2490 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version); 2491 2492 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, 2493 AL.getRange(), 2494 NewII, 2495 true/*Implicit*/, 2496 NewIntroduced, 2497 NewDeprecated, 2498 NewObsoleted, 2499 IsUnavailable, Str, 2500 IsStrict, 2501 Replacement, 2502 Sema::AMK_None, 2503 Index); 2504 if (NewAttr) 2505 D->addAttr(NewAttr); 2506 } 2507 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) { 2508 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning 2509 // matches before the start of the tvOS platform. 2510 IdentifierInfo *NewII = nullptr; 2511 if (II->getName() == "ios") 2512 NewII = &S.Context.Idents.get("tvos"); 2513 else if (II->getName() == "ios_app_extension") 2514 NewII = &S.Context.Idents.get("tvos_app_extension"); 2515 2516 if (NewII) { 2517 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, 2518 AL.getRange(), 2519 NewII, 2520 true/*Implicit*/, 2521 Introduced.Version, 2522 Deprecated.Version, 2523 Obsoleted.Version, 2524 IsUnavailable, Str, 2525 IsStrict, 2526 Replacement, 2527 Sema::AMK_None, 2528 Index); 2529 if (NewAttr) 2530 D->addAttr(NewAttr); 2531 } 2532 } 2533 } 2534 2535 static void handleExternalSourceSymbolAttr(Sema &S, Decl *D, 2536 const AttributeList &AL) { 2537 if (!checkAttributeAtLeastNumArgs(S, AL, 1)) 2538 return; 2539 assert(checkAttributeAtMostNumArgs(S, AL, 3) && 2540 "Invalid number of arguments in an external_source_symbol attribute"); 2541 2542 StringRef Language; 2543 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0))) 2544 Language = SE->getString(); 2545 StringRef DefinedIn; 2546 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1))) 2547 DefinedIn = SE->getString(); 2548 bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr; 2549 2550 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr( 2551 AL.getRange(), S.Context, Language, DefinedIn, IsGeneratedDeclaration, 2552 AL.getAttributeSpellingListIndex())); 2553 } 2554 2555 template <class T> 2556 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range, 2557 typename T::VisibilityType value, 2558 unsigned attrSpellingListIndex) { 2559 T *existingAttr = D->getAttr<T>(); 2560 if (existingAttr) { 2561 typename T::VisibilityType existingValue = existingAttr->getVisibility(); 2562 if (existingValue == value) 2563 return nullptr; 2564 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility); 2565 S.Diag(range.getBegin(), diag::note_previous_attribute); 2566 D->dropAttr<T>(); 2567 } 2568 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex); 2569 } 2570 2571 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range, 2572 VisibilityAttr::VisibilityType Vis, 2573 unsigned AttrSpellingListIndex) { 2574 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis, 2575 AttrSpellingListIndex); 2576 } 2577 2578 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range, 2579 TypeVisibilityAttr::VisibilityType Vis, 2580 unsigned AttrSpellingListIndex) { 2581 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis, 2582 AttrSpellingListIndex); 2583 } 2584 2585 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &AL, 2586 bool isTypeVisibility) { 2587 // Visibility attributes don't mean anything on a typedef. 2588 if (isa<TypedefNameDecl>(D)) { 2589 S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) 2590 << AL.getName(); 2591 return; 2592 } 2593 2594 // 'type_visibility' can only go on a type or namespace. 2595 if (isTypeVisibility && 2596 !(isa<TagDecl>(D) || 2597 isa<ObjCInterfaceDecl>(D) || 2598 isa<NamespaceDecl>(D))) { 2599 S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type) 2600 << AL.getName() << ExpectedTypeOrNamespace; 2601 return; 2602 } 2603 2604 // Check that the argument is a string literal. 2605 StringRef TypeStr; 2606 SourceLocation LiteralLoc; 2607 if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc)) 2608 return; 2609 2610 VisibilityAttr::VisibilityType type; 2611 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) { 2612 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) 2613 << AL.getName() << TypeStr; 2614 return; 2615 } 2616 2617 // Complain about attempts to use protected visibility on targets 2618 // (like Darwin) that don't support it. 2619 if (type == VisibilityAttr::Protected && 2620 !S.Context.getTargetInfo().hasProtectedVisibility()) { 2621 S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility); 2622 type = VisibilityAttr::Default; 2623 } 2624 2625 unsigned Index = AL.getAttributeSpellingListIndex(); 2626 Attr *newAttr; 2627 if (isTypeVisibility) { 2628 newAttr = S.mergeTypeVisibilityAttr(D, AL.getRange(), 2629 (TypeVisibilityAttr::VisibilityType) type, 2630 Index); 2631 } else { 2632 newAttr = S.mergeVisibilityAttr(D, AL.getRange(), type, Index); 2633 } 2634 if (newAttr) 2635 D->addAttr(newAttr); 2636 } 2637 2638 static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, 2639 const AttributeList &AL) { 2640 const auto *M = cast<ObjCMethodDecl>(D); 2641 if (!AL.isArgIdent(0)) { 2642 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 2643 << AL.getName() << 1 << AANT_ArgumentIdentifier; 2644 return; 2645 } 2646 2647 IdentifierLoc *IL = AL.getArgAsIdent(0); 2648 ObjCMethodFamilyAttr::FamilyKind F; 2649 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) { 2650 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) 2651 << AL.getName() << IL->Ident; 2652 return; 2653 } 2654 2655 if (F == ObjCMethodFamilyAttr::OMF_init && 2656 !M->getReturnType()->isObjCObjectPointerType()) { 2657 S.Diag(M->getLocation(), diag::err_init_method_bad_return_type) 2658 << M->getReturnType(); 2659 // Ignore the attribute. 2660 return; 2661 } 2662 2663 D->addAttr(new (S.Context) ObjCMethodFamilyAttr( 2664 AL.getRange(), S.Context, F, AL.getAttributeSpellingListIndex())); 2665 } 2666 2667 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &AL) { 2668 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 2669 QualType T = TD->getUnderlyingType(); 2670 if (!T->isCARCBridgableType()) { 2671 S.Diag(TD->getLocation(), diag::err_nsobject_attribute); 2672 return; 2673 } 2674 } 2675 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) { 2676 QualType T = PD->getType(); 2677 if (!T->isCARCBridgableType()) { 2678 S.Diag(PD->getLocation(), diag::err_nsobject_attribute); 2679 return; 2680 } 2681 } 2682 else { 2683 // It is okay to include this attribute on properties, e.g.: 2684 // 2685 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject)); 2686 // 2687 // In this case it follows tradition and suppresses an error in the above 2688 // case. 2689 S.Diag(D->getLocation(), diag::warn_nsobject_attribute); 2690 } 2691 D->addAttr(::new (S.Context) 2692 ObjCNSObjectAttr(AL.getRange(), S.Context, 2693 AL.getAttributeSpellingListIndex())); 2694 } 2695 2696 static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &AL) { 2697 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 2698 QualType T = TD->getUnderlyingType(); 2699 if (!T->isObjCObjectPointerType()) { 2700 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute); 2701 return; 2702 } 2703 } else { 2704 S.Diag(D->getLocation(), diag::warn_independentclass_attribute); 2705 return; 2706 } 2707 D->addAttr(::new (S.Context) 2708 ObjCIndependentClassAttr(AL.getRange(), S.Context, 2709 AL.getAttributeSpellingListIndex())); 2710 } 2711 2712 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &AL) { 2713 if (!AL.isArgIdent(0)) { 2714 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 2715 << AL.getName() << 1 << AANT_ArgumentIdentifier; 2716 return; 2717 } 2718 2719 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 2720 BlocksAttr::BlockType type; 2721 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) { 2722 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) 2723 << AL.getName() << II; 2724 return; 2725 } 2726 2727 D->addAttr(::new (S.Context) 2728 BlocksAttr(AL.getRange(), S.Context, type, 2729 AL.getAttributeSpellingListIndex())); 2730 } 2731 2732 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &AL) { 2733 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel; 2734 if (AL.getNumArgs() > 0) { 2735 Expr *E = AL.getArgAsExpr(0); 2736 llvm::APSInt Idx(32); 2737 if (E->isTypeDependent() || E->isValueDependent() || 2738 !E->isIntegerConstantExpr(Idx, S.Context)) { 2739 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 2740 << AL.getName() << 1 << AANT_ArgumentIntegerConstant 2741 << E->getSourceRange(); 2742 return; 2743 } 2744 2745 if (Idx.isSigned() && Idx.isNegative()) { 2746 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero) 2747 << E->getSourceRange(); 2748 return; 2749 } 2750 2751 sentinel = Idx.getZExtValue(); 2752 } 2753 2754 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos; 2755 if (AL.getNumArgs() > 1) { 2756 Expr *E = AL.getArgAsExpr(1); 2757 llvm::APSInt Idx(32); 2758 if (E->isTypeDependent() || E->isValueDependent() || 2759 !E->isIntegerConstantExpr(Idx, S.Context)) { 2760 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 2761 << AL.getName() << 2 << AANT_ArgumentIntegerConstant 2762 << E->getSourceRange(); 2763 return; 2764 } 2765 nullPos = Idx.getZExtValue(); 2766 2767 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) { 2768 // FIXME: This error message could be improved, it would be nice 2769 // to say what the bounds actually are. 2770 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one) 2771 << E->getSourceRange(); 2772 return; 2773 } 2774 } 2775 2776 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 2777 const FunctionType *FT = FD->getType()->castAs<FunctionType>(); 2778 if (isa<FunctionNoProtoType>(FT)) { 2779 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments); 2780 return; 2781 } 2782 2783 if (!cast<FunctionProtoType>(FT)->isVariadic()) { 2784 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; 2785 return; 2786 } 2787 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) { 2788 if (!MD->isVariadic()) { 2789 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; 2790 return; 2791 } 2792 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) { 2793 if (!BD->isVariadic()) { 2794 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1; 2795 return; 2796 } 2797 } else if (const auto *V = dyn_cast<VarDecl>(D)) { 2798 QualType Ty = V->getType(); 2799 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) { 2800 const FunctionType *FT = Ty->isFunctionPointerType() 2801 ? D->getFunctionType() 2802 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>(); 2803 if (!cast<FunctionProtoType>(FT)->isVariadic()) { 2804 int m = Ty->isFunctionPointerType() ? 0 : 1; 2805 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m; 2806 return; 2807 } 2808 } else { 2809 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 2810 << AL.getName() << ExpectedFunctionMethodOrBlock; 2811 return; 2812 } 2813 } else { 2814 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 2815 << AL.getName() << ExpectedFunctionMethodOrBlock; 2816 return; 2817 } 2818 D->addAttr(::new (S.Context) 2819 SentinelAttr(AL.getRange(), S.Context, sentinel, nullPos, 2820 AL.getAttributeSpellingListIndex())); 2821 } 2822 2823 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &AL) { 2824 if (D->getFunctionType() && 2825 D->getFunctionType()->getReturnType()->isVoidType()) { 2826 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) 2827 << AL.getName() << 0; 2828 return; 2829 } 2830 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 2831 if (MD->getReturnType()->isVoidType()) { 2832 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) 2833 << AL.getName() << 1; 2834 return; 2835 } 2836 2837 // If this is spelled as the standard C++17 attribute, but not in C++17, warn 2838 // about using it as an extension. 2839 if (!S.getLangOpts().CPlusPlus17 && AL.isCXX11Attribute() && 2840 !AL.getScopeName()) 2841 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL.getName(); 2842 2843 D->addAttr(::new (S.Context) 2844 WarnUnusedResultAttr(AL.getRange(), S.Context, 2845 AL.getAttributeSpellingListIndex())); 2846 } 2847 2848 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &AL) { 2849 // weak_import only applies to variable & function declarations. 2850 bool isDef = false; 2851 if (!D->canBeWeakImported(isDef)) { 2852 if (isDef) 2853 S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition) 2854 << "weak_import"; 2855 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) || 2856 (S.Context.getTargetInfo().getTriple().isOSDarwin() && 2857 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) { 2858 // Nothing to warn about here. 2859 } else 2860 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 2861 << AL.getName() << ExpectedVariableOrFunction; 2862 2863 return; 2864 } 2865 2866 D->addAttr(::new (S.Context) 2867 WeakImportAttr(AL.getRange(), S.Context, 2868 AL.getAttributeSpellingListIndex())); 2869 } 2870 2871 // Handles reqd_work_group_size and work_group_size_hint. 2872 template <typename WorkGroupAttr> 2873 static void handleWorkGroupSize(Sema &S, Decl *D, 2874 const AttributeList &AL) { 2875 uint32_t WGSize[3]; 2876 for (unsigned i = 0; i < 3; ++i) { 2877 const Expr *E = AL.getArgAsExpr(i); 2878 if (!checkUInt32Argument(S, AL, E, WGSize[i], i)) 2879 return; 2880 if (WGSize[i] == 0) { 2881 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero) 2882 << AL.getName() << E->getSourceRange(); 2883 return; 2884 } 2885 } 2886 2887 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>(); 2888 if (Existing && !(Existing->getXDim() == WGSize[0] && 2889 Existing->getYDim() == WGSize[1] && 2890 Existing->getZDim() == WGSize[2])) 2891 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL.getName(); 2892 2893 D->addAttr(::new (S.Context) WorkGroupAttr(AL.getRange(), S.Context, 2894 WGSize[0], WGSize[1], WGSize[2], 2895 AL.getAttributeSpellingListIndex())); 2896 } 2897 2898 // Handles intel_reqd_sub_group_size. 2899 static void handleSubGroupSize(Sema &S, Decl *D, const AttributeList &AL) { 2900 uint32_t SGSize; 2901 const Expr *E = AL.getArgAsExpr(0); 2902 if (!checkUInt32Argument(S, AL, E, SGSize)) 2903 return; 2904 if (SGSize == 0) { 2905 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero) 2906 << AL.getName() << E->getSourceRange(); 2907 return; 2908 } 2909 2910 OpenCLIntelReqdSubGroupSizeAttr *Existing = 2911 D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>(); 2912 if (Existing && Existing->getSubGroupSize() != SGSize) 2913 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL.getName(); 2914 2915 D->addAttr(::new (S.Context) OpenCLIntelReqdSubGroupSizeAttr( 2916 AL.getRange(), S.Context, SGSize, 2917 AL.getAttributeSpellingListIndex())); 2918 } 2919 2920 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &AL) { 2921 if (!AL.hasParsedType()) { 2922 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) 2923 << AL.getName() << 1; 2924 return; 2925 } 2926 2927 TypeSourceInfo *ParmTSI = nullptr; 2928 QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI); 2929 assert(ParmTSI && "no type source info for attribute argument"); 2930 2931 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() && 2932 (ParmType->isBooleanType() || 2933 !ParmType->isIntegralType(S.getASTContext()))) { 2934 S.Diag(AL.getLoc(), diag::err_attribute_argument_vec_type_hint) 2935 << ParmType; 2936 return; 2937 } 2938 2939 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) { 2940 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) { 2941 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL.getName(); 2942 return; 2943 } 2944 } 2945 2946 D->addAttr(::new (S.Context) VecTypeHintAttr(AL.getLoc(), S.Context, 2947 ParmTSI, 2948 AL.getAttributeSpellingListIndex())); 2949 } 2950 2951 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range, 2952 StringRef Name, 2953 unsigned AttrSpellingListIndex) { 2954 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) { 2955 if (ExistingAttr->getName() == Name) 2956 return nullptr; 2957 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section); 2958 Diag(Range.getBegin(), diag::note_previous_attribute); 2959 return nullptr; 2960 } 2961 return ::new (Context) SectionAttr(Range, Context, Name, 2962 AttrSpellingListIndex); 2963 } 2964 2965 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) { 2966 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName); 2967 if (!Error.empty()) { 2968 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error; 2969 return false; 2970 } 2971 return true; 2972 } 2973 2974 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &AL) { 2975 // Make sure that there is a string literal as the sections's single 2976 // argument. 2977 StringRef Str; 2978 SourceLocation LiteralLoc; 2979 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc)) 2980 return; 2981 2982 if (!S.checkSectionName(LiteralLoc, Str)) 2983 return; 2984 2985 // If the target wants to validate the section specifier, make it happen. 2986 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str); 2987 if (!Error.empty()) { 2988 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) 2989 << Error; 2990 return; 2991 } 2992 2993 unsigned Index = AL.getAttributeSpellingListIndex(); 2994 SectionAttr *NewAttr = S.mergeSectionAttr(D, AL.getRange(), Str, Index); 2995 if (NewAttr) 2996 D->addAttr(NewAttr); 2997 } 2998 2999 // Check for things we'd like to warn about. Multiversioning issues are 3000 // handled later in the process, once we know how many exist. 3001 bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) { 3002 enum FirstParam { Unsupported, Duplicate }; 3003 enum SecondParam { None, Architecture }; 3004 for (auto Str : {"tune=", "fpmath="}) 3005 if (AttrStr.find(Str) != StringRef::npos) 3006 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3007 << Unsupported << None << Str; 3008 3009 TargetAttr::ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr); 3010 3011 if (!ParsedAttrs.Architecture.empty() && 3012 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture)) 3013 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3014 << Unsupported << Architecture << ParsedAttrs.Architecture; 3015 3016 if (ParsedAttrs.DuplicateArchitecture) 3017 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3018 << Duplicate << None << "arch="; 3019 3020 for (const auto &Feature : ParsedAttrs.Features) { 3021 auto CurFeature = StringRef(Feature).drop_front(); // remove + or -. 3022 if (!Context.getTargetInfo().isValidFeatureName(CurFeature)) 3023 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3024 << Unsupported << None << CurFeature; 3025 } 3026 3027 return false; 3028 } 3029 3030 static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &AL) { 3031 StringRef Str; 3032 SourceLocation LiteralLoc; 3033 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) || 3034 S.checkTargetAttr(LiteralLoc, Str)) 3035 return; 3036 3037 unsigned Index = AL.getAttributeSpellingListIndex(); 3038 TargetAttr *NewAttr = 3039 ::new (S.Context) TargetAttr(AL.getRange(), S.Context, Str, Index); 3040 D->addAttr(NewAttr); 3041 } 3042 3043 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &AL) { 3044 Expr *E = AL.getArgAsExpr(0); 3045 SourceLocation Loc = E->getExprLoc(); 3046 FunctionDecl *FD = nullptr; 3047 DeclarationNameInfo NI; 3048 3049 // gcc only allows for simple identifiers. Since we support more than gcc, we 3050 // will warn the user. 3051 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 3052 if (DRE->hasQualifier()) 3053 S.Diag(Loc, diag::warn_cleanup_ext); 3054 FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 3055 NI = DRE->getNameInfo(); 3056 if (!FD) { 3057 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1 3058 << NI.getName(); 3059 return; 3060 } 3061 } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 3062 if (ULE->hasExplicitTemplateArgs()) 3063 S.Diag(Loc, diag::warn_cleanup_ext); 3064 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true); 3065 NI = ULE->getNameInfo(); 3066 if (!FD) { 3067 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2 3068 << NI.getName(); 3069 if (ULE->getType() == S.Context.OverloadTy) 3070 S.NoteAllOverloadCandidates(ULE); 3071 return; 3072 } 3073 } else { 3074 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0; 3075 return; 3076 } 3077 3078 if (FD->getNumParams() != 1) { 3079 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg) 3080 << NI.getName(); 3081 return; 3082 } 3083 3084 // We're currently more strict than GCC about what function types we accept. 3085 // If this ever proves to be a problem it should be easy to fix. 3086 QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType()); 3087 QualType ParamTy = FD->getParamDecl(0)->getType(); 3088 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(), 3089 ParamTy, Ty) != Sema::Compatible) { 3090 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type) 3091 << NI.getName() << ParamTy << Ty; 3092 return; 3093 } 3094 3095 D->addAttr(::new (S.Context) 3096 CleanupAttr(AL.getRange(), S.Context, FD, 3097 AL.getAttributeSpellingListIndex())); 3098 } 3099 3100 static void handleEnumExtensibilityAttr(Sema &S, Decl *D, 3101 const AttributeList &AL) { 3102 if (!AL.isArgIdent(0)) { 3103 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 3104 << AL.getName() << 0 << AANT_ArgumentIdentifier; 3105 return; 3106 } 3107 3108 EnumExtensibilityAttr::Kind ExtensibilityKind; 3109 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 3110 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(), 3111 ExtensibilityKind)) { 3112 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) 3113 << AL.getName() << II; 3114 return; 3115 } 3116 3117 D->addAttr(::new (S.Context) EnumExtensibilityAttr( 3118 AL.getRange(), S.Context, ExtensibilityKind, 3119 AL.getAttributeSpellingListIndex())); 3120 } 3121 3122 /// Handle __attribute__((format_arg((idx)))) attribute based on 3123 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 3124 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &AL) { 3125 Expr *IdxExpr = AL.getArgAsExpr(0); 3126 uint64_t Idx; 3127 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx)) 3128 return; 3129 3130 // Make sure the format string is really a string. 3131 QualType Ty = getFunctionOrMethodParamType(D, Idx); 3132 3133 bool NotNSStringTy = !isNSStringType(Ty, S.Context); 3134 if (NotNSStringTy && 3135 !isCFStringType(Ty, S.Context) && 3136 (!Ty->isPointerType() || 3137 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) { 3138 S.Diag(AL.getLoc(), diag::err_format_attribute_not) 3139 << "a string type" << IdxExpr->getSourceRange() 3140 << getFunctionOrMethodParamRange(D, 0); 3141 return; 3142 } 3143 Ty = getFunctionOrMethodResultType(D); 3144 if (!isNSStringType(Ty, S.Context) && 3145 !isCFStringType(Ty, S.Context) && 3146 (!Ty->isPointerType() || 3147 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) { 3148 S.Diag(AL.getLoc(), diag::err_format_attribute_result_not) 3149 << (NotNSStringTy ? "string type" : "NSString") 3150 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0); 3151 return; 3152 } 3153 3154 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex 3155 // because that has corrected for the implicit this parameter, and is zero- 3156 // based. The attribute expects what the user wrote explicitly. 3157 llvm::APSInt Val; 3158 IdxExpr->EvaluateAsInt(Val, S.Context); 3159 3160 D->addAttr(::new (S.Context) 3161 FormatArgAttr(AL.getRange(), S.Context, Val.getZExtValue(), 3162 AL.getAttributeSpellingListIndex())); 3163 } 3164 3165 enum FormatAttrKind { 3166 CFStringFormat, 3167 NSStringFormat, 3168 StrftimeFormat, 3169 SupportedFormat, 3170 IgnoredFormat, 3171 InvalidFormat 3172 }; 3173 3174 /// getFormatAttrKind - Map from format attribute names to supported format 3175 /// types. 3176 static FormatAttrKind getFormatAttrKind(StringRef Format) { 3177 return llvm::StringSwitch<FormatAttrKind>(Format) 3178 // Check for formats that get handled specially. 3179 .Case("NSString", NSStringFormat) 3180 .Case("CFString", CFStringFormat) 3181 .Case("strftime", StrftimeFormat) 3182 3183 // Otherwise, check for supported formats. 3184 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat) 3185 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat) 3186 .Case("kprintf", SupportedFormat) // OpenBSD. 3187 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD. 3188 .Case("os_trace", SupportedFormat) 3189 .Case("os_log", SupportedFormat) 3190 3191 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat) 3192 .Default(InvalidFormat); 3193 } 3194 3195 /// Handle __attribute__((init_priority(priority))) attributes based on 3196 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html 3197 static void handleInitPriorityAttr(Sema &S, Decl *D, 3198 const AttributeList &AL) { 3199 if (!S.getLangOpts().CPlusPlus) { 3200 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL.getName(); 3201 return; 3202 } 3203 3204 if (S.getCurFunctionOrMethodDecl()) { 3205 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr); 3206 AL.setInvalid(); 3207 return; 3208 } 3209 QualType T = cast<VarDecl>(D)->getType(); 3210 if (S.Context.getAsArrayType(T)) 3211 T = S.Context.getBaseElementType(T); 3212 if (!T->getAs<RecordType>()) { 3213 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr); 3214 AL.setInvalid(); 3215 return; 3216 } 3217 3218 Expr *E = AL.getArgAsExpr(0); 3219 uint32_t prioritynum; 3220 if (!checkUInt32Argument(S, AL, E, prioritynum)) { 3221 AL.setInvalid(); 3222 return; 3223 } 3224 3225 if (prioritynum < 101 || prioritynum > 65535) { 3226 S.Diag(AL.getLoc(), diag::err_attribute_argument_outof_range) 3227 << E->getSourceRange() << AL.getName() << 101 << 65535; 3228 AL.setInvalid(); 3229 return; 3230 } 3231 D->addAttr(::new (S.Context) 3232 InitPriorityAttr(AL.getRange(), S.Context, prioritynum, 3233 AL.getAttributeSpellingListIndex())); 3234 } 3235 3236 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range, 3237 IdentifierInfo *Format, int FormatIdx, 3238 int FirstArg, 3239 unsigned AttrSpellingListIndex) { 3240 // Check whether we already have an equivalent format attribute. 3241 for (auto *F : D->specific_attrs<FormatAttr>()) { 3242 if (F->getType() == Format && 3243 F->getFormatIdx() == FormatIdx && 3244 F->getFirstArg() == FirstArg) { 3245 // If we don't have a valid location for this attribute, adopt the 3246 // location. 3247 if (F->getLocation().isInvalid()) 3248 F->setRange(Range); 3249 return nullptr; 3250 } 3251 } 3252 3253 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx, 3254 FirstArg, AttrSpellingListIndex); 3255 } 3256 3257 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on 3258 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 3259 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &AL) { 3260 if (!AL.isArgIdent(0)) { 3261 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 3262 << AL.getName() << 1 << AANT_ArgumentIdentifier; 3263 return; 3264 } 3265 3266 // In C++ the implicit 'this' function parameter also counts, and they are 3267 // counted from one. 3268 bool HasImplicitThisParam = isInstanceMethod(D); 3269 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam; 3270 3271 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 3272 StringRef Format = II->getName(); 3273 3274 if (normalizeName(Format)) { 3275 // If we've modified the string name, we need a new identifier for it. 3276 II = &S.Context.Idents.get(Format); 3277 } 3278 3279 // Check for supported formats. 3280 FormatAttrKind Kind = getFormatAttrKind(Format); 3281 3282 if (Kind == IgnoredFormat) 3283 return; 3284 3285 if (Kind == InvalidFormat) { 3286 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) 3287 << AL.getName() << II->getName(); 3288 return; 3289 } 3290 3291 // checks for the 2nd argument 3292 Expr *IdxExpr = AL.getArgAsExpr(1); 3293 uint32_t Idx; 3294 if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2)) 3295 return; 3296 3297 if (Idx < 1 || Idx > NumArgs) { 3298 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 3299 << AL.getName() << 2 << IdxExpr->getSourceRange(); 3300 return; 3301 } 3302 3303 // FIXME: Do we need to bounds check? 3304 unsigned ArgIdx = Idx - 1; 3305 3306 if (HasImplicitThisParam) { 3307 if (ArgIdx == 0) { 3308 S.Diag(AL.getLoc(), 3309 diag::err_format_attribute_implicit_this_format_string) 3310 << IdxExpr->getSourceRange(); 3311 return; 3312 } 3313 ArgIdx--; 3314 } 3315 3316 // make sure the format string is really a string 3317 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx); 3318 3319 if (Kind == CFStringFormat) { 3320 if (!isCFStringType(Ty, S.Context)) { 3321 S.Diag(AL.getLoc(), diag::err_format_attribute_not) 3322 << "a CFString" << IdxExpr->getSourceRange() 3323 << getFunctionOrMethodParamRange(D, ArgIdx); 3324 return; 3325 } 3326 } else if (Kind == NSStringFormat) { 3327 // FIXME: do we need to check if the type is NSString*? What are the 3328 // semantics? 3329 if (!isNSStringType(Ty, S.Context)) { 3330 S.Diag(AL.getLoc(), diag::err_format_attribute_not) 3331 << "an NSString" << IdxExpr->getSourceRange() 3332 << getFunctionOrMethodParamRange(D, ArgIdx); 3333 return; 3334 } 3335 } else if (!Ty->isPointerType() || 3336 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) { 3337 S.Diag(AL.getLoc(), diag::err_format_attribute_not) 3338 << "a string type" << IdxExpr->getSourceRange() 3339 << getFunctionOrMethodParamRange(D, ArgIdx); 3340 return; 3341 } 3342 3343 // check the 3rd argument 3344 Expr *FirstArgExpr = AL.getArgAsExpr(2); 3345 uint32_t FirstArg; 3346 if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3)) 3347 return; 3348 3349 // check if the function is variadic if the 3rd argument non-zero 3350 if (FirstArg != 0) { 3351 if (isFunctionOrMethodVariadic(D)) { 3352 ++NumArgs; // +1 for ... 3353 } else { 3354 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic); 3355 return; 3356 } 3357 } 3358 3359 // strftime requires FirstArg to be 0 because it doesn't read from any 3360 // variable the input is just the current time + the format string. 3361 if (Kind == StrftimeFormat) { 3362 if (FirstArg != 0) { 3363 S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter) 3364 << FirstArgExpr->getSourceRange(); 3365 return; 3366 } 3367 // if 0 it disables parameter checking (to use with e.g. va_list) 3368 } else if (FirstArg != 0 && FirstArg != NumArgs) { 3369 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 3370 << AL.getName() << 3 << FirstArgExpr->getSourceRange(); 3371 return; 3372 } 3373 3374 FormatAttr *NewAttr = S.mergeFormatAttr(D, AL.getRange(), II, 3375 Idx, FirstArg, 3376 AL.getAttributeSpellingListIndex()); 3377 if (NewAttr) 3378 D->addAttr(NewAttr); 3379 } 3380 3381 static void handleTransparentUnionAttr(Sema &S, Decl *D, 3382 const AttributeList &AL) { 3383 // Try to find the underlying union declaration. 3384 RecordDecl *RD = nullptr; 3385 const auto *TD = dyn_cast<TypedefNameDecl>(D); 3386 if (TD && TD->getUnderlyingType()->isUnionType()) 3387 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl(); 3388 else 3389 RD = dyn_cast<RecordDecl>(D); 3390 3391 if (!RD || !RD->isUnion()) { 3392 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 3393 << AL.getName() << ExpectedUnion; 3394 return; 3395 } 3396 3397 if (!RD->isCompleteDefinition()) { 3398 if (!RD->isBeingDefined()) 3399 S.Diag(AL.getLoc(), 3400 diag::warn_transparent_union_attribute_not_definition); 3401 return; 3402 } 3403 3404 RecordDecl::field_iterator Field = RD->field_begin(), 3405 FieldEnd = RD->field_end(); 3406 if (Field == FieldEnd) { 3407 S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields); 3408 return; 3409 } 3410 3411 FieldDecl *FirstField = *Field; 3412 QualType FirstType = FirstField->getType(); 3413 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) { 3414 S.Diag(FirstField->getLocation(), 3415 diag::warn_transparent_union_attribute_floating) 3416 << FirstType->isVectorType() << FirstType; 3417 return; 3418 } 3419 3420 if (FirstType->isIncompleteType()) 3421 return; 3422 uint64_t FirstSize = S.Context.getTypeSize(FirstType); 3423 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType); 3424 for (; Field != FieldEnd; ++Field) { 3425 QualType FieldType = Field->getType(); 3426 if (FieldType->isIncompleteType()) 3427 return; 3428 // FIXME: this isn't fully correct; we also need to test whether the 3429 // members of the union would all have the same calling convention as the 3430 // first member of the union. Checking just the size and alignment isn't 3431 // sufficient (consider structs passed on the stack instead of in registers 3432 // as an example). 3433 if (S.Context.getTypeSize(FieldType) != FirstSize || 3434 S.Context.getTypeAlign(FieldType) > FirstAlign) { 3435 // Warn if we drop the attribute. 3436 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize; 3437 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType) 3438 : S.Context.getTypeAlign(FieldType); 3439 S.Diag(Field->getLocation(), 3440 diag::warn_transparent_union_attribute_field_size_align) 3441 << isSize << Field->getDeclName() << FieldBits; 3442 unsigned FirstBits = isSize? FirstSize : FirstAlign; 3443 S.Diag(FirstField->getLocation(), 3444 diag::note_transparent_union_first_field_size_align) 3445 << isSize << FirstBits; 3446 return; 3447 } 3448 } 3449 3450 RD->addAttr(::new (S.Context) 3451 TransparentUnionAttr(AL.getRange(), S.Context, 3452 AL.getAttributeSpellingListIndex())); 3453 } 3454 3455 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &AL) { 3456 // Make sure that there is a string literal as the annotation's single 3457 // argument. 3458 StringRef Str; 3459 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str)) 3460 return; 3461 3462 // Don't duplicate annotations that are already set. 3463 for (const auto *I : D->specific_attrs<AnnotateAttr>()) { 3464 if (I->getAnnotation() == Str) 3465 return; 3466 } 3467 3468 D->addAttr(::new (S.Context) 3469 AnnotateAttr(AL.getRange(), S.Context, Str, 3470 AL.getAttributeSpellingListIndex())); 3471 } 3472 3473 static void handleAlignValueAttr(Sema &S, Decl *D, 3474 const AttributeList &AL) { 3475 S.AddAlignValueAttr(AL.getRange(), D, AL.getArgAsExpr(0), 3476 AL.getAttributeSpellingListIndex()); 3477 } 3478 3479 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E, 3480 unsigned SpellingListIndex) { 3481 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex); 3482 SourceLocation AttrLoc = AttrRange.getBegin(); 3483 3484 QualType T; 3485 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) 3486 T = TD->getUnderlyingType(); 3487 else if (const auto *VD = dyn_cast<ValueDecl>(D)) 3488 T = VD->getType(); 3489 else 3490 llvm_unreachable("Unknown decl type for align_value"); 3491 3492 if (!T->isDependentType() && !T->isAnyPointerType() && 3493 !T->isReferenceType() && !T->isMemberPointerType()) { 3494 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only) 3495 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange(); 3496 return; 3497 } 3498 3499 if (!E->isValueDependent()) { 3500 llvm::APSInt Alignment; 3501 ExprResult ICE 3502 = VerifyIntegerConstantExpression(E, &Alignment, 3503 diag::err_align_value_attribute_argument_not_int, 3504 /*AllowFold*/ false); 3505 if (ICE.isInvalid()) 3506 return; 3507 3508 if (!Alignment.isPowerOf2()) { 3509 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 3510 << E->getSourceRange(); 3511 return; 3512 } 3513 3514 D->addAttr(::new (Context) 3515 AlignValueAttr(AttrRange, Context, ICE.get(), 3516 SpellingListIndex)); 3517 return; 3518 } 3519 3520 // Save dependent expressions in the AST to be instantiated. 3521 D->addAttr(::new (Context) AlignValueAttr(TmpAttr)); 3522 } 3523 3524 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &AL) { 3525 // check the attribute arguments. 3526 if (AL.getNumArgs() > 1) { 3527 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) 3528 << AL.getName() << 1; 3529 return; 3530 } 3531 3532 if (AL.getNumArgs() == 0) { 3533 D->addAttr(::new (S.Context) AlignedAttr(AL.getRange(), S.Context, 3534 true, nullptr, AL.getAttributeSpellingListIndex())); 3535 return; 3536 } 3537 3538 Expr *E = AL.getArgAsExpr(0); 3539 if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) { 3540 S.Diag(AL.getEllipsisLoc(), 3541 diag::err_pack_expansion_without_parameter_packs); 3542 return; 3543 } 3544 3545 if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E)) 3546 return; 3547 3548 if (E->isValueDependent()) { 3549 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) { 3550 if (!TND->getUnderlyingType()->isDependentType()) { 3551 S.Diag(AL.getLoc(), diag::err_alignment_dependent_typedef_name) 3552 << E->getSourceRange(); 3553 return; 3554 } 3555 } 3556 } 3557 3558 S.AddAlignedAttr(AL.getRange(), D, E, AL.getAttributeSpellingListIndex(), 3559 AL.isPackExpansion()); 3560 } 3561 3562 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, 3563 unsigned SpellingListIndex, bool IsPackExpansion) { 3564 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex); 3565 SourceLocation AttrLoc = AttrRange.getBegin(); 3566 3567 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements. 3568 if (TmpAttr.isAlignas()) { 3569 // C++11 [dcl.align]p1: 3570 // An alignment-specifier may be applied to a variable or to a class 3571 // data member, but it shall not be applied to a bit-field, a function 3572 // parameter, the formal parameter of a catch clause, or a variable 3573 // declared with the register storage class specifier. An 3574 // alignment-specifier may also be applied to the declaration of a class 3575 // or enumeration type. 3576 // C11 6.7.5/2: 3577 // An alignment attribute shall not be specified in a declaration of 3578 // a typedef, or a bit-field, or a function, or a parameter, or an 3579 // object declared with the register storage-class specifier. 3580 int DiagKind = -1; 3581 if (isa<ParmVarDecl>(D)) { 3582 DiagKind = 0; 3583 } else if (const auto *VD = dyn_cast<VarDecl>(D)) { 3584 if (VD->getStorageClass() == SC_Register) 3585 DiagKind = 1; 3586 if (VD->isExceptionVariable()) 3587 DiagKind = 2; 3588 } else if (const auto *FD = dyn_cast<FieldDecl>(D)) { 3589 if (FD->isBitField()) 3590 DiagKind = 3; 3591 } else if (!isa<TagDecl>(D)) { 3592 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr 3593 << (TmpAttr.isC11() ? ExpectedVariableOrField 3594 : ExpectedVariableFieldOrTag); 3595 return; 3596 } 3597 if (DiagKind != -1) { 3598 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type) 3599 << &TmpAttr << DiagKind; 3600 return; 3601 } 3602 } 3603 3604 if (E->isTypeDependent() || E->isValueDependent()) { 3605 // Save dependent expressions in the AST to be instantiated. 3606 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr); 3607 AA->setPackExpansion(IsPackExpansion); 3608 D->addAttr(AA); 3609 return; 3610 } 3611 3612 // FIXME: Cache the number on the AL object? 3613 llvm::APSInt Alignment; 3614 ExprResult ICE 3615 = VerifyIntegerConstantExpression(E, &Alignment, 3616 diag::err_aligned_attribute_argument_not_int, 3617 /*AllowFold*/ false); 3618 if (ICE.isInvalid()) 3619 return; 3620 3621 uint64_t AlignVal = Alignment.getZExtValue(); 3622 3623 // C++11 [dcl.align]p2: 3624 // -- if the constant expression evaluates to zero, the alignment 3625 // specifier shall have no effect 3626 // C11 6.7.5p6: 3627 // An alignment specification of zero has no effect. 3628 if (!(TmpAttr.isAlignas() && !Alignment)) { 3629 if (!llvm::isPowerOf2_64(AlignVal)) { 3630 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 3631 << E->getSourceRange(); 3632 return; 3633 } 3634 } 3635 3636 // Alignment calculations can wrap around if it's greater than 2**28. 3637 unsigned MaxValidAlignment = 3638 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192 3639 : 268435456; 3640 if (AlignVal > MaxValidAlignment) { 3641 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment 3642 << E->getSourceRange(); 3643 return; 3644 } 3645 3646 if (Context.getTargetInfo().isTLSSupported()) { 3647 unsigned MaxTLSAlign = 3648 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign()) 3649 .getQuantity(); 3650 const auto *VD = dyn_cast<VarDecl>(D); 3651 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD && 3652 VD->getTLSKind() != VarDecl::TLS_None) { 3653 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 3654 << (unsigned)AlignVal << VD << MaxTLSAlign; 3655 return; 3656 } 3657 } 3658 3659 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true, 3660 ICE.get(), SpellingListIndex); 3661 AA->setPackExpansion(IsPackExpansion); 3662 D->addAttr(AA); 3663 } 3664 3665 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS, 3666 unsigned SpellingListIndex, bool IsPackExpansion) { 3667 // FIXME: Cache the number on the AL object if non-dependent? 3668 // FIXME: Perform checking of type validity 3669 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS, 3670 SpellingListIndex); 3671 AA->setPackExpansion(IsPackExpansion); 3672 D->addAttr(AA); 3673 } 3674 3675 void Sema::CheckAlignasUnderalignment(Decl *D) { 3676 assert(D->hasAttrs() && "no attributes on decl"); 3677 3678 QualType UnderlyingTy, DiagTy; 3679 if (const auto *VD = dyn_cast<ValueDecl>(D)) { 3680 UnderlyingTy = DiagTy = VD->getType(); 3681 } else { 3682 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D)); 3683 if (const auto *ED = dyn_cast<EnumDecl>(D)) 3684 UnderlyingTy = ED->getIntegerType(); 3685 } 3686 if (DiagTy->isDependentType() || DiagTy->isIncompleteType()) 3687 return; 3688 3689 // C++11 [dcl.align]p5, C11 6.7.5/4: 3690 // The combined effect of all alignment attributes in a declaration shall 3691 // not specify an alignment that is less strict than the alignment that 3692 // would otherwise be required for the entity being declared. 3693 AlignedAttr *AlignasAttr = nullptr; 3694 unsigned Align = 0; 3695 for (auto *I : D->specific_attrs<AlignedAttr>()) { 3696 if (I->isAlignmentDependent()) 3697 return; 3698 if (I->isAlignas()) 3699 AlignasAttr = I; 3700 Align = std::max(Align, I->getAlignment(Context)); 3701 } 3702 3703 if (AlignasAttr && Align) { 3704 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align); 3705 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy); 3706 if (NaturalAlign > RequestedAlign) 3707 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned) 3708 << DiagTy << (unsigned)NaturalAlign.getQuantity(); 3709 } 3710 } 3711 3712 bool Sema::checkMSInheritanceAttrOnDefinition( 3713 CXXRecordDecl *RD, SourceRange Range, bool BestCase, 3714 MSInheritanceAttr::Spelling SemanticSpelling) { 3715 assert(RD->hasDefinition() && "RD has no definition!"); 3716 3717 // We may not have seen base specifiers or any virtual methods yet. We will 3718 // have to wait until the record is defined to catch any mismatches. 3719 if (!RD->getDefinition()->isCompleteDefinition()) 3720 return false; 3721 3722 // The unspecified model never matches what a definition could need. 3723 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance) 3724 return false; 3725 3726 if (BestCase) { 3727 if (RD->calculateInheritanceModel() == SemanticSpelling) 3728 return false; 3729 } else { 3730 if (RD->calculateInheritanceModel() <= SemanticSpelling) 3731 return false; 3732 } 3733 3734 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance) 3735 << 0 /*definition*/; 3736 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) 3737 << RD->getNameAsString(); 3738 return true; 3739 } 3740 3741 /// parseModeAttrArg - Parses attribute mode string and returns parsed type 3742 /// attribute. 3743 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth, 3744 bool &IntegerMode, bool &ComplexMode) { 3745 IntegerMode = true; 3746 ComplexMode = false; 3747 switch (Str.size()) { 3748 case 2: 3749 switch (Str[0]) { 3750 case 'Q': 3751 DestWidth = 8; 3752 break; 3753 case 'H': 3754 DestWidth = 16; 3755 break; 3756 case 'S': 3757 DestWidth = 32; 3758 break; 3759 case 'D': 3760 DestWidth = 64; 3761 break; 3762 case 'X': 3763 DestWidth = 96; 3764 break; 3765 case 'T': 3766 DestWidth = 128; 3767 break; 3768 } 3769 if (Str[1] == 'F') { 3770 IntegerMode = false; 3771 } else if (Str[1] == 'C') { 3772 IntegerMode = false; 3773 ComplexMode = true; 3774 } else if (Str[1] != 'I') { 3775 DestWidth = 0; 3776 } 3777 break; 3778 case 4: 3779 // FIXME: glibc uses 'word' to define register_t; this is narrower than a 3780 // pointer on PIC16 and other embedded platforms. 3781 if (Str == "word") 3782 DestWidth = S.Context.getTargetInfo().getRegisterWidth(); 3783 else if (Str == "byte") 3784 DestWidth = S.Context.getTargetInfo().getCharWidth(); 3785 break; 3786 case 7: 3787 if (Str == "pointer") 3788 DestWidth = S.Context.getTargetInfo().getPointerWidth(0); 3789 break; 3790 case 11: 3791 if (Str == "unwind_word") 3792 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth(); 3793 break; 3794 } 3795 } 3796 3797 /// handleModeAttr - This attribute modifies the width of a decl with primitive 3798 /// type. 3799 /// 3800 /// Despite what would be logical, the mode attribute is a decl attribute, not a 3801 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be 3802 /// HImode, not an intermediate pointer. 3803 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &AL) { 3804 // This attribute isn't documented, but glibc uses it. It changes 3805 // the width of an int or unsigned int to the specified size. 3806 if (!AL.isArgIdent(0)) { 3807 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) << AL.getName() 3808 << AANT_ArgumentIdentifier; 3809 return; 3810 } 3811 3812 IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident; 3813 3814 S.AddModeAttr(AL.getRange(), D, Name, AL.getAttributeSpellingListIndex()); 3815 } 3816 3817 void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name, 3818 unsigned SpellingListIndex, bool InInstantiation) { 3819 StringRef Str = Name->getName(); 3820 normalizeName(Str); 3821 SourceLocation AttrLoc = AttrRange.getBegin(); 3822 3823 unsigned DestWidth = 0; 3824 bool IntegerMode = true; 3825 bool ComplexMode = false; 3826 llvm::APInt VectorSize(64, 0); 3827 if (Str.size() >= 4 && Str[0] == 'V') { 3828 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2). 3829 size_t StrSize = Str.size(); 3830 size_t VectorStringLength = 0; 3831 while ((VectorStringLength + 1) < StrSize && 3832 isdigit(Str[VectorStringLength + 1])) 3833 ++VectorStringLength; 3834 if (VectorStringLength && 3835 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) && 3836 VectorSize.isPowerOf2()) { 3837 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth, 3838 IntegerMode, ComplexMode); 3839 // Avoid duplicate warning from template instantiation. 3840 if (!InInstantiation) 3841 Diag(AttrLoc, diag::warn_vector_mode_deprecated); 3842 } else { 3843 VectorSize = 0; 3844 } 3845 } 3846 3847 if (!VectorSize) 3848 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode); 3849 3850 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t 3851 // and friends, at least with glibc. 3852 // FIXME: Make sure floating-point mappings are accurate 3853 // FIXME: Support XF and TF types 3854 if (!DestWidth) { 3855 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name; 3856 return; 3857 } 3858 3859 QualType OldTy; 3860 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) 3861 OldTy = TD->getUnderlyingType(); 3862 else if (const auto *ED = dyn_cast<EnumDecl>(D)) { 3863 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'. 3864 // Try to get type from enum declaration, default to int. 3865 OldTy = ED->getIntegerType(); 3866 if (OldTy.isNull()) 3867 OldTy = Context.IntTy; 3868 } else 3869 OldTy = cast<ValueDecl>(D)->getType(); 3870 3871 if (OldTy->isDependentType()) { 3872 D->addAttr(::new (Context) 3873 ModeAttr(AttrRange, Context, Name, SpellingListIndex)); 3874 return; 3875 } 3876 3877 // Base type can also be a vector type (see PR17453). 3878 // Distinguish between base type and base element type. 3879 QualType OldElemTy = OldTy; 3880 if (const auto *VT = OldTy->getAs<VectorType>()) 3881 OldElemTy = VT->getElementType(); 3882 3883 // GCC allows 'mode' attribute on enumeration types (even incomplete), except 3884 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete 3885 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected. 3886 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) && 3887 VectorSize.getBoolValue()) { 3888 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange; 3889 return; 3890 } 3891 bool IntegralOrAnyEnumType = 3892 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>(); 3893 3894 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() && 3895 !IntegralOrAnyEnumType) 3896 Diag(AttrLoc, diag::err_mode_not_primitive); 3897 else if (IntegerMode) { 3898 if (!IntegralOrAnyEnumType) 3899 Diag(AttrLoc, diag::err_mode_wrong_type); 3900 } else if (ComplexMode) { 3901 if (!OldElemTy->isComplexType()) 3902 Diag(AttrLoc, diag::err_mode_wrong_type); 3903 } else { 3904 if (!OldElemTy->isFloatingType()) 3905 Diag(AttrLoc, diag::err_mode_wrong_type); 3906 } 3907 3908 QualType NewElemTy; 3909 3910 if (IntegerMode) 3911 NewElemTy = Context.getIntTypeForBitwidth(DestWidth, 3912 OldElemTy->isSignedIntegerType()); 3913 else 3914 NewElemTy = Context.getRealTypeForBitwidth(DestWidth); 3915 3916 if (NewElemTy.isNull()) { 3917 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name; 3918 return; 3919 } 3920 3921 if (ComplexMode) { 3922 NewElemTy = Context.getComplexType(NewElemTy); 3923 } 3924 3925 QualType NewTy = NewElemTy; 3926 if (VectorSize.getBoolValue()) { 3927 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(), 3928 VectorType::GenericVector); 3929 } else if (const auto *OldVT = OldTy->getAs<VectorType>()) { 3930 // Complex machine mode does not support base vector types. 3931 if (ComplexMode) { 3932 Diag(AttrLoc, diag::err_complex_mode_vector_type); 3933 return; 3934 } 3935 unsigned NumElements = Context.getTypeSize(OldElemTy) * 3936 OldVT->getNumElements() / 3937 Context.getTypeSize(NewElemTy); 3938 NewTy = 3939 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind()); 3940 } 3941 3942 if (NewTy.isNull()) { 3943 Diag(AttrLoc, diag::err_mode_wrong_type); 3944 return; 3945 } 3946 3947 // Install the new type. 3948 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) 3949 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy); 3950 else if (auto *ED = dyn_cast<EnumDecl>(D)) 3951 ED->setIntegerType(NewTy); 3952 else 3953 cast<ValueDecl>(D)->setType(NewTy); 3954 3955 D->addAttr(::new (Context) 3956 ModeAttr(AttrRange, Context, Name, SpellingListIndex)); 3957 } 3958 3959 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &AL) { 3960 D->addAttr(::new (S.Context) 3961 NoDebugAttr(AL.getRange(), S.Context, 3962 AL.getAttributeSpellingListIndex())); 3963 } 3964 3965 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range, 3966 IdentifierInfo *Ident, 3967 unsigned AttrSpellingListIndex) { 3968 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) { 3969 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident; 3970 Diag(Optnone->getLocation(), diag::note_conflicting_attribute); 3971 return nullptr; 3972 } 3973 3974 if (D->hasAttr<AlwaysInlineAttr>()) 3975 return nullptr; 3976 3977 return ::new (Context) AlwaysInlineAttr(Range, Context, 3978 AttrSpellingListIndex); 3979 } 3980 3981 CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range, 3982 IdentifierInfo *Ident, 3983 unsigned AttrSpellingListIndex) { 3984 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident)) 3985 return nullptr; 3986 3987 return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex); 3988 } 3989 3990 InternalLinkageAttr * 3991 Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range, 3992 IdentifierInfo *Ident, 3993 unsigned AttrSpellingListIndex) { 3994 if (const auto *VD = dyn_cast<VarDecl>(D)) { 3995 // Attribute applies to Var but not any subclass of it (like ParmVar, 3996 // ImplicitParm or VarTemplateSpecialization). 3997 if (VD->getKind() != Decl::Var) { 3998 Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type) 3999 << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass 4000 : ExpectedVariableOrFunction); 4001 return nullptr; 4002 } 4003 // Attribute does not apply to non-static local variables. 4004 if (VD->hasLocalStorage()) { 4005 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage); 4006 return nullptr; 4007 } 4008 } 4009 4010 if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident)) 4011 return nullptr; 4012 4013 return ::new (Context) 4014 InternalLinkageAttr(Range, Context, AttrSpellingListIndex); 4015 } 4016 4017 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range, 4018 unsigned AttrSpellingListIndex) { 4019 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) { 4020 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'"; 4021 Diag(Optnone->getLocation(), diag::note_conflicting_attribute); 4022 return nullptr; 4023 } 4024 4025 if (D->hasAttr<MinSizeAttr>()) 4026 return nullptr; 4027 4028 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex); 4029 } 4030 4031 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range, 4032 unsigned AttrSpellingListIndex) { 4033 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) { 4034 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline; 4035 Diag(Range.getBegin(), diag::note_conflicting_attribute); 4036 D->dropAttr<AlwaysInlineAttr>(); 4037 } 4038 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) { 4039 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize; 4040 Diag(Range.getBegin(), diag::note_conflicting_attribute); 4041 D->dropAttr<MinSizeAttr>(); 4042 } 4043 4044 if (D->hasAttr<OptimizeNoneAttr>()) 4045 return nullptr; 4046 4047 return ::new (Context) OptimizeNoneAttr(Range, Context, 4048 AttrSpellingListIndex); 4049 } 4050 4051 static void handleAlwaysInlineAttr(Sema &S, Decl *D, 4052 const AttributeList &AL) { 4053 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, AL.getRange(), 4054 AL.getName())) 4055 return; 4056 4057 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr( 4058 D, AL.getRange(), AL.getName(), 4059 AL.getAttributeSpellingListIndex())) 4060 D->addAttr(Inline); 4061 } 4062 4063 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &AL) { 4064 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr( 4065 D, AL.getRange(), AL.getAttributeSpellingListIndex())) 4066 D->addAttr(MinSize); 4067 } 4068 4069 static void handleOptimizeNoneAttr(Sema &S, Decl *D, 4070 const AttributeList &AL) { 4071 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr( 4072 D, AL.getRange(), AL.getAttributeSpellingListIndex())) 4073 D->addAttr(Optnone); 4074 } 4075 4076 static void handleConstantAttr(Sema &S, Decl *D, const AttributeList &AL) { 4077 if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, AL.getRange(), 4078 AL.getName())) 4079 return; 4080 const auto *VD = cast<VarDecl>(D); 4081 if (!VD->hasGlobalStorage()) { 4082 S.Diag(AL.getLoc(), diag::err_cuda_nonglobal_constant); 4083 return; 4084 } 4085 D->addAttr(::new (S.Context) CUDAConstantAttr( 4086 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); 4087 } 4088 4089 static void handleSharedAttr(Sema &S, Decl *D, const AttributeList &AL) { 4090 if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, AL.getRange(), 4091 AL.getName())) 4092 return; 4093 const auto *VD = cast<VarDecl>(D); 4094 // extern __shared__ is only allowed on arrays with no length (e.g. 4095 // "int x[]"). 4096 if (!S.getLangOpts().CUDARelocatableDeviceCode && VD->hasExternalStorage() && 4097 !isa<IncompleteArrayType>(VD->getType())) { 4098 S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD; 4099 return; 4100 } 4101 if (S.getLangOpts().CUDA && VD->hasLocalStorage() && 4102 S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared) 4103 << S.CurrentCUDATarget()) 4104 return; 4105 D->addAttr(::new (S.Context) CUDASharedAttr( 4106 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); 4107 } 4108 4109 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &AL) { 4110 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, AL.getRange(), 4111 AL.getName()) || 4112 checkAttrMutualExclusion<CUDAHostAttr>(S, D, AL.getRange(), 4113 AL.getName())) { 4114 return; 4115 } 4116 const auto *FD = cast<FunctionDecl>(D); 4117 if (!FD->getReturnType()->isVoidType()) { 4118 SourceRange RTRange = FD->getReturnTypeSourceRange(); 4119 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return) 4120 << FD->getType() 4121 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 4122 : FixItHint()); 4123 return; 4124 } 4125 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) { 4126 if (Method->isInstance()) { 4127 S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method) 4128 << Method; 4129 return; 4130 } 4131 S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method; 4132 } 4133 // Only warn for "inline" when compiling for host, to cut down on noise. 4134 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice) 4135 S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD; 4136 4137 D->addAttr(::new (S.Context) 4138 CUDAGlobalAttr(AL.getRange(), S.Context, 4139 AL.getAttributeSpellingListIndex())); 4140 } 4141 4142 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &AL) { 4143 const auto *Fn = cast<FunctionDecl>(D); 4144 if (!Fn->isInlineSpecified()) { 4145 S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline); 4146 return; 4147 } 4148 4149 D->addAttr(::new (S.Context) 4150 GNUInlineAttr(AL.getRange(), S.Context, 4151 AL.getAttributeSpellingListIndex())); 4152 } 4153 4154 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &AL) { 4155 if (hasDeclarator(D)) return; 4156 4157 // Diagnostic is emitted elsewhere: here we store the (valid) AL 4158 // in the Decl node for syntactic reasoning, e.g., pretty-printing. 4159 CallingConv CC; 4160 if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr)) 4161 return; 4162 4163 if (!isa<ObjCMethodDecl>(D)) { 4164 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 4165 << AL.getName() << ExpectedFunctionOrMethod; 4166 return; 4167 } 4168 4169 switch (AL.getKind()) { 4170 case AttributeList::AT_FastCall: 4171 D->addAttr(::new (S.Context) 4172 FastCallAttr(AL.getRange(), S.Context, 4173 AL.getAttributeSpellingListIndex())); 4174 return; 4175 case AttributeList::AT_StdCall: 4176 D->addAttr(::new (S.Context) 4177 StdCallAttr(AL.getRange(), S.Context, 4178 AL.getAttributeSpellingListIndex())); 4179 return; 4180 case AttributeList::AT_ThisCall: 4181 D->addAttr(::new (S.Context) 4182 ThisCallAttr(AL.getRange(), S.Context, 4183 AL.getAttributeSpellingListIndex())); 4184 return; 4185 case AttributeList::AT_CDecl: 4186 D->addAttr(::new (S.Context) 4187 CDeclAttr(AL.getRange(), S.Context, 4188 AL.getAttributeSpellingListIndex())); 4189 return; 4190 case AttributeList::AT_Pascal: 4191 D->addAttr(::new (S.Context) 4192 PascalAttr(AL.getRange(), S.Context, 4193 AL.getAttributeSpellingListIndex())); 4194 return; 4195 case AttributeList::AT_SwiftCall: 4196 D->addAttr(::new (S.Context) 4197 SwiftCallAttr(AL.getRange(), S.Context, 4198 AL.getAttributeSpellingListIndex())); 4199 return; 4200 case AttributeList::AT_VectorCall: 4201 D->addAttr(::new (S.Context) 4202 VectorCallAttr(AL.getRange(), S.Context, 4203 AL.getAttributeSpellingListIndex())); 4204 return; 4205 case AttributeList::AT_MSABI: 4206 D->addAttr(::new (S.Context) 4207 MSABIAttr(AL.getRange(), S.Context, 4208 AL.getAttributeSpellingListIndex())); 4209 return; 4210 case AttributeList::AT_SysVABI: 4211 D->addAttr(::new (S.Context) 4212 SysVABIAttr(AL.getRange(), S.Context, 4213 AL.getAttributeSpellingListIndex())); 4214 return; 4215 case AttributeList::AT_RegCall: 4216 D->addAttr(::new (S.Context) RegCallAttr( 4217 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); 4218 return; 4219 case AttributeList::AT_Pcs: { 4220 PcsAttr::PCSType PCS; 4221 switch (CC) { 4222 case CC_AAPCS: 4223 PCS = PcsAttr::AAPCS; 4224 break; 4225 case CC_AAPCS_VFP: 4226 PCS = PcsAttr::AAPCS_VFP; 4227 break; 4228 default: 4229 llvm_unreachable("unexpected calling convention in pcs attribute"); 4230 } 4231 4232 D->addAttr(::new (S.Context) 4233 PcsAttr(AL.getRange(), S.Context, PCS, 4234 AL.getAttributeSpellingListIndex())); 4235 return; 4236 } 4237 case AttributeList::AT_IntelOclBicc: 4238 D->addAttr(::new (S.Context) 4239 IntelOclBiccAttr(AL.getRange(), S.Context, 4240 AL.getAttributeSpellingListIndex())); 4241 return; 4242 case AttributeList::AT_PreserveMost: 4243 D->addAttr(::new (S.Context) PreserveMostAttr( 4244 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); 4245 return; 4246 case AttributeList::AT_PreserveAll: 4247 D->addAttr(::new (S.Context) PreserveAllAttr( 4248 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); 4249 return; 4250 default: 4251 llvm_unreachable("unexpected attribute kind"); 4252 } 4253 } 4254 4255 static void handleSuppressAttr(Sema &S, Decl *D, const AttributeList &AL) { 4256 if (!checkAttributeAtLeastNumArgs(S, AL, 1)) 4257 return; 4258 4259 std::vector<StringRef> DiagnosticIdentifiers; 4260 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) { 4261 StringRef RuleName; 4262 4263 if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr)) 4264 return; 4265 4266 // FIXME: Warn if the rule name is unknown. This is tricky because only 4267 // clang-tidy knows about available rules. 4268 DiagnosticIdentifiers.push_back(RuleName); 4269 } 4270 D->addAttr(::new (S.Context) SuppressAttr( 4271 AL.getRange(), S.Context, DiagnosticIdentifiers.data(), 4272 DiagnosticIdentifiers.size(), AL.getAttributeSpellingListIndex())); 4273 } 4274 4275 bool Sema::CheckCallingConvAttr(const AttributeList &Attrs, CallingConv &CC, 4276 const FunctionDecl *FD) { 4277 if (Attrs.isInvalid()) 4278 return true; 4279 4280 if (Attrs.hasProcessingCache()) { 4281 CC = (CallingConv) Attrs.getProcessingCache(); 4282 return false; 4283 } 4284 4285 unsigned ReqArgs = Attrs.getKind() == AttributeList::AT_Pcs ? 1 : 0; 4286 if (!checkAttributeNumArgs(*this, Attrs, ReqArgs)) { 4287 Attrs.setInvalid(); 4288 return true; 4289 } 4290 4291 // TODO: diagnose uses of these conventions on the wrong target. 4292 switch (Attrs.getKind()) { 4293 case AttributeList::AT_CDecl: CC = CC_C; break; 4294 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break; 4295 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break; 4296 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break; 4297 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break; 4298 case AttributeList::AT_SwiftCall: CC = CC_Swift; break; 4299 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break; 4300 case AttributeList::AT_RegCall: CC = CC_X86RegCall; break; 4301 case AttributeList::AT_MSABI: 4302 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C : 4303 CC_Win64; 4304 break; 4305 case AttributeList::AT_SysVABI: 4306 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV : 4307 CC_C; 4308 break; 4309 case AttributeList::AT_Pcs: { 4310 StringRef StrRef; 4311 if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) { 4312 Attrs.setInvalid(); 4313 return true; 4314 } 4315 if (StrRef == "aapcs") { 4316 CC = CC_AAPCS; 4317 break; 4318 } else if (StrRef == "aapcs-vfp") { 4319 CC = CC_AAPCS_VFP; 4320 break; 4321 } 4322 4323 Attrs.setInvalid(); 4324 Diag(Attrs.getLoc(), diag::err_invalid_pcs); 4325 return true; 4326 } 4327 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break; 4328 case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break; 4329 case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break; 4330 default: llvm_unreachable("unexpected attribute kind"); 4331 } 4332 4333 const TargetInfo &TI = Context.getTargetInfo(); 4334 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC); 4335 if (A != TargetInfo::CCCR_OK) { 4336 if (A == TargetInfo::CCCR_Warning) 4337 Diag(Attrs.getLoc(), diag::warn_cconv_ignored) << Attrs.getName(); 4338 4339 // This convention is not valid for the target. Use the default function or 4340 // method calling convention. 4341 bool IsCXXMethod = false, IsVariadic = false; 4342 if (FD) { 4343 IsCXXMethod = FD->isCXXInstanceMember(); 4344 IsVariadic = FD->isVariadic(); 4345 } 4346 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod); 4347 } 4348 4349 Attrs.setProcessingCache((unsigned) CC); 4350 return false; 4351 } 4352 4353 /// Pointer-like types in the default address space. 4354 static bool isValidSwiftContextType(QualType Ty) { 4355 if (!Ty->hasPointerRepresentation()) 4356 return Ty->isDependentType(); 4357 return Ty->getPointeeType().getAddressSpace() == LangAS::Default; 4358 } 4359 4360 /// Pointers and references in the default address space. 4361 static bool isValidSwiftIndirectResultType(QualType Ty) { 4362 if (const auto *PtrType = Ty->getAs<PointerType>()) { 4363 Ty = PtrType->getPointeeType(); 4364 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) { 4365 Ty = RefType->getPointeeType(); 4366 } else { 4367 return Ty->isDependentType(); 4368 } 4369 return Ty.getAddressSpace() == LangAS::Default; 4370 } 4371 4372 /// Pointers and references to pointers in the default address space. 4373 static bool isValidSwiftErrorResultType(QualType Ty) { 4374 if (const auto *PtrType = Ty->getAs<PointerType>()) { 4375 Ty = PtrType->getPointeeType(); 4376 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) { 4377 Ty = RefType->getPointeeType(); 4378 } else { 4379 return Ty->isDependentType(); 4380 } 4381 if (!Ty.getQualifiers().empty()) 4382 return false; 4383 return isValidSwiftContextType(Ty); 4384 } 4385 4386 static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &Attrs, 4387 ParameterABI Abi) { 4388 S.AddParameterABIAttr(Attrs.getRange(), D, Abi, 4389 Attrs.getAttributeSpellingListIndex()); 4390 } 4391 4392 void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi, 4393 unsigned spellingIndex) { 4394 4395 QualType type = cast<ParmVarDecl>(D)->getType(); 4396 4397 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) { 4398 if (existingAttr->getABI() != abi) { 4399 Diag(range.getBegin(), diag::err_attributes_are_not_compatible) 4400 << getParameterABISpelling(abi) << existingAttr; 4401 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute); 4402 return; 4403 } 4404 } 4405 4406 switch (abi) { 4407 case ParameterABI::Ordinary: 4408 llvm_unreachable("explicit attribute for ordinary parameter ABI?"); 4409 4410 case ParameterABI::SwiftContext: 4411 if (!isValidSwiftContextType(type)) { 4412 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) 4413 << getParameterABISpelling(abi) 4414 << /*pointer to pointer */ 0 << type; 4415 } 4416 D->addAttr(::new (Context) 4417 SwiftContextAttr(range, Context, spellingIndex)); 4418 return; 4419 4420 case ParameterABI::SwiftErrorResult: 4421 if (!isValidSwiftErrorResultType(type)) { 4422 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) 4423 << getParameterABISpelling(abi) 4424 << /*pointer to pointer */ 1 << type; 4425 } 4426 D->addAttr(::new (Context) 4427 SwiftErrorResultAttr(range, Context, spellingIndex)); 4428 return; 4429 4430 case ParameterABI::SwiftIndirectResult: 4431 if (!isValidSwiftIndirectResultType(type)) { 4432 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) 4433 << getParameterABISpelling(abi) 4434 << /*pointer*/ 0 << type; 4435 } 4436 D->addAttr(::new (Context) 4437 SwiftIndirectResultAttr(range, Context, spellingIndex)); 4438 return; 4439 } 4440 llvm_unreachable("bad parameter ABI attribute"); 4441 } 4442 4443 /// Checks a regparm attribute, returning true if it is ill-formed and 4444 /// otherwise setting numParams to the appropriate value. 4445 bool Sema::CheckRegparmAttr(const AttributeList &AL, unsigned &numParams) { 4446 if (AL.isInvalid()) 4447 return true; 4448 4449 if (!checkAttributeNumArgs(*this, AL, 1)) { 4450 AL.setInvalid(); 4451 return true; 4452 } 4453 4454 uint32_t NP; 4455 Expr *NumParamsExpr = AL.getArgAsExpr(0); 4456 if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) { 4457 AL.setInvalid(); 4458 return true; 4459 } 4460 4461 if (Context.getTargetInfo().getRegParmMax() == 0) { 4462 Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform) 4463 << NumParamsExpr->getSourceRange(); 4464 AL.setInvalid(); 4465 return true; 4466 } 4467 4468 numParams = NP; 4469 if (numParams > Context.getTargetInfo().getRegParmMax()) { 4470 Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number) 4471 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange(); 4472 AL.setInvalid(); 4473 return true; 4474 } 4475 4476 return false; 4477 } 4478 4479 // Checks whether an argument of launch_bounds attribute is 4480 // acceptable, performs implicit conversion to Rvalue, and returns 4481 // non-nullptr Expr result on success. Otherwise, it returns nullptr 4482 // and may output an error. 4483 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E, 4484 const CUDALaunchBoundsAttr &AL, 4485 const unsigned Idx) { 4486 if (S.DiagnoseUnexpandedParameterPack(E)) 4487 return nullptr; 4488 4489 // Accept template arguments for now as they depend on something else. 4490 // We'll get to check them when they eventually get instantiated. 4491 if (E->isValueDependent()) 4492 return E; 4493 4494 llvm::APSInt I(64); 4495 if (!E->isIntegerConstantExpr(I, S.Context)) { 4496 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type) 4497 << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange(); 4498 return nullptr; 4499 } 4500 // Make sure we can fit it in 32 bits. 4501 if (!I.isIntN(32)) { 4502 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false) 4503 << 32 << /* Unsigned */ 1; 4504 return nullptr; 4505 } 4506 if (I < 0) 4507 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative) 4508 << &AL << Idx << E->getSourceRange(); 4509 4510 // We may need to perform implicit conversion of the argument. 4511 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4512 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false); 4513 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E); 4514 assert(!ValArg.isInvalid() && 4515 "Unexpected PerformCopyInitialization() failure."); 4516 4517 return ValArg.getAs<Expr>(); 4518 } 4519 4520 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads, 4521 Expr *MinBlocks, unsigned SpellingListIndex) { 4522 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks, 4523 SpellingListIndex); 4524 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0); 4525 if (MaxThreads == nullptr) 4526 return; 4527 4528 if (MinBlocks) { 4529 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1); 4530 if (MinBlocks == nullptr) 4531 return; 4532 } 4533 4534 D->addAttr(::new (Context) CUDALaunchBoundsAttr( 4535 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex)); 4536 } 4537 4538 static void handleLaunchBoundsAttr(Sema &S, Decl *D, 4539 const AttributeList &AL) { 4540 if (!checkAttributeAtLeastNumArgs(S, AL, 1) || 4541 !checkAttributeAtMostNumArgs(S, AL, 2)) 4542 return; 4543 4544 S.AddLaunchBoundsAttr(AL.getRange(), D, AL.getArgAsExpr(0), 4545 AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr, 4546 AL.getAttributeSpellingListIndex()); 4547 } 4548 4549 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D, 4550 const AttributeList &AL) { 4551 if (!AL.isArgIdent(0)) { 4552 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 4553 << AL.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier; 4554 return; 4555 } 4556 4557 if (!checkAttributeNumArgs(S, AL, 3)) 4558 return; 4559 4560 IdentifierInfo *ArgumentKind = AL.getArgAsIdent(0)->Ident; 4561 4562 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) { 4563 S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type) 4564 << AL.getName() << ExpectedFunctionOrMethod; 4565 return; 4566 } 4567 4568 uint64_t ArgumentIdx; 4569 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1), 4570 ArgumentIdx)) 4571 return; 4572 4573 uint64_t TypeTagIdx; 4574 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2), 4575 TypeTagIdx)) 4576 return; 4577 4578 bool IsPointer = (AL.getName()->getName() == "pointer_with_type_tag"); 4579 if (IsPointer) { 4580 // Ensure that buffer has a pointer type. 4581 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx); 4582 if (!BufferTy->isPointerType()) { 4583 S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) 4584 << AL.getName() << 0; 4585 } 4586 } 4587 4588 D->addAttr(::new (S.Context) 4589 ArgumentWithTypeTagAttr(AL.getRange(), S.Context, ArgumentKind, 4590 ArgumentIdx, TypeTagIdx, IsPointer, 4591 AL.getAttributeSpellingListIndex())); 4592 } 4593 4594 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D, 4595 const AttributeList &AL) { 4596 if (!AL.isArgIdent(0)) { 4597 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 4598 << AL.getName() << 1 << AANT_ArgumentIdentifier; 4599 return; 4600 } 4601 4602 if (!checkAttributeNumArgs(S, AL, 1)) 4603 return; 4604 4605 if (!isa<VarDecl>(D)) { 4606 S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type) 4607 << AL.getName() << ExpectedVariable; 4608 return; 4609 } 4610 4611 IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident; 4612 TypeSourceInfo *MatchingCTypeLoc = nullptr; 4613 S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc); 4614 assert(MatchingCTypeLoc && "no type source info for attribute argument"); 4615 4616 D->addAttr(::new (S.Context) 4617 TypeTagForDatatypeAttr(AL.getRange(), S.Context, PointerKind, 4618 MatchingCTypeLoc, 4619 AL.getLayoutCompatible(), 4620 AL.getMustBeNull(), 4621 AL.getAttributeSpellingListIndex())); 4622 } 4623 4624 static void handleXRayLogArgsAttr(Sema &S, Decl *D, 4625 const AttributeList &AL) { 4626 uint64_t ArgCount; 4627 4628 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0), 4629 ArgCount, 4630 true /* AllowImplicitThis*/)) 4631 return; 4632 4633 // ArgCount isn't a parameter index [0;n), it's a count [1;n] - hence + 1. 4634 D->addAttr(::new (S.Context) 4635 XRayLogArgsAttr(AL.getRange(), S.Context, ++ArgCount, 4636 AL.getAttributeSpellingListIndex())); 4637 } 4638 4639 //===----------------------------------------------------------------------===// 4640 // Checker-specific attribute handlers. 4641 //===----------------------------------------------------------------------===// 4642 4643 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) { 4644 return QT->isDependentType() || QT->isObjCRetainableType(); 4645 } 4646 4647 static bool isValidSubjectOfNSAttribute(Sema &S, QualType QT) { 4648 return QT->isDependentType() || QT->isObjCObjectPointerType() || 4649 S.Context.isObjCNSObjectType(QT); 4650 } 4651 4652 static bool isValidSubjectOfCFAttribute(Sema &S, QualType QT) { 4653 return QT->isDependentType() || QT->isPointerType() || 4654 isValidSubjectOfNSAttribute(S, QT); 4655 } 4656 4657 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &AL) { 4658 S.AddNSConsumedAttr(AL.getRange(), D, AL.getAttributeSpellingListIndex(), 4659 AL.getKind() == AttributeList::AT_NSConsumed, 4660 /*template instantiation*/ false); 4661 } 4662 4663 void Sema::AddNSConsumedAttr(SourceRange AttrRange, Decl *D, 4664 unsigned SpellingIndex, bool IsNSConsumed, 4665 bool IsTemplateInstantiation) { 4666 const auto *Param = cast<ParmVarDecl>(D); 4667 bool TypeOK; 4668 4669 if (IsNSConsumed) 4670 TypeOK = isValidSubjectOfNSAttribute(*this, Param->getType()); 4671 else 4672 TypeOK = isValidSubjectOfCFAttribute(*this, Param->getType()); 4673 4674 if (!TypeOK) { 4675 // These attributes are normally just advisory, but in ARC, ns_consumed 4676 // is significant. Allow non-dependent code to contain inappropriate 4677 // attributes even in ARC, but require template instantiations to be 4678 // set up correctly. 4679 Diag(D->getLocStart(), (IsTemplateInstantiation && IsNSConsumed && 4680 getLangOpts().ObjCAutoRefCount 4681 ? diag::err_ns_attribute_wrong_parameter_type 4682 : diag::warn_ns_attribute_wrong_parameter_type)) 4683 << AttrRange << (IsNSConsumed ? "ns_consumed" : "cf_consumed") 4684 << (IsNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1); 4685 return; 4686 } 4687 4688 if (IsNSConsumed) 4689 D->addAttr(::new (Context) 4690 NSConsumedAttr(AttrRange, Context, SpellingIndex)); 4691 else 4692 D->addAttr(::new (Context) 4693 CFConsumedAttr(AttrRange, Context, SpellingIndex)); 4694 } 4695 4696 bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc, QualType QT) { 4697 if (isValidSubjectOfNSReturnsRetainedAttribute(QT)) 4698 return false; 4699 4700 Diag(Loc, diag::warn_ns_attribute_wrong_return_type) 4701 << "'ns_returns_retained'" << 0 << 0; 4702 return true; 4703 } 4704 4705 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D, 4706 const AttributeList &AL) { 4707 QualType ReturnType; 4708 4709 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 4710 ReturnType = MD->getReturnType(); 4711 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) && 4712 (AL.getKind() == AttributeList::AT_NSReturnsRetained)) 4713 return; // ignore: was handled as a type attribute 4714 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) 4715 ReturnType = PD->getType(); 4716 else if (const auto *FD = dyn_cast<FunctionDecl>(D)) 4717 ReturnType = FD->getReturnType(); 4718 else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) { 4719 ReturnType = Param->getType()->getPointeeType(); 4720 if (ReturnType.isNull()) { 4721 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type) 4722 << AL.getName() << /*pointer-to-CF*/2 4723 << AL.getRange(); 4724 return; 4725 } 4726 } else if (AL.isUsedAsTypeAttr()) { 4727 return; 4728 } else { 4729 AttributeDeclKind ExpectedDeclKind; 4730 switch (AL.getKind()) { 4731 default: llvm_unreachable("invalid ownership attribute"); 4732 case AttributeList::AT_NSReturnsRetained: 4733 case AttributeList::AT_NSReturnsAutoreleased: 4734 case AttributeList::AT_NSReturnsNotRetained: 4735 ExpectedDeclKind = ExpectedFunctionOrMethod; 4736 break; 4737 4738 case AttributeList::AT_CFReturnsRetained: 4739 case AttributeList::AT_CFReturnsNotRetained: 4740 ExpectedDeclKind = ExpectedFunctionMethodOrParameter; 4741 break; 4742 } 4743 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type) 4744 << AL.getRange() << AL.getName() << ExpectedDeclKind; 4745 return; 4746 } 4747 4748 bool TypeOK; 4749 bool Cf; 4750 switch (AL.getKind()) { 4751 default: llvm_unreachable("invalid ownership attribute"); 4752 case AttributeList::AT_NSReturnsRetained: 4753 TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType); 4754 Cf = false; 4755 break; 4756 4757 case AttributeList::AT_NSReturnsAutoreleased: 4758 case AttributeList::AT_NSReturnsNotRetained: 4759 TypeOK = isValidSubjectOfNSAttribute(S, ReturnType); 4760 Cf = false; 4761 break; 4762 4763 case AttributeList::AT_CFReturnsRetained: 4764 case AttributeList::AT_CFReturnsNotRetained: 4765 TypeOK = isValidSubjectOfCFAttribute(S, ReturnType); 4766 Cf = true; 4767 break; 4768 } 4769 4770 if (!TypeOK) { 4771 if (AL.isUsedAsTypeAttr()) 4772 return; 4773 4774 if (isa<ParmVarDecl>(D)) { 4775 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type) 4776 << AL.getName() << /*pointer-to-CF*/2 4777 << AL.getRange(); 4778 } else { 4779 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type. 4780 enum : unsigned { 4781 Function, 4782 Method, 4783 Property 4784 } SubjectKind = Function; 4785 if (isa<ObjCMethodDecl>(D)) 4786 SubjectKind = Method; 4787 else if (isa<ObjCPropertyDecl>(D)) 4788 SubjectKind = Property; 4789 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type) 4790 << AL.getName() << SubjectKind << Cf 4791 << AL.getRange(); 4792 } 4793 return; 4794 } 4795 4796 switch (AL.getKind()) { 4797 default: 4798 llvm_unreachable("invalid ownership attribute"); 4799 case AttributeList::AT_NSReturnsAutoreleased: 4800 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr( 4801 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); 4802 return; 4803 case AttributeList::AT_CFReturnsNotRetained: 4804 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr( 4805 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); 4806 return; 4807 case AttributeList::AT_NSReturnsNotRetained: 4808 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr( 4809 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); 4810 return; 4811 case AttributeList::AT_CFReturnsRetained: 4812 D->addAttr(::new (S.Context) CFReturnsRetainedAttr( 4813 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); 4814 return; 4815 case AttributeList::AT_NSReturnsRetained: 4816 D->addAttr(::new (S.Context) NSReturnsRetainedAttr( 4817 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); 4818 return; 4819 }; 4820 } 4821 4822 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D, 4823 const AttributeList &Attrs) { 4824 const int EP_ObjCMethod = 1; 4825 const int EP_ObjCProperty = 2; 4826 4827 SourceLocation loc = Attrs.getLoc(); 4828 QualType resultType; 4829 if (isa<ObjCMethodDecl>(D)) 4830 resultType = cast<ObjCMethodDecl>(D)->getReturnType(); 4831 else 4832 resultType = cast<ObjCPropertyDecl>(D)->getType(); 4833 4834 if (!resultType->isReferenceType() && 4835 (!resultType->isPointerType() || resultType->isObjCRetainableType())) { 4836 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type) 4837 << SourceRange(loc) 4838 << Attrs.getName() 4839 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty) 4840 << /*non-retainable pointer*/ 2; 4841 4842 // Drop the attribute. 4843 return; 4844 } 4845 4846 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr( 4847 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex())); 4848 } 4849 4850 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D, 4851 const AttributeList &Attrs) { 4852 const auto *Method = cast<ObjCMethodDecl>(D); 4853 4854 const DeclContext *DC = Method->getDeclContext(); 4855 if (const auto *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) { 4856 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol) 4857 << Attrs.getName() << 0; 4858 S.Diag(PDecl->getLocation(), diag::note_protocol_decl); 4859 return; 4860 } 4861 if (Method->getMethodFamily() == OMF_dealloc) { 4862 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol) 4863 << Attrs.getName() << 1; 4864 return; 4865 } 4866 4867 D->addAttr(::new (S.Context) ObjCRequiresSuperAttr( 4868 Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex())); 4869 } 4870 4871 static void handleCFAuditedTransferAttr(Sema &S, Decl *D, 4872 const AttributeList &AL) { 4873 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, AL.getRange(), 4874 AL.getName())) 4875 return; 4876 4877 D->addAttr(::new (S.Context) 4878 CFAuditedTransferAttr(AL.getRange(), S.Context, 4879 AL.getAttributeSpellingListIndex())); 4880 } 4881 4882 static void handleCFUnknownTransferAttr(Sema &S, Decl *D, 4883 const AttributeList &AL) { 4884 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, AL.getRange(), 4885 AL.getName())) 4886 return; 4887 4888 D->addAttr(::new (S.Context) 4889 CFUnknownTransferAttr(AL.getRange(), S.Context, 4890 AL.getAttributeSpellingListIndex())); 4891 } 4892 4893 static void handleObjCBridgeAttr(Sema &S, Decl *D, const AttributeList &AL) { 4894 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr; 4895 4896 if (!Parm) { 4897 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << AL.getName() << 0; 4898 return; 4899 } 4900 4901 // Typedefs only allow objc_bridge(id) and have some additional checking. 4902 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 4903 if (!Parm->Ident->isStr("id")) { 4904 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) 4905 << AL.getName(); 4906 return; 4907 } 4908 4909 // Only allow 'cv void *'. 4910 QualType T = TD->getUnderlyingType(); 4911 if (!T->isVoidPointerType()) { 4912 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer); 4913 return; 4914 } 4915 } 4916 4917 D->addAttr(::new (S.Context) 4918 ObjCBridgeAttr(AL.getRange(), S.Context, Parm->Ident, 4919 AL.getAttributeSpellingListIndex())); 4920 } 4921 4922 static void handleObjCBridgeMutableAttr(Sema &S, Decl *D, 4923 const AttributeList &AL) { 4924 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr; 4925 4926 if (!Parm) { 4927 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << AL.getName() << 0; 4928 return; 4929 } 4930 4931 D->addAttr(::new (S.Context) 4932 ObjCBridgeMutableAttr(AL.getRange(), S.Context, Parm->Ident, 4933 AL.getAttributeSpellingListIndex())); 4934 } 4935 4936 static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D, 4937 const AttributeList &AL) { 4938 IdentifierInfo *RelatedClass = 4939 AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr; 4940 if (!RelatedClass) { 4941 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << AL.getName() << 0; 4942 return; 4943 } 4944 IdentifierInfo *ClassMethod = 4945 AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr; 4946 IdentifierInfo *InstanceMethod = 4947 AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr; 4948 D->addAttr(::new (S.Context) 4949 ObjCBridgeRelatedAttr(AL.getRange(), S.Context, RelatedClass, 4950 ClassMethod, InstanceMethod, 4951 AL.getAttributeSpellingListIndex())); 4952 } 4953 4954 static void handleObjCDesignatedInitializer(Sema &S, Decl *D, 4955 const AttributeList &AL) { 4956 ObjCInterfaceDecl *IFace; 4957 if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(D->getDeclContext())) 4958 IFace = CatDecl->getClassInterface(); 4959 else 4960 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext()); 4961 4962 if (!IFace) 4963 return; 4964 4965 IFace->setHasDesignatedInitializers(); 4966 D->addAttr(::new (S.Context) 4967 ObjCDesignatedInitializerAttr(AL.getRange(), S.Context, 4968 AL.getAttributeSpellingListIndex())); 4969 } 4970 4971 static void handleObjCRuntimeName(Sema &S, Decl *D, 4972 const AttributeList &AL) { 4973 StringRef MetaDataName; 4974 if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName)) 4975 return; 4976 D->addAttr(::new (S.Context) 4977 ObjCRuntimeNameAttr(AL.getRange(), S.Context, 4978 MetaDataName, 4979 AL.getAttributeSpellingListIndex())); 4980 } 4981 4982 // When a user wants to use objc_boxable with a union or struct 4983 // but they don't have access to the declaration (legacy/third-party code) 4984 // then they can 'enable' this feature with a typedef: 4985 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct; 4986 static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &AL) { 4987 bool notify = false; 4988 4989 auto *RD = dyn_cast<RecordDecl>(D); 4990 if (RD && RD->getDefinition()) { 4991 RD = RD->getDefinition(); 4992 notify = true; 4993 } 4994 4995 if (RD) { 4996 ObjCBoxableAttr *BoxableAttr = ::new (S.Context) 4997 ObjCBoxableAttr(AL.getRange(), S.Context, 4998 AL.getAttributeSpellingListIndex()); 4999 RD->addAttr(BoxableAttr); 5000 if (notify) { 5001 // we need to notify ASTReader/ASTWriter about 5002 // modification of existing declaration 5003 if (ASTMutationListener *L = S.getASTMutationListener()) 5004 L->AddedAttributeToRecord(BoxableAttr, RD); 5005 } 5006 } 5007 } 5008 5009 static void handleObjCOwnershipAttr(Sema &S, Decl *D, 5010 const AttributeList &AL) { 5011 if (hasDeclarator(D)) return; 5012 5013 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type) 5014 << AL.getRange() << AL.getName() << ExpectedVariable; 5015 } 5016 5017 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D, 5018 const AttributeList &AL) { 5019 const auto *VD = cast<ValueDecl>(D); 5020 QualType QT = VD->getType(); 5021 5022 if (!QT->isDependentType() && 5023 !QT->isObjCLifetimeType()) { 5024 S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type) 5025 << QT; 5026 return; 5027 } 5028 5029 Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime(); 5030 5031 // If we have no lifetime yet, check the lifetime we're presumably 5032 // going to infer. 5033 if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType()) 5034 Lifetime = QT->getObjCARCImplicitLifetime(); 5035 5036 switch (Lifetime) { 5037 case Qualifiers::OCL_None: 5038 assert(QT->isDependentType() && 5039 "didn't infer lifetime for non-dependent type?"); 5040 break; 5041 5042 case Qualifiers::OCL_Weak: // meaningful 5043 case Qualifiers::OCL_Strong: // meaningful 5044 break; 5045 5046 case Qualifiers::OCL_ExplicitNone: 5047 case Qualifiers::OCL_Autoreleasing: 5048 S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless) 5049 << (Lifetime == Qualifiers::OCL_Autoreleasing); 5050 break; 5051 } 5052 5053 D->addAttr(::new (S.Context) 5054 ObjCPreciseLifetimeAttr(AL.getRange(), S.Context, 5055 AL.getAttributeSpellingListIndex())); 5056 } 5057 5058 //===----------------------------------------------------------------------===// 5059 // Microsoft specific attribute handlers. 5060 //===----------------------------------------------------------------------===// 5061 5062 UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range, 5063 unsigned AttrSpellingListIndex, StringRef Uuid) { 5064 if (const auto *UA = D->getAttr<UuidAttr>()) { 5065 if (UA->getGuid().equals_lower(Uuid)) 5066 return nullptr; 5067 Diag(UA->getLocation(), diag::err_mismatched_uuid); 5068 Diag(Range.getBegin(), diag::note_previous_uuid); 5069 D->dropAttr<UuidAttr>(); 5070 } 5071 5072 return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex); 5073 } 5074 5075 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &AL) { 5076 if (!S.LangOpts.CPlusPlus) { 5077 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang) 5078 << AL.getName() << AttributeLangSupport::C; 5079 return; 5080 } 5081 5082 StringRef StrRef; 5083 SourceLocation LiteralLoc; 5084 if (!S.checkStringLiteralArgumentAttr(AL, 0, StrRef, &LiteralLoc)) 5085 return; 5086 5087 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or 5088 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former. 5089 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}') 5090 StrRef = StrRef.drop_front().drop_back(); 5091 5092 // Validate GUID length. 5093 if (StrRef.size() != 36) { 5094 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 5095 return; 5096 } 5097 5098 for (unsigned i = 0; i < 36; ++i) { 5099 if (i == 8 || i == 13 || i == 18 || i == 23) { 5100 if (StrRef[i] != '-') { 5101 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 5102 return; 5103 } 5104 } else if (!isHexDigit(StrRef[i])) { 5105 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 5106 return; 5107 } 5108 } 5109 5110 // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's 5111 // the only thing in the [] list, the [] too), and add an insertion of 5112 // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas 5113 // separating attributes nor of the [ and the ] are in the AST. 5114 // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc" 5115 // on cfe-dev. 5116 if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling. 5117 S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated); 5118 5119 UuidAttr *UA = S.mergeUuidAttr(D, AL.getRange(), 5120 AL.getAttributeSpellingListIndex(), StrRef); 5121 if (UA) 5122 D->addAttr(UA); 5123 } 5124 5125 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &AL) { 5126 if (!S.LangOpts.CPlusPlus) { 5127 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang) 5128 << AL.getName() << AttributeLangSupport::C; 5129 return; 5130 } 5131 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr( 5132 D, AL.getRange(), /*BestCase=*/true, 5133 AL.getAttributeSpellingListIndex(), 5134 (MSInheritanceAttr::Spelling)AL.getSemanticSpelling()); 5135 if (IA) { 5136 D->addAttr(IA); 5137 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 5138 } 5139 } 5140 5141 static void handleDeclspecThreadAttr(Sema &S, Decl *D, 5142 const AttributeList &AL) { 5143 const auto *VD = cast<VarDecl>(D); 5144 if (!S.Context.getTargetInfo().isTLSSupported()) { 5145 S.Diag(AL.getLoc(), diag::err_thread_unsupported); 5146 return; 5147 } 5148 if (VD->getTSCSpec() != TSCS_unspecified) { 5149 S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable); 5150 return; 5151 } 5152 if (VD->hasLocalStorage()) { 5153 S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)"; 5154 return; 5155 } 5156 D->addAttr(::new (S.Context) ThreadAttr(AL.getRange(), S.Context, 5157 AL.getAttributeSpellingListIndex())); 5158 } 5159 5160 static void handleAbiTagAttr(Sema &S, Decl *D, const AttributeList &AL) { 5161 SmallVector<StringRef, 4> Tags; 5162 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) { 5163 StringRef Tag; 5164 if (!S.checkStringLiteralArgumentAttr(AL, I, Tag)) 5165 return; 5166 Tags.push_back(Tag); 5167 } 5168 5169 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) { 5170 if (!NS->isInline()) { 5171 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0; 5172 return; 5173 } 5174 if (NS->isAnonymousNamespace()) { 5175 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1; 5176 return; 5177 } 5178 if (AL.getNumArgs() == 0) 5179 Tags.push_back(NS->getName()); 5180 } else if (!checkAttributeAtLeastNumArgs(S, AL, 1)) 5181 return; 5182 5183 // Store tags sorted and without duplicates. 5184 std::sort(Tags.begin(), Tags.end()); 5185 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end()); 5186 5187 D->addAttr(::new (S.Context) 5188 AbiTagAttr(AL.getRange(), S.Context, Tags.data(), Tags.size(), 5189 AL.getAttributeSpellingListIndex())); 5190 } 5191 5192 static void handleARMInterruptAttr(Sema &S, Decl *D, 5193 const AttributeList &AL) { 5194 // Check the attribute arguments. 5195 if (AL.getNumArgs() > 1) { 5196 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) 5197 << AL.getName() << 1; 5198 return; 5199 } 5200 5201 StringRef Str; 5202 SourceLocation ArgLoc; 5203 5204 if (AL.getNumArgs() == 0) 5205 Str = ""; 5206 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) 5207 return; 5208 5209 ARMInterruptAttr::InterruptType Kind; 5210 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { 5211 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) 5212 << AL.getName() << Str << ArgLoc; 5213 return; 5214 } 5215 5216 unsigned Index = AL.getAttributeSpellingListIndex(); 5217 D->addAttr(::new (S.Context) 5218 ARMInterruptAttr(AL.getLoc(), S.Context, Kind, Index)); 5219 } 5220 5221 static void handleMSP430InterruptAttr(Sema &S, Decl *D, 5222 const AttributeList &AL) { 5223 if (!checkAttributeNumArgs(S, AL, 1)) 5224 return; 5225 5226 if (!AL.isArgExpr(0)) { 5227 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) << AL.getName() 5228 << AANT_ArgumentIntegerConstant; 5229 return; 5230 } 5231 5232 // FIXME: Check for decl - it should be void ()(void). 5233 5234 Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0)); 5235 llvm::APSInt NumParams(32); 5236 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) { 5237 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 5238 << AL.getName() << AANT_ArgumentIntegerConstant 5239 << NumParamsExpr->getSourceRange(); 5240 return; 5241 } 5242 5243 unsigned Num = NumParams.getLimitedValue(255); 5244 if ((Num & 1) || Num > 30) { 5245 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 5246 << AL.getName() << (int)NumParams.getSExtValue() 5247 << NumParamsExpr->getSourceRange(); 5248 return; 5249 } 5250 5251 D->addAttr(::new (S.Context) 5252 MSP430InterruptAttr(AL.getLoc(), S.Context, Num, 5253 AL.getAttributeSpellingListIndex())); 5254 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 5255 } 5256 5257 static void handleMipsInterruptAttr(Sema &S, Decl *D, 5258 const AttributeList &AL) { 5259 // Only one optional argument permitted. 5260 if (AL.getNumArgs() > 1) { 5261 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) 5262 << AL.getName() << 1; 5263 return; 5264 } 5265 5266 StringRef Str; 5267 SourceLocation ArgLoc; 5268 5269 if (AL.getNumArgs() == 0) 5270 Str = ""; 5271 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) 5272 return; 5273 5274 // Semantic checks for a function with the 'interrupt' attribute for MIPS: 5275 // a) Must be a function. 5276 // b) Must have no parameters. 5277 // c) Must have the 'void' return type. 5278 // d) Cannot have the 'mips16' attribute, as that instruction set 5279 // lacks the 'eret' instruction. 5280 // e) The attribute itself must either have no argument or one of the 5281 // valid interrupt types, see [MipsInterruptDocs]. 5282 5283 if (!isFunctionOrMethod(D)) { 5284 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 5285 << "'interrupt'" << ExpectedFunctionOrMethod; 5286 return; 5287 } 5288 5289 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) { 5290 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute) 5291 << 0; 5292 return; 5293 } 5294 5295 if (!getFunctionOrMethodResultType(D)->isVoidType()) { 5296 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute) 5297 << 1; 5298 return; 5299 } 5300 5301 if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL.getRange(), 5302 AL.getName())) 5303 return; 5304 5305 MipsInterruptAttr::InterruptType Kind; 5306 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { 5307 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) 5308 << AL.getName() << "'" + std::string(Str) + "'"; 5309 return; 5310 } 5311 5312 D->addAttr(::new (S.Context) MipsInterruptAttr( 5313 AL.getLoc(), S.Context, Kind, AL.getAttributeSpellingListIndex())); 5314 } 5315 5316 static void handleAnyX86InterruptAttr(Sema &S, Decl *D, 5317 const AttributeList &AL) { 5318 // Semantic checks for a function with the 'interrupt' attribute. 5319 // a) Must be a function. 5320 // b) Must have the 'void' return type. 5321 // c) Must take 1 or 2 arguments. 5322 // d) The 1st argument must be a pointer. 5323 // e) The 2nd argument (if any) must be an unsigned integer. 5324 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) || 5325 CXXMethodDecl::isStaticOverloadedOperator( 5326 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) { 5327 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 5328 << AL.getName() << ExpectedFunctionWithProtoType; 5329 return; 5330 } 5331 // Interrupt handler must have void return type. 5332 if (!getFunctionOrMethodResultType(D)->isVoidType()) { 5333 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(), 5334 diag::err_anyx86_interrupt_attribute) 5335 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 5336 ? 0 5337 : 1) 5338 << 0; 5339 return; 5340 } 5341 // Interrupt handler must have 1 or 2 parameters. 5342 unsigned NumParams = getFunctionOrMethodNumParams(D); 5343 if (NumParams < 1 || NumParams > 2) { 5344 S.Diag(D->getLocStart(), diag::err_anyx86_interrupt_attribute) 5345 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 5346 ? 0 5347 : 1) 5348 << 1; 5349 return; 5350 } 5351 // The first argument must be a pointer. 5352 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) { 5353 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(), 5354 diag::err_anyx86_interrupt_attribute) 5355 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 5356 ? 0 5357 : 1) 5358 << 2; 5359 return; 5360 } 5361 // The second argument, if present, must be an unsigned integer. 5362 unsigned TypeSize = 5363 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64 5364 ? 64 5365 : 32; 5366 if (NumParams == 2 && 5367 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() || 5368 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) { 5369 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(), 5370 diag::err_anyx86_interrupt_attribute) 5371 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 5372 ? 0 5373 : 1) 5374 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false); 5375 return; 5376 } 5377 D->addAttr(::new (S.Context) AnyX86InterruptAttr( 5378 AL.getLoc(), S.Context, AL.getAttributeSpellingListIndex())); 5379 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 5380 } 5381 5382 static void handleAVRInterruptAttr(Sema &S, Decl *D, const AttributeList &AL) { 5383 if (!isFunctionOrMethod(D)) { 5384 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 5385 << "'interrupt'" << ExpectedFunction; 5386 return; 5387 } 5388 5389 if (!checkAttributeNumArgs(S, AL, 0)) 5390 return; 5391 5392 handleSimpleAttribute<AVRInterruptAttr>(S, D, AL); 5393 } 5394 5395 static void handleAVRSignalAttr(Sema &S, Decl *D, const AttributeList &AL) { 5396 if (!isFunctionOrMethod(D)) { 5397 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 5398 << "'signal'" << ExpectedFunction; 5399 return; 5400 } 5401 5402 if (!checkAttributeNumArgs(S, AL, 0)) 5403 return; 5404 5405 handleSimpleAttribute<AVRSignalAttr>(S, D, AL); 5406 } 5407 5408 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &AL) { 5409 // Dispatch the interrupt attribute based on the current target. 5410 switch (S.Context.getTargetInfo().getTriple().getArch()) { 5411 case llvm::Triple::msp430: 5412 handleMSP430InterruptAttr(S, D, AL); 5413 break; 5414 case llvm::Triple::mipsel: 5415 case llvm::Triple::mips: 5416 handleMipsInterruptAttr(S, D, AL); 5417 break; 5418 case llvm::Triple::x86: 5419 case llvm::Triple::x86_64: 5420 handleAnyX86InterruptAttr(S, D, AL); 5421 break; 5422 case llvm::Triple::avr: 5423 handleAVRInterruptAttr(S, D, AL); 5424 break; 5425 default: 5426 handleARMInterruptAttr(S, D, AL); 5427 break; 5428 } 5429 } 5430 5431 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D, 5432 const AttributeList &AL) { 5433 uint32_t Min = 0; 5434 Expr *MinExpr = AL.getArgAsExpr(0); 5435 if (!checkUInt32Argument(S, AL, MinExpr, Min)) 5436 return; 5437 5438 uint32_t Max = 0; 5439 Expr *MaxExpr = AL.getArgAsExpr(1); 5440 if (!checkUInt32Argument(S, AL, MaxExpr, Max)) 5441 return; 5442 5443 if (Min == 0 && Max != 0) { 5444 S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid) 5445 << AL.getName() << 0; 5446 return; 5447 } 5448 if (Min > Max) { 5449 S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid) 5450 << AL.getName() << 1; 5451 return; 5452 } 5453 5454 D->addAttr(::new (S.Context) 5455 AMDGPUFlatWorkGroupSizeAttr(AL.getLoc(), S.Context, Min, Max, 5456 AL.getAttributeSpellingListIndex())); 5457 } 5458 5459 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, 5460 const AttributeList &AL) { 5461 uint32_t Min = 0; 5462 Expr *MinExpr = AL.getArgAsExpr(0); 5463 if (!checkUInt32Argument(S, AL, MinExpr, Min)) 5464 return; 5465 5466 uint32_t Max = 0; 5467 if (AL.getNumArgs() == 2) { 5468 Expr *MaxExpr = AL.getArgAsExpr(1); 5469 if (!checkUInt32Argument(S, AL, MaxExpr, Max)) 5470 return; 5471 } 5472 5473 if (Min == 0 && Max != 0) { 5474 S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid) 5475 << AL.getName() << 0; 5476 return; 5477 } 5478 if (Max != 0 && Min > Max) { 5479 S.Diag(AL.getLoc(), diag::err_attribute_argument_invalid) 5480 << AL.getName() << 1; 5481 return; 5482 } 5483 5484 D->addAttr(::new (S.Context) 5485 AMDGPUWavesPerEUAttr(AL.getLoc(), S.Context, Min, Max, 5486 AL.getAttributeSpellingListIndex())); 5487 } 5488 5489 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, 5490 const AttributeList &AL) { 5491 uint32_t NumSGPR = 0; 5492 Expr *NumSGPRExpr = AL.getArgAsExpr(0); 5493 if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR)) 5494 return; 5495 5496 D->addAttr(::new (S.Context) 5497 AMDGPUNumSGPRAttr(AL.getLoc(), S.Context, NumSGPR, 5498 AL.getAttributeSpellingListIndex())); 5499 } 5500 5501 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, 5502 const AttributeList &AL) { 5503 uint32_t NumVGPR = 0; 5504 Expr *NumVGPRExpr = AL.getArgAsExpr(0); 5505 if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR)) 5506 return; 5507 5508 D->addAttr(::new (S.Context) 5509 AMDGPUNumVGPRAttr(AL.getLoc(), S.Context, NumVGPR, 5510 AL.getAttributeSpellingListIndex())); 5511 } 5512 5513 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D, 5514 const AttributeList& AL) { 5515 // If we try to apply it to a function pointer, don't warn, but don't 5516 // do anything, either. It doesn't matter anyway, because there's nothing 5517 // special about calling a force_align_arg_pointer function. 5518 const auto *VD = dyn_cast<ValueDecl>(D); 5519 if (VD && VD->getType()->isFunctionPointerType()) 5520 return; 5521 // Also don't warn on function pointer typedefs. 5522 const auto *TD = dyn_cast<TypedefNameDecl>(D); 5523 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() || 5524 TD->getUnderlyingType()->isFunctionType())) 5525 return; 5526 // Attribute can only be applied to function types. 5527 if (!isa<FunctionDecl>(D)) { 5528 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 5529 << AL.getName() << ExpectedFunction; 5530 return; 5531 } 5532 5533 D->addAttr(::new (S.Context) 5534 X86ForceAlignArgPointerAttr(AL.getRange(), S.Context, 5535 AL.getAttributeSpellingListIndex())); 5536 } 5537 5538 static void handleLayoutVersion(Sema &S, Decl *D, const AttributeList &AL) { 5539 uint32_t Version; 5540 Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(0)); 5541 if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version)) 5542 return; 5543 5544 // TODO: Investigate what happens with the next major version of MSVC. 5545 if (Version != LangOptions::MSVC2015) { 5546 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 5547 << AL.getName() << Version << VersionExpr->getSourceRange(); 5548 return; 5549 } 5550 5551 D->addAttr(::new (S.Context) 5552 LayoutVersionAttr(AL.getRange(), S.Context, Version, 5553 AL.getAttributeSpellingListIndex())); 5554 } 5555 5556 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range, 5557 unsigned AttrSpellingListIndex) { 5558 if (D->hasAttr<DLLExportAttr>()) { 5559 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'"; 5560 return nullptr; 5561 } 5562 5563 if (D->hasAttr<DLLImportAttr>()) 5564 return nullptr; 5565 5566 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex); 5567 } 5568 5569 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range, 5570 unsigned AttrSpellingListIndex) { 5571 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) { 5572 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import; 5573 D->dropAttr<DLLImportAttr>(); 5574 } 5575 5576 if (D->hasAttr<DLLExportAttr>()) 5577 return nullptr; 5578 5579 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex); 5580 } 5581 5582 static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) { 5583 if (isa<ClassTemplatePartialSpecializationDecl>(D) && 5584 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5585 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) 5586 << A.getName(); 5587 return; 5588 } 5589 5590 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 5591 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport && 5592 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5593 // MinGW doesn't allow dllimport on inline functions. 5594 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline) 5595 << A.getName(); 5596 return; 5597 } 5598 } 5599 5600 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) { 5601 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && 5602 MD->getParent()->isLambda()) { 5603 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName(); 5604 return; 5605 } 5606 } 5607 5608 unsigned Index = A.getAttributeSpellingListIndex(); 5609 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport 5610 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index) 5611 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index); 5612 if (NewAttr) 5613 D->addAttr(NewAttr); 5614 } 5615 5616 MSInheritanceAttr * 5617 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase, 5618 unsigned AttrSpellingListIndex, 5619 MSInheritanceAttr::Spelling SemanticSpelling) { 5620 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) { 5621 if (IA->getSemanticSpelling() == SemanticSpelling) 5622 return nullptr; 5623 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance) 5624 << 1 /*previous declaration*/; 5625 Diag(Range.getBegin(), diag::note_previous_ms_inheritance); 5626 D->dropAttr<MSInheritanceAttr>(); 5627 } 5628 5629 auto *RD = cast<CXXRecordDecl>(D); 5630 if (RD->hasDefinition()) { 5631 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase, 5632 SemanticSpelling)) { 5633 return nullptr; 5634 } 5635 } else { 5636 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) { 5637 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance) 5638 << 1 /*partial specialization*/; 5639 return nullptr; 5640 } 5641 if (RD->getDescribedClassTemplate()) { 5642 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance) 5643 << 0 /*primary template*/; 5644 return nullptr; 5645 } 5646 } 5647 5648 return ::new (Context) 5649 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex); 5650 } 5651 5652 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &AL) { 5653 // The capability attributes take a single string parameter for the name of 5654 // the capability they represent. The lockable attribute does not take any 5655 // parameters. However, semantically, both attributes represent the same 5656 // concept, and so they use the same semantic attribute. Eventually, the 5657 // lockable attribute will be removed. 5658 // 5659 // For backward compatibility, any capability which has no specified string 5660 // literal will be considered a "mutex." 5661 StringRef N("mutex"); 5662 SourceLocation LiteralLoc; 5663 if (AL.getKind() == AttributeList::AT_Capability && 5664 !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc)) 5665 return; 5666 5667 // Currently, there are only two names allowed for a capability: role and 5668 // mutex (case insensitive). Diagnose other capability names. 5669 if (!N.equals_lower("mutex") && !N.equals_lower("role")) 5670 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N; 5671 5672 D->addAttr(::new (S.Context) CapabilityAttr(AL.getRange(), S.Context, N, 5673 AL.getAttributeSpellingListIndex())); 5674 } 5675 5676 static void handleAssertCapabilityAttr(Sema &S, Decl *D, 5677 const AttributeList &AL) { 5678 SmallVector<Expr*, 1> Args; 5679 if (!checkLockFunAttrCommon(S, D, AL, Args)) 5680 return; 5681 5682 D->addAttr(::new (S.Context) AssertCapabilityAttr(AL.getRange(), S.Context, 5683 Args.data(), Args.size(), 5684 AL.getAttributeSpellingListIndex())); 5685 } 5686 5687 static void handleAcquireCapabilityAttr(Sema &S, Decl *D, 5688 const AttributeList &AL) { 5689 SmallVector<Expr*, 1> Args; 5690 if (!checkLockFunAttrCommon(S, D, AL, Args)) 5691 return; 5692 5693 D->addAttr(::new (S.Context) AcquireCapabilityAttr(AL.getRange(), 5694 S.Context, 5695 Args.data(), Args.size(), 5696 AL.getAttributeSpellingListIndex())); 5697 } 5698 5699 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D, 5700 const AttributeList &AL) { 5701 SmallVector<Expr*, 2> Args; 5702 if (!checkTryLockFunAttrCommon(S, D, AL, Args)) 5703 return; 5704 5705 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(AL.getRange(), 5706 S.Context, 5707 AL.getArgAsExpr(0), 5708 Args.data(), 5709 Args.size(), 5710 AL.getAttributeSpellingListIndex())); 5711 } 5712 5713 static void handleReleaseCapabilityAttr(Sema &S, Decl *D, 5714 const AttributeList &AL) { 5715 // Check that all arguments are lockable objects. 5716 SmallVector<Expr *, 1> Args; 5717 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true); 5718 5719 D->addAttr(::new (S.Context) ReleaseCapabilityAttr( 5720 AL.getRange(), S.Context, Args.data(), Args.size(), 5721 AL.getAttributeSpellingListIndex())); 5722 } 5723 5724 static void handleRequiresCapabilityAttr(Sema &S, Decl *D, 5725 const AttributeList &AL) { 5726 if (!checkAttributeAtLeastNumArgs(S, AL, 1)) 5727 return; 5728 5729 // check that all arguments are lockable objects 5730 SmallVector<Expr*, 1> Args; 5731 checkAttrArgsAreCapabilityObjs(S, D, AL, Args); 5732 if (Args.empty()) 5733 return; 5734 5735 RequiresCapabilityAttr *RCA = ::new (S.Context) 5736 RequiresCapabilityAttr(AL.getRange(), S.Context, Args.data(), 5737 Args.size(), AL.getAttributeSpellingListIndex()); 5738 5739 D->addAttr(RCA); 5740 } 5741 5742 static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &AL) { 5743 if (const auto *NSD = dyn_cast<NamespaceDecl>(D)) { 5744 if (NSD->isAnonymousNamespace()) { 5745 S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace); 5746 // Do not want to attach the attribute to the namespace because that will 5747 // cause confusing diagnostic reports for uses of declarations within the 5748 // namespace. 5749 return; 5750 } 5751 } 5752 5753 // Handle the cases where the attribute has a text message. 5754 StringRef Str, Replacement; 5755 if (AL.isArgExpr(0) && AL.getArgAsExpr(0) && 5756 !S.checkStringLiteralArgumentAttr(AL, 0, Str)) 5757 return; 5758 5759 // Only support a single optional message for Declspec and CXX11. 5760 if (AL.isDeclspecAttribute() || AL.isCXX11Attribute()) 5761 checkAttributeAtMostNumArgs(S, AL, 1); 5762 else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) && 5763 !S.checkStringLiteralArgumentAttr(AL, 1, Replacement)) 5764 return; 5765 5766 if (!S.getLangOpts().CPlusPlus14) 5767 if (AL.isCXX11Attribute() && 5768 !(AL.hasScope() && AL.getScopeName()->isStr("gnu"))) 5769 S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL.getName(); 5770 5771 D->addAttr(::new (S.Context) 5772 DeprecatedAttr(AL.getRange(), S.Context, Str, Replacement, 5773 AL.getAttributeSpellingListIndex())); 5774 } 5775 5776 static bool isGlobalVar(const Decl *D) { 5777 if (const auto *S = dyn_cast<VarDecl>(D)) 5778 return S->hasGlobalStorage(); 5779 return false; 5780 } 5781 5782 static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &AL) { 5783 if (!checkAttributeAtLeastNumArgs(S, AL, 1)) 5784 return; 5785 5786 std::vector<StringRef> Sanitizers; 5787 5788 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) { 5789 StringRef SanitizerName; 5790 SourceLocation LiteralLoc; 5791 5792 if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc)) 5793 return; 5794 5795 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0) 5796 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName; 5797 else if (isGlobalVar(D) && SanitizerName != "address") 5798 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 5799 << AL.getName() << ExpectedFunctionOrMethod; 5800 Sanitizers.push_back(SanitizerName); 5801 } 5802 5803 D->addAttr(::new (S.Context) NoSanitizeAttr( 5804 AL.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(), 5805 AL.getAttributeSpellingListIndex())); 5806 } 5807 5808 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D, 5809 const AttributeList &AL) { 5810 StringRef AttrName = AL.getName()->getName(); 5811 normalizeName(AttrName); 5812 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName) 5813 .Case("no_address_safety_analysis", "address") 5814 .Case("no_sanitize_address", "address") 5815 .Case("no_sanitize_thread", "thread") 5816 .Case("no_sanitize_memory", "memory"); 5817 if (isGlobalVar(D) && SanitizerName != "address") 5818 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 5819 << AL.getName() << ExpectedFunction; 5820 D->addAttr(::new (S.Context) 5821 NoSanitizeAttr(AL.getRange(), S.Context, &SanitizerName, 1, 5822 AL.getAttributeSpellingListIndex())); 5823 } 5824 5825 static void handleInternalLinkageAttr(Sema &S, Decl *D, 5826 const AttributeList &AL) { 5827 if (InternalLinkageAttr *Internal = 5828 S.mergeInternalLinkageAttr(D, AL.getRange(), AL.getName(), 5829 AL.getAttributeSpellingListIndex())) 5830 D->addAttr(Internal); 5831 } 5832 5833 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const AttributeList &AL) { 5834 if (S.LangOpts.OpenCLVersion != 200) 5835 S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version) 5836 << AL.getName() << "2.0" << 0; 5837 else 5838 S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored) 5839 << AL.getName() << "2.0"; 5840 } 5841 5842 /// Handles semantic checking for features that are common to all attributes, 5843 /// such as checking whether a parameter was properly specified, or the correct 5844 /// number of arguments were passed, etc. 5845 static bool handleCommonAttributeFeatures(Sema &S, Decl *D, 5846 const AttributeList &AL) { 5847 // Several attributes carry different semantics than the parsing requires, so 5848 // those are opted out of the common argument checks. 5849 // 5850 // We also bail on unknown and ignored attributes because those are handled 5851 // as part of the target-specific handling logic. 5852 if (AL.getKind() == AttributeList::UnknownAttribute) 5853 return false; 5854 // Check whether the attribute requires specific language extensions to be 5855 // enabled. 5856 if (!AL.diagnoseLangOpts(S)) 5857 return true; 5858 // Check whether the attribute appertains to the given subject. 5859 if (!AL.diagnoseAppertainsTo(S, D)) 5860 return true; 5861 if (AL.hasCustomParsing()) 5862 return false; 5863 5864 if (AL.getMinArgs() == AL.getMaxArgs()) { 5865 // If there are no optional arguments, then checking for the argument count 5866 // is trivial. 5867 if (!checkAttributeNumArgs(S, AL, AL.getMinArgs())) 5868 return true; 5869 } else { 5870 // There are optional arguments, so checking is slightly more involved. 5871 if (AL.getMinArgs() && 5872 !checkAttributeAtLeastNumArgs(S, AL, AL.getMinArgs())) 5873 return true; 5874 else if (!AL.hasVariadicArg() && AL.getMaxArgs() && 5875 !checkAttributeAtMostNumArgs(S, AL, AL.getMaxArgs())) 5876 return true; 5877 } 5878 5879 return false; 5880 } 5881 5882 static void handleOpenCLAccessAttr(Sema &S, Decl *D, 5883 const AttributeList &AL) { 5884 if (D->isInvalidDecl()) 5885 return; 5886 5887 // Check if there is only one access qualifier. 5888 if (D->hasAttr<OpenCLAccessAttr>()) { 5889 S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers) 5890 << D->getSourceRange(); 5891 D->setInvalidDecl(true); 5892 return; 5893 } 5894 5895 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an 5896 // image object can be read and written. 5897 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe 5898 // object. Using the read_write (or __read_write) qualifier with the pipe 5899 // qualifier is a compilation error. 5900 if (const auto *PDecl = dyn_cast<ParmVarDecl>(D)) { 5901 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr(); 5902 if (AL.getName()->getName().find("read_write") != StringRef::npos) { 5903 if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) { 5904 S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write) 5905 << AL.getName() << PDecl->getType() << DeclTy->isImageType(); 5906 D->setInvalidDecl(true); 5907 return; 5908 } 5909 } 5910 } 5911 5912 D->addAttr(::new (S.Context) OpenCLAccessAttr( 5913 AL.getRange(), S.Context, AL.getAttributeSpellingListIndex())); 5914 } 5915 5916 //===----------------------------------------------------------------------===// 5917 // Top Level Sema Entry Points 5918 //===----------------------------------------------------------------------===// 5919 5920 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if 5921 /// the attribute applies to decls. If the attribute is a type attribute, just 5922 /// silently ignore it if a GNU attribute. 5923 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, 5924 const AttributeList &AL, 5925 bool IncludeCXX11Attributes) { 5926 if (AL.isInvalid() || AL.getKind() == AttributeList::IgnoredAttribute) 5927 return; 5928 5929 // Ignore C++11 attributes on declarator chunks: they appertain to the type 5930 // instead. 5931 if (AL.isCXX11Attribute() && !IncludeCXX11Attributes) 5932 return; 5933 5934 // Unknown attributes are automatically warned on. Target-specific attributes 5935 // which do not apply to the current target architecture are treated as 5936 // though they were unknown attributes. 5937 if (AL.getKind() == AttributeList::UnknownAttribute || 5938 !AL.existsInTarget(S.Context.getTargetInfo())) { 5939 S.Diag(AL.getLoc(), AL.isDeclspecAttribute() 5940 ? diag::warn_unhandled_ms_attribute_ignored 5941 : diag::warn_unknown_attribute_ignored) 5942 << AL.getName(); 5943 return; 5944 } 5945 5946 if (handleCommonAttributeFeatures(S, D, AL)) 5947 return; 5948 5949 switch (AL.getKind()) { 5950 default: 5951 if (!AL.isStmtAttr()) { 5952 // Type attributes are handled elsewhere; silently move on. 5953 assert(AL.isTypeAttr() && "Non-type attribute not handled"); 5954 break; 5955 } 5956 S.Diag(AL.getLoc(), diag::err_stmt_attribute_invalid_on_decl) 5957 << AL.getName() << D->getLocation(); 5958 break; 5959 case AttributeList::AT_Interrupt: 5960 handleInterruptAttr(S, D, AL); 5961 break; 5962 case AttributeList::AT_X86ForceAlignArgPointer: 5963 handleX86ForceAlignArgPointerAttr(S, D, AL); 5964 break; 5965 case AttributeList::AT_DLLExport: 5966 case AttributeList::AT_DLLImport: 5967 handleDLLAttr(S, D, AL); 5968 break; 5969 case AttributeList::AT_Mips16: 5970 handleSimpleAttributeWithExclusions<Mips16Attr, MicroMipsAttr, 5971 MipsInterruptAttr>(S, D, AL); 5972 break; 5973 case AttributeList::AT_NoMips16: 5974 handleSimpleAttribute<NoMips16Attr>(S, D, AL); 5975 break; 5976 case AttributeList::AT_MicroMips: 5977 handleSimpleAttributeWithExclusions<MicroMipsAttr, Mips16Attr>(S, D, AL); 5978 break; 5979 case AttributeList::AT_NoMicroMips: 5980 handleSimpleAttribute<NoMicroMipsAttr>(S, D, AL); 5981 break; 5982 case AttributeList::AT_MipsLongCall: 5983 handleSimpleAttributeWithExclusions<MipsLongCallAttr, MipsShortCallAttr>( 5984 S, D, AL); 5985 break; 5986 case AttributeList::AT_MipsShortCall: 5987 handleSimpleAttributeWithExclusions<MipsShortCallAttr, MipsLongCallAttr>( 5988 S, D, AL); 5989 break; 5990 case AttributeList::AT_AMDGPUFlatWorkGroupSize: 5991 handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL); 5992 break; 5993 case AttributeList::AT_AMDGPUWavesPerEU: 5994 handleAMDGPUWavesPerEUAttr(S, D, AL); 5995 break; 5996 case AttributeList::AT_AMDGPUNumSGPR: 5997 handleAMDGPUNumSGPRAttr(S, D, AL); 5998 break; 5999 case AttributeList::AT_AMDGPUNumVGPR: 6000 handleAMDGPUNumVGPRAttr(S, D, AL); 6001 break; 6002 case AttributeList::AT_AVRSignal: 6003 handleAVRSignalAttr(S, D, AL); 6004 break; 6005 case AttributeList::AT_IBAction: 6006 handleSimpleAttribute<IBActionAttr>(S, D, AL); 6007 break; 6008 case AttributeList::AT_IBOutlet: 6009 handleIBOutlet(S, D, AL); 6010 break; 6011 case AttributeList::AT_IBOutletCollection: 6012 handleIBOutletCollection(S, D, AL); 6013 break; 6014 case AttributeList::AT_IFunc: 6015 handleIFuncAttr(S, D, AL); 6016 break; 6017 case AttributeList::AT_Alias: 6018 handleAliasAttr(S, D, AL); 6019 break; 6020 case AttributeList::AT_Aligned: 6021 handleAlignedAttr(S, D, AL); 6022 break; 6023 case AttributeList::AT_AlignValue: 6024 handleAlignValueAttr(S, D, AL); 6025 break; 6026 case AttributeList::AT_AllocSize: 6027 handleAllocSizeAttr(S, D, AL); 6028 break; 6029 case AttributeList::AT_AlwaysInline: 6030 handleAlwaysInlineAttr(S, D, AL); 6031 break; 6032 case AttributeList::AT_Artificial: 6033 handleSimpleAttribute<ArtificialAttr>(S, D, AL); 6034 break; 6035 case AttributeList::AT_AnalyzerNoReturn: 6036 handleAnalyzerNoReturnAttr(S, D, AL); 6037 break; 6038 case AttributeList::AT_TLSModel: 6039 handleTLSModelAttr(S, D, AL); 6040 break; 6041 case AttributeList::AT_Annotate: 6042 handleAnnotateAttr(S, D, AL); 6043 break; 6044 case AttributeList::AT_Availability: 6045 handleAvailabilityAttr(S, D, AL); 6046 break; 6047 case AttributeList::AT_CarriesDependency: 6048 handleDependencyAttr(S, scope, D, AL); 6049 break; 6050 case AttributeList::AT_Common: 6051 handleCommonAttr(S, D, AL); 6052 break; 6053 case AttributeList::AT_CUDAConstant: 6054 handleConstantAttr(S, D, AL); 6055 break; 6056 case AttributeList::AT_PassObjectSize: 6057 handlePassObjectSizeAttr(S, D, AL); 6058 break; 6059 case AttributeList::AT_Constructor: 6060 handleConstructorAttr(S, D, AL); 6061 break; 6062 case AttributeList::AT_CXX11NoReturn: 6063 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, AL); 6064 break; 6065 case AttributeList::AT_Deprecated: 6066 handleDeprecatedAttr(S, D, AL); 6067 break; 6068 case AttributeList::AT_Destructor: 6069 handleDestructorAttr(S, D, AL); 6070 break; 6071 case AttributeList::AT_EnableIf: 6072 handleEnableIfAttr(S, D, AL); 6073 break; 6074 case AttributeList::AT_DiagnoseIf: 6075 handleDiagnoseIfAttr(S, D, AL); 6076 break; 6077 case AttributeList::AT_ExtVectorType: 6078 handleExtVectorTypeAttr(S, D, AL); 6079 break; 6080 case AttributeList::AT_ExternalSourceSymbol: 6081 handleExternalSourceSymbolAttr(S, D, AL); 6082 break; 6083 case AttributeList::AT_MinSize: 6084 handleMinSizeAttr(S, D, AL); 6085 break; 6086 case AttributeList::AT_OptimizeNone: 6087 handleOptimizeNoneAttr(S, D, AL); 6088 break; 6089 case AttributeList::AT_FlagEnum: 6090 handleSimpleAttribute<FlagEnumAttr>(S, D, AL); 6091 break; 6092 case AttributeList::AT_EnumExtensibility: 6093 handleEnumExtensibilityAttr(S, D, AL); 6094 break; 6095 case AttributeList::AT_Flatten: 6096 handleSimpleAttribute<FlattenAttr>(S, D, AL); 6097 break; 6098 case AttributeList::AT_Format: 6099 handleFormatAttr(S, D, AL); 6100 break; 6101 case AttributeList::AT_FormatArg: 6102 handleFormatArgAttr(S, D, AL); 6103 break; 6104 case AttributeList::AT_CUDAGlobal: 6105 handleGlobalAttr(S, D, AL); 6106 break; 6107 case AttributeList::AT_CUDADevice: 6108 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D, 6109 AL); 6110 break; 6111 case AttributeList::AT_CUDAHost: 6112 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D, 6113 AL); 6114 break; 6115 case AttributeList::AT_GNUInline: 6116 handleGNUInlineAttr(S, D, AL); 6117 break; 6118 case AttributeList::AT_CUDALaunchBounds: 6119 handleLaunchBoundsAttr(S, D, AL); 6120 break; 6121 case AttributeList::AT_Restrict: 6122 handleRestrictAttr(S, D, AL); 6123 break; 6124 case AttributeList::AT_MayAlias: 6125 handleSimpleAttribute<MayAliasAttr>(S, D, AL); 6126 break; 6127 case AttributeList::AT_Mode: 6128 handleModeAttr(S, D, AL); 6129 break; 6130 case AttributeList::AT_NoAlias: 6131 handleSimpleAttribute<NoAliasAttr>(S, D, AL); 6132 break; 6133 case AttributeList::AT_NoCommon: 6134 handleSimpleAttribute<NoCommonAttr>(S, D, AL); 6135 break; 6136 case AttributeList::AT_NoSplitStack: 6137 handleSimpleAttribute<NoSplitStackAttr>(S, D, AL); 6138 break; 6139 case AttributeList::AT_NonNull: 6140 if (auto *PVD = dyn_cast<ParmVarDecl>(D)) 6141 handleNonNullAttrParameter(S, PVD, AL); 6142 else 6143 handleNonNullAttr(S, D, AL); 6144 break; 6145 case AttributeList::AT_ReturnsNonNull: 6146 handleReturnsNonNullAttr(S, D, AL); 6147 break; 6148 case AttributeList::AT_NoEscape: 6149 handleNoEscapeAttr(S, D, AL); 6150 break; 6151 case AttributeList::AT_AssumeAligned: 6152 handleAssumeAlignedAttr(S, D, AL); 6153 break; 6154 case AttributeList::AT_AllocAlign: 6155 handleAllocAlignAttr(S, D, AL); 6156 break; 6157 case AttributeList::AT_Overloadable: 6158 handleSimpleAttribute<OverloadableAttr>(S, D, AL); 6159 break; 6160 case AttributeList::AT_Ownership: 6161 handleOwnershipAttr(S, D, AL); 6162 break; 6163 case AttributeList::AT_Cold: 6164 handleColdAttr(S, D, AL); 6165 break; 6166 case AttributeList::AT_Hot: 6167 handleHotAttr(S, D, AL); 6168 break; 6169 case AttributeList::AT_Naked: 6170 handleNakedAttr(S, D, AL); 6171 break; 6172 case AttributeList::AT_NoReturn: 6173 handleNoReturnAttr(S, D, AL); 6174 break; 6175 case AttributeList::AT_NoThrow: 6176 handleSimpleAttribute<NoThrowAttr>(S, D, AL); 6177 break; 6178 case AttributeList::AT_CUDAShared: 6179 handleSharedAttr(S, D, AL); 6180 break; 6181 case AttributeList::AT_VecReturn: 6182 handleVecReturnAttr(S, D, AL); 6183 break; 6184 case AttributeList::AT_ObjCOwnership: 6185 handleObjCOwnershipAttr(S, D, AL); 6186 break; 6187 case AttributeList::AT_ObjCPreciseLifetime: 6188 handleObjCPreciseLifetimeAttr(S, D, AL); 6189 break; 6190 case AttributeList::AT_ObjCReturnsInnerPointer: 6191 handleObjCReturnsInnerPointerAttr(S, D, AL); 6192 break; 6193 case AttributeList::AT_ObjCRequiresSuper: 6194 handleObjCRequiresSuperAttr(S, D, AL); 6195 break; 6196 case AttributeList::AT_ObjCBridge: 6197 handleObjCBridgeAttr(S, D, AL); 6198 break; 6199 case AttributeList::AT_ObjCBridgeMutable: 6200 handleObjCBridgeMutableAttr(S, D, AL); 6201 break; 6202 case AttributeList::AT_ObjCBridgeRelated: 6203 handleObjCBridgeRelatedAttr(S, D, AL); 6204 break; 6205 case AttributeList::AT_ObjCDesignatedInitializer: 6206 handleObjCDesignatedInitializer(S, D, AL); 6207 break; 6208 case AttributeList::AT_ObjCRuntimeName: 6209 handleObjCRuntimeName(S, D, AL); 6210 break; 6211 case AttributeList::AT_ObjCRuntimeVisible: 6212 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, AL); 6213 break; 6214 case AttributeList::AT_ObjCBoxable: 6215 handleObjCBoxable(S, D, AL); 6216 break; 6217 case AttributeList::AT_CFAuditedTransfer: 6218 handleCFAuditedTransferAttr(S, D, AL); 6219 break; 6220 case AttributeList::AT_CFUnknownTransfer: 6221 handleCFUnknownTransferAttr(S, D, AL); 6222 break; 6223 case AttributeList::AT_CFConsumed: 6224 case AttributeList::AT_NSConsumed: 6225 handleNSConsumedAttr(S, D, AL); 6226 break; 6227 case AttributeList::AT_NSConsumesSelf: 6228 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, AL); 6229 break; 6230 case AttributeList::AT_NSReturnsAutoreleased: 6231 case AttributeList::AT_NSReturnsNotRetained: 6232 case AttributeList::AT_CFReturnsNotRetained: 6233 case AttributeList::AT_NSReturnsRetained: 6234 case AttributeList::AT_CFReturnsRetained: 6235 handleNSReturnsRetainedAttr(S, D, AL); 6236 break; 6237 case AttributeList::AT_WorkGroupSizeHint: 6238 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL); 6239 break; 6240 case AttributeList::AT_ReqdWorkGroupSize: 6241 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL); 6242 break; 6243 case AttributeList::AT_OpenCLIntelReqdSubGroupSize: 6244 handleSubGroupSize(S, D, AL); 6245 break; 6246 case AttributeList::AT_VecTypeHint: 6247 handleVecTypeHint(S, D, AL); 6248 break; 6249 case AttributeList::AT_RequireConstantInit: 6250 handleSimpleAttribute<RequireConstantInitAttr>(S, D, AL); 6251 break; 6252 case AttributeList::AT_InitPriority: 6253 handleInitPriorityAttr(S, D, AL); 6254 break; 6255 case AttributeList::AT_Packed: 6256 handlePackedAttr(S, D, AL); 6257 break; 6258 case AttributeList::AT_Section: 6259 handleSectionAttr(S, D, AL); 6260 break; 6261 case AttributeList::AT_Target: 6262 handleTargetAttr(S, D, AL); 6263 break; 6264 case AttributeList::AT_Unavailable: 6265 handleAttrWithMessage<UnavailableAttr>(S, D, AL); 6266 break; 6267 case AttributeList::AT_ArcWeakrefUnavailable: 6268 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, AL); 6269 break; 6270 case AttributeList::AT_ObjCRootClass: 6271 handleSimpleAttribute<ObjCRootClassAttr>(S, D, AL); 6272 break; 6273 case AttributeList::AT_ObjCSubclassingRestricted: 6274 handleSimpleAttribute<ObjCSubclassingRestrictedAttr>(S, D, AL); 6275 break; 6276 case AttributeList::AT_ObjCExplicitProtocolImpl: 6277 handleObjCSuppresProtocolAttr(S, D, AL); 6278 break; 6279 case AttributeList::AT_ObjCRequiresPropertyDefs: 6280 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, AL); 6281 break; 6282 case AttributeList::AT_Unused: 6283 handleUnusedAttr(S, D, AL); 6284 break; 6285 case AttributeList::AT_ReturnsTwice: 6286 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, AL); 6287 break; 6288 case AttributeList::AT_NotTailCalled: 6289 handleNotTailCalledAttr(S, D, AL); 6290 break; 6291 case AttributeList::AT_DisableTailCalls: 6292 handleDisableTailCallsAttr(S, D, AL); 6293 break; 6294 case AttributeList::AT_Used: 6295 handleUsedAttr(S, D, AL); 6296 break; 6297 case AttributeList::AT_Visibility: 6298 handleVisibilityAttr(S, D, AL, false); 6299 break; 6300 case AttributeList::AT_TypeVisibility: 6301 handleVisibilityAttr(S, D, AL, true); 6302 break; 6303 case AttributeList::AT_WarnUnused: 6304 handleSimpleAttribute<WarnUnusedAttr>(S, D, AL); 6305 break; 6306 case AttributeList::AT_WarnUnusedResult: 6307 handleWarnUnusedResult(S, D, AL); 6308 break; 6309 case AttributeList::AT_Weak: 6310 handleSimpleAttribute<WeakAttr>(S, D, AL); 6311 break; 6312 case AttributeList::AT_WeakRef: 6313 handleWeakRefAttr(S, D, AL); 6314 break; 6315 case AttributeList::AT_WeakImport: 6316 handleWeakImportAttr(S, D, AL); 6317 break; 6318 case AttributeList::AT_TransparentUnion: 6319 handleTransparentUnionAttr(S, D, AL); 6320 break; 6321 case AttributeList::AT_ObjCException: 6322 handleSimpleAttribute<ObjCExceptionAttr>(S, D, AL); 6323 break; 6324 case AttributeList::AT_ObjCMethodFamily: 6325 handleObjCMethodFamilyAttr(S, D, AL); 6326 break; 6327 case AttributeList::AT_ObjCNSObject: 6328 handleObjCNSObject(S, D, AL); 6329 break; 6330 case AttributeList::AT_ObjCIndependentClass: 6331 handleObjCIndependentClass(S, D, AL); 6332 break; 6333 case AttributeList::AT_Blocks: 6334 handleBlocksAttr(S, D, AL); 6335 break; 6336 case AttributeList::AT_Sentinel: 6337 handleSentinelAttr(S, D, AL); 6338 break; 6339 case AttributeList::AT_Const: 6340 handleSimpleAttribute<ConstAttr>(S, D, AL); 6341 break; 6342 case AttributeList::AT_Pure: 6343 handleSimpleAttribute<PureAttr>(S, D, AL); 6344 break; 6345 case AttributeList::AT_Cleanup: 6346 handleCleanupAttr(S, D, AL); 6347 break; 6348 case AttributeList::AT_NoDebug: 6349 handleNoDebugAttr(S, D, AL); 6350 break; 6351 case AttributeList::AT_NoDuplicate: 6352 handleSimpleAttribute<NoDuplicateAttr>(S, D, AL); 6353 break; 6354 case AttributeList::AT_Convergent: 6355 handleSimpleAttribute<ConvergentAttr>(S, D, AL); 6356 break; 6357 case AttributeList::AT_NoInline: 6358 handleSimpleAttribute<NoInlineAttr>(S, D, AL); 6359 break; 6360 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg. 6361 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, AL); 6362 break; 6363 case AttributeList::AT_StdCall: 6364 case AttributeList::AT_CDecl: 6365 case AttributeList::AT_FastCall: 6366 case AttributeList::AT_ThisCall: 6367 case AttributeList::AT_Pascal: 6368 case AttributeList::AT_RegCall: 6369 case AttributeList::AT_SwiftCall: 6370 case AttributeList::AT_VectorCall: 6371 case AttributeList::AT_MSABI: 6372 case AttributeList::AT_SysVABI: 6373 case AttributeList::AT_Pcs: 6374 case AttributeList::AT_IntelOclBicc: 6375 case AttributeList::AT_PreserveMost: 6376 case AttributeList::AT_PreserveAll: 6377 handleCallConvAttr(S, D, AL); 6378 break; 6379 case AttributeList::AT_Suppress: 6380 handleSuppressAttr(S, D, AL); 6381 break; 6382 case AttributeList::AT_OpenCLKernel: 6383 handleSimpleAttribute<OpenCLKernelAttr>(S, D, AL); 6384 break; 6385 case AttributeList::AT_OpenCLAccess: 6386 handleOpenCLAccessAttr(S, D, AL); 6387 break; 6388 case AttributeList::AT_OpenCLNoSVM: 6389 handleOpenCLNoSVMAttr(S, D, AL); 6390 break; 6391 case AttributeList::AT_SwiftContext: 6392 handleParameterABIAttr(S, D, AL, ParameterABI::SwiftContext); 6393 break; 6394 case AttributeList::AT_SwiftErrorResult: 6395 handleParameterABIAttr(S, D, AL, ParameterABI::SwiftErrorResult); 6396 break; 6397 case AttributeList::AT_SwiftIndirectResult: 6398 handleParameterABIAttr(S, D, AL, ParameterABI::SwiftIndirectResult); 6399 break; 6400 case AttributeList::AT_InternalLinkage: 6401 handleInternalLinkageAttr(S, D, AL); 6402 break; 6403 case AttributeList::AT_LTOVisibilityPublic: 6404 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, AL); 6405 break; 6406 6407 // Microsoft attributes: 6408 case AttributeList::AT_EmptyBases: 6409 handleSimpleAttribute<EmptyBasesAttr>(S, D, AL); 6410 break; 6411 case AttributeList::AT_LayoutVersion: 6412 handleLayoutVersion(S, D, AL); 6413 break; 6414 case AttributeList::AT_TrivialABI: 6415 handleSimpleAttribute<TrivialABIAttr>(S, D, AL); 6416 break; 6417 case AttributeList::AT_MSNoVTable: 6418 handleSimpleAttribute<MSNoVTableAttr>(S, D, AL); 6419 break; 6420 case AttributeList::AT_MSStruct: 6421 handleSimpleAttribute<MSStructAttr>(S, D, AL); 6422 break; 6423 case AttributeList::AT_Uuid: 6424 handleUuidAttr(S, D, AL); 6425 break; 6426 case AttributeList::AT_MSInheritance: 6427 handleMSInheritanceAttr(S, D, AL); 6428 break; 6429 case AttributeList::AT_SelectAny: 6430 handleSimpleAttribute<SelectAnyAttr>(S, D, AL); 6431 break; 6432 case AttributeList::AT_Thread: 6433 handleDeclspecThreadAttr(S, D, AL); 6434 break; 6435 6436 case AttributeList::AT_AbiTag: 6437 handleAbiTagAttr(S, D, AL); 6438 break; 6439 6440 // Thread safety attributes: 6441 case AttributeList::AT_AssertExclusiveLock: 6442 handleAssertExclusiveLockAttr(S, D, AL); 6443 break; 6444 case AttributeList::AT_AssertSharedLock: 6445 handleAssertSharedLockAttr(S, D, AL); 6446 break; 6447 case AttributeList::AT_GuardedVar: 6448 handleSimpleAttribute<GuardedVarAttr>(S, D, AL); 6449 break; 6450 case AttributeList::AT_PtGuardedVar: 6451 handlePtGuardedVarAttr(S, D, AL); 6452 break; 6453 case AttributeList::AT_ScopedLockable: 6454 handleSimpleAttribute<ScopedLockableAttr>(S, D, AL); 6455 break; 6456 case AttributeList::AT_NoSanitize: 6457 handleNoSanitizeAttr(S, D, AL); 6458 break; 6459 case AttributeList::AT_NoSanitizeSpecific: 6460 handleNoSanitizeSpecificAttr(S, D, AL); 6461 break; 6462 case AttributeList::AT_NoThreadSafetyAnalysis: 6463 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, AL); 6464 break; 6465 case AttributeList::AT_GuardedBy: 6466 handleGuardedByAttr(S, D, AL); 6467 break; 6468 case AttributeList::AT_PtGuardedBy: 6469 handlePtGuardedByAttr(S, D, AL); 6470 break; 6471 case AttributeList::AT_ExclusiveTrylockFunction: 6472 handleExclusiveTrylockFunctionAttr(S, D, AL); 6473 break; 6474 case AttributeList::AT_LockReturned: 6475 handleLockReturnedAttr(S, D, AL); 6476 break; 6477 case AttributeList::AT_LocksExcluded: 6478 handleLocksExcludedAttr(S, D, AL); 6479 break; 6480 case AttributeList::AT_SharedTrylockFunction: 6481 handleSharedTrylockFunctionAttr(S, D, AL); 6482 break; 6483 case AttributeList::AT_AcquiredBefore: 6484 handleAcquiredBeforeAttr(S, D, AL); 6485 break; 6486 case AttributeList::AT_AcquiredAfter: 6487 handleAcquiredAfterAttr(S, D, AL); 6488 break; 6489 6490 // Capability analysis attributes. 6491 case AttributeList::AT_Capability: 6492 case AttributeList::AT_Lockable: 6493 handleCapabilityAttr(S, D, AL); 6494 break; 6495 case AttributeList::AT_RequiresCapability: 6496 handleRequiresCapabilityAttr(S, D, AL); 6497 break; 6498 6499 case AttributeList::AT_AssertCapability: 6500 handleAssertCapabilityAttr(S, D, AL); 6501 break; 6502 case AttributeList::AT_AcquireCapability: 6503 handleAcquireCapabilityAttr(S, D, AL); 6504 break; 6505 case AttributeList::AT_ReleaseCapability: 6506 handleReleaseCapabilityAttr(S, D, AL); 6507 break; 6508 case AttributeList::AT_TryAcquireCapability: 6509 handleTryAcquireCapabilityAttr(S, D, AL); 6510 break; 6511 6512 // Consumed analysis attributes. 6513 case AttributeList::AT_Consumable: 6514 handleConsumableAttr(S, D, AL); 6515 break; 6516 case AttributeList::AT_ConsumableAutoCast: 6517 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, AL); 6518 break; 6519 case AttributeList::AT_ConsumableSetOnRead: 6520 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, AL); 6521 break; 6522 case AttributeList::AT_CallableWhen: 6523 handleCallableWhenAttr(S, D, AL); 6524 break; 6525 case AttributeList::AT_ParamTypestate: 6526 handleParamTypestateAttr(S, D, AL); 6527 break; 6528 case AttributeList::AT_ReturnTypestate: 6529 handleReturnTypestateAttr(S, D, AL); 6530 break; 6531 case AttributeList::AT_SetTypestate: 6532 handleSetTypestateAttr(S, D, AL); 6533 break; 6534 case AttributeList::AT_TestTypestate: 6535 handleTestTypestateAttr(S, D, AL); 6536 break; 6537 6538 // Type safety attributes. 6539 case AttributeList::AT_ArgumentWithTypeTag: 6540 handleArgumentWithTypeTagAttr(S, D, AL); 6541 break; 6542 case AttributeList::AT_TypeTagForDatatype: 6543 handleTypeTagForDatatypeAttr(S, D, AL); 6544 break; 6545 case AttributeList::AT_AnyX86NoCallerSavedRegisters: 6546 handleNoCallerSavedRegsAttr(S, D, AL); 6547 break; 6548 case AttributeList::AT_RenderScriptKernel: 6549 handleSimpleAttribute<RenderScriptKernelAttr>(S, D, AL); 6550 break; 6551 // XRay attributes. 6552 case AttributeList::AT_XRayInstrument: 6553 handleSimpleAttribute<XRayInstrumentAttr>(S, D, AL); 6554 break; 6555 case AttributeList::AT_XRayLogArgs: 6556 handleXRayLogArgsAttr(S, D, AL); 6557 break; 6558 } 6559 } 6560 6561 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified 6562 /// attribute list to the specified decl, ignoring any type attributes. 6563 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D, 6564 const AttributeList *AttrList, 6565 bool IncludeCXX11Attributes) { 6566 for (const AttributeList* l = AttrList; l; l = l->getNext()) 6567 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes); 6568 6569 // FIXME: We should be able to handle these cases in TableGen. 6570 // GCC accepts 6571 // static int a9 __attribute__((weakref)); 6572 // but that looks really pointless. We reject it. 6573 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) { 6574 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias) 6575 << cast<NamedDecl>(D); 6576 D->dropAttr<WeakRefAttr>(); 6577 return; 6578 } 6579 6580 // FIXME: We should be able to handle this in TableGen as well. It would be 6581 // good to have a way to specify "these attributes must appear as a group", 6582 // for these. Additionally, it would be good to have a way to specify "these 6583 // attribute must never appear as a group" for attributes like cold and hot. 6584 if (!D->hasAttr<OpenCLKernelAttr>()) { 6585 // These attributes cannot be applied to a non-kernel function. 6586 if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) { 6587 // FIXME: This emits a different error message than 6588 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction. 6589 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 6590 D->setInvalidDecl(); 6591 } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) { 6592 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 6593 D->setInvalidDecl(); 6594 } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) { 6595 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 6596 D->setInvalidDecl(); 6597 } else if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) { 6598 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 6599 << A << ExpectedKernelFunction; 6600 D->setInvalidDecl(); 6601 } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) { 6602 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 6603 << A << ExpectedKernelFunction; 6604 D->setInvalidDecl(); 6605 } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) { 6606 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 6607 << A << ExpectedKernelFunction; 6608 D->setInvalidDecl(); 6609 } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) { 6610 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 6611 << A << ExpectedKernelFunction; 6612 D->setInvalidDecl(); 6613 } else if (const auto *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) { 6614 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 6615 D->setInvalidDecl(); 6616 } 6617 } 6618 } 6619 6620 // Helper for delayed processing TransparentUnion attribute. 6621 void Sema::ProcessDeclAttributeDelayed(Decl *D, const AttributeList *AttrList) { 6622 for (const AttributeList *AL = AttrList; AL; AL = AL->getNext()) 6623 if (AL->getKind() == AttributeList::AT_TransparentUnion) { 6624 handleTransparentUnionAttr(*this, D, *AL); 6625 break; 6626 } 6627 } 6628 6629 // Annotation attributes are the only attributes allowed after an access 6630 // specifier. 6631 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, 6632 const AttributeList *AttrList) { 6633 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 6634 if (l->getKind() == AttributeList::AT_Annotate) { 6635 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute()); 6636 } else { 6637 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec); 6638 return true; 6639 } 6640 } 6641 6642 return false; 6643 } 6644 6645 /// checkUnusedDeclAttributes - Check a list of attributes to see if it 6646 /// contains any decl attributes that we should warn about. 6647 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) { 6648 for ( ; A; A = A->getNext()) { 6649 // Only warn if the attribute is an unignored, non-type attribute. 6650 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue; 6651 if (A->getKind() == AttributeList::IgnoredAttribute) continue; 6652 6653 if (A->getKind() == AttributeList::UnknownAttribute) { 6654 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored) 6655 << A->getName() << A->getRange(); 6656 } else { 6657 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl) 6658 << A->getName() << A->getRange(); 6659 } 6660 } 6661 } 6662 6663 /// checkUnusedDeclAttributes - Given a declarator which is not being 6664 /// used to build a declaration, complain about any decl attributes 6665 /// which might be lying around on it. 6666 void Sema::checkUnusedDeclAttributes(Declarator &D) { 6667 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList()); 6668 ::checkUnusedDeclAttributes(*this, D.getAttributes()); 6669 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) 6670 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs()); 6671 } 6672 6673 /// DeclClonePragmaWeak - clone existing decl (maybe definition), 6674 /// \#pragma weak needs a non-definition decl and source may not have one. 6675 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 6676 SourceLocation Loc) { 6677 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND)); 6678 NamedDecl *NewD = nullptr; 6679 if (auto *FD = dyn_cast<FunctionDecl>(ND)) { 6680 FunctionDecl *NewFD; 6681 // FIXME: Missing call to CheckFunctionDeclaration(). 6682 // FIXME: Mangling? 6683 // FIXME: Is the qualifier info correct? 6684 // FIXME: Is the DeclContext correct? 6685 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(), 6686 Loc, Loc, DeclarationName(II), 6687 FD->getType(), FD->getTypeSourceInfo(), 6688 SC_None, false/*isInlineSpecified*/, 6689 FD->hasPrototype(), 6690 false/*isConstexprSpecified*/); 6691 NewD = NewFD; 6692 6693 if (FD->getQualifier()) 6694 NewFD->setQualifierInfo(FD->getQualifierLoc()); 6695 6696 // Fake up parameter variables; they are declared as if this were 6697 // a typedef. 6698 QualType FDTy = FD->getType(); 6699 if (const auto *FT = FDTy->getAs<FunctionProtoType>()) { 6700 SmallVector<ParmVarDecl*, 16> Params; 6701 for (const auto &AI : FT->param_types()) { 6702 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI); 6703 Param->setScopeInfo(0, Params.size()); 6704 Params.push_back(Param); 6705 } 6706 NewFD->setParams(Params); 6707 } 6708 } else if (auto *VD = dyn_cast<VarDecl>(ND)) { 6709 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(), 6710 VD->getInnerLocStart(), VD->getLocation(), II, 6711 VD->getType(), VD->getTypeSourceInfo(), 6712 VD->getStorageClass()); 6713 if (VD->getQualifier()) 6714 cast<VarDecl>(NewD)->setQualifierInfo(VD->getQualifierLoc()); 6715 } 6716 return NewD; 6717 } 6718 6719 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak 6720 /// applied to it, possibly with an alias. 6721 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) { 6722 if (W.getUsed()) return; // only do this once 6723 W.setUsed(true); 6724 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...)) 6725 IdentifierInfo *NDId = ND->getIdentifier(); 6726 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation()); 6727 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(), 6728 W.getLocation())); 6729 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation())); 6730 WeakTopLevelDecl.push_back(NewD); 6731 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin 6732 // to insert Decl at TU scope, sorry. 6733 DeclContext *SavedContext = CurContext; 6734 CurContext = Context.getTranslationUnitDecl(); 6735 NewD->setDeclContext(CurContext); 6736 NewD->setLexicalDeclContext(CurContext); 6737 PushOnScopeChains(NewD, S); 6738 CurContext = SavedContext; 6739 } else { // just add weak to existing 6740 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation())); 6741 } 6742 } 6743 6744 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) { 6745 // It's valid to "forward-declare" #pragma weak, in which case we 6746 // have to do this. 6747 LoadExternalWeakUndeclaredIdentifiers(); 6748 if (!WeakUndeclaredIdentifiers.empty()) { 6749 NamedDecl *ND = nullptr; 6750 if (auto *VD = dyn_cast<VarDecl>(D)) 6751 if (VD->isExternC()) 6752 ND = VD; 6753 if (auto *FD = dyn_cast<FunctionDecl>(D)) 6754 if (FD->isExternC()) 6755 ND = FD; 6756 if (ND) { 6757 if (IdentifierInfo *Id = ND->getIdentifier()) { 6758 auto I = WeakUndeclaredIdentifiers.find(Id); 6759 if (I != WeakUndeclaredIdentifiers.end()) { 6760 WeakInfo W = I->second; 6761 DeclApplyPragmaWeak(S, ND, W); 6762 WeakUndeclaredIdentifiers[Id] = W; 6763 } 6764 } 6765 } 6766 } 6767 } 6768 6769 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in 6770 /// it, apply them to D. This is a bit tricky because PD can have attributes 6771 /// specified in many different places, and we need to find and apply them all. 6772 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) { 6773 // Apply decl attributes from the DeclSpec if present. 6774 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList()) 6775 ProcessDeclAttributeList(S, D, Attrs); 6776 6777 // Walk the declarator structure, applying decl attributes that were in a type 6778 // position to the decl itself. This handles cases like: 6779 // int *__attr__(x)** D; 6780 // when X is a decl attribute. 6781 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i) 6782 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs()) 6783 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false); 6784 6785 // Finally, apply any attributes on the decl itself. 6786 if (const AttributeList *Attrs = PD.getAttributes()) 6787 ProcessDeclAttributeList(S, D, Attrs); 6788 6789 // Apply additional attributes specified by '#pragma clang attribute'. 6790 AddPragmaAttributes(S, D); 6791 } 6792 6793 /// Is the given declaration allowed to use a forbidden type? 6794 /// If so, it'll still be annotated with an attribute that makes it 6795 /// illegal to actually use. 6796 static bool isForbiddenTypeAllowed(Sema &S, Decl *D, 6797 const DelayedDiagnostic &diag, 6798 UnavailableAttr::ImplicitReason &reason) { 6799 // Private ivars are always okay. Unfortunately, people don't 6800 // always properly make their ivars private, even in system headers. 6801 // Plus we need to make fields okay, too. 6802 if (!isa<FieldDecl>(D) && !isa<ObjCPropertyDecl>(D) && 6803 !isa<FunctionDecl>(D)) 6804 return false; 6805 6806 // Silently accept unsupported uses of __weak in both user and system 6807 // declarations when it's been disabled, for ease of integration with 6808 // -fno-objc-arc files. We do have to take some care against attempts 6809 // to define such things; for now, we've only done that for ivars 6810 // and properties. 6811 if ((isa<ObjCIvarDecl>(D) || isa<ObjCPropertyDecl>(D))) { 6812 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled || 6813 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) { 6814 reason = UnavailableAttr::IR_ForbiddenWeak; 6815 return true; 6816 } 6817 } 6818 6819 // Allow all sorts of things in system headers. 6820 if (S.Context.getSourceManager().isInSystemHeader(D->getLocation())) { 6821 // Currently, all the failures dealt with this way are due to ARC 6822 // restrictions. 6823 reason = UnavailableAttr::IR_ARCForbiddenType; 6824 return true; 6825 } 6826 6827 return false; 6828 } 6829 6830 /// Handle a delayed forbidden-type diagnostic. 6831 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD, 6832 Decl *D) { 6833 auto Reason = UnavailableAttr::IR_None; 6834 if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) { 6835 assert(Reason && "didn't set reason?"); 6836 D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc)); 6837 return; 6838 } 6839 if (S.getLangOpts().ObjCAutoRefCount) 6840 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 6841 // FIXME: we may want to suppress diagnostics for all 6842 // kind of forbidden type messages on unavailable functions. 6843 if (FD->hasAttr<UnavailableAttr>() && 6844 DD.getForbiddenTypeDiagnostic() == 6845 diag::err_arc_array_param_no_ownership) { 6846 DD.Triggered = true; 6847 return; 6848 } 6849 } 6850 6851 S.Diag(DD.Loc, DD.getForbiddenTypeDiagnostic()) 6852 << DD.getForbiddenTypeOperand() << DD.getForbiddenTypeArgument(); 6853 DD.Triggered = true; 6854 } 6855 6856 static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context, 6857 const Decl *D) { 6858 // Check each AvailabilityAttr to find the one for this platform. 6859 for (const auto *A : D->attrs()) { 6860 if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) { 6861 // FIXME: this is copied from CheckAvailability. We should try to 6862 // de-duplicate. 6863 6864 // Check if this is an App Extension "platform", and if so chop off 6865 // the suffix for matching with the actual platform. 6866 StringRef ActualPlatform = Avail->getPlatform()->getName(); 6867 StringRef RealizedPlatform = ActualPlatform; 6868 if (Context.getLangOpts().AppExt) { 6869 size_t suffix = RealizedPlatform.rfind("_app_extension"); 6870 if (suffix != StringRef::npos) 6871 RealizedPlatform = RealizedPlatform.slice(0, suffix); 6872 } 6873 6874 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName(); 6875 6876 // Match the platform name. 6877 if (RealizedPlatform == TargetPlatform) 6878 return Avail; 6879 } 6880 } 6881 return nullptr; 6882 } 6883 6884 /// The diagnostic we should emit for \c D, and the declaration that 6885 /// originated it, or \c AR_Available. 6886 /// 6887 /// \param D The declaration to check. 6888 /// \param Message If non-null, this will be populated with the message from 6889 /// the availability attribute that is selected. 6890 static std::pair<AvailabilityResult, const NamedDecl *> 6891 ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message) { 6892 AvailabilityResult Result = D->getAvailability(Message); 6893 6894 // For typedefs, if the typedef declaration appears available look 6895 // to the underlying type to see if it is more restrictive. 6896 while (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 6897 if (Result == AR_Available) { 6898 if (const auto *TT = TD->getUnderlyingType()->getAs<TagType>()) { 6899 D = TT->getDecl(); 6900 Result = D->getAvailability(Message); 6901 continue; 6902 } 6903 } 6904 break; 6905 } 6906 6907 // Forward class declarations get their attributes from their definition. 6908 if (const auto *IDecl = dyn_cast<ObjCInterfaceDecl>(D)) { 6909 if (IDecl->getDefinition()) { 6910 D = IDecl->getDefinition(); 6911 Result = D->getAvailability(Message); 6912 } 6913 } 6914 6915 if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) 6916 if (Result == AR_Available) { 6917 const DeclContext *DC = ECD->getDeclContext(); 6918 if (const auto *TheEnumDecl = dyn_cast<EnumDecl>(DC)) { 6919 Result = TheEnumDecl->getAvailability(Message); 6920 D = TheEnumDecl; 6921 } 6922 } 6923 6924 return {Result, D}; 6925 } 6926 6927 6928 /// \brief whether we should emit a diagnostic for \c K and \c DeclVersion in 6929 /// the context of \c Ctx. For example, we should emit an unavailable diagnostic 6930 /// in a deprecated context, but not the other way around. 6931 static bool ShouldDiagnoseAvailabilityInContext(Sema &S, AvailabilityResult K, 6932 VersionTuple DeclVersion, 6933 Decl *Ctx) { 6934 assert(K != AR_Available && "Expected an unavailable declaration here!"); 6935 6936 // Checks if we should emit the availability diagnostic in the context of C. 6937 auto CheckContext = [&](const Decl *C) { 6938 if (K == AR_NotYetIntroduced) { 6939 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, C)) 6940 if (AA->getIntroduced() >= DeclVersion) 6941 return true; 6942 } else if (K == AR_Deprecated) 6943 if (C->isDeprecated()) 6944 return true; 6945 6946 if (C->isUnavailable()) 6947 return true; 6948 return false; 6949 }; 6950 6951 // FIXME: This is a temporary workaround! Some existing Apple headers depends 6952 // on nested declarations in an @interface having the availability of the 6953 // interface when they really shouldn't: they are members of the enclosing 6954 // context, and can referenced from there. 6955 if (S.OriginalLexicalContext && cast<Decl>(S.OriginalLexicalContext) != Ctx) { 6956 const auto *OrigCtx = cast<Decl>(S.OriginalLexicalContext); 6957 if (CheckContext(OrigCtx)) 6958 return false; 6959 6960 // An implementation implicitly has the availability of the interface. 6961 if (const auto *CatOrImpl = dyn_cast<ObjCImplDecl>(OrigCtx)) { 6962 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface()) 6963 if (CheckContext(Interface)) 6964 return false; 6965 } 6966 // A category implicitly has the availability of the interface. 6967 else if (const auto *CatD = dyn_cast<ObjCCategoryDecl>(OrigCtx)) 6968 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface()) 6969 if (CheckContext(Interface)) 6970 return false; 6971 } 6972 6973 do { 6974 if (CheckContext(Ctx)) 6975 return false; 6976 6977 // An implementation implicitly has the availability of the interface. 6978 if (const auto *CatOrImpl = dyn_cast<ObjCImplDecl>(Ctx)) { 6979 if (const ObjCInterfaceDecl *Interface = CatOrImpl->getClassInterface()) 6980 if (CheckContext(Interface)) 6981 return false; 6982 } 6983 // A category implicitly has the availability of the interface. 6984 else if (const auto *CatD = dyn_cast<ObjCCategoryDecl>(Ctx)) 6985 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface()) 6986 if (CheckContext(Interface)) 6987 return false; 6988 } while ((Ctx = cast_or_null<Decl>(Ctx->getDeclContext()))); 6989 6990 return true; 6991 } 6992 6993 static bool 6994 shouldDiagnoseAvailabilityByDefault(const ASTContext &Context, 6995 const VersionTuple &DeploymentVersion, 6996 const VersionTuple &DeclVersion) { 6997 const auto &Triple = Context.getTargetInfo().getTriple(); 6998 VersionTuple ForceAvailabilityFromVersion; 6999 switch (Triple.getOS()) { 7000 case llvm::Triple::IOS: 7001 case llvm::Triple::TvOS: 7002 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/11); 7003 break; 7004 case llvm::Triple::WatchOS: 7005 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/4); 7006 break; 7007 case llvm::Triple::Darwin: 7008 case llvm::Triple::MacOSX: 7009 ForceAvailabilityFromVersion = VersionTuple(/*Major=*/10, /*Minor=*/13); 7010 break; 7011 default: 7012 // New targets should always warn about availability. 7013 return Triple.getVendor() == llvm::Triple::Apple; 7014 } 7015 return DeploymentVersion >= ForceAvailabilityFromVersion || 7016 DeclVersion >= ForceAvailabilityFromVersion; 7017 } 7018 7019 static NamedDecl *findEnclosingDeclToAnnotate(Decl *OrigCtx) { 7020 for (Decl *Ctx = OrigCtx; Ctx; 7021 Ctx = cast_or_null<Decl>(Ctx->getDeclContext())) { 7022 if (isa<TagDecl>(Ctx) || isa<FunctionDecl>(Ctx) || isa<ObjCMethodDecl>(Ctx)) 7023 return cast<NamedDecl>(Ctx); 7024 if (auto *CD = dyn_cast<ObjCContainerDecl>(Ctx)) { 7025 if (auto *Imp = dyn_cast<ObjCImplDecl>(Ctx)) 7026 return Imp->getClassInterface(); 7027 return CD; 7028 } 7029 } 7030 7031 return dyn_cast<NamedDecl>(OrigCtx); 7032 } 7033 7034 namespace { 7035 7036 struct AttributeInsertion { 7037 StringRef Prefix; 7038 SourceLocation Loc; 7039 StringRef Suffix; 7040 7041 static AttributeInsertion createInsertionAfter(const NamedDecl *D) { 7042 return {" ", D->getLocEnd(), ""}; 7043 } 7044 static AttributeInsertion createInsertionAfter(SourceLocation Loc) { 7045 return {" ", Loc, ""}; 7046 } 7047 static AttributeInsertion createInsertionBefore(const NamedDecl *D) { 7048 return {"", D->getLocStart(), "\n"}; 7049 } 7050 }; 7051 7052 } // end anonymous namespace 7053 7054 /// Returns a source location in which it's appropriate to insert a new 7055 /// attribute for the given declaration \D. 7056 static Optional<AttributeInsertion> 7057 createAttributeInsertion(const NamedDecl *D, const SourceManager &SM, 7058 const LangOptions &LangOpts) { 7059 if (isa<ObjCPropertyDecl>(D)) 7060 return AttributeInsertion::createInsertionAfter(D); 7061 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) { 7062 if (MD->hasBody()) 7063 return None; 7064 return AttributeInsertion::createInsertionAfter(D); 7065 } 7066 if (const auto *TD = dyn_cast<TagDecl>(D)) { 7067 SourceLocation Loc = 7068 Lexer::getLocForEndOfToken(TD->getInnerLocStart(), 0, SM, LangOpts); 7069 if (Loc.isInvalid()) 7070 return None; 7071 // Insert after the 'struct'/whatever keyword. 7072 return AttributeInsertion::createInsertionAfter(Loc); 7073 } 7074 return AttributeInsertion::createInsertionBefore(D); 7075 } 7076 7077 /// Actually emit an availability diagnostic for a reference to an unavailable 7078 /// decl. 7079 /// 7080 /// \param Ctx The context that the reference occurred in 7081 /// \param ReferringDecl The exact declaration that was referenced. 7082 /// \param OffendingDecl A related decl to \c ReferringDecl that has an 7083 /// availability attribute corrisponding to \c K attached to it. Note that this 7084 /// may not be the same as ReferringDecl, i.e. if an EnumDecl is annotated and 7085 /// we refer to a member EnumConstantDecl, ReferringDecl is the EnumConstantDecl 7086 /// and OffendingDecl is the EnumDecl. 7087 static void DoEmitAvailabilityWarning(Sema &S, AvailabilityResult K, 7088 Decl *Ctx, const NamedDecl *ReferringDecl, 7089 const NamedDecl *OffendingDecl, 7090 StringRef Message, SourceLocation Loc, 7091 const ObjCInterfaceDecl *UnknownObjCClass, 7092 const ObjCPropertyDecl *ObjCProperty, 7093 bool ObjCPropertyAccess) { 7094 // Diagnostics for deprecated or unavailable. 7095 unsigned diag, diag_message, diag_fwdclass_message; 7096 unsigned diag_available_here = diag::note_availability_specified_here; 7097 SourceLocation NoteLocation = OffendingDecl->getLocation(); 7098 7099 // Matches 'diag::note_property_attribute' options. 7100 unsigned property_note_select; 7101 7102 // Matches diag::note_availability_specified_here. 7103 unsigned available_here_select_kind; 7104 7105 VersionTuple DeclVersion; 7106 if (const AvailabilityAttr *AA = getAttrForPlatform(S.Context, OffendingDecl)) 7107 DeclVersion = AA->getIntroduced(); 7108 7109 if (!ShouldDiagnoseAvailabilityInContext(S, K, DeclVersion, Ctx)) 7110 return; 7111 7112 // The declaration can have multiple availability attributes, we are looking 7113 // at one of them. 7114 const AvailabilityAttr *A = getAttrForPlatform(S.Context, OffendingDecl); 7115 if (A && A->isInherited()) { 7116 for (const Decl *Redecl = OffendingDecl->getMostRecentDecl(); Redecl; 7117 Redecl = Redecl->getPreviousDecl()) { 7118 const AvailabilityAttr *AForRedecl = 7119 getAttrForPlatform(S.Context, Redecl); 7120 if (AForRedecl && !AForRedecl->isInherited()) { 7121 // If D is a declaration with inherited attributes, the note should 7122 // point to the declaration with actual attributes. 7123 NoteLocation = Redecl->getLocation(); 7124 break; 7125 } 7126 } 7127 } 7128 7129 switch (K) { 7130 case AR_NotYetIntroduced: { 7131 // We would like to emit the diagnostic even if -Wunguarded-availability is 7132 // not specified for deployment targets >= to iOS 11 or equivalent or 7133 // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or 7134 // later. 7135 const AvailabilityAttr *AA = 7136 getAttrForPlatform(S.getASTContext(), OffendingDecl); 7137 VersionTuple Introduced = AA->getIntroduced(); 7138 7139 bool UseNewWarning = shouldDiagnoseAvailabilityByDefault( 7140 S.Context, S.Context.getTargetInfo().getPlatformMinVersion(), 7141 Introduced); 7142 unsigned Warning = UseNewWarning ? diag::warn_unguarded_availability_new 7143 : diag::warn_unguarded_availability; 7144 7145 S.Diag(Loc, Warning) 7146 << OffendingDecl 7147 << AvailabilityAttr::getPrettyPlatformName( 7148 S.getASTContext().getTargetInfo().getPlatformName()) 7149 << Introduced.getAsString(); 7150 7151 S.Diag(OffendingDecl->getLocation(), diag::note_availability_specified_here) 7152 << OffendingDecl << /* partial */ 3; 7153 7154 if (const auto *Enclosing = findEnclosingDeclToAnnotate(Ctx)) { 7155 if (const auto *TD = dyn_cast<TagDecl>(Enclosing)) 7156 if (TD->getDeclName().isEmpty()) { 7157 S.Diag(TD->getLocation(), 7158 diag::note_decl_unguarded_availability_silence) 7159 << /*Anonymous*/ 1 << TD->getKindName(); 7160 return; 7161 } 7162 auto FixitNoteDiag = 7163 S.Diag(Enclosing->getLocation(), 7164 diag::note_decl_unguarded_availability_silence) 7165 << /*Named*/ 0 << Enclosing; 7166 // Don't offer a fixit for declarations with availability attributes. 7167 if (Enclosing->hasAttr<AvailabilityAttr>()) 7168 return; 7169 if (!S.getPreprocessor().isMacroDefined("API_AVAILABLE")) 7170 return; 7171 Optional<AttributeInsertion> Insertion = createAttributeInsertion( 7172 Enclosing, S.getSourceManager(), S.getLangOpts()); 7173 if (!Insertion) 7174 return; 7175 std::string PlatformName = 7176 AvailabilityAttr::getPlatformNameSourceSpelling( 7177 S.getASTContext().getTargetInfo().getPlatformName()) 7178 .lower(); 7179 std::string Introduced = 7180 OffendingDecl->getVersionIntroduced().getAsString(); 7181 FixitNoteDiag << FixItHint::CreateInsertion( 7182 Insertion->Loc, 7183 (llvm::Twine(Insertion->Prefix) + "API_AVAILABLE(" + PlatformName + 7184 "(" + Introduced + "))" + Insertion->Suffix) 7185 .str()); 7186 } 7187 return; 7188 } 7189 case AR_Deprecated: 7190 diag = !ObjCPropertyAccess ? diag::warn_deprecated 7191 : diag::warn_property_method_deprecated; 7192 diag_message = diag::warn_deprecated_message; 7193 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message; 7194 property_note_select = /* deprecated */ 0; 7195 available_here_select_kind = /* deprecated */ 2; 7196 if (const auto *AL = OffendingDecl->getAttr<DeprecatedAttr>()) 7197 NoteLocation = AL->getLocation(); 7198 break; 7199 7200 case AR_Unavailable: 7201 diag = !ObjCPropertyAccess ? diag::err_unavailable 7202 : diag::err_property_method_unavailable; 7203 diag_message = diag::err_unavailable_message; 7204 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message; 7205 property_note_select = /* unavailable */ 1; 7206 available_here_select_kind = /* unavailable */ 0; 7207 7208 if (auto AL = OffendingDecl->getAttr<UnavailableAttr>()) { 7209 if (AL->isImplicit() && AL->getImplicitReason()) { 7210 // Most of these failures are due to extra restrictions in ARC; 7211 // reflect that in the primary diagnostic when applicable. 7212 auto flagARCError = [&] { 7213 if (S.getLangOpts().ObjCAutoRefCount && 7214 S.getSourceManager().isInSystemHeader( 7215 OffendingDecl->getLocation())) 7216 diag = diag::err_unavailable_in_arc; 7217 }; 7218 7219 switch (AL->getImplicitReason()) { 7220 case UnavailableAttr::IR_None: break; 7221 7222 case UnavailableAttr::IR_ARCForbiddenType: 7223 flagARCError(); 7224 diag_available_here = diag::note_arc_forbidden_type; 7225 break; 7226 7227 case UnavailableAttr::IR_ForbiddenWeak: 7228 if (S.getLangOpts().ObjCWeakRuntime) 7229 diag_available_here = diag::note_arc_weak_disabled; 7230 else 7231 diag_available_here = diag::note_arc_weak_no_runtime; 7232 break; 7233 7234 case UnavailableAttr::IR_ARCForbiddenConversion: 7235 flagARCError(); 7236 diag_available_here = diag::note_performs_forbidden_arc_conversion; 7237 break; 7238 7239 case UnavailableAttr::IR_ARCInitReturnsUnrelated: 7240 flagARCError(); 7241 diag_available_here = diag::note_arc_init_returns_unrelated; 7242 break; 7243 7244 case UnavailableAttr::IR_ARCFieldWithOwnership: 7245 flagARCError(); 7246 diag_available_here = diag::note_arc_field_with_ownership; 7247 break; 7248 } 7249 } 7250 } 7251 break; 7252 7253 case AR_Available: 7254 llvm_unreachable("Warning for availability of available declaration?"); 7255 } 7256 7257 CharSourceRange UseRange; 7258 StringRef Replacement; 7259 if (K == AR_Deprecated) { 7260 if (auto AL = OffendingDecl->getAttr<DeprecatedAttr>()) 7261 Replacement = AL->getReplacement(); 7262 if (auto AL = getAttrForPlatform(S.Context, OffendingDecl)) 7263 Replacement = AL->getReplacement(); 7264 7265 if (!Replacement.empty()) 7266 UseRange = 7267 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 7268 } 7269 7270 if (!Message.empty()) { 7271 S.Diag(Loc, diag_message) << ReferringDecl << Message 7272 << (UseRange.isValid() ? 7273 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint()); 7274 if (ObjCProperty) 7275 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute) 7276 << ObjCProperty->getDeclName() << property_note_select; 7277 } else if (!UnknownObjCClass) { 7278 S.Diag(Loc, diag) << ReferringDecl 7279 << (UseRange.isValid() ? 7280 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint()); 7281 if (ObjCProperty) 7282 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute) 7283 << ObjCProperty->getDeclName() << property_note_select; 7284 } else { 7285 S.Diag(Loc, diag_fwdclass_message) << ReferringDecl 7286 << (UseRange.isValid() ? 7287 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint()); 7288 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class); 7289 } 7290 7291 S.Diag(NoteLocation, diag_available_here) 7292 << OffendingDecl << available_here_select_kind; 7293 } 7294 7295 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD, 7296 Decl *Ctx) { 7297 assert(DD.Kind == DelayedDiagnostic::Availability && 7298 "Expected an availability diagnostic here"); 7299 7300 DD.Triggered = true; 7301 DoEmitAvailabilityWarning( 7302 S, DD.getAvailabilityResult(), Ctx, DD.getAvailabilityReferringDecl(), 7303 DD.getAvailabilityOffendingDecl(), DD.getAvailabilityMessage(), DD.Loc, 7304 DD.getUnknownObjCClass(), DD.getObjCProperty(), false); 7305 } 7306 7307 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) { 7308 assert(DelayedDiagnostics.getCurrentPool()); 7309 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool(); 7310 DelayedDiagnostics.popWithoutEmitting(state); 7311 7312 // When delaying diagnostics to run in the context of a parsed 7313 // declaration, we only want to actually emit anything if parsing 7314 // succeeds. 7315 if (!decl) return; 7316 7317 // We emit all the active diagnostics in this pool or any of its 7318 // parents. In general, we'll get one pool for the decl spec 7319 // and a child pool for each declarator; in a decl group like: 7320 // deprecated_typedef foo, *bar, baz(); 7321 // only the declarator pops will be passed decls. This is correct; 7322 // we really do need to consider delayed diagnostics from the decl spec 7323 // for each of the different declarations. 7324 const DelayedDiagnosticPool *pool = &poppedPool; 7325 do { 7326 for (DelayedDiagnosticPool::pool_iterator 7327 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) { 7328 // This const_cast is a bit lame. Really, Triggered should be mutable. 7329 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i); 7330 if (diag.Triggered) 7331 continue; 7332 7333 switch (diag.Kind) { 7334 case DelayedDiagnostic::Availability: 7335 // Don't bother giving deprecation/unavailable diagnostics if 7336 // the decl is invalid. 7337 if (!decl->isInvalidDecl()) 7338 handleDelayedAvailabilityCheck(*this, diag, decl); 7339 break; 7340 7341 case DelayedDiagnostic::Access: 7342 HandleDelayedAccessCheck(diag, decl); 7343 break; 7344 7345 case DelayedDiagnostic::ForbiddenType: 7346 handleDelayedForbiddenType(*this, diag, decl); 7347 break; 7348 } 7349 } 7350 } while ((pool = pool->getParent())); 7351 } 7352 7353 /// Given a set of delayed diagnostics, re-emit them as if they had 7354 /// been delayed in the current context instead of in the given pool. 7355 /// Essentially, this just moves them to the current pool. 7356 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) { 7357 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool(); 7358 assert(curPool && "re-emitting in undelayed context not supported"); 7359 curPool->steal(pool); 7360 } 7361 7362 static void EmitAvailabilityWarning(Sema &S, AvailabilityResult AR, 7363 const NamedDecl *ReferringDecl, 7364 const NamedDecl *OffendingDecl, 7365 StringRef Message, SourceLocation Loc, 7366 const ObjCInterfaceDecl *UnknownObjCClass, 7367 const ObjCPropertyDecl *ObjCProperty, 7368 bool ObjCPropertyAccess) { 7369 // Delay if we're currently parsing a declaration. 7370 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) { 7371 S.DelayedDiagnostics.add( 7372 DelayedDiagnostic::makeAvailability( 7373 AR, Loc, ReferringDecl, OffendingDecl, UnknownObjCClass, 7374 ObjCProperty, Message, ObjCPropertyAccess)); 7375 return; 7376 } 7377 7378 Decl *Ctx = cast<Decl>(S.getCurLexicalContext()); 7379 DoEmitAvailabilityWarning(S, AR, Ctx, ReferringDecl, OffendingDecl, 7380 Message, Loc, UnknownObjCClass, ObjCProperty, 7381 ObjCPropertyAccess); 7382 } 7383 7384 namespace { 7385 7386 /// Returns true if the given statement can be a body-like child of \p Parent. 7387 bool isBodyLikeChildStmt(const Stmt *S, const Stmt *Parent) { 7388 switch (Parent->getStmtClass()) { 7389 case Stmt::IfStmtClass: 7390 return cast<IfStmt>(Parent)->getThen() == S || 7391 cast<IfStmt>(Parent)->getElse() == S; 7392 case Stmt::WhileStmtClass: 7393 return cast<WhileStmt>(Parent)->getBody() == S; 7394 case Stmt::DoStmtClass: 7395 return cast<DoStmt>(Parent)->getBody() == S; 7396 case Stmt::ForStmtClass: 7397 return cast<ForStmt>(Parent)->getBody() == S; 7398 case Stmt::CXXForRangeStmtClass: 7399 return cast<CXXForRangeStmt>(Parent)->getBody() == S; 7400 case Stmt::ObjCForCollectionStmtClass: 7401 return cast<ObjCForCollectionStmt>(Parent)->getBody() == S; 7402 case Stmt::CaseStmtClass: 7403 case Stmt::DefaultStmtClass: 7404 return cast<SwitchCase>(Parent)->getSubStmt() == S; 7405 default: 7406 return false; 7407 } 7408 } 7409 7410 class StmtUSEFinder : public RecursiveASTVisitor<StmtUSEFinder> { 7411 const Stmt *Target; 7412 7413 public: 7414 bool VisitStmt(Stmt *S) { return S != Target; } 7415 7416 /// Returns true if the given statement is present in the given declaration. 7417 static bool isContained(const Stmt *Target, const Decl *D) { 7418 StmtUSEFinder Visitor; 7419 Visitor.Target = Target; 7420 return !Visitor.TraverseDecl(const_cast<Decl *>(D)); 7421 } 7422 }; 7423 7424 /// Traverses the AST and finds the last statement that used a given 7425 /// declaration. 7426 class LastDeclUSEFinder : public RecursiveASTVisitor<LastDeclUSEFinder> { 7427 const Decl *D; 7428 7429 public: 7430 bool VisitDeclRefExpr(DeclRefExpr *DRE) { 7431 if (DRE->getDecl() == D) 7432 return false; 7433 return true; 7434 } 7435 7436 static const Stmt *findLastStmtThatUsesDecl(const Decl *D, 7437 const CompoundStmt *Scope) { 7438 LastDeclUSEFinder Visitor; 7439 Visitor.D = D; 7440 for (auto I = Scope->body_rbegin(), E = Scope->body_rend(); I != E; ++I) { 7441 const Stmt *S = *I; 7442 if (!Visitor.TraverseStmt(const_cast<Stmt *>(S))) 7443 return S; 7444 } 7445 return nullptr; 7446 } 7447 }; 7448 7449 /// \brief This class implements -Wunguarded-availability. 7450 /// 7451 /// This is done with a traversal of the AST of a function that makes reference 7452 /// to a partially available declaration. Whenever we encounter an \c if of the 7453 /// form: \c if(@available(...)), we use the version from the condition to visit 7454 /// the then statement. 7455 class DiagnoseUnguardedAvailability 7456 : public RecursiveASTVisitor<DiagnoseUnguardedAvailability> { 7457 typedef RecursiveASTVisitor<DiagnoseUnguardedAvailability> Base; 7458 7459 Sema &SemaRef; 7460 Decl *Ctx; 7461 7462 /// Stack of potentially nested 'if (@available(...))'s. 7463 SmallVector<VersionTuple, 8> AvailabilityStack; 7464 SmallVector<const Stmt *, 16> StmtStack; 7465 7466 void DiagnoseDeclAvailability(NamedDecl *D, SourceRange Range); 7467 7468 public: 7469 DiagnoseUnguardedAvailability(Sema &SemaRef, Decl *Ctx) 7470 : SemaRef(SemaRef), Ctx(Ctx) { 7471 AvailabilityStack.push_back( 7472 SemaRef.Context.getTargetInfo().getPlatformMinVersion()); 7473 } 7474 7475 bool TraverseDecl(Decl *D) { 7476 // Avoid visiting nested functions to prevent duplicate warnings. 7477 if (!D || isa<FunctionDecl>(D)) 7478 return true; 7479 return Base::TraverseDecl(D); 7480 } 7481 7482 bool TraverseStmt(Stmt *S) { 7483 if (!S) 7484 return true; 7485 StmtStack.push_back(S); 7486 bool Result = Base::TraverseStmt(S); 7487 StmtStack.pop_back(); 7488 return Result; 7489 } 7490 7491 void IssueDiagnostics(Stmt *S) { TraverseStmt(S); } 7492 7493 bool TraverseIfStmt(IfStmt *If); 7494 7495 bool TraverseLambdaExpr(LambdaExpr *E) { return true; } 7496 7497 // for 'case X:' statements, don't bother looking at the 'X'; it can't lead 7498 // to any useful diagnostics. 7499 bool TraverseCaseStmt(CaseStmt *CS) { return TraverseStmt(CS->getSubStmt()); } 7500 7501 bool VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *PRE) { 7502 if (PRE->isClassReceiver()) 7503 DiagnoseDeclAvailability(PRE->getClassReceiver(), PRE->getReceiverLocation()); 7504 return true; 7505 } 7506 7507 bool VisitObjCMessageExpr(ObjCMessageExpr *Msg) { 7508 if (ObjCMethodDecl *D = Msg->getMethodDecl()) 7509 DiagnoseDeclAvailability( 7510 D, SourceRange(Msg->getSelectorStartLoc(), Msg->getLocEnd())); 7511 return true; 7512 } 7513 7514 bool VisitDeclRefExpr(DeclRefExpr *DRE) { 7515 DiagnoseDeclAvailability(DRE->getDecl(), 7516 SourceRange(DRE->getLocStart(), DRE->getLocEnd())); 7517 return true; 7518 } 7519 7520 bool VisitMemberExpr(MemberExpr *ME) { 7521 DiagnoseDeclAvailability(ME->getMemberDecl(), 7522 SourceRange(ME->getLocStart(), ME->getLocEnd())); 7523 return true; 7524 } 7525 7526 bool VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) { 7527 SemaRef.Diag(E->getLocStart(), diag::warn_at_available_unchecked_use) 7528 << (!SemaRef.getLangOpts().ObjC1); 7529 return true; 7530 } 7531 7532 bool VisitTypeLoc(TypeLoc Ty); 7533 }; 7534 7535 void DiagnoseUnguardedAvailability::DiagnoseDeclAvailability( 7536 NamedDecl *D, SourceRange Range) { 7537 AvailabilityResult Result; 7538 const NamedDecl *OffendingDecl; 7539 std::tie(Result, OffendingDecl) = 7540 ShouldDiagnoseAvailabilityOfDecl(D, nullptr); 7541 if (Result != AR_Available) { 7542 // All other diagnostic kinds have already been handled in 7543 // DiagnoseAvailabilityOfDecl. 7544 if (Result != AR_NotYetIntroduced) 7545 return; 7546 7547 const AvailabilityAttr *AA = 7548 getAttrForPlatform(SemaRef.getASTContext(), OffendingDecl); 7549 VersionTuple Introduced = AA->getIntroduced(); 7550 7551 if (AvailabilityStack.back() >= Introduced) 7552 return; 7553 7554 // If the context of this function is less available than D, we should not 7555 // emit a diagnostic. 7556 if (!ShouldDiagnoseAvailabilityInContext(SemaRef, Result, Introduced, Ctx)) 7557 return; 7558 7559 // We would like to emit the diagnostic even if -Wunguarded-availability is 7560 // not specified for deployment targets >= to iOS 11 or equivalent or 7561 // for declarations that were introduced in iOS 11 (macOS 10.13, ...) or 7562 // later. 7563 unsigned DiagKind = 7564 shouldDiagnoseAvailabilityByDefault( 7565 SemaRef.Context, 7566 SemaRef.Context.getTargetInfo().getPlatformMinVersion(), Introduced) 7567 ? diag::warn_unguarded_availability_new 7568 : diag::warn_unguarded_availability; 7569 7570 SemaRef.Diag(Range.getBegin(), DiagKind) 7571 << Range << D 7572 << AvailabilityAttr::getPrettyPlatformName( 7573 SemaRef.getASTContext().getTargetInfo().getPlatformName()) 7574 << Introduced.getAsString(); 7575 7576 SemaRef.Diag(OffendingDecl->getLocation(), 7577 diag::note_availability_specified_here) 7578 << OffendingDecl << /* partial */ 3; 7579 7580 auto FixitDiag = 7581 SemaRef.Diag(Range.getBegin(), diag::note_unguarded_available_silence) 7582 << Range << D 7583 << (SemaRef.getLangOpts().ObjC1 ? /*@available*/ 0 7584 : /*__builtin_available*/ 1); 7585 7586 // Find the statement which should be enclosed in the if @available check. 7587 if (StmtStack.empty()) 7588 return; 7589 const Stmt *StmtOfUse = StmtStack.back(); 7590 const CompoundStmt *Scope = nullptr; 7591 for (const Stmt *S : llvm::reverse(StmtStack)) { 7592 if (const auto *CS = dyn_cast<CompoundStmt>(S)) { 7593 Scope = CS; 7594 break; 7595 } 7596 if (isBodyLikeChildStmt(StmtOfUse, S)) { 7597 // The declaration won't be seen outside of the statement, so we don't 7598 // have to wrap the uses of any declared variables in if (@available). 7599 // Therefore we can avoid setting Scope here. 7600 break; 7601 } 7602 StmtOfUse = S; 7603 } 7604 const Stmt *LastStmtOfUse = nullptr; 7605 if (isa<DeclStmt>(StmtOfUse) && Scope) { 7606 for (const Decl *D : cast<DeclStmt>(StmtOfUse)->decls()) { 7607 if (StmtUSEFinder::isContained(StmtStack.back(), D)) { 7608 LastStmtOfUse = LastDeclUSEFinder::findLastStmtThatUsesDecl(D, Scope); 7609 break; 7610 } 7611 } 7612 } 7613 7614 const SourceManager &SM = SemaRef.getSourceManager(); 7615 SourceLocation IfInsertionLoc = 7616 SM.getExpansionLoc(StmtOfUse->getLocStart()); 7617 SourceLocation StmtEndLoc = 7618 SM.getExpansionRange( 7619 (LastStmtOfUse ? LastStmtOfUse : StmtOfUse)->getLocEnd()) 7620 .second; 7621 if (SM.getFileID(IfInsertionLoc) != SM.getFileID(StmtEndLoc)) 7622 return; 7623 7624 StringRef Indentation = Lexer::getIndentationForLine(IfInsertionLoc, SM); 7625 const char *ExtraIndentation = " "; 7626 std::string FixItString; 7627 llvm::raw_string_ostream FixItOS(FixItString); 7628 FixItOS << "if (" << (SemaRef.getLangOpts().ObjC1 ? "@available" 7629 : "__builtin_available") 7630 << "(" 7631 << AvailabilityAttr::getPlatformNameSourceSpelling( 7632 SemaRef.getASTContext().getTargetInfo().getPlatformName()) 7633 << " " << Introduced.getAsString() << ", *)) {\n" 7634 << Indentation << ExtraIndentation; 7635 FixitDiag << FixItHint::CreateInsertion(IfInsertionLoc, FixItOS.str()); 7636 SourceLocation ElseInsertionLoc = Lexer::findLocationAfterToken( 7637 StmtEndLoc, tok::semi, SM, SemaRef.getLangOpts(), 7638 /*SkipTrailingWhitespaceAndNewLine=*/false); 7639 if (ElseInsertionLoc.isInvalid()) 7640 ElseInsertionLoc = 7641 Lexer::getLocForEndOfToken(StmtEndLoc, 0, SM, SemaRef.getLangOpts()); 7642 FixItOS.str().clear(); 7643 FixItOS << "\n" 7644 << Indentation << "} else {\n" 7645 << Indentation << ExtraIndentation 7646 << "// Fallback on earlier versions\n" 7647 << Indentation << "}"; 7648 FixitDiag << FixItHint::CreateInsertion(ElseInsertionLoc, FixItOS.str()); 7649 } 7650 } 7651 7652 bool DiagnoseUnguardedAvailability::VisitTypeLoc(TypeLoc Ty) { 7653 const Type *TyPtr = Ty.getTypePtr(); 7654 SourceRange Range{Ty.getBeginLoc(), Ty.getEndLoc()}; 7655 7656 if (Range.isInvalid()) 7657 return true; 7658 7659 if (const auto *TT = dyn_cast<TagType>(TyPtr)) { 7660 TagDecl *TD = TT->getDecl(); 7661 DiagnoseDeclAvailability(TD, Range); 7662 7663 } else if (const auto *TD = dyn_cast<TypedefType>(TyPtr)) { 7664 TypedefNameDecl *D = TD->getDecl(); 7665 DiagnoseDeclAvailability(D, Range); 7666 7667 } else if (const auto *ObjCO = dyn_cast<ObjCObjectType>(TyPtr)) { 7668 if (NamedDecl *D = ObjCO->getInterface()) 7669 DiagnoseDeclAvailability(D, Range); 7670 } 7671 7672 return true; 7673 } 7674 7675 bool DiagnoseUnguardedAvailability::TraverseIfStmt(IfStmt *If) { 7676 VersionTuple CondVersion; 7677 if (auto *E = dyn_cast<ObjCAvailabilityCheckExpr>(If->getCond())) { 7678 CondVersion = E->getVersion(); 7679 7680 // If we're using the '*' case here or if this check is redundant, then we 7681 // use the enclosing version to check both branches. 7682 if (CondVersion.empty() || CondVersion <= AvailabilityStack.back()) 7683 return TraverseStmt(If->getThen()) && TraverseStmt(If->getElse()); 7684 } else { 7685 // This isn't an availability checking 'if', we can just continue. 7686 return Base::TraverseIfStmt(If); 7687 } 7688 7689 AvailabilityStack.push_back(CondVersion); 7690 bool ShouldContinue = TraverseStmt(If->getThen()); 7691 AvailabilityStack.pop_back(); 7692 7693 return ShouldContinue && TraverseStmt(If->getElse()); 7694 } 7695 7696 } // end anonymous namespace 7697 7698 void Sema::DiagnoseUnguardedAvailabilityViolations(Decl *D) { 7699 Stmt *Body = nullptr; 7700 7701 if (auto *FD = D->getAsFunction()) { 7702 // FIXME: We only examine the pattern decl for availability violations now, 7703 // but we should also examine instantiated templates. 7704 if (FD->isTemplateInstantiation()) 7705 return; 7706 7707 Body = FD->getBody(); 7708 } else if (auto *MD = dyn_cast<ObjCMethodDecl>(D)) 7709 Body = MD->getBody(); 7710 else if (auto *BD = dyn_cast<BlockDecl>(D)) 7711 Body = BD->getBody(); 7712 7713 assert(Body && "Need a body here!"); 7714 7715 DiagnoseUnguardedAvailability(*this, D).IssueDiagnostics(Body); 7716 } 7717 7718 void Sema::DiagnoseAvailabilityOfDecl(NamedDecl *D, SourceLocation Loc, 7719 const ObjCInterfaceDecl *UnknownObjCClass, 7720 bool ObjCPropertyAccess, 7721 bool AvoidPartialAvailabilityChecks) { 7722 std::string Message; 7723 AvailabilityResult Result; 7724 const NamedDecl* OffendingDecl; 7725 // See if this declaration is unavailable, deprecated, or partial. 7726 std::tie(Result, OffendingDecl) = ShouldDiagnoseAvailabilityOfDecl(D, &Message); 7727 if (Result == AR_Available) 7728 return; 7729 7730 if (Result == AR_NotYetIntroduced) { 7731 if (AvoidPartialAvailabilityChecks) 7732 return; 7733 7734 // We need to know the @available context in the current function to 7735 // diagnose this use, let DiagnoseUnguardedAvailabilityViolations do that 7736 // when we're done parsing the current function. 7737 if (getCurFunctionOrMethodDecl()) { 7738 getEnclosingFunction()->HasPotentialAvailabilityViolations = true; 7739 return; 7740 } else if (getCurBlock() || getCurLambda()) { 7741 getCurFunction()->HasPotentialAvailabilityViolations = true; 7742 return; 7743 } 7744 } 7745 7746 const ObjCPropertyDecl *ObjCPDecl = nullptr; 7747 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) { 7748 if (const ObjCPropertyDecl *PD = MD->findPropertyDecl()) { 7749 AvailabilityResult PDeclResult = PD->getAvailability(nullptr); 7750 if (PDeclResult == Result) 7751 ObjCPDecl = PD; 7752 } 7753 } 7754 7755 EmitAvailabilityWarning(*this, Result, D, OffendingDecl, Message, Loc, 7756 UnknownObjCClass, ObjCPDecl, ObjCPropertyAccess); 7757 } 7758