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