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/Sema/SemaInternal.h" 15 #include "clang/AST/ASTContext.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/DeclCXX.h" 18 #include "clang/AST/DeclObjC.h" 19 #include "clang/AST/DeclTemplate.h" 20 #include "clang/AST/Expr.h" 21 #include "clang/AST/ExprCXX.h" 22 #include "clang/AST/Mangle.h" 23 #include "clang/Basic/CharInfo.h" 24 #include "clang/Basic/SourceManager.h" 25 #include "clang/Basic/TargetInfo.h" 26 #include "clang/Lex/Preprocessor.h" 27 #include "clang/Sema/DeclSpec.h" 28 #include "clang/Sema/DelayedDiagnostic.h" 29 #include "clang/Sema/Lookup.h" 30 #include "clang/Sema/Scope.h" 31 #include "llvm/ADT/StringExtras.h" 32 #include "llvm/Support/MathExtras.h" 33 using namespace clang; 34 using namespace sema; 35 36 namespace AttributeLangSupport { 37 enum LANG { 38 C, 39 Cpp, 40 ObjC 41 }; 42 } 43 44 //===----------------------------------------------------------------------===// 45 // Helper functions 46 //===----------------------------------------------------------------------===// 47 48 /// isFunctionOrMethod - Return true if the given decl has function 49 /// type (function or function-typed variable) or an Objective-C 50 /// method. 51 static bool isFunctionOrMethod(const Decl *D) { 52 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D); 53 } 54 55 /// Return true if the given decl has a declarator that should have 56 /// been processed by Sema::GetTypeForDeclarator. 57 static bool hasDeclarator(const Decl *D) { 58 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl. 59 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) || 60 isa<ObjCPropertyDecl>(D); 61 } 62 63 /// hasFunctionProto - Return true if the given decl has a argument 64 /// information. This decl should have already passed 65 /// isFunctionOrMethod or isFunctionOrMethodOrBlock. 66 static bool hasFunctionProto(const Decl *D) { 67 if (const FunctionType *FnTy = D->getFunctionType()) 68 return isa<FunctionProtoType>(FnTy); 69 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D); 70 } 71 72 /// getFunctionOrMethodNumParams - Return number of function or method 73 /// parameters. It is an error to call this on a K&R function (use 74 /// hasFunctionProto first). 75 static unsigned getFunctionOrMethodNumParams(const Decl *D) { 76 if (const FunctionType *FnTy = D->getFunctionType()) 77 return cast<FunctionProtoType>(FnTy)->getNumParams(); 78 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) 79 return BD->getNumParams(); 80 return cast<ObjCMethodDecl>(D)->param_size(); 81 } 82 83 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) { 84 if (const FunctionType *FnTy = D->getFunctionType()) 85 return cast<FunctionProtoType>(FnTy)->getParamType(Idx); 86 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) 87 return BD->getParamDecl(Idx)->getType(); 88 89 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType(); 90 } 91 92 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) { 93 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 94 return FD->getParamDecl(Idx)->getSourceRange(); 95 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 96 return MD->parameters()[Idx]->getSourceRange(); 97 if (const auto *BD = dyn_cast<BlockDecl>(D)) 98 return BD->getParamDecl(Idx)->getSourceRange(); 99 return SourceRange(); 100 } 101 102 static QualType getFunctionOrMethodResultType(const Decl *D) { 103 if (const FunctionType *FnTy = D->getFunctionType()) 104 return cast<FunctionType>(FnTy)->getReturnType(); 105 return cast<ObjCMethodDecl>(D)->getReturnType(); 106 } 107 108 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) { 109 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 110 return FD->getReturnTypeSourceRange(); 111 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 112 return MD->getReturnTypeSourceRange(); 113 return SourceRange(); 114 } 115 116 static bool isFunctionOrMethodVariadic(const Decl *D) { 117 if (const FunctionType *FnTy = D->getFunctionType()) { 118 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy); 119 return proto->isVariadic(); 120 } 121 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) 122 return BD->isVariadic(); 123 124 return cast<ObjCMethodDecl>(D)->isVariadic(); 125 } 126 127 static bool isInstanceMethod(const Decl *D) { 128 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) 129 return MethodDecl->isInstance(); 130 return false; 131 } 132 133 static inline bool isNSStringType(QualType T, ASTContext &Ctx) { 134 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>(); 135 if (!PT) 136 return false; 137 138 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface(); 139 if (!Cls) 140 return false; 141 142 IdentifierInfo* ClsName = Cls->getIdentifier(); 143 144 // FIXME: Should we walk the chain of classes? 145 return ClsName == &Ctx.Idents.get("NSString") || 146 ClsName == &Ctx.Idents.get("NSMutableString"); 147 } 148 149 static inline bool isCFStringType(QualType T, ASTContext &Ctx) { 150 const PointerType *PT = T->getAs<PointerType>(); 151 if (!PT) 152 return false; 153 154 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>(); 155 if (!RT) 156 return false; 157 158 const RecordDecl *RD = RT->getDecl(); 159 if (RD->getTagKind() != TTK_Struct) 160 return false; 161 162 return RD->getIdentifier() == &Ctx.Idents.get("__CFString"); 163 } 164 165 static unsigned getNumAttributeArgs(const AttributeList &Attr) { 166 // FIXME: Include the type in the argument list. 167 return Attr.getNumArgs() + Attr.hasParsedType(); 168 } 169 170 template <typename Compare> 171 static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr, 172 unsigned Num, unsigned Diag, 173 Compare Comp) { 174 if (Comp(getNumAttributeArgs(Attr), Num)) { 175 S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num; 176 return false; 177 } 178 179 return true; 180 } 181 182 /// \brief Check if the attribute has exactly as many args as Num. May 183 /// output an error. 184 static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr, 185 unsigned Num) { 186 return checkAttributeNumArgsImpl(S, Attr, Num, 187 diag::err_attribute_wrong_number_arguments, 188 std::not_equal_to<unsigned>()); 189 } 190 191 /// \brief Check if the attribute has at least as many args as Num. May 192 /// output an error. 193 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr, 194 unsigned Num) { 195 return checkAttributeNumArgsImpl(S, Attr, Num, 196 diag::err_attribute_too_few_arguments, 197 std::less<unsigned>()); 198 } 199 200 /// \brief Check if the attribute has at most as many args as Num. May 201 /// output an error. 202 static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr, 203 unsigned Num) { 204 return checkAttributeNumArgsImpl(S, Attr, Num, 205 diag::err_attribute_too_many_arguments, 206 std::greater<unsigned>()); 207 } 208 209 /// \brief If Expr is a valid integer constant, get the value of the integer 210 /// expression and return success or failure. May output an error. 211 static bool checkUInt32Argument(Sema &S, const AttributeList &Attr, 212 const Expr *Expr, uint32_t &Val, 213 unsigned Idx = UINT_MAX) { 214 llvm::APSInt I(32); 215 if (Expr->isTypeDependent() || Expr->isValueDependent() || 216 !Expr->isIntegerConstantExpr(I, S.Context)) { 217 if (Idx != UINT_MAX) 218 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 219 << Attr.getName() << Idx << AANT_ArgumentIntegerConstant 220 << Expr->getSourceRange(); 221 else 222 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 223 << Attr.getName() << AANT_ArgumentIntegerConstant 224 << Expr->getSourceRange(); 225 return false; 226 } 227 228 if (!I.isIntN(32)) { 229 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large) 230 << I.toString(10, false) << 32 << /* Unsigned */ 1; 231 return false; 232 } 233 234 Val = (uint32_t)I.getZExtValue(); 235 return true; 236 } 237 238 /// \brief Diagnose mutually exclusive attributes when present on a given 239 /// declaration. Returns true if diagnosed. 240 template <typename AttrTy> 241 static bool checkAttrMutualExclusion(Sema &S, Decl *D, 242 const AttributeList &Attr) { 243 if (AttrTy *A = D->getAttr<AttrTy>()) { 244 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 245 << Attr.getName() << A; 246 return true; 247 } 248 return false; 249 } 250 251 /// \brief Check if IdxExpr is a valid parameter index for a function or 252 /// instance method D. May output an error. 253 /// 254 /// \returns true if IdxExpr is a valid index. 255 static bool checkFunctionOrMethodParameterIndex(Sema &S, const Decl *D, 256 const AttributeList &Attr, 257 unsigned AttrArgNum, 258 const Expr *IdxExpr, 259 uint64_t &Idx) { 260 assert(isFunctionOrMethod(D)); 261 262 // In C++ the implicit 'this' function parameter also counts. 263 // Parameters are counted from one. 264 bool HP = hasFunctionProto(D); 265 bool HasImplicitThisParam = isInstanceMethod(D); 266 bool IV = HP && isFunctionOrMethodVariadic(D); 267 unsigned NumParams = 268 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam; 269 270 llvm::APSInt IdxInt; 271 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() || 272 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) { 273 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 274 << Attr.getName() << AttrArgNum << AANT_ArgumentIntegerConstant 275 << IdxExpr->getSourceRange(); 276 return false; 277 } 278 279 Idx = IdxInt.getLimitedValue(); 280 if (Idx < 1 || (!IV && Idx > NumParams)) { 281 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 282 << Attr.getName() << AttrArgNum << IdxExpr->getSourceRange(); 283 return false; 284 } 285 Idx--; // Convert to zero-based. 286 if (HasImplicitThisParam) { 287 if (Idx == 0) { 288 S.Diag(Attr.getLoc(), 289 diag::err_attribute_invalid_implicit_this_argument) 290 << Attr.getName() << IdxExpr->getSourceRange(); 291 return false; 292 } 293 --Idx; 294 } 295 296 return true; 297 } 298 299 /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal. 300 /// If not emit an error and return false. If the argument is an identifier it 301 /// will emit an error with a fixit hint and treat it as if it was a string 302 /// literal. 303 bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr, 304 unsigned ArgNum, StringRef &Str, 305 SourceLocation *ArgLocation) { 306 // Look for identifiers. If we have one emit a hint to fix it to a literal. 307 if (Attr.isArgIdent(ArgNum)) { 308 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum); 309 Diag(Loc->Loc, diag::err_attribute_argument_type) 310 << Attr.getName() << AANT_ArgumentString 311 << FixItHint::CreateInsertion(Loc->Loc, "\"") 312 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(Loc->Loc), "\""); 313 Str = Loc->Ident->getName(); 314 if (ArgLocation) 315 *ArgLocation = Loc->Loc; 316 return true; 317 } 318 319 // Now check for an actual string literal. 320 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum); 321 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts()); 322 if (ArgLocation) 323 *ArgLocation = ArgExpr->getLocStart(); 324 325 if (!Literal || !Literal->isAscii()) { 326 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type) 327 << Attr.getName() << AANT_ArgumentString; 328 return false; 329 } 330 331 Str = Literal->getString(); 332 return true; 333 } 334 335 /// \brief Applies the given attribute to the Decl without performing any 336 /// additional semantic checking. 337 template <typename AttrType> 338 static void handleSimpleAttribute(Sema &S, Decl *D, 339 const AttributeList &Attr) { 340 D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context, 341 Attr.getAttributeSpellingListIndex())); 342 } 343 344 /// \brief Check if the passed-in expression is of type int or bool. 345 static bool isIntOrBool(Expr *Exp) { 346 QualType QT = Exp->getType(); 347 return QT->isBooleanType() || QT->isIntegerType(); 348 } 349 350 351 // Check to see if the type is a smart pointer of some kind. We assume 352 // it's a smart pointer if it defines both operator-> and operator*. 353 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) { 354 DeclContextLookupConstResult Res1 = RT->getDecl()->lookup( 355 S.Context.DeclarationNames.getCXXOperatorName(OO_Star)); 356 if (Res1.empty()) 357 return false; 358 359 DeclContextLookupConstResult Res2 = RT->getDecl()->lookup( 360 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow)); 361 if (Res2.empty()) 362 return false; 363 364 return true; 365 } 366 367 /// \brief Check if passed in Decl is a pointer type. 368 /// Note that this function may produce an error message. 369 /// \return true if the Decl is a pointer type; false otherwise 370 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D, 371 const AttributeList &Attr) { 372 const ValueDecl *vd = cast<ValueDecl>(D); 373 QualType QT = vd->getType(); 374 if (QT->isAnyPointerType()) 375 return true; 376 377 if (const RecordType *RT = QT->getAs<RecordType>()) { 378 // If it's an incomplete type, it could be a smart pointer; skip it. 379 // (We don't want to force template instantiation if we can avoid it, 380 // since that would alter the order in which templates are instantiated.) 381 if (RT->isIncompleteType()) 382 return true; 383 384 if (threadSafetyCheckIsSmartPointer(S, RT)) 385 return true; 386 } 387 388 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer) 389 << Attr.getName() << QT; 390 return false; 391 } 392 393 /// \brief Checks that the passed in QualType either is of RecordType or points 394 /// to RecordType. Returns the relevant RecordType, null if it does not exit. 395 static const RecordType *getRecordType(QualType QT) { 396 if (const RecordType *RT = QT->getAs<RecordType>()) 397 return RT; 398 399 // Now check if we point to record type. 400 if (const PointerType *PT = QT->getAs<PointerType>()) 401 return PT->getPointeeType()->getAs<RecordType>(); 402 403 return nullptr; 404 } 405 406 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) { 407 const RecordType *RT = getRecordType(Ty); 408 409 if (!RT) 410 return false; 411 412 // Don't check for the capability if the class hasn't been defined yet. 413 if (RT->isIncompleteType()) 414 return true; 415 416 // Allow smart pointers to be used as capability objects. 417 // FIXME -- Check the type that the smart pointer points to. 418 if (threadSafetyCheckIsSmartPointer(S, RT)) 419 return true; 420 421 // Check if the record itself has a capability. 422 RecordDecl *RD = RT->getDecl(); 423 if (RD->hasAttr<CapabilityAttr>()) 424 return true; 425 426 // Else check if any base classes have a capability. 427 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 428 CXXBasePaths BPaths(false, false); 429 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &P, 430 void *) { 431 return BS->getType()->getAs<RecordType>() 432 ->getDecl()->hasAttr<CapabilityAttr>(); 433 }, nullptr, BPaths)) 434 return true; 435 } 436 return false; 437 } 438 439 static bool checkTypedefTypeForCapability(QualType Ty) { 440 const auto *TD = Ty->getAs<TypedefType>(); 441 if (!TD) 442 return false; 443 444 TypedefNameDecl *TN = TD->getDecl(); 445 if (!TN) 446 return false; 447 448 return TN->hasAttr<CapabilityAttr>(); 449 } 450 451 static bool typeHasCapability(Sema &S, QualType Ty) { 452 if (checkTypedefTypeForCapability(Ty)) 453 return true; 454 455 if (checkRecordTypeForCapability(S, Ty)) 456 return true; 457 458 return false; 459 } 460 461 static bool isCapabilityExpr(Sema &S, const Expr *Ex) { 462 // Capability expressions are simple expressions involving the boolean logic 463 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once 464 // a DeclRefExpr is found, its type should be checked to determine whether it 465 // is a capability or not. 466 467 if (const auto *E = dyn_cast<DeclRefExpr>(Ex)) 468 return typeHasCapability(S, E->getType()); 469 else if (const auto *E = dyn_cast<CastExpr>(Ex)) 470 return isCapabilityExpr(S, E->getSubExpr()); 471 else if (const auto *E = dyn_cast<ParenExpr>(Ex)) 472 return isCapabilityExpr(S, E->getSubExpr()); 473 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) { 474 if (E->getOpcode() == UO_LNot) 475 return isCapabilityExpr(S, E->getSubExpr()); 476 return false; 477 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) { 478 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr) 479 return isCapabilityExpr(S, E->getLHS()) && 480 isCapabilityExpr(S, E->getRHS()); 481 return false; 482 } 483 484 return false; 485 } 486 487 /// \brief Checks that all attribute arguments, starting from Sidx, resolve to 488 /// a capability object. 489 /// \param Sidx The attribute argument index to start checking with. 490 /// \param ParamIdxOk Whether an argument can be indexing into a function 491 /// parameter list. 492 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D, 493 const AttributeList &Attr, 494 SmallVectorImpl<Expr *> &Args, 495 int Sidx = 0, 496 bool ParamIdxOk = false) { 497 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) { 498 Expr *ArgExp = Attr.getArgAsExpr(Idx); 499 500 if (ArgExp->isTypeDependent()) { 501 // FIXME -- need to check this again on template instantiation 502 Args.push_back(ArgExp); 503 continue; 504 } 505 506 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) { 507 if (StrLit->getLength() == 0 || 508 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) { 509 // Pass empty strings to the analyzer without warnings. 510 // Treat "*" as the universal lock. 511 Args.push_back(ArgExp); 512 continue; 513 } 514 515 // We allow constant strings to be used as a placeholder for expressions 516 // that are not valid C++ syntax, but warn that they are ignored. 517 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) << 518 Attr.getName(); 519 Args.push_back(ArgExp); 520 continue; 521 } 522 523 QualType ArgTy = ArgExp->getType(); 524 525 // A pointer to member expression of the form &MyClass::mu is treated 526 // specially -- we need to look at the type of the member. 527 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp)) 528 if (UOp->getOpcode() == UO_AddrOf) 529 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr())) 530 if (DRE->getDecl()->isCXXInstanceMember()) 531 ArgTy = DRE->getDecl()->getType(); 532 533 // First see if we can just cast to record type, or pointer to record type. 534 const RecordType *RT = getRecordType(ArgTy); 535 536 // Now check if we index into a record type function param. 537 if(!RT && ParamIdxOk) { 538 FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 539 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp); 540 if(FD && IL) { 541 unsigned int NumParams = FD->getNumParams(); 542 llvm::APInt ArgValue = IL->getValue(); 543 uint64_t ParamIdxFromOne = ArgValue.getZExtValue(); 544 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1; 545 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) { 546 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range) 547 << Attr.getName() << Idx + 1 << NumParams; 548 continue; 549 } 550 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType(); 551 } 552 } 553 554 // If the type does not have a capability, see if the components of the 555 // expression have capabilities. This allows for writing C code where the 556 // capability may be on the type, and the expression is a capability 557 // boolean logic expression. Eg) requires_capability(A || B && !C) 558 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp)) 559 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable) 560 << Attr.getName() << ArgTy; 561 562 Args.push_back(ArgExp); 563 } 564 } 565 566 //===----------------------------------------------------------------------===// 567 // Attribute Implementations 568 //===----------------------------------------------------------------------===// 569 570 static void handlePtGuardedVarAttr(Sema &S, Decl *D, 571 const AttributeList &Attr) { 572 if (!threadSafetyCheckIsPointer(S, D, Attr)) 573 return; 574 575 D->addAttr(::new (S.Context) 576 PtGuardedVarAttr(Attr.getRange(), S.Context, 577 Attr.getAttributeSpellingListIndex())); 578 } 579 580 static bool checkGuardedByAttrCommon(Sema &S, Decl *D, 581 const AttributeList &Attr, 582 Expr* &Arg) { 583 SmallVector<Expr*, 1> Args; 584 // check that all arguments are lockable objects 585 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 586 unsigned Size = Args.size(); 587 if (Size != 1) 588 return false; 589 590 Arg = Args[0]; 591 592 return true; 593 } 594 595 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) { 596 Expr *Arg = nullptr; 597 if (!checkGuardedByAttrCommon(S, D, Attr, Arg)) 598 return; 599 600 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg, 601 Attr.getAttributeSpellingListIndex())); 602 } 603 604 static void handlePtGuardedByAttr(Sema &S, Decl *D, 605 const AttributeList &Attr) { 606 Expr *Arg = nullptr; 607 if (!checkGuardedByAttrCommon(S, D, Attr, Arg)) 608 return; 609 610 if (!threadSafetyCheckIsPointer(S, D, Attr)) 611 return; 612 613 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(), 614 S.Context, Arg, 615 Attr.getAttributeSpellingListIndex())); 616 } 617 618 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, 619 const AttributeList &Attr, 620 SmallVectorImpl<Expr *> &Args) { 621 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 622 return false; 623 624 // Check that this attribute only applies to lockable types. 625 QualType QT = cast<ValueDecl>(D)->getType(); 626 if (!QT->isDependentType()) { 627 const RecordType *RT = getRecordType(QT); 628 if (!RT || !RT->getDecl()->hasAttr<CapabilityAttr>()) { 629 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable) 630 << Attr.getName(); 631 return false; 632 } 633 } 634 635 // Check that all arguments are lockable objects. 636 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 637 if (Args.empty()) 638 return false; 639 640 return true; 641 } 642 643 static void handleAcquiredAfterAttr(Sema &S, Decl *D, 644 const AttributeList &Attr) { 645 SmallVector<Expr*, 1> Args; 646 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args)) 647 return; 648 649 Expr **StartArg = &Args[0]; 650 D->addAttr(::new (S.Context) 651 AcquiredAfterAttr(Attr.getRange(), S.Context, 652 StartArg, Args.size(), 653 Attr.getAttributeSpellingListIndex())); 654 } 655 656 static void handleAcquiredBeforeAttr(Sema &S, Decl *D, 657 const AttributeList &Attr) { 658 SmallVector<Expr*, 1> Args; 659 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args)) 660 return; 661 662 Expr **StartArg = &Args[0]; 663 D->addAttr(::new (S.Context) 664 AcquiredBeforeAttr(Attr.getRange(), S.Context, 665 StartArg, Args.size(), 666 Attr.getAttributeSpellingListIndex())); 667 } 668 669 static bool checkLockFunAttrCommon(Sema &S, Decl *D, 670 const AttributeList &Attr, 671 SmallVectorImpl<Expr *> &Args) { 672 // zero or more arguments ok 673 // check that all arguments are lockable objects 674 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true); 675 676 return true; 677 } 678 679 static void handleAssertSharedLockAttr(Sema &S, Decl *D, 680 const AttributeList &Attr) { 681 SmallVector<Expr*, 1> Args; 682 if (!checkLockFunAttrCommon(S, D, Attr, Args)) 683 return; 684 685 unsigned Size = Args.size(); 686 Expr **StartArg = Size == 0 ? nullptr : &Args[0]; 687 D->addAttr(::new (S.Context) 688 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size, 689 Attr.getAttributeSpellingListIndex())); 690 } 691 692 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D, 693 const AttributeList &Attr) { 694 SmallVector<Expr*, 1> Args; 695 if (!checkLockFunAttrCommon(S, D, Attr, Args)) 696 return; 697 698 unsigned Size = Args.size(); 699 Expr **StartArg = Size == 0 ? nullptr : &Args[0]; 700 D->addAttr(::new (S.Context) 701 AssertExclusiveLockAttr(Attr.getRange(), S.Context, 702 StartArg, Size, 703 Attr.getAttributeSpellingListIndex())); 704 } 705 706 707 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, 708 const AttributeList &Attr, 709 SmallVectorImpl<Expr *> &Args) { 710 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 711 return false; 712 713 if (!isIntOrBool(Attr.getArgAsExpr(0))) { 714 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 715 << Attr.getName() << 1 << AANT_ArgumentIntOrBool; 716 return false; 717 } 718 719 // check that all arguments are lockable objects 720 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1); 721 722 return true; 723 } 724 725 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D, 726 const AttributeList &Attr) { 727 SmallVector<Expr*, 2> Args; 728 if (!checkTryLockFunAttrCommon(S, D, Attr, Args)) 729 return; 730 731 D->addAttr(::new (S.Context) 732 SharedTrylockFunctionAttr(Attr.getRange(), S.Context, 733 Attr.getArgAsExpr(0), 734 Args.data(), Args.size(), 735 Attr.getAttributeSpellingListIndex())); 736 } 737 738 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D, 739 const AttributeList &Attr) { 740 SmallVector<Expr*, 2> Args; 741 if (!checkTryLockFunAttrCommon(S, D, Attr, Args)) 742 return; 743 744 D->addAttr(::new (S.Context) 745 ExclusiveTrylockFunctionAttr(Attr.getRange(), S.Context, 746 Attr.getArgAsExpr(0), 747 Args.data(), Args.size(), 748 Attr.getAttributeSpellingListIndex())); 749 } 750 751 static void handleLockReturnedAttr(Sema &S, Decl *D, 752 const AttributeList &Attr) { 753 // check that the argument is lockable object 754 SmallVector<Expr*, 1> Args; 755 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 756 unsigned Size = Args.size(); 757 if (Size == 0) 758 return; 759 760 D->addAttr(::new (S.Context) 761 LockReturnedAttr(Attr.getRange(), S.Context, Args[0], 762 Attr.getAttributeSpellingListIndex())); 763 } 764 765 static void handleLocksExcludedAttr(Sema &S, Decl *D, 766 const AttributeList &Attr) { 767 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 768 return; 769 770 // check that all arguments are lockable objects 771 SmallVector<Expr*, 1> Args; 772 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 773 unsigned Size = Args.size(); 774 if (Size == 0) 775 return; 776 Expr **StartArg = &Args[0]; 777 778 D->addAttr(::new (S.Context) 779 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size, 780 Attr.getAttributeSpellingListIndex())); 781 } 782 783 static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) { 784 Expr *Cond = Attr.getArgAsExpr(0); 785 if (!Cond->isTypeDependent()) { 786 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond); 787 if (Converted.isInvalid()) 788 return; 789 Cond = Converted.get(); 790 } 791 792 StringRef Msg; 793 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg)) 794 return; 795 796 SmallVector<PartialDiagnosticAt, 8> Diags; 797 if (!Cond->isValueDependent() && 798 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D), 799 Diags)) { 800 S.Diag(Attr.getLoc(), diag::err_enable_if_never_constant_expr); 801 for (int I = 0, N = Diags.size(); I != N; ++I) 802 S.Diag(Diags[I].first, Diags[I].second); 803 return; 804 } 805 806 D->addAttr(::new (S.Context) 807 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg, 808 Attr.getAttributeSpellingListIndex())); 809 } 810 811 static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) { 812 ConsumableAttr::ConsumedState DefaultState; 813 814 if (Attr.isArgIdent(0)) { 815 IdentifierLoc *IL = Attr.getArgAsIdent(0); 816 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(), 817 DefaultState)) { 818 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) 819 << Attr.getName() << IL->Ident; 820 return; 821 } 822 } else { 823 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 824 << Attr.getName() << AANT_ArgumentIdentifier; 825 return; 826 } 827 828 D->addAttr(::new (S.Context) 829 ConsumableAttr(Attr.getRange(), S.Context, DefaultState, 830 Attr.getAttributeSpellingListIndex())); 831 } 832 833 834 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD, 835 const AttributeList &Attr) { 836 ASTContext &CurrContext = S.getASTContext(); 837 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType(); 838 839 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) { 840 if (!RD->hasAttr<ConsumableAttr>()) { 841 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) << 842 RD->getNameAsString(); 843 844 return false; 845 } 846 } 847 848 return true; 849 } 850 851 852 static void handleCallableWhenAttr(Sema &S, Decl *D, 853 const AttributeList &Attr) { 854 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 855 return; 856 857 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr)) 858 return; 859 860 SmallVector<CallableWhenAttr::ConsumedState, 3> States; 861 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) { 862 CallableWhenAttr::ConsumedState CallableState; 863 864 StringRef StateString; 865 SourceLocation Loc; 866 if (Attr.isArgIdent(ArgIndex)) { 867 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex); 868 StateString = Ident->Ident->getName(); 869 Loc = Ident->Loc; 870 } else { 871 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc)) 872 return; 873 } 874 875 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString, 876 CallableState)) { 877 S.Diag(Loc, diag::warn_attribute_type_not_supported) 878 << Attr.getName() << StateString; 879 return; 880 } 881 882 States.push_back(CallableState); 883 } 884 885 D->addAttr(::new (S.Context) 886 CallableWhenAttr(Attr.getRange(), S.Context, States.data(), 887 States.size(), Attr.getAttributeSpellingListIndex())); 888 } 889 890 891 static void handleParamTypestateAttr(Sema &S, Decl *D, 892 const AttributeList &Attr) { 893 ParamTypestateAttr::ConsumedState ParamState; 894 895 if (Attr.isArgIdent(0)) { 896 IdentifierLoc *Ident = Attr.getArgAsIdent(0); 897 StringRef StateString = Ident->Ident->getName(); 898 899 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString, 900 ParamState)) { 901 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) 902 << Attr.getName() << StateString; 903 return; 904 } 905 } else { 906 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << 907 Attr.getName() << AANT_ArgumentIdentifier; 908 return; 909 } 910 911 // FIXME: This check is currently being done in the analysis. It can be 912 // enabled here only after the parser propagates attributes at 913 // template specialization definition, not declaration. 914 //QualType ReturnType = cast<ParmVarDecl>(D)->getType(); 915 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); 916 // 917 //if (!RD || !RD->hasAttr<ConsumableAttr>()) { 918 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) << 919 // ReturnType.getAsString(); 920 // return; 921 //} 922 923 D->addAttr(::new (S.Context) 924 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState, 925 Attr.getAttributeSpellingListIndex())); 926 } 927 928 929 static void handleReturnTypestateAttr(Sema &S, Decl *D, 930 const AttributeList &Attr) { 931 ReturnTypestateAttr::ConsumedState ReturnState; 932 933 if (Attr.isArgIdent(0)) { 934 IdentifierLoc *IL = Attr.getArgAsIdent(0); 935 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(), 936 ReturnState)) { 937 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) 938 << Attr.getName() << IL->Ident; 939 return; 940 } 941 } else { 942 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << 943 Attr.getName() << AANT_ArgumentIdentifier; 944 return; 945 } 946 947 // FIXME: This check is currently being done in the analysis. It can be 948 // enabled here only after the parser propagates attributes at 949 // template specialization definition, not declaration. 950 //QualType ReturnType; 951 // 952 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) { 953 // ReturnType = Param->getType(); 954 // 955 //} else if (const CXXConstructorDecl *Constructor = 956 // dyn_cast<CXXConstructorDecl>(D)) { 957 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType(); 958 // 959 //} else { 960 // 961 // ReturnType = cast<FunctionDecl>(D)->getCallResultType(); 962 //} 963 // 964 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); 965 // 966 //if (!RD || !RD->hasAttr<ConsumableAttr>()) { 967 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) << 968 // ReturnType.getAsString(); 969 // return; 970 //} 971 972 D->addAttr(::new (S.Context) 973 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState, 974 Attr.getAttributeSpellingListIndex())); 975 } 976 977 978 static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) { 979 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr)) 980 return; 981 982 SetTypestateAttr::ConsumedState NewState; 983 if (Attr.isArgIdent(0)) { 984 IdentifierLoc *Ident = Attr.getArgAsIdent(0); 985 StringRef Param = Ident->Ident->getName(); 986 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) { 987 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) 988 << Attr.getName() << Param; 989 return; 990 } 991 } else { 992 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << 993 Attr.getName() << AANT_ArgumentIdentifier; 994 return; 995 } 996 997 D->addAttr(::new (S.Context) 998 SetTypestateAttr(Attr.getRange(), S.Context, NewState, 999 Attr.getAttributeSpellingListIndex())); 1000 } 1001 1002 static void handleTestTypestateAttr(Sema &S, Decl *D, 1003 const AttributeList &Attr) { 1004 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr)) 1005 return; 1006 1007 TestTypestateAttr::ConsumedState TestState; 1008 if (Attr.isArgIdent(0)) { 1009 IdentifierLoc *Ident = Attr.getArgAsIdent(0); 1010 StringRef Param = Ident->Ident->getName(); 1011 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) { 1012 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) 1013 << Attr.getName() << Param; 1014 return; 1015 } 1016 } else { 1017 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << 1018 Attr.getName() << AANT_ArgumentIdentifier; 1019 return; 1020 } 1021 1022 D->addAttr(::new (S.Context) 1023 TestTypestateAttr(Attr.getRange(), S.Context, TestState, 1024 Attr.getAttributeSpellingListIndex())); 1025 } 1026 1027 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D, 1028 const AttributeList &Attr) { 1029 // Remember this typedef decl, we will need it later for diagnostics. 1030 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D)); 1031 } 1032 1033 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1034 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 1035 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context, 1036 Attr.getAttributeSpellingListIndex())); 1037 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1038 // If the alignment is less than or equal to 8 bits, the packed attribute 1039 // has no effect. 1040 if (!FD->getType()->isDependentType() && 1041 !FD->getType()->isIncompleteType() && 1042 S.Context.getTypeAlign(FD->getType()) <= 8) 1043 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored_for_field_of_type) 1044 << Attr.getName() << FD->getType(); 1045 else 1046 FD->addAttr(::new (S.Context) 1047 PackedAttr(Attr.getRange(), S.Context, 1048 Attr.getAttributeSpellingListIndex())); 1049 } else 1050 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 1051 } 1052 1053 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) { 1054 // The IBOutlet/IBOutletCollection attributes only apply to instance 1055 // variables or properties of Objective-C classes. The outlet must also 1056 // have an object reference type. 1057 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) { 1058 if (!VD->getType()->getAs<ObjCObjectPointerType>()) { 1059 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type) 1060 << Attr.getName() << VD->getType() << 0; 1061 return false; 1062 } 1063 } 1064 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) { 1065 if (!PD->getType()->getAs<ObjCObjectPointerType>()) { 1066 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type) 1067 << Attr.getName() << PD->getType() << 1; 1068 return false; 1069 } 1070 } 1071 else { 1072 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName(); 1073 return false; 1074 } 1075 1076 return true; 1077 } 1078 1079 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) { 1080 if (!checkIBOutletCommon(S, D, Attr)) 1081 return; 1082 1083 D->addAttr(::new (S.Context) 1084 IBOutletAttr(Attr.getRange(), S.Context, 1085 Attr.getAttributeSpellingListIndex())); 1086 } 1087 1088 static void handleIBOutletCollection(Sema &S, Decl *D, 1089 const AttributeList &Attr) { 1090 1091 // The iboutletcollection attribute can have zero or one arguments. 1092 if (Attr.getNumArgs() > 1) { 1093 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 1094 << Attr.getName() << 1; 1095 return; 1096 } 1097 1098 if (!checkIBOutletCommon(S, D, Attr)) 1099 return; 1100 1101 ParsedType PT; 1102 1103 if (Attr.hasParsedType()) 1104 PT = Attr.getTypeArg(); 1105 else { 1106 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(), 1107 S.getScopeForContext(D->getDeclContext()->getParent())); 1108 if (!PT) { 1109 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject"; 1110 return; 1111 } 1112 } 1113 1114 TypeSourceInfo *QTLoc = nullptr; 1115 QualType QT = S.GetTypeFromParser(PT, &QTLoc); 1116 if (!QTLoc) 1117 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc()); 1118 1119 // Diagnose use of non-object type in iboutletcollection attribute. 1120 // FIXME. Gnu attribute extension ignores use of builtin types in 1121 // attributes. So, __attribute__((iboutletcollection(char))) will be 1122 // treated as __attribute__((iboutletcollection())). 1123 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) { 1124 S.Diag(Attr.getLoc(), 1125 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype 1126 : diag::err_iboutletcollection_type) << QT; 1127 return; 1128 } 1129 1130 D->addAttr(::new (S.Context) 1131 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc, 1132 Attr.getAttributeSpellingListIndex())); 1133 } 1134 1135 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) { 1136 if (RefOkay) { 1137 if (T->isReferenceType()) 1138 return true; 1139 } else { 1140 T = T.getNonReferenceType(); 1141 } 1142 1143 // The nonnull attribute, and other similar attributes, can be applied to a 1144 // transparent union that contains a pointer type. 1145 if (const RecordType *UT = T->getAsUnionType()) { 1146 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) { 1147 RecordDecl *UD = UT->getDecl(); 1148 for (const auto *I : UD->fields()) { 1149 QualType QT = I->getType(); 1150 if (QT->isAnyPointerType() || QT->isBlockPointerType()) 1151 return true; 1152 } 1153 } 1154 } 1155 1156 return T->isAnyPointerType() || T->isBlockPointerType(); 1157 } 1158 1159 static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr, 1160 SourceRange AttrParmRange, 1161 SourceRange TypeRange, 1162 bool isReturnValue = false) { 1163 if (!S.isValidPointerAttrType(T)) { 1164 S.Diag(Attr.getLoc(), isReturnValue 1165 ? diag::warn_attribute_return_pointers_only 1166 : diag::warn_attribute_pointers_only) 1167 << Attr.getName() << AttrParmRange << TypeRange; 1168 return false; 1169 } 1170 return true; 1171 } 1172 1173 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1174 SmallVector<unsigned, 8> NonNullArgs; 1175 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) { 1176 Expr *Ex = Attr.getArgAsExpr(I); 1177 uint64_t Idx; 1178 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx)) 1179 return; 1180 1181 // Is the function argument a pointer type? 1182 if (Idx < getFunctionOrMethodNumParams(D) && 1183 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr, 1184 Ex->getSourceRange(), 1185 getFunctionOrMethodParamRange(D, Idx))) 1186 continue; 1187 1188 NonNullArgs.push_back(Idx); 1189 } 1190 1191 // If no arguments were specified to __attribute__((nonnull)) then all pointer 1192 // arguments have a nonnull attribute; warn if there aren't any. Skip this 1193 // check if the attribute came from a macro expansion or a template 1194 // instantiation. 1195 if (NonNullArgs.empty() && Attr.getLoc().isFileID() && 1196 S.ActiveTemplateInstantiations.empty()) { 1197 bool AnyPointers = isFunctionOrMethodVariadic(D); 1198 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); 1199 I != E && !AnyPointers; ++I) { 1200 QualType T = getFunctionOrMethodParamType(D, I); 1201 if (T->isDependentType() || S.isValidPointerAttrType(T)) 1202 AnyPointers = true; 1203 } 1204 1205 if (!AnyPointers) 1206 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers); 1207 } 1208 1209 unsigned *Start = NonNullArgs.data(); 1210 unsigned Size = NonNullArgs.size(); 1211 llvm::array_pod_sort(Start, Start + Size); 1212 D->addAttr(::new (S.Context) 1213 NonNullAttr(Attr.getRange(), S.Context, Start, Size, 1214 Attr.getAttributeSpellingListIndex())); 1215 } 1216 1217 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D, 1218 const AttributeList &Attr) { 1219 if (Attr.getNumArgs() > 0) { 1220 if (D->getFunctionType()) { 1221 handleNonNullAttr(S, D, Attr); 1222 } else { 1223 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args) 1224 << D->getSourceRange(); 1225 } 1226 return; 1227 } 1228 1229 // Is the argument a pointer type? 1230 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(), 1231 D->getSourceRange())) 1232 return; 1233 1234 D->addAttr(::new (S.Context) 1235 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0, 1236 Attr.getAttributeSpellingListIndex())); 1237 } 1238 1239 static void handleReturnsNonNullAttr(Sema &S, Decl *D, 1240 const AttributeList &Attr) { 1241 QualType ResultType = getFunctionOrMethodResultType(D); 1242 SourceRange SR = getFunctionOrMethodResultSourceRange(D); 1243 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR, 1244 /* isReturnValue */ true)) 1245 return; 1246 1247 D->addAttr(::new (S.Context) 1248 ReturnsNonNullAttr(Attr.getRange(), S.Context, 1249 Attr.getAttributeSpellingListIndex())); 1250 } 1251 1252 static void handleAssumeAlignedAttr(Sema &S, Decl *D, 1253 const AttributeList &Attr) { 1254 Expr *E = Attr.getArgAsExpr(0), 1255 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr; 1256 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE, 1257 Attr.getAttributeSpellingListIndex()); 1258 } 1259 1260 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, 1261 Expr *OE, unsigned SpellingListIndex) { 1262 QualType ResultType = getFunctionOrMethodResultType(D); 1263 SourceRange SR = getFunctionOrMethodResultSourceRange(D); 1264 1265 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex); 1266 SourceLocation AttrLoc = AttrRange.getBegin(); 1267 1268 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) { 1269 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only) 1270 << &TmpAttr << AttrRange << SR; 1271 return; 1272 } 1273 1274 if (!E->isValueDependent()) { 1275 llvm::APSInt I(64); 1276 if (!E->isIntegerConstantExpr(I, Context)) { 1277 if (OE) 1278 Diag(AttrLoc, diag::err_attribute_argument_n_type) 1279 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant 1280 << E->getSourceRange(); 1281 else 1282 Diag(AttrLoc, diag::err_attribute_argument_type) 1283 << &TmpAttr << AANT_ArgumentIntegerConstant 1284 << E->getSourceRange(); 1285 return; 1286 } 1287 1288 if (!I.isPowerOf2()) { 1289 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 1290 << E->getSourceRange(); 1291 return; 1292 } 1293 } 1294 1295 if (OE) { 1296 if (!OE->isValueDependent()) { 1297 llvm::APSInt I(64); 1298 if (!OE->isIntegerConstantExpr(I, Context)) { 1299 Diag(AttrLoc, diag::err_attribute_argument_n_type) 1300 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant 1301 << OE->getSourceRange(); 1302 return; 1303 } 1304 } 1305 } 1306 1307 D->addAttr(::new (Context) 1308 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex)); 1309 } 1310 1311 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) { 1312 // This attribute must be applied to a function declaration. The first 1313 // argument to the attribute must be an identifier, the name of the resource, 1314 // for example: malloc. The following arguments must be argument indexes, the 1315 // arguments must be of integer type for Returns, otherwise of pointer type. 1316 // The difference between Holds and Takes is that a pointer may still be used 1317 // after being held. free() should be __attribute((ownership_takes)), whereas 1318 // a list append function may well be __attribute((ownership_holds)). 1319 1320 if (!AL.isArgIdent(0)) { 1321 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 1322 << AL.getName() << 1 << AANT_ArgumentIdentifier; 1323 return; 1324 } 1325 1326 // Figure out our Kind. 1327 OwnershipAttr::OwnershipKind K = 1328 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0, 1329 AL.getAttributeSpellingListIndex()).getOwnKind(); 1330 1331 // Check arguments. 1332 switch (K) { 1333 case OwnershipAttr::Takes: 1334 case OwnershipAttr::Holds: 1335 if (AL.getNumArgs() < 2) { 1336 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) 1337 << AL.getName() << 2; 1338 return; 1339 } 1340 break; 1341 case OwnershipAttr::Returns: 1342 if (AL.getNumArgs() > 2) { 1343 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) 1344 << AL.getName() << 1; 1345 return; 1346 } 1347 break; 1348 } 1349 1350 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident; 1351 1352 // Normalize the argument, __foo__ becomes foo. 1353 StringRef ModuleName = Module->getName(); 1354 if (ModuleName.startswith("__") && ModuleName.endswith("__") && 1355 ModuleName.size() > 4) { 1356 ModuleName = ModuleName.drop_front(2).drop_back(2); 1357 Module = &S.PP.getIdentifierTable().get(ModuleName); 1358 } 1359 1360 SmallVector<unsigned, 8> OwnershipArgs; 1361 for (unsigned i = 1; i < AL.getNumArgs(); ++i) { 1362 Expr *Ex = AL.getArgAsExpr(i); 1363 uint64_t Idx; 1364 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx)) 1365 return; 1366 1367 // Is the function argument a pointer type? 1368 QualType T = getFunctionOrMethodParamType(D, Idx); 1369 int Err = -1; // No error 1370 switch (K) { 1371 case OwnershipAttr::Takes: 1372 case OwnershipAttr::Holds: 1373 if (!T->isAnyPointerType() && !T->isBlockPointerType()) 1374 Err = 0; 1375 break; 1376 case OwnershipAttr::Returns: 1377 if (!T->isIntegerType()) 1378 Err = 1; 1379 break; 1380 } 1381 if (-1 != Err) { 1382 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err 1383 << Ex->getSourceRange(); 1384 return; 1385 } 1386 1387 // Check we don't have a conflict with another ownership attribute. 1388 for (const auto *I : D->specific_attrs<OwnershipAttr>()) { 1389 // Cannot have two ownership attributes of different kinds for the same 1390 // index. 1391 if (I->getOwnKind() != K && I->args_end() != 1392 std::find(I->args_begin(), I->args_end(), Idx)) { 1393 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) 1394 << AL.getName() << I; 1395 return; 1396 } else if (K == OwnershipAttr::Returns && 1397 I->getOwnKind() == OwnershipAttr::Returns) { 1398 // A returns attribute conflicts with any other returns attribute using 1399 // a different index. Note, diagnostic reporting is 1-based, but stored 1400 // argument indexes are 0-based. 1401 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) { 1402 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch) 1403 << *(I->args_begin()) + 1; 1404 if (I->args_size()) 1405 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch) 1406 << (unsigned)Idx + 1 << Ex->getSourceRange(); 1407 return; 1408 } 1409 } 1410 } 1411 OwnershipArgs.push_back(Idx); 1412 } 1413 1414 unsigned* start = OwnershipArgs.data(); 1415 unsigned size = OwnershipArgs.size(); 1416 llvm::array_pod_sort(start, start + size); 1417 1418 D->addAttr(::new (S.Context) 1419 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size, 1420 AL.getAttributeSpellingListIndex())); 1421 } 1422 1423 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1424 // Check the attribute arguments. 1425 if (Attr.getNumArgs() > 1) { 1426 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 1427 << Attr.getName() << 1; 1428 return; 1429 } 1430 1431 NamedDecl *nd = cast<NamedDecl>(D); 1432 1433 // gcc rejects 1434 // class c { 1435 // static int a __attribute__((weakref ("v2"))); 1436 // static int b() __attribute__((weakref ("f3"))); 1437 // }; 1438 // and ignores the attributes of 1439 // void f(void) { 1440 // static int a __attribute__((weakref ("v2"))); 1441 // } 1442 // we reject them 1443 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext(); 1444 if (!Ctx->isFileContext()) { 1445 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context) 1446 << nd; 1447 return; 1448 } 1449 1450 // The GCC manual says 1451 // 1452 // At present, a declaration to which `weakref' is attached can only 1453 // be `static'. 1454 // 1455 // It also says 1456 // 1457 // Without a TARGET, 1458 // given as an argument to `weakref' or to `alias', `weakref' is 1459 // equivalent to `weak'. 1460 // 1461 // gcc 4.4.1 will accept 1462 // int a7 __attribute__((weakref)); 1463 // as 1464 // int a7 __attribute__((weak)); 1465 // This looks like a bug in gcc. We reject that for now. We should revisit 1466 // it if this behaviour is actually used. 1467 1468 // GCC rejects 1469 // static ((alias ("y"), weakref)). 1470 // Should we? How to check that weakref is before or after alias? 1471 1472 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead 1473 // of transforming it into an AliasAttr. The WeakRefAttr never uses the 1474 // StringRef parameter it was given anyway. 1475 StringRef Str; 1476 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 1477 // GCC will accept anything as the argument of weakref. Should we 1478 // check for an existing decl? 1479 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str, 1480 Attr.getAttributeSpellingListIndex())); 1481 1482 D->addAttr(::new (S.Context) 1483 WeakRefAttr(Attr.getRange(), S.Context, 1484 Attr.getAttributeSpellingListIndex())); 1485 } 1486 1487 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1488 StringRef Str; 1489 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 1490 return; 1491 1492 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 1493 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin); 1494 return; 1495 } 1496 1497 // FIXME: check if target symbol exists in current file 1498 1499 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str, 1500 Attr.getAttributeSpellingListIndex())); 1501 } 1502 1503 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1504 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr)) 1505 return; 1506 1507 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context, 1508 Attr.getAttributeSpellingListIndex())); 1509 } 1510 1511 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1512 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr)) 1513 return; 1514 1515 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context, 1516 Attr.getAttributeSpellingListIndex())); 1517 } 1518 1519 static void handleTLSModelAttr(Sema &S, Decl *D, 1520 const AttributeList &Attr) { 1521 StringRef Model; 1522 SourceLocation LiteralLoc; 1523 // Check that it is a string. 1524 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc)) 1525 return; 1526 1527 // Check that the value. 1528 if (Model != "global-dynamic" && Model != "local-dynamic" 1529 && Model != "initial-exec" && Model != "local-exec") { 1530 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg); 1531 return; 1532 } 1533 1534 D->addAttr(::new (S.Context) 1535 TLSModelAttr(Attr.getRange(), S.Context, Model, 1536 Attr.getAttributeSpellingListIndex())); 1537 } 1538 1539 static void handleMallocAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1540 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 1541 QualType RetTy = FD->getReturnType(); 1542 if (RetTy->isAnyPointerType() || RetTy->isBlockPointerType()) { 1543 D->addAttr(::new (S.Context) 1544 MallocAttr(Attr.getRange(), S.Context, 1545 Attr.getAttributeSpellingListIndex())); 1546 return; 1547 } 1548 } 1549 1550 S.Diag(Attr.getLoc(), diag::warn_attribute_malloc_pointer_only); 1551 } 1552 1553 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1554 if (S.LangOpts.CPlusPlus) { 1555 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang) 1556 << Attr.getName() << AttributeLangSupport::Cpp; 1557 return; 1558 } 1559 1560 D->addAttr(::new (S.Context) CommonAttr(Attr.getRange(), S.Context, 1561 Attr.getAttributeSpellingListIndex())); 1562 } 1563 1564 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) { 1565 if (hasDeclarator(D)) return; 1566 1567 if (S.CheckNoReturnAttr(attr)) return; 1568 1569 if (!isa<ObjCMethodDecl>(D)) { 1570 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type) 1571 << attr.getName() << ExpectedFunctionOrMethod; 1572 return; 1573 } 1574 1575 D->addAttr(::new (S.Context) 1576 NoReturnAttr(attr.getRange(), S.Context, 1577 attr.getAttributeSpellingListIndex())); 1578 } 1579 1580 bool Sema::CheckNoReturnAttr(const AttributeList &attr) { 1581 if (!checkAttributeNumArgs(*this, attr, 0)) { 1582 attr.setInvalid(); 1583 return true; 1584 } 1585 1586 return false; 1587 } 1588 1589 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, 1590 const AttributeList &Attr) { 1591 1592 // The checking path for 'noreturn' and 'analyzer_noreturn' are different 1593 // because 'analyzer_noreturn' does not impact the type. 1594 if (!isFunctionOrMethod(D) && !isa<BlockDecl>(D)) { 1595 ValueDecl *VD = dyn_cast<ValueDecl>(D); 1596 if (!VD || (!VD->getType()->isBlockPointerType() && 1597 !VD->getType()->isFunctionPointerType())) { 1598 S.Diag(Attr.getLoc(), 1599 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type 1600 : diag::warn_attribute_wrong_decl_type) 1601 << Attr.getName() << ExpectedFunctionMethodOrBlock; 1602 return; 1603 } 1604 } 1605 1606 D->addAttr(::new (S.Context) 1607 AnalyzerNoReturnAttr(Attr.getRange(), S.Context, 1608 Attr.getAttributeSpellingListIndex())); 1609 } 1610 1611 // PS3 PPU-specific. 1612 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1613 /* 1614 Returning a Vector Class in Registers 1615 1616 According to the PPU ABI specifications, a class with a single member of 1617 vector type is returned in memory when used as the return value of a function. 1618 This results in inefficient code when implementing vector classes. To return 1619 the value in a single vector register, add the vecreturn attribute to the 1620 class definition. This attribute is also applicable to struct types. 1621 1622 Example: 1623 1624 struct Vector 1625 { 1626 __vector float xyzw; 1627 } __attribute__((vecreturn)); 1628 1629 Vector Add(Vector lhs, Vector rhs) 1630 { 1631 Vector result; 1632 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw); 1633 return result; // This will be returned in a register 1634 } 1635 */ 1636 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) { 1637 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A; 1638 return; 1639 } 1640 1641 RecordDecl *record = cast<RecordDecl>(D); 1642 int count = 0; 1643 1644 if (!isa<CXXRecordDecl>(record)) { 1645 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member); 1646 return; 1647 } 1648 1649 if (!cast<CXXRecordDecl>(record)->isPOD()) { 1650 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record); 1651 return; 1652 } 1653 1654 for (const auto *I : record->fields()) { 1655 if ((count == 1) || !I->getType()->isVectorType()) { 1656 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member); 1657 return; 1658 } 1659 count++; 1660 } 1661 1662 D->addAttr(::new (S.Context) 1663 VecReturnAttr(Attr.getRange(), S.Context, 1664 Attr.getAttributeSpellingListIndex())); 1665 } 1666 1667 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D, 1668 const AttributeList &Attr) { 1669 if (isa<ParmVarDecl>(D)) { 1670 // [[carries_dependency]] can only be applied to a parameter if it is a 1671 // parameter of a function declaration or lambda. 1672 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) { 1673 S.Diag(Attr.getLoc(), 1674 diag::err_carries_dependency_param_not_function_decl); 1675 return; 1676 } 1677 } 1678 1679 D->addAttr(::new (S.Context) CarriesDependencyAttr( 1680 Attr.getRange(), S.Context, 1681 Attr.getAttributeSpellingListIndex())); 1682 } 1683 1684 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1685 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1686 if (VD->hasLocalStorage()) { 1687 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 1688 return; 1689 } 1690 } else if (!isFunctionOrMethod(D)) { 1691 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 1692 << Attr.getName() << ExpectedVariableOrFunction; 1693 return; 1694 } 1695 1696 D->addAttr(::new (S.Context) 1697 UsedAttr(Attr.getRange(), S.Context, 1698 Attr.getAttributeSpellingListIndex())); 1699 } 1700 1701 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1702 uint32_t priority = ConstructorAttr::DefaultPriority; 1703 if (Attr.getNumArgs() && 1704 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority)) 1705 return; 1706 1707 D->addAttr(::new (S.Context) 1708 ConstructorAttr(Attr.getRange(), S.Context, priority, 1709 Attr.getAttributeSpellingListIndex())); 1710 } 1711 1712 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1713 uint32_t priority = DestructorAttr::DefaultPriority; 1714 if (Attr.getNumArgs() && 1715 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority)) 1716 return; 1717 1718 D->addAttr(::new (S.Context) 1719 DestructorAttr(Attr.getRange(), S.Context, priority, 1720 Attr.getAttributeSpellingListIndex())); 1721 } 1722 1723 template <typename AttrTy> 1724 static void handleAttrWithMessage(Sema &S, Decl *D, 1725 const AttributeList &Attr) { 1726 // Handle the case where the attribute has a text message. 1727 StringRef Str; 1728 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 1729 return; 1730 1731 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str, 1732 Attr.getAttributeSpellingListIndex())); 1733 } 1734 1735 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D, 1736 const AttributeList &Attr) { 1737 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) { 1738 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition) 1739 << Attr.getName() << Attr.getRange(); 1740 return; 1741 } 1742 1743 D->addAttr(::new (S.Context) 1744 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context, 1745 Attr.getAttributeSpellingListIndex())); 1746 } 1747 1748 static bool checkAvailabilityAttr(Sema &S, SourceRange Range, 1749 IdentifierInfo *Platform, 1750 VersionTuple Introduced, 1751 VersionTuple Deprecated, 1752 VersionTuple Obsoleted) { 1753 StringRef PlatformName 1754 = AvailabilityAttr::getPrettyPlatformName(Platform->getName()); 1755 if (PlatformName.empty()) 1756 PlatformName = Platform->getName(); 1757 1758 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all 1759 // of these steps are needed). 1760 if (!Introduced.empty() && !Deprecated.empty() && 1761 !(Introduced <= Deprecated)) { 1762 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 1763 << 1 << PlatformName << Deprecated.getAsString() 1764 << 0 << Introduced.getAsString(); 1765 return true; 1766 } 1767 1768 if (!Introduced.empty() && !Obsoleted.empty() && 1769 !(Introduced <= Obsoleted)) { 1770 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 1771 << 2 << PlatformName << Obsoleted.getAsString() 1772 << 0 << Introduced.getAsString(); 1773 return true; 1774 } 1775 1776 if (!Deprecated.empty() && !Obsoleted.empty() && 1777 !(Deprecated <= Obsoleted)) { 1778 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 1779 << 2 << PlatformName << Obsoleted.getAsString() 1780 << 1 << Deprecated.getAsString(); 1781 return true; 1782 } 1783 1784 return false; 1785 } 1786 1787 /// \brief Check whether the two versions match. 1788 /// 1789 /// If either version tuple is empty, then they are assumed to match. If 1790 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y. 1791 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y, 1792 bool BeforeIsOkay) { 1793 if (X.empty() || Y.empty()) 1794 return true; 1795 1796 if (X == Y) 1797 return true; 1798 1799 if (BeforeIsOkay && X < Y) 1800 return true; 1801 1802 return false; 1803 } 1804 1805 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range, 1806 IdentifierInfo *Platform, 1807 VersionTuple Introduced, 1808 VersionTuple Deprecated, 1809 VersionTuple Obsoleted, 1810 bool IsUnavailable, 1811 StringRef Message, 1812 bool Override, 1813 unsigned AttrSpellingListIndex) { 1814 VersionTuple MergedIntroduced = Introduced; 1815 VersionTuple MergedDeprecated = Deprecated; 1816 VersionTuple MergedObsoleted = Obsoleted; 1817 bool FoundAny = false; 1818 1819 if (D->hasAttrs()) { 1820 AttrVec &Attrs = D->getAttrs(); 1821 for (unsigned i = 0, e = Attrs.size(); i != e;) { 1822 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]); 1823 if (!OldAA) { 1824 ++i; 1825 continue; 1826 } 1827 1828 IdentifierInfo *OldPlatform = OldAA->getPlatform(); 1829 if (OldPlatform != Platform) { 1830 ++i; 1831 continue; 1832 } 1833 1834 FoundAny = true; 1835 VersionTuple OldIntroduced = OldAA->getIntroduced(); 1836 VersionTuple OldDeprecated = OldAA->getDeprecated(); 1837 VersionTuple OldObsoleted = OldAA->getObsoleted(); 1838 bool OldIsUnavailable = OldAA->getUnavailable(); 1839 1840 if (!versionsMatch(OldIntroduced, Introduced, Override) || 1841 !versionsMatch(Deprecated, OldDeprecated, Override) || 1842 !versionsMatch(Obsoleted, OldObsoleted, Override) || 1843 !(OldIsUnavailable == IsUnavailable || 1844 (Override && !OldIsUnavailable && IsUnavailable))) { 1845 if (Override) { 1846 int Which = -1; 1847 VersionTuple FirstVersion; 1848 VersionTuple SecondVersion; 1849 if (!versionsMatch(OldIntroduced, Introduced, Override)) { 1850 Which = 0; 1851 FirstVersion = OldIntroduced; 1852 SecondVersion = Introduced; 1853 } else if (!versionsMatch(Deprecated, OldDeprecated, Override)) { 1854 Which = 1; 1855 FirstVersion = Deprecated; 1856 SecondVersion = OldDeprecated; 1857 } else if (!versionsMatch(Obsoleted, OldObsoleted, Override)) { 1858 Which = 2; 1859 FirstVersion = Obsoleted; 1860 SecondVersion = OldObsoleted; 1861 } 1862 1863 if (Which == -1) { 1864 Diag(OldAA->getLocation(), 1865 diag::warn_mismatched_availability_override_unavail) 1866 << AvailabilityAttr::getPrettyPlatformName(Platform->getName()); 1867 } else { 1868 Diag(OldAA->getLocation(), 1869 diag::warn_mismatched_availability_override) 1870 << Which 1871 << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) 1872 << FirstVersion.getAsString() << SecondVersion.getAsString(); 1873 } 1874 Diag(Range.getBegin(), diag::note_overridden_method); 1875 } else { 1876 Diag(OldAA->getLocation(), diag::warn_mismatched_availability); 1877 Diag(Range.getBegin(), diag::note_previous_attribute); 1878 } 1879 1880 Attrs.erase(Attrs.begin() + i); 1881 --e; 1882 continue; 1883 } 1884 1885 VersionTuple MergedIntroduced2 = MergedIntroduced; 1886 VersionTuple MergedDeprecated2 = MergedDeprecated; 1887 VersionTuple MergedObsoleted2 = MergedObsoleted; 1888 1889 if (MergedIntroduced2.empty()) 1890 MergedIntroduced2 = OldIntroduced; 1891 if (MergedDeprecated2.empty()) 1892 MergedDeprecated2 = OldDeprecated; 1893 if (MergedObsoleted2.empty()) 1894 MergedObsoleted2 = OldObsoleted; 1895 1896 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform, 1897 MergedIntroduced2, MergedDeprecated2, 1898 MergedObsoleted2)) { 1899 Attrs.erase(Attrs.begin() + i); 1900 --e; 1901 continue; 1902 } 1903 1904 MergedIntroduced = MergedIntroduced2; 1905 MergedDeprecated = MergedDeprecated2; 1906 MergedObsoleted = MergedObsoleted2; 1907 ++i; 1908 } 1909 } 1910 1911 if (FoundAny && 1912 MergedIntroduced == Introduced && 1913 MergedDeprecated == Deprecated && 1914 MergedObsoleted == Obsoleted) 1915 return nullptr; 1916 1917 // Only create a new attribute if !Override, but we want to do 1918 // the checking. 1919 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced, 1920 MergedDeprecated, MergedObsoleted) && 1921 !Override) { 1922 return ::new (Context) AvailabilityAttr(Range, Context, Platform, 1923 Introduced, Deprecated, 1924 Obsoleted, IsUnavailable, Message, 1925 AttrSpellingListIndex); 1926 } 1927 return nullptr; 1928 } 1929 1930 static void handleAvailabilityAttr(Sema &S, Decl *D, 1931 const AttributeList &Attr) { 1932 if (!checkAttributeNumArgs(S, Attr, 1)) 1933 return; 1934 IdentifierLoc *Platform = Attr.getArgAsIdent(0); 1935 unsigned Index = Attr.getAttributeSpellingListIndex(); 1936 1937 IdentifierInfo *II = Platform->Ident; 1938 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty()) 1939 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform) 1940 << Platform->Ident; 1941 1942 NamedDecl *ND = dyn_cast<NamedDecl>(D); 1943 if (!ND) { 1944 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 1945 return; 1946 } 1947 1948 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced(); 1949 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated(); 1950 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted(); 1951 bool IsUnavailable = Attr.getUnavailableLoc().isValid(); 1952 StringRef Str; 1953 if (const StringLiteral *SE = 1954 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr())) 1955 Str = SE->getString(); 1956 1957 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II, 1958 Introduced.Version, 1959 Deprecated.Version, 1960 Obsoleted.Version, 1961 IsUnavailable, Str, 1962 /*Override=*/false, 1963 Index); 1964 if (NewAttr) 1965 D->addAttr(NewAttr); 1966 } 1967 1968 template <class T> 1969 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range, 1970 typename T::VisibilityType value, 1971 unsigned attrSpellingListIndex) { 1972 T *existingAttr = D->getAttr<T>(); 1973 if (existingAttr) { 1974 typename T::VisibilityType existingValue = existingAttr->getVisibility(); 1975 if (existingValue == value) 1976 return nullptr; 1977 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility); 1978 S.Diag(range.getBegin(), diag::note_previous_attribute); 1979 D->dropAttr<T>(); 1980 } 1981 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex); 1982 } 1983 1984 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range, 1985 VisibilityAttr::VisibilityType Vis, 1986 unsigned AttrSpellingListIndex) { 1987 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis, 1988 AttrSpellingListIndex); 1989 } 1990 1991 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range, 1992 TypeVisibilityAttr::VisibilityType Vis, 1993 unsigned AttrSpellingListIndex) { 1994 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis, 1995 AttrSpellingListIndex); 1996 } 1997 1998 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr, 1999 bool isTypeVisibility) { 2000 // Visibility attributes don't mean anything on a typedef. 2001 if (isa<TypedefNameDecl>(D)) { 2002 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored) 2003 << Attr.getName(); 2004 return; 2005 } 2006 2007 // 'type_visibility' can only go on a type or namespace. 2008 if (isTypeVisibility && 2009 !(isa<TagDecl>(D) || 2010 isa<ObjCInterfaceDecl>(D) || 2011 isa<NamespaceDecl>(D))) { 2012 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type) 2013 << Attr.getName() << ExpectedTypeOrNamespace; 2014 return; 2015 } 2016 2017 // Check that the argument is a string literal. 2018 StringRef TypeStr; 2019 SourceLocation LiteralLoc; 2020 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc)) 2021 return; 2022 2023 VisibilityAttr::VisibilityType type; 2024 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) { 2025 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) 2026 << Attr.getName() << TypeStr; 2027 return; 2028 } 2029 2030 // Complain about attempts to use protected visibility on targets 2031 // (like Darwin) that don't support it. 2032 if (type == VisibilityAttr::Protected && 2033 !S.Context.getTargetInfo().hasProtectedVisibility()) { 2034 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility); 2035 type = VisibilityAttr::Default; 2036 } 2037 2038 unsigned Index = Attr.getAttributeSpellingListIndex(); 2039 clang::Attr *newAttr; 2040 if (isTypeVisibility) { 2041 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(), 2042 (TypeVisibilityAttr::VisibilityType) type, 2043 Index); 2044 } else { 2045 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index); 2046 } 2047 if (newAttr) 2048 D->addAttr(newAttr); 2049 } 2050 2051 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl, 2052 const AttributeList &Attr) { 2053 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl); 2054 if (!Attr.isArgIdent(0)) { 2055 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2056 << Attr.getName() << 1 << AANT_ArgumentIdentifier; 2057 return; 2058 } 2059 2060 IdentifierLoc *IL = Attr.getArgAsIdent(0); 2061 ObjCMethodFamilyAttr::FamilyKind F; 2062 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) { 2063 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName() 2064 << IL->Ident; 2065 return; 2066 } 2067 2068 if (F == ObjCMethodFamilyAttr::OMF_init && 2069 !method->getReturnType()->isObjCObjectPointerType()) { 2070 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type) 2071 << method->getReturnType(); 2072 // Ignore the attribute. 2073 return; 2074 } 2075 2076 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(), 2077 S.Context, F, 2078 Attr.getAttributeSpellingListIndex())); 2079 } 2080 2081 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) { 2082 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 2083 QualType T = TD->getUnderlyingType(); 2084 if (!T->isCARCBridgableType()) { 2085 S.Diag(TD->getLocation(), diag::err_nsobject_attribute); 2086 return; 2087 } 2088 } 2089 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) { 2090 QualType T = PD->getType(); 2091 if (!T->isCARCBridgableType()) { 2092 S.Diag(PD->getLocation(), diag::err_nsobject_attribute); 2093 return; 2094 } 2095 } 2096 else { 2097 // It is okay to include this attribute on properties, e.g.: 2098 // 2099 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject)); 2100 // 2101 // In this case it follows tradition and suppresses an error in the above 2102 // case. 2103 S.Diag(D->getLocation(), diag::warn_nsobject_attribute); 2104 } 2105 D->addAttr(::new (S.Context) 2106 ObjCNSObjectAttr(Attr.getRange(), S.Context, 2107 Attr.getAttributeSpellingListIndex())); 2108 } 2109 2110 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2111 if (!Attr.isArgIdent(0)) { 2112 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2113 << Attr.getName() << 1 << AANT_ArgumentIdentifier; 2114 return; 2115 } 2116 2117 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident; 2118 BlocksAttr::BlockType type; 2119 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) { 2120 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 2121 << Attr.getName() << II; 2122 return; 2123 } 2124 2125 D->addAttr(::new (S.Context) 2126 BlocksAttr(Attr.getRange(), S.Context, type, 2127 Attr.getAttributeSpellingListIndex())); 2128 } 2129 2130 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2131 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel; 2132 if (Attr.getNumArgs() > 0) { 2133 Expr *E = Attr.getArgAsExpr(0); 2134 llvm::APSInt Idx(32); 2135 if (E->isTypeDependent() || E->isValueDependent() || 2136 !E->isIntegerConstantExpr(Idx, S.Context)) { 2137 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2138 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant 2139 << E->getSourceRange(); 2140 return; 2141 } 2142 2143 if (Idx.isSigned() && Idx.isNegative()) { 2144 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero) 2145 << E->getSourceRange(); 2146 return; 2147 } 2148 2149 sentinel = Idx.getZExtValue(); 2150 } 2151 2152 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos; 2153 if (Attr.getNumArgs() > 1) { 2154 Expr *E = Attr.getArgAsExpr(1); 2155 llvm::APSInt Idx(32); 2156 if (E->isTypeDependent() || E->isValueDependent() || 2157 !E->isIntegerConstantExpr(Idx, S.Context)) { 2158 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2159 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant 2160 << E->getSourceRange(); 2161 return; 2162 } 2163 nullPos = Idx.getZExtValue(); 2164 2165 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) { 2166 // FIXME: This error message could be improved, it would be nice 2167 // to say what the bounds actually are. 2168 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one) 2169 << E->getSourceRange(); 2170 return; 2171 } 2172 } 2173 2174 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2175 const FunctionType *FT = FD->getType()->castAs<FunctionType>(); 2176 if (isa<FunctionNoProtoType>(FT)) { 2177 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments); 2178 return; 2179 } 2180 2181 if (!cast<FunctionProtoType>(FT)->isVariadic()) { 2182 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; 2183 return; 2184 } 2185 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 2186 if (!MD->isVariadic()) { 2187 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; 2188 return; 2189 } 2190 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 2191 if (!BD->isVariadic()) { 2192 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1; 2193 return; 2194 } 2195 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) { 2196 QualType Ty = V->getType(); 2197 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) { 2198 const FunctionType *FT = Ty->isFunctionPointerType() 2199 ? D->getFunctionType() 2200 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>(); 2201 if (!cast<FunctionProtoType>(FT)->isVariadic()) { 2202 int m = Ty->isFunctionPointerType() ? 0 : 1; 2203 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m; 2204 return; 2205 } 2206 } else { 2207 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 2208 << Attr.getName() << ExpectedFunctionMethodOrBlock; 2209 return; 2210 } 2211 } else { 2212 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 2213 << Attr.getName() << ExpectedFunctionMethodOrBlock; 2214 return; 2215 } 2216 D->addAttr(::new (S.Context) 2217 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos, 2218 Attr.getAttributeSpellingListIndex())); 2219 } 2220 2221 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) { 2222 if (D->getFunctionType() && 2223 D->getFunctionType()->getReturnType()->isVoidType()) { 2224 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method) 2225 << Attr.getName() << 0; 2226 return; 2227 } 2228 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 2229 if (MD->getReturnType()->isVoidType()) { 2230 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method) 2231 << Attr.getName() << 1; 2232 return; 2233 } 2234 2235 D->addAttr(::new (S.Context) 2236 WarnUnusedResultAttr(Attr.getRange(), S.Context, 2237 Attr.getAttributeSpellingListIndex())); 2238 } 2239 2240 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2241 // weak_import only applies to variable & function declarations. 2242 bool isDef = false; 2243 if (!D->canBeWeakImported(isDef)) { 2244 if (isDef) 2245 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition) 2246 << "weak_import"; 2247 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) || 2248 (S.Context.getTargetInfo().getTriple().isOSDarwin() && 2249 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) { 2250 // Nothing to warn about here. 2251 } else 2252 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 2253 << Attr.getName() << ExpectedVariableOrFunction; 2254 2255 return; 2256 } 2257 2258 D->addAttr(::new (S.Context) 2259 WeakImportAttr(Attr.getRange(), S.Context, 2260 Attr.getAttributeSpellingListIndex())); 2261 } 2262 2263 // Handles reqd_work_group_size and work_group_size_hint. 2264 template <typename WorkGroupAttr> 2265 static void handleWorkGroupSize(Sema &S, Decl *D, 2266 const AttributeList &Attr) { 2267 uint32_t WGSize[3]; 2268 for (unsigned i = 0; i < 3; ++i) { 2269 const Expr *E = Attr.getArgAsExpr(i); 2270 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i)) 2271 return; 2272 if (WGSize[i] == 0) { 2273 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero) 2274 << Attr.getName() << E->getSourceRange(); 2275 return; 2276 } 2277 } 2278 2279 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>(); 2280 if (Existing && !(Existing->getXDim() == WGSize[0] && 2281 Existing->getYDim() == WGSize[1] && 2282 Existing->getZDim() == WGSize[2])) 2283 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName(); 2284 2285 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context, 2286 WGSize[0], WGSize[1], WGSize[2], 2287 Attr.getAttributeSpellingListIndex())); 2288 } 2289 2290 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) { 2291 if (!Attr.hasParsedType()) { 2292 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 2293 << Attr.getName() << 1; 2294 return; 2295 } 2296 2297 TypeSourceInfo *ParmTSI = nullptr; 2298 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI); 2299 assert(ParmTSI && "no type source info for attribute argument"); 2300 2301 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() && 2302 (ParmType->isBooleanType() || 2303 !ParmType->isIntegralType(S.getASTContext()))) { 2304 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint) 2305 << ParmType; 2306 return; 2307 } 2308 2309 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) { 2310 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) { 2311 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName(); 2312 return; 2313 } 2314 } 2315 2316 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context, 2317 ParmTSI, 2318 Attr.getAttributeSpellingListIndex())); 2319 } 2320 2321 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range, 2322 StringRef Name, 2323 unsigned AttrSpellingListIndex) { 2324 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) { 2325 if (ExistingAttr->getName() == Name) 2326 return nullptr; 2327 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section); 2328 Diag(Range.getBegin(), diag::note_previous_attribute); 2329 return nullptr; 2330 } 2331 return ::new (Context) SectionAttr(Range, Context, Name, 2332 AttrSpellingListIndex); 2333 } 2334 2335 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2336 // Make sure that there is a string literal as the sections's single 2337 // argument. 2338 StringRef Str; 2339 SourceLocation LiteralLoc; 2340 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc)) 2341 return; 2342 2343 // If the target wants to validate the section specifier, make it happen. 2344 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str); 2345 if (!Error.empty()) { 2346 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) 2347 << Error; 2348 return; 2349 } 2350 2351 unsigned Index = Attr.getAttributeSpellingListIndex(); 2352 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index); 2353 if (NewAttr) 2354 D->addAttr(NewAttr); 2355 } 2356 2357 2358 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2359 VarDecl *VD = cast<VarDecl>(D); 2360 if (!VD->hasLocalStorage()) { 2361 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 2362 return; 2363 } 2364 2365 Expr *E = Attr.getArgAsExpr(0); 2366 SourceLocation Loc = E->getExprLoc(); 2367 FunctionDecl *FD = nullptr; 2368 DeclarationNameInfo NI; 2369 2370 // gcc only allows for simple identifiers. Since we support more than gcc, we 2371 // will warn the user. 2372 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 2373 if (DRE->hasQualifier()) 2374 S.Diag(Loc, diag::warn_cleanup_ext); 2375 FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 2376 NI = DRE->getNameInfo(); 2377 if (!FD) { 2378 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1 2379 << NI.getName(); 2380 return; 2381 } 2382 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 2383 if (ULE->hasExplicitTemplateArgs()) 2384 S.Diag(Loc, diag::warn_cleanup_ext); 2385 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true); 2386 NI = ULE->getNameInfo(); 2387 if (!FD) { 2388 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2 2389 << NI.getName(); 2390 if (ULE->getType() == S.Context.OverloadTy) 2391 S.NoteAllOverloadCandidates(ULE); 2392 return; 2393 } 2394 } else { 2395 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0; 2396 return; 2397 } 2398 2399 if (FD->getNumParams() != 1) { 2400 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg) 2401 << NI.getName(); 2402 return; 2403 } 2404 2405 // We're currently more strict than GCC about what function types we accept. 2406 // If this ever proves to be a problem it should be easy to fix. 2407 QualType Ty = S.Context.getPointerType(VD->getType()); 2408 QualType ParamTy = FD->getParamDecl(0)->getType(); 2409 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(), 2410 ParamTy, Ty) != Sema::Compatible) { 2411 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type) 2412 << NI.getName() << ParamTy << Ty; 2413 return; 2414 } 2415 2416 D->addAttr(::new (S.Context) 2417 CleanupAttr(Attr.getRange(), S.Context, FD, 2418 Attr.getAttributeSpellingListIndex())); 2419 } 2420 2421 /// Handle __attribute__((format_arg((idx)))) attribute based on 2422 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 2423 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2424 Expr *IdxExpr = Attr.getArgAsExpr(0); 2425 uint64_t Idx; 2426 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx)) 2427 return; 2428 2429 // make sure the format string is really a string 2430 QualType Ty = getFunctionOrMethodParamType(D, Idx); 2431 2432 bool not_nsstring_type = !isNSStringType(Ty, S.Context); 2433 if (not_nsstring_type && 2434 !isCFStringType(Ty, S.Context) && 2435 (!Ty->isPointerType() || 2436 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) { 2437 S.Diag(Attr.getLoc(), diag::err_format_attribute_not) 2438 << (not_nsstring_type ? "a string type" : "an NSString") 2439 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0); 2440 return; 2441 } 2442 Ty = getFunctionOrMethodResultType(D); 2443 if (!isNSStringType(Ty, S.Context) && 2444 !isCFStringType(Ty, S.Context) && 2445 (!Ty->isPointerType() || 2446 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) { 2447 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not) 2448 << (not_nsstring_type ? "string type" : "NSString") 2449 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0); 2450 return; 2451 } 2452 2453 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex 2454 // because that has corrected for the implicit this parameter, and is zero- 2455 // based. The attribute expects what the user wrote explicitly. 2456 llvm::APSInt Val; 2457 IdxExpr->EvaluateAsInt(Val, S.Context); 2458 2459 D->addAttr(::new (S.Context) 2460 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(), 2461 Attr.getAttributeSpellingListIndex())); 2462 } 2463 2464 enum FormatAttrKind { 2465 CFStringFormat, 2466 NSStringFormat, 2467 StrftimeFormat, 2468 SupportedFormat, 2469 IgnoredFormat, 2470 InvalidFormat 2471 }; 2472 2473 /// getFormatAttrKind - Map from format attribute names to supported format 2474 /// types. 2475 static FormatAttrKind getFormatAttrKind(StringRef Format) { 2476 return llvm::StringSwitch<FormatAttrKind>(Format) 2477 // Check for formats that get handled specially. 2478 .Case("NSString", NSStringFormat) 2479 .Case("CFString", CFStringFormat) 2480 .Case("strftime", StrftimeFormat) 2481 2482 // Otherwise, check for supported formats. 2483 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat) 2484 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat) 2485 .Case("kprintf", SupportedFormat) // OpenBSD. 2486 2487 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat) 2488 .Default(InvalidFormat); 2489 } 2490 2491 /// Handle __attribute__((init_priority(priority))) attributes based on 2492 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html 2493 static void handleInitPriorityAttr(Sema &S, Decl *D, 2494 const AttributeList &Attr) { 2495 if (!S.getLangOpts().CPlusPlus) { 2496 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 2497 return; 2498 } 2499 2500 if (S.getCurFunctionOrMethodDecl()) { 2501 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr); 2502 Attr.setInvalid(); 2503 return; 2504 } 2505 QualType T = cast<VarDecl>(D)->getType(); 2506 if (S.Context.getAsArrayType(T)) 2507 T = S.Context.getBaseElementType(T); 2508 if (!T->getAs<RecordType>()) { 2509 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr); 2510 Attr.setInvalid(); 2511 return; 2512 } 2513 2514 Expr *E = Attr.getArgAsExpr(0); 2515 uint32_t prioritynum; 2516 if (!checkUInt32Argument(S, Attr, E, prioritynum)) { 2517 Attr.setInvalid(); 2518 return; 2519 } 2520 2521 if (prioritynum < 101 || prioritynum > 65535) { 2522 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range) 2523 << E->getSourceRange(); 2524 Attr.setInvalid(); 2525 return; 2526 } 2527 D->addAttr(::new (S.Context) 2528 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum, 2529 Attr.getAttributeSpellingListIndex())); 2530 } 2531 2532 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range, 2533 IdentifierInfo *Format, int FormatIdx, 2534 int FirstArg, 2535 unsigned AttrSpellingListIndex) { 2536 // Check whether we already have an equivalent format attribute. 2537 for (auto *F : D->specific_attrs<FormatAttr>()) { 2538 if (F->getType() == Format && 2539 F->getFormatIdx() == FormatIdx && 2540 F->getFirstArg() == FirstArg) { 2541 // If we don't have a valid location for this attribute, adopt the 2542 // location. 2543 if (F->getLocation().isInvalid()) 2544 F->setRange(Range); 2545 return nullptr; 2546 } 2547 } 2548 2549 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx, 2550 FirstArg, AttrSpellingListIndex); 2551 } 2552 2553 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on 2554 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 2555 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2556 if (!Attr.isArgIdent(0)) { 2557 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2558 << Attr.getName() << 1 << AANT_ArgumentIdentifier; 2559 return; 2560 } 2561 2562 // In C++ the implicit 'this' function parameter also counts, and they are 2563 // counted from one. 2564 bool HasImplicitThisParam = isInstanceMethod(D); 2565 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam; 2566 2567 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident; 2568 StringRef Format = II->getName(); 2569 2570 // Normalize the argument, __foo__ becomes foo. 2571 if (Format.startswith("__") && Format.endswith("__")) { 2572 Format = Format.substr(2, Format.size() - 4); 2573 // If we've modified the string name, we need a new identifier for it. 2574 II = &S.Context.Idents.get(Format); 2575 } 2576 2577 // Check for supported formats. 2578 FormatAttrKind Kind = getFormatAttrKind(Format); 2579 2580 if (Kind == IgnoredFormat) 2581 return; 2582 2583 if (Kind == InvalidFormat) { 2584 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 2585 << Attr.getName() << II->getName(); 2586 return; 2587 } 2588 2589 // checks for the 2nd argument 2590 Expr *IdxExpr = Attr.getArgAsExpr(1); 2591 uint32_t Idx; 2592 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2)) 2593 return; 2594 2595 if (Idx < 1 || Idx > NumArgs) { 2596 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 2597 << Attr.getName() << 2 << IdxExpr->getSourceRange(); 2598 return; 2599 } 2600 2601 // FIXME: Do we need to bounds check? 2602 unsigned ArgIdx = Idx - 1; 2603 2604 if (HasImplicitThisParam) { 2605 if (ArgIdx == 0) { 2606 S.Diag(Attr.getLoc(), 2607 diag::err_format_attribute_implicit_this_format_string) 2608 << IdxExpr->getSourceRange(); 2609 return; 2610 } 2611 ArgIdx--; 2612 } 2613 2614 // make sure the format string is really a string 2615 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx); 2616 2617 if (Kind == CFStringFormat) { 2618 if (!isCFStringType(Ty, S.Context)) { 2619 S.Diag(Attr.getLoc(), diag::err_format_attribute_not) 2620 << "a CFString" << IdxExpr->getSourceRange() 2621 << getFunctionOrMethodParamRange(D, ArgIdx); 2622 return; 2623 } 2624 } else if (Kind == NSStringFormat) { 2625 // FIXME: do we need to check if the type is NSString*? What are the 2626 // semantics? 2627 if (!isNSStringType(Ty, S.Context)) { 2628 S.Diag(Attr.getLoc(), diag::err_format_attribute_not) 2629 << "an NSString" << IdxExpr->getSourceRange() 2630 << getFunctionOrMethodParamRange(D, ArgIdx); 2631 return; 2632 } 2633 } else if (!Ty->isPointerType() || 2634 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) { 2635 S.Diag(Attr.getLoc(), diag::err_format_attribute_not) 2636 << "a string type" << IdxExpr->getSourceRange() 2637 << getFunctionOrMethodParamRange(D, ArgIdx); 2638 return; 2639 } 2640 2641 // check the 3rd argument 2642 Expr *FirstArgExpr = Attr.getArgAsExpr(2); 2643 uint32_t FirstArg; 2644 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3)) 2645 return; 2646 2647 // check if the function is variadic if the 3rd argument non-zero 2648 if (FirstArg != 0) { 2649 if (isFunctionOrMethodVariadic(D)) { 2650 ++NumArgs; // +1 for ... 2651 } else { 2652 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic); 2653 return; 2654 } 2655 } 2656 2657 // strftime requires FirstArg to be 0 because it doesn't read from any 2658 // variable the input is just the current time + the format string. 2659 if (Kind == StrftimeFormat) { 2660 if (FirstArg != 0) { 2661 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter) 2662 << FirstArgExpr->getSourceRange(); 2663 return; 2664 } 2665 // if 0 it disables parameter checking (to use with e.g. va_list) 2666 } else if (FirstArg != 0 && FirstArg != NumArgs) { 2667 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 2668 << Attr.getName() << 3 << FirstArgExpr->getSourceRange(); 2669 return; 2670 } 2671 2672 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II, 2673 Idx, FirstArg, 2674 Attr.getAttributeSpellingListIndex()); 2675 if (NewAttr) 2676 D->addAttr(NewAttr); 2677 } 2678 2679 static void handleTransparentUnionAttr(Sema &S, Decl *D, 2680 const AttributeList &Attr) { 2681 // Try to find the underlying union declaration. 2682 RecordDecl *RD = nullptr; 2683 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D); 2684 if (TD && TD->getUnderlyingType()->isUnionType()) 2685 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl(); 2686 else 2687 RD = dyn_cast<RecordDecl>(D); 2688 2689 if (!RD || !RD->isUnion()) { 2690 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 2691 << Attr.getName() << ExpectedUnion; 2692 return; 2693 } 2694 2695 if (!RD->isCompleteDefinition()) { 2696 S.Diag(Attr.getLoc(), 2697 diag::warn_transparent_union_attribute_not_definition); 2698 return; 2699 } 2700 2701 RecordDecl::field_iterator Field = RD->field_begin(), 2702 FieldEnd = RD->field_end(); 2703 if (Field == FieldEnd) { 2704 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields); 2705 return; 2706 } 2707 2708 FieldDecl *FirstField = *Field; 2709 QualType FirstType = FirstField->getType(); 2710 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) { 2711 S.Diag(FirstField->getLocation(), 2712 diag::warn_transparent_union_attribute_floating) 2713 << FirstType->isVectorType() << FirstType; 2714 return; 2715 } 2716 2717 uint64_t FirstSize = S.Context.getTypeSize(FirstType); 2718 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType); 2719 for (; Field != FieldEnd; ++Field) { 2720 QualType FieldType = Field->getType(); 2721 // FIXME: this isn't fully correct; we also need to test whether the 2722 // members of the union would all have the same calling convention as the 2723 // first member of the union. Checking just the size and alignment isn't 2724 // sufficient (consider structs passed on the stack instead of in registers 2725 // as an example). 2726 if (S.Context.getTypeSize(FieldType) != FirstSize || 2727 S.Context.getTypeAlign(FieldType) > FirstAlign) { 2728 // Warn if we drop the attribute. 2729 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize; 2730 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType) 2731 : S.Context.getTypeAlign(FieldType); 2732 S.Diag(Field->getLocation(), 2733 diag::warn_transparent_union_attribute_field_size_align) 2734 << isSize << Field->getDeclName() << FieldBits; 2735 unsigned FirstBits = isSize? FirstSize : FirstAlign; 2736 S.Diag(FirstField->getLocation(), 2737 diag::note_transparent_union_first_field_size_align) 2738 << isSize << FirstBits; 2739 return; 2740 } 2741 } 2742 2743 RD->addAttr(::new (S.Context) 2744 TransparentUnionAttr(Attr.getRange(), S.Context, 2745 Attr.getAttributeSpellingListIndex())); 2746 } 2747 2748 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2749 // Make sure that there is a string literal as the annotation's single 2750 // argument. 2751 StringRef Str; 2752 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 2753 return; 2754 2755 // Don't duplicate annotations that are already set. 2756 for (const auto *I : D->specific_attrs<AnnotateAttr>()) { 2757 if (I->getAnnotation() == Str) 2758 return; 2759 } 2760 2761 D->addAttr(::new (S.Context) 2762 AnnotateAttr(Attr.getRange(), S.Context, Str, 2763 Attr.getAttributeSpellingListIndex())); 2764 } 2765 2766 static void handleAlignValueAttr(Sema &S, Decl *D, 2767 const AttributeList &Attr) { 2768 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0), 2769 Attr.getAttributeSpellingListIndex()); 2770 } 2771 2772 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E, 2773 unsigned SpellingListIndex) { 2774 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex); 2775 SourceLocation AttrLoc = AttrRange.getBegin(); 2776 2777 QualType T; 2778 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) 2779 T = TD->getUnderlyingType(); 2780 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) 2781 T = VD->getType(); 2782 else 2783 llvm_unreachable("Unknown decl type for align_value"); 2784 2785 if (!T->isDependentType() && !T->isAnyPointerType() && 2786 !T->isReferenceType() && !T->isMemberPointerType()) { 2787 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only) 2788 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange(); 2789 return; 2790 } 2791 2792 if (!E->isValueDependent()) { 2793 llvm::APSInt Alignment(32); 2794 ExprResult ICE 2795 = VerifyIntegerConstantExpression(E, &Alignment, 2796 diag::err_align_value_attribute_argument_not_int, 2797 /*AllowFold*/ false); 2798 if (ICE.isInvalid()) 2799 return; 2800 2801 if (!Alignment.isPowerOf2()) { 2802 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 2803 << E->getSourceRange(); 2804 return; 2805 } 2806 2807 D->addAttr(::new (Context) 2808 AlignValueAttr(AttrRange, Context, ICE.get(), 2809 SpellingListIndex)); 2810 return; 2811 } 2812 2813 // Save dependent expressions in the AST to be instantiated. 2814 D->addAttr(::new (Context) AlignValueAttr(TmpAttr)); 2815 return; 2816 } 2817 2818 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2819 // check the attribute arguments. 2820 if (Attr.getNumArgs() > 1) { 2821 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 2822 << Attr.getName() << 1; 2823 return; 2824 } 2825 2826 if (Attr.getNumArgs() == 0) { 2827 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context, 2828 true, nullptr, Attr.getAttributeSpellingListIndex())); 2829 return; 2830 } 2831 2832 Expr *E = Attr.getArgAsExpr(0); 2833 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) { 2834 S.Diag(Attr.getEllipsisLoc(), 2835 diag::err_pack_expansion_without_parameter_packs); 2836 return; 2837 } 2838 2839 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E)) 2840 return; 2841 2842 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(), 2843 Attr.isPackExpansion()); 2844 } 2845 2846 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, 2847 unsigned SpellingListIndex, bool IsPackExpansion) { 2848 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex); 2849 SourceLocation AttrLoc = AttrRange.getBegin(); 2850 2851 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements. 2852 if (TmpAttr.isAlignas()) { 2853 // C++11 [dcl.align]p1: 2854 // An alignment-specifier may be applied to a variable or to a class 2855 // data member, but it shall not be applied to a bit-field, a function 2856 // parameter, the formal parameter of a catch clause, or a variable 2857 // declared with the register storage class specifier. An 2858 // alignment-specifier may also be applied to the declaration of a class 2859 // or enumeration type. 2860 // C11 6.7.5/2: 2861 // An alignment attribute shall not be specified in a declaration of 2862 // a typedef, or a bit-field, or a function, or a parameter, or an 2863 // object declared with the register storage-class specifier. 2864 int DiagKind = -1; 2865 if (isa<ParmVarDecl>(D)) { 2866 DiagKind = 0; 2867 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 2868 if (VD->getStorageClass() == SC_Register) 2869 DiagKind = 1; 2870 if (VD->isExceptionVariable()) 2871 DiagKind = 2; 2872 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 2873 if (FD->isBitField()) 2874 DiagKind = 3; 2875 } else if (!isa<TagDecl>(D)) { 2876 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr 2877 << (TmpAttr.isC11() ? ExpectedVariableOrField 2878 : ExpectedVariableFieldOrTag); 2879 return; 2880 } 2881 if (DiagKind != -1) { 2882 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type) 2883 << &TmpAttr << DiagKind; 2884 return; 2885 } 2886 } 2887 2888 if (E->isTypeDependent() || E->isValueDependent()) { 2889 // Save dependent expressions in the AST to be instantiated. 2890 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr); 2891 AA->setPackExpansion(IsPackExpansion); 2892 D->addAttr(AA); 2893 return; 2894 } 2895 2896 // FIXME: Cache the number on the Attr object? 2897 llvm::APSInt Alignment(32); 2898 ExprResult ICE 2899 = VerifyIntegerConstantExpression(E, &Alignment, 2900 diag::err_aligned_attribute_argument_not_int, 2901 /*AllowFold*/ false); 2902 if (ICE.isInvalid()) 2903 return; 2904 2905 // C++11 [dcl.align]p2: 2906 // -- if the constant expression evaluates to zero, the alignment 2907 // specifier shall have no effect 2908 // C11 6.7.5p6: 2909 // An alignment specification of zero has no effect. 2910 if (!(TmpAttr.isAlignas() && !Alignment) && 2911 !llvm::isPowerOf2_64(Alignment.getZExtValue())) { 2912 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 2913 << E->getSourceRange(); 2914 return; 2915 } 2916 2917 // Alignment calculations can wrap around if it's greater than 2**28. 2918 unsigned MaxValidAlignment = TmpAttr.isDeclspec() ? 8192 : 268435456; 2919 if (Alignment.getZExtValue() > MaxValidAlignment) { 2920 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment 2921 << E->getSourceRange(); 2922 return; 2923 } 2924 2925 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true, 2926 ICE.get(), SpellingListIndex); 2927 AA->setPackExpansion(IsPackExpansion); 2928 D->addAttr(AA); 2929 } 2930 2931 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS, 2932 unsigned SpellingListIndex, bool IsPackExpansion) { 2933 // FIXME: Cache the number on the Attr object if non-dependent? 2934 // FIXME: Perform checking of type validity 2935 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS, 2936 SpellingListIndex); 2937 AA->setPackExpansion(IsPackExpansion); 2938 D->addAttr(AA); 2939 } 2940 2941 void Sema::CheckAlignasUnderalignment(Decl *D) { 2942 assert(D->hasAttrs() && "no attributes on decl"); 2943 2944 QualType Ty; 2945 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) 2946 Ty = VD->getType(); 2947 else 2948 Ty = Context.getTagDeclType(cast<TagDecl>(D)); 2949 if (Ty->isDependentType() || Ty->isIncompleteType()) 2950 return; 2951 2952 // C++11 [dcl.align]p5, C11 6.7.5/4: 2953 // The combined effect of all alignment attributes in a declaration shall 2954 // not specify an alignment that is less strict than the alignment that 2955 // would otherwise be required for the entity being declared. 2956 AlignedAttr *AlignasAttr = nullptr; 2957 unsigned Align = 0; 2958 for (auto *I : D->specific_attrs<AlignedAttr>()) { 2959 if (I->isAlignmentDependent()) 2960 return; 2961 if (I->isAlignas()) 2962 AlignasAttr = I; 2963 Align = std::max(Align, I->getAlignment(Context)); 2964 } 2965 2966 if (AlignasAttr && Align) { 2967 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align); 2968 CharUnits NaturalAlign = Context.getTypeAlignInChars(Ty); 2969 if (NaturalAlign > RequestedAlign) 2970 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned) 2971 << Ty << (unsigned)NaturalAlign.getQuantity(); 2972 } 2973 } 2974 2975 bool Sema::checkMSInheritanceAttrOnDefinition( 2976 CXXRecordDecl *RD, SourceRange Range, bool BestCase, 2977 MSInheritanceAttr::Spelling SemanticSpelling) { 2978 assert(RD->hasDefinition() && "RD has no definition!"); 2979 2980 // We may not have seen base specifiers or any virtual methods yet. We will 2981 // have to wait until the record is defined to catch any mismatches. 2982 if (!RD->getDefinition()->isCompleteDefinition()) 2983 return false; 2984 2985 // The unspecified model never matches what a definition could need. 2986 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance) 2987 return false; 2988 2989 if (BestCase) { 2990 if (RD->calculateInheritanceModel() == SemanticSpelling) 2991 return false; 2992 } else { 2993 if (RD->calculateInheritanceModel() <= SemanticSpelling) 2994 return false; 2995 } 2996 2997 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance) 2998 << 0 /*definition*/; 2999 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) 3000 << RD->getNameAsString(); 3001 return true; 3002 } 3003 3004 /// handleModeAttr - This attribute modifies the width of a decl with primitive 3005 /// type. 3006 /// 3007 /// Despite what would be logical, the mode attribute is a decl attribute, not a 3008 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be 3009 /// HImode, not an intermediate pointer. 3010 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3011 // This attribute isn't documented, but glibc uses it. It changes 3012 // the width of an int or unsigned int to the specified size. 3013 if (!Attr.isArgIdent(0)) { 3014 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName() 3015 << AANT_ArgumentIdentifier; 3016 return; 3017 } 3018 3019 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident; 3020 StringRef Str = Name->getName(); 3021 3022 // Normalize the attribute name, __foo__ becomes foo. 3023 if (Str.startswith("__") && Str.endswith("__")) 3024 Str = Str.substr(2, Str.size() - 4); 3025 3026 unsigned DestWidth = 0; 3027 bool IntegerMode = true; 3028 bool ComplexMode = false; 3029 switch (Str.size()) { 3030 case 2: 3031 switch (Str[0]) { 3032 case 'Q': DestWidth = 8; break; 3033 case 'H': DestWidth = 16; break; 3034 case 'S': DestWidth = 32; break; 3035 case 'D': DestWidth = 64; break; 3036 case 'X': DestWidth = 96; break; 3037 case 'T': DestWidth = 128; break; 3038 } 3039 if (Str[1] == 'F') { 3040 IntegerMode = false; 3041 } else if (Str[1] == 'C') { 3042 IntegerMode = false; 3043 ComplexMode = true; 3044 } else if (Str[1] != 'I') { 3045 DestWidth = 0; 3046 } 3047 break; 3048 case 4: 3049 // FIXME: glibc uses 'word' to define register_t; this is narrower than a 3050 // pointer on PIC16 and other embedded platforms. 3051 if (Str == "word") 3052 DestWidth = S.Context.getTargetInfo().getPointerWidth(0); 3053 else if (Str == "byte") 3054 DestWidth = S.Context.getTargetInfo().getCharWidth(); 3055 break; 3056 case 7: 3057 if (Str == "pointer") 3058 DestWidth = S.Context.getTargetInfo().getPointerWidth(0); 3059 break; 3060 case 11: 3061 if (Str == "unwind_word") 3062 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth(); 3063 break; 3064 } 3065 3066 QualType OldTy; 3067 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) 3068 OldTy = TD->getUnderlyingType(); 3069 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) 3070 OldTy = VD->getType(); 3071 else { 3072 S.Diag(D->getLocation(), diag::err_attr_wrong_decl) 3073 << Attr.getName() << Attr.getRange(); 3074 return; 3075 } 3076 3077 if (!OldTy->getAs<BuiltinType>() && !OldTy->isComplexType()) 3078 S.Diag(Attr.getLoc(), diag::err_mode_not_primitive); 3079 else if (IntegerMode) { 3080 if (!OldTy->isIntegralOrEnumerationType()) 3081 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type); 3082 } else if (ComplexMode) { 3083 if (!OldTy->isComplexType()) 3084 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type); 3085 } else { 3086 if (!OldTy->isFloatingType()) 3087 S.Diag(Attr.getLoc(), diag::err_mode_wrong_type); 3088 } 3089 3090 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t 3091 // and friends, at least with glibc. 3092 // FIXME: Make sure floating-point mappings are accurate 3093 // FIXME: Support XF and TF types 3094 if (!DestWidth) { 3095 S.Diag(Attr.getLoc(), diag::err_machine_mode) << 0 /*Unknown*/ << Name; 3096 return; 3097 } 3098 3099 QualType NewTy; 3100 3101 if (IntegerMode) 3102 NewTy = S.Context.getIntTypeForBitwidth(DestWidth, 3103 OldTy->isSignedIntegerType()); 3104 else 3105 NewTy = S.Context.getRealTypeForBitwidth(DestWidth); 3106 3107 if (NewTy.isNull()) { 3108 S.Diag(Attr.getLoc(), diag::err_machine_mode) << 1 /*Unsupported*/ << Name; 3109 return; 3110 } 3111 3112 if (ComplexMode) { 3113 NewTy = S.Context.getComplexType(NewTy); 3114 } 3115 3116 // Install the new type. 3117 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) 3118 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy); 3119 else 3120 cast<ValueDecl>(D)->setType(NewTy); 3121 3122 D->addAttr(::new (S.Context) 3123 ModeAttr(Attr.getRange(), S.Context, Name, 3124 Attr.getAttributeSpellingListIndex())); 3125 } 3126 3127 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3128 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 3129 if (!VD->hasGlobalStorage()) 3130 S.Diag(Attr.getLoc(), 3131 diag::warn_attribute_requires_functions_or_static_globals) 3132 << Attr.getName(); 3133 } else if (!isFunctionOrMethod(D)) { 3134 S.Diag(Attr.getLoc(), 3135 diag::warn_attribute_requires_functions_or_static_globals) 3136 << Attr.getName(); 3137 return; 3138 } 3139 3140 D->addAttr(::new (S.Context) 3141 NoDebugAttr(Attr.getRange(), S.Context, 3142 Attr.getAttributeSpellingListIndex())); 3143 } 3144 3145 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range, 3146 unsigned AttrSpellingListIndex) { 3147 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) { 3148 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'always_inline'"; 3149 Diag(Optnone->getLocation(), diag::note_conflicting_attribute); 3150 return nullptr; 3151 } 3152 3153 if (D->hasAttr<AlwaysInlineAttr>()) 3154 return nullptr; 3155 3156 return ::new (Context) AlwaysInlineAttr(Range, Context, 3157 AttrSpellingListIndex); 3158 } 3159 3160 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range, 3161 unsigned AttrSpellingListIndex) { 3162 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) { 3163 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'"; 3164 Diag(Optnone->getLocation(), diag::note_conflicting_attribute); 3165 return nullptr; 3166 } 3167 3168 if (D->hasAttr<MinSizeAttr>()) 3169 return nullptr; 3170 3171 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex); 3172 } 3173 3174 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range, 3175 unsigned AttrSpellingListIndex) { 3176 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) { 3177 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline; 3178 Diag(Range.getBegin(), diag::note_conflicting_attribute); 3179 D->dropAttr<AlwaysInlineAttr>(); 3180 } 3181 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) { 3182 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize; 3183 Diag(Range.getBegin(), diag::note_conflicting_attribute); 3184 D->dropAttr<MinSizeAttr>(); 3185 } 3186 3187 if (D->hasAttr<OptimizeNoneAttr>()) 3188 return nullptr; 3189 3190 return ::new (Context) OptimizeNoneAttr(Range, Context, 3191 AttrSpellingListIndex); 3192 } 3193 3194 static void handleAlwaysInlineAttr(Sema &S, Decl *D, 3195 const AttributeList &Attr) { 3196 if (checkAttrMutualExclusion<OptimizeNoneAttr>(S, D, Attr)) 3197 return; 3198 3199 D->addAttr(::new (S.Context) 3200 AlwaysInlineAttr(Attr.getRange(), S.Context, 3201 Attr.getAttributeSpellingListIndex())); 3202 } 3203 3204 static void handleMinSizeAttr(Sema &S, Decl *D, 3205 const AttributeList &Attr) { 3206 if (checkAttrMutualExclusion<OptimizeNoneAttr>(S, D, Attr)) 3207 return; 3208 3209 D->addAttr(::new (S.Context) 3210 MinSizeAttr(Attr.getRange(), S.Context, 3211 Attr.getAttributeSpellingListIndex())); 3212 } 3213 3214 static void handleOptimizeNoneAttr(Sema &S, Decl *D, 3215 const AttributeList &Attr) { 3216 if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr)) 3217 return; 3218 if (checkAttrMutualExclusion<MinSizeAttr>(S, D, Attr)) 3219 return; 3220 3221 D->addAttr(::new (S.Context) 3222 OptimizeNoneAttr(Attr.getRange(), S.Context, 3223 Attr.getAttributeSpellingListIndex())); 3224 } 3225 3226 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3227 FunctionDecl *FD = cast<FunctionDecl>(D); 3228 if (!FD->getReturnType()->isVoidType()) { 3229 SourceRange RTRange = FD->getReturnTypeSourceRange(); 3230 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return) 3231 << FD->getType() 3232 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 3233 : FixItHint()); 3234 return; 3235 } 3236 3237 D->addAttr(::new (S.Context) 3238 CUDAGlobalAttr(Attr.getRange(), S.Context, 3239 Attr.getAttributeSpellingListIndex())); 3240 } 3241 3242 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3243 FunctionDecl *Fn = cast<FunctionDecl>(D); 3244 if (!Fn->isInlineSpecified()) { 3245 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline); 3246 return; 3247 } 3248 3249 D->addAttr(::new (S.Context) 3250 GNUInlineAttr(Attr.getRange(), S.Context, 3251 Attr.getAttributeSpellingListIndex())); 3252 } 3253 3254 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3255 if (hasDeclarator(D)) return; 3256 3257 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 3258 // Diagnostic is emitted elsewhere: here we store the (valid) Attr 3259 // in the Decl node for syntactic reasoning, e.g., pretty-printing. 3260 CallingConv CC; 3261 if (S.CheckCallingConvAttr(Attr, CC, FD)) 3262 return; 3263 3264 if (!isa<ObjCMethodDecl>(D)) { 3265 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 3266 << Attr.getName() << ExpectedFunctionOrMethod; 3267 return; 3268 } 3269 3270 switch (Attr.getKind()) { 3271 case AttributeList::AT_FastCall: 3272 D->addAttr(::new (S.Context) 3273 FastCallAttr(Attr.getRange(), S.Context, 3274 Attr.getAttributeSpellingListIndex())); 3275 return; 3276 case AttributeList::AT_StdCall: 3277 D->addAttr(::new (S.Context) 3278 StdCallAttr(Attr.getRange(), S.Context, 3279 Attr.getAttributeSpellingListIndex())); 3280 return; 3281 case AttributeList::AT_ThisCall: 3282 D->addAttr(::new (S.Context) 3283 ThisCallAttr(Attr.getRange(), S.Context, 3284 Attr.getAttributeSpellingListIndex())); 3285 return; 3286 case AttributeList::AT_CDecl: 3287 D->addAttr(::new (S.Context) 3288 CDeclAttr(Attr.getRange(), S.Context, 3289 Attr.getAttributeSpellingListIndex())); 3290 return; 3291 case AttributeList::AT_Pascal: 3292 D->addAttr(::new (S.Context) 3293 PascalAttr(Attr.getRange(), S.Context, 3294 Attr.getAttributeSpellingListIndex())); 3295 return; 3296 case AttributeList::AT_VectorCall: 3297 D->addAttr(::new (S.Context) 3298 VectorCallAttr(Attr.getRange(), S.Context, 3299 Attr.getAttributeSpellingListIndex())); 3300 return; 3301 case AttributeList::AT_MSABI: 3302 D->addAttr(::new (S.Context) 3303 MSABIAttr(Attr.getRange(), S.Context, 3304 Attr.getAttributeSpellingListIndex())); 3305 return; 3306 case AttributeList::AT_SysVABI: 3307 D->addAttr(::new (S.Context) 3308 SysVABIAttr(Attr.getRange(), S.Context, 3309 Attr.getAttributeSpellingListIndex())); 3310 return; 3311 case AttributeList::AT_Pcs: { 3312 PcsAttr::PCSType PCS; 3313 switch (CC) { 3314 case CC_AAPCS: 3315 PCS = PcsAttr::AAPCS; 3316 break; 3317 case CC_AAPCS_VFP: 3318 PCS = PcsAttr::AAPCS_VFP; 3319 break; 3320 default: 3321 llvm_unreachable("unexpected calling convention in pcs attribute"); 3322 } 3323 3324 D->addAttr(::new (S.Context) 3325 PcsAttr(Attr.getRange(), S.Context, PCS, 3326 Attr.getAttributeSpellingListIndex())); 3327 return; 3328 } 3329 case AttributeList::AT_PnaclCall: 3330 D->addAttr(::new (S.Context) 3331 PnaclCallAttr(Attr.getRange(), S.Context, 3332 Attr.getAttributeSpellingListIndex())); 3333 return; 3334 case AttributeList::AT_IntelOclBicc: 3335 D->addAttr(::new (S.Context) 3336 IntelOclBiccAttr(Attr.getRange(), S.Context, 3337 Attr.getAttributeSpellingListIndex())); 3338 return; 3339 3340 default: 3341 llvm_unreachable("unexpected attribute kind"); 3342 } 3343 } 3344 3345 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC, 3346 const FunctionDecl *FD) { 3347 if (attr.isInvalid()) 3348 return true; 3349 3350 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0; 3351 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) { 3352 attr.setInvalid(); 3353 return true; 3354 } 3355 3356 // TODO: diagnose uses of these conventions on the wrong target. 3357 switch (attr.getKind()) { 3358 case AttributeList::AT_CDecl: CC = CC_C; break; 3359 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break; 3360 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break; 3361 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break; 3362 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break; 3363 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break; 3364 case AttributeList::AT_MSABI: 3365 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C : 3366 CC_X86_64Win64; 3367 break; 3368 case AttributeList::AT_SysVABI: 3369 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV : 3370 CC_C; 3371 break; 3372 case AttributeList::AT_Pcs: { 3373 StringRef StrRef; 3374 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) { 3375 attr.setInvalid(); 3376 return true; 3377 } 3378 if (StrRef == "aapcs") { 3379 CC = CC_AAPCS; 3380 break; 3381 } else if (StrRef == "aapcs-vfp") { 3382 CC = CC_AAPCS_VFP; 3383 break; 3384 } 3385 3386 attr.setInvalid(); 3387 Diag(attr.getLoc(), diag::err_invalid_pcs); 3388 return true; 3389 } 3390 case AttributeList::AT_PnaclCall: CC = CC_PnaclCall; break; 3391 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break; 3392 default: llvm_unreachable("unexpected attribute kind"); 3393 } 3394 3395 const TargetInfo &TI = Context.getTargetInfo(); 3396 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC); 3397 if (A == TargetInfo::CCCR_Warning) { 3398 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName(); 3399 3400 TargetInfo::CallingConvMethodType MT = TargetInfo::CCMT_Unknown; 3401 if (FD) 3402 MT = FD->isCXXInstanceMember() ? TargetInfo::CCMT_Member : 3403 TargetInfo::CCMT_NonMember; 3404 CC = TI.getDefaultCallingConv(MT); 3405 } 3406 3407 return false; 3408 } 3409 3410 /// Checks a regparm attribute, returning true if it is ill-formed and 3411 /// otherwise setting numParams to the appropriate value. 3412 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) { 3413 if (Attr.isInvalid()) 3414 return true; 3415 3416 if (!checkAttributeNumArgs(*this, Attr, 1)) { 3417 Attr.setInvalid(); 3418 return true; 3419 } 3420 3421 uint32_t NP; 3422 Expr *NumParamsExpr = Attr.getArgAsExpr(0); 3423 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) { 3424 Attr.setInvalid(); 3425 return true; 3426 } 3427 3428 if (Context.getTargetInfo().getRegParmMax() == 0) { 3429 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform) 3430 << NumParamsExpr->getSourceRange(); 3431 Attr.setInvalid(); 3432 return true; 3433 } 3434 3435 numParams = NP; 3436 if (numParams > Context.getTargetInfo().getRegParmMax()) { 3437 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number) 3438 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange(); 3439 Attr.setInvalid(); 3440 return true; 3441 } 3442 3443 return false; 3444 } 3445 3446 static void handleLaunchBoundsAttr(Sema &S, Decl *D, 3447 const AttributeList &Attr) { 3448 uint32_t MaxThreads, MinBlocks = 0; 3449 if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), MaxThreads, 1)) 3450 return; 3451 if (Attr.getNumArgs() > 1 && !checkUInt32Argument(S, Attr, 3452 Attr.getArgAsExpr(1), 3453 MinBlocks, 2)) 3454 return; 3455 3456 D->addAttr(::new (S.Context) 3457 CUDALaunchBoundsAttr(Attr.getRange(), S.Context, 3458 MaxThreads, MinBlocks, 3459 Attr.getAttributeSpellingListIndex())); 3460 } 3461 3462 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D, 3463 const AttributeList &Attr) { 3464 if (!Attr.isArgIdent(0)) { 3465 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 3466 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier; 3467 return; 3468 } 3469 3470 if (!checkAttributeNumArgs(S, Attr, 3)) 3471 return; 3472 3473 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident; 3474 3475 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) { 3476 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type) 3477 << Attr.getName() << ExpectedFunctionOrMethod; 3478 return; 3479 } 3480 3481 uint64_t ArgumentIdx; 3482 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1), 3483 ArgumentIdx)) 3484 return; 3485 3486 uint64_t TypeTagIdx; 3487 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2), 3488 TypeTagIdx)) 3489 return; 3490 3491 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag"); 3492 if (IsPointer) { 3493 // Ensure that buffer has a pointer type. 3494 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx); 3495 if (!BufferTy->isPointerType()) { 3496 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only) 3497 << Attr.getName(); 3498 } 3499 } 3500 3501 D->addAttr(::new (S.Context) 3502 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind, 3503 ArgumentIdx, TypeTagIdx, IsPointer, 3504 Attr.getAttributeSpellingListIndex())); 3505 } 3506 3507 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D, 3508 const AttributeList &Attr) { 3509 if (!Attr.isArgIdent(0)) { 3510 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 3511 << Attr.getName() << 1 << AANT_ArgumentIdentifier; 3512 return; 3513 } 3514 3515 if (!checkAttributeNumArgs(S, Attr, 1)) 3516 return; 3517 3518 if (!isa<VarDecl>(D)) { 3519 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type) 3520 << Attr.getName() << ExpectedVariable; 3521 return; 3522 } 3523 3524 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident; 3525 TypeSourceInfo *MatchingCTypeLoc = nullptr; 3526 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc); 3527 assert(MatchingCTypeLoc && "no type source info for attribute argument"); 3528 3529 D->addAttr(::new (S.Context) 3530 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind, 3531 MatchingCTypeLoc, 3532 Attr.getLayoutCompatible(), 3533 Attr.getMustBeNull(), 3534 Attr.getAttributeSpellingListIndex())); 3535 } 3536 3537 //===----------------------------------------------------------------------===// 3538 // Checker-specific attribute handlers. 3539 //===----------------------------------------------------------------------===// 3540 3541 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) { 3542 return type->isDependentType() || 3543 type->isObjCRetainableType(); 3544 } 3545 3546 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) { 3547 return type->isDependentType() || 3548 type->isObjCObjectPointerType() || 3549 S.Context.isObjCNSObjectType(type); 3550 } 3551 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) { 3552 return type->isDependentType() || 3553 type->isPointerType() || 3554 isValidSubjectOfNSAttribute(S, type); 3555 } 3556 3557 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3558 ParmVarDecl *param = cast<ParmVarDecl>(D); 3559 bool typeOK, cf; 3560 3561 if (Attr.getKind() == AttributeList::AT_NSConsumed) { 3562 typeOK = isValidSubjectOfNSAttribute(S, param->getType()); 3563 cf = false; 3564 } else { 3565 typeOK = isValidSubjectOfCFAttribute(S, param->getType()); 3566 cf = true; 3567 } 3568 3569 if (!typeOK) { 3570 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type) 3571 << Attr.getRange() << Attr.getName() << cf; 3572 return; 3573 } 3574 3575 if (cf) 3576 param->addAttr(::new (S.Context) 3577 CFConsumedAttr(Attr.getRange(), S.Context, 3578 Attr.getAttributeSpellingListIndex())); 3579 else 3580 param->addAttr(::new (S.Context) 3581 NSConsumedAttr(Attr.getRange(), S.Context, 3582 Attr.getAttributeSpellingListIndex())); 3583 } 3584 3585 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D, 3586 const AttributeList &Attr) { 3587 3588 QualType returnType; 3589 3590 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 3591 returnType = MD->getReturnType(); 3592 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) && 3593 (Attr.getKind() == AttributeList::AT_NSReturnsRetained)) 3594 return; // ignore: was handled as a type attribute 3595 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) 3596 returnType = PD->getType(); 3597 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 3598 returnType = FD->getReturnType(); 3599 else { 3600 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type) 3601 << Attr.getRange() << Attr.getName() 3602 << ExpectedFunctionOrMethod; 3603 return; 3604 } 3605 3606 bool typeOK; 3607 bool cf; 3608 switch (Attr.getKind()) { 3609 default: llvm_unreachable("invalid ownership attribute"); 3610 case AttributeList::AT_NSReturnsRetained: 3611 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType); 3612 cf = false; 3613 break; 3614 3615 case AttributeList::AT_NSReturnsAutoreleased: 3616 case AttributeList::AT_NSReturnsNotRetained: 3617 typeOK = isValidSubjectOfNSAttribute(S, returnType); 3618 cf = false; 3619 break; 3620 3621 case AttributeList::AT_CFReturnsRetained: 3622 case AttributeList::AT_CFReturnsNotRetained: 3623 typeOK = isValidSubjectOfCFAttribute(S, returnType); 3624 cf = true; 3625 break; 3626 } 3627 3628 if (!typeOK) { 3629 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type) 3630 << Attr.getRange() << Attr.getName() << isa<ObjCMethodDecl>(D) << cf; 3631 return; 3632 } 3633 3634 switch (Attr.getKind()) { 3635 default: 3636 llvm_unreachable("invalid ownership attribute"); 3637 case AttributeList::AT_NSReturnsAutoreleased: 3638 D->addAttr(::new (S.Context) 3639 NSReturnsAutoreleasedAttr(Attr.getRange(), S.Context, 3640 Attr.getAttributeSpellingListIndex())); 3641 return; 3642 case AttributeList::AT_CFReturnsNotRetained: 3643 D->addAttr(::new (S.Context) 3644 CFReturnsNotRetainedAttr(Attr.getRange(), S.Context, 3645 Attr.getAttributeSpellingListIndex())); 3646 return; 3647 case AttributeList::AT_NSReturnsNotRetained: 3648 D->addAttr(::new (S.Context) 3649 NSReturnsNotRetainedAttr(Attr.getRange(), S.Context, 3650 Attr.getAttributeSpellingListIndex())); 3651 return; 3652 case AttributeList::AT_CFReturnsRetained: 3653 D->addAttr(::new (S.Context) 3654 CFReturnsRetainedAttr(Attr.getRange(), S.Context, 3655 Attr.getAttributeSpellingListIndex())); 3656 return; 3657 case AttributeList::AT_NSReturnsRetained: 3658 D->addAttr(::new (S.Context) 3659 NSReturnsRetainedAttr(Attr.getRange(), S.Context, 3660 Attr.getAttributeSpellingListIndex())); 3661 return; 3662 }; 3663 } 3664 3665 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D, 3666 const AttributeList &attr) { 3667 const int EP_ObjCMethod = 1; 3668 const int EP_ObjCProperty = 2; 3669 3670 SourceLocation loc = attr.getLoc(); 3671 QualType resultType; 3672 if (isa<ObjCMethodDecl>(D)) 3673 resultType = cast<ObjCMethodDecl>(D)->getReturnType(); 3674 else 3675 resultType = cast<ObjCPropertyDecl>(D)->getType(); 3676 3677 if (!resultType->isReferenceType() && 3678 (!resultType->isPointerType() || resultType->isObjCRetainableType())) { 3679 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type) 3680 << SourceRange(loc) 3681 << attr.getName() 3682 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty) 3683 << /*non-retainable pointer*/ 2; 3684 3685 // Drop the attribute. 3686 return; 3687 } 3688 3689 D->addAttr(::new (S.Context) 3690 ObjCReturnsInnerPointerAttr(attr.getRange(), S.Context, 3691 attr.getAttributeSpellingListIndex())); 3692 } 3693 3694 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D, 3695 const AttributeList &attr) { 3696 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D); 3697 3698 DeclContext *DC = method->getDeclContext(); 3699 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) { 3700 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol) 3701 << attr.getName() << 0; 3702 S.Diag(PDecl->getLocation(), diag::note_protocol_decl); 3703 return; 3704 } 3705 if (method->getMethodFamily() == OMF_dealloc) { 3706 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol) 3707 << attr.getName() << 1; 3708 return; 3709 } 3710 3711 method->addAttr(::new (S.Context) 3712 ObjCRequiresSuperAttr(attr.getRange(), S.Context, 3713 attr.getAttributeSpellingListIndex())); 3714 } 3715 3716 static void handleCFAuditedTransferAttr(Sema &S, Decl *D, 3717 const AttributeList &Attr) { 3718 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr)) 3719 return; 3720 3721 D->addAttr(::new (S.Context) 3722 CFAuditedTransferAttr(Attr.getRange(), S.Context, 3723 Attr.getAttributeSpellingListIndex())); 3724 } 3725 3726 static void handleCFUnknownTransferAttr(Sema &S, Decl *D, 3727 const AttributeList &Attr) { 3728 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr)) 3729 return; 3730 3731 D->addAttr(::new (S.Context) 3732 CFUnknownTransferAttr(Attr.getRange(), S.Context, 3733 Attr.getAttributeSpellingListIndex())); 3734 } 3735 3736 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D, 3737 const AttributeList &Attr) { 3738 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr; 3739 3740 if (!Parm) { 3741 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0; 3742 return; 3743 } 3744 3745 D->addAttr(::new (S.Context) 3746 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident, 3747 Attr.getAttributeSpellingListIndex())); 3748 } 3749 3750 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D, 3751 const AttributeList &Attr) { 3752 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr; 3753 3754 if (!Parm) { 3755 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0; 3756 return; 3757 } 3758 3759 D->addAttr(::new (S.Context) 3760 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident, 3761 Attr.getAttributeSpellingListIndex())); 3762 } 3763 3764 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D, 3765 const AttributeList &Attr) { 3766 IdentifierInfo *RelatedClass = 3767 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr; 3768 if (!RelatedClass) { 3769 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0; 3770 return; 3771 } 3772 IdentifierInfo *ClassMethod = 3773 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr; 3774 IdentifierInfo *InstanceMethod = 3775 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr; 3776 D->addAttr(::new (S.Context) 3777 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass, 3778 ClassMethod, InstanceMethod, 3779 Attr.getAttributeSpellingListIndex())); 3780 } 3781 3782 static void handleObjCDesignatedInitializer(Sema &S, Decl *D, 3783 const AttributeList &Attr) { 3784 ObjCInterfaceDecl *IFace; 3785 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(D->getDeclContext())) 3786 IFace = CatDecl->getClassInterface(); 3787 else 3788 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext()); 3789 IFace->setHasDesignatedInitializers(); 3790 D->addAttr(::new (S.Context) 3791 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context, 3792 Attr.getAttributeSpellingListIndex())); 3793 } 3794 3795 static void handleObjCRuntimeName(Sema &S, Decl *D, 3796 const AttributeList &Attr) { 3797 StringRef MetaDataName; 3798 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName)) 3799 return; 3800 D->addAttr(::new (S.Context) 3801 ObjCRuntimeNameAttr(Attr.getRange(), S.Context, 3802 MetaDataName, 3803 Attr.getAttributeSpellingListIndex())); 3804 } 3805 3806 static void handleObjCOwnershipAttr(Sema &S, Decl *D, 3807 const AttributeList &Attr) { 3808 if (hasDeclarator(D)) return; 3809 3810 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type) 3811 << Attr.getRange() << Attr.getName() << ExpectedVariable; 3812 } 3813 3814 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D, 3815 const AttributeList &Attr) { 3816 ValueDecl *vd = cast<ValueDecl>(D); 3817 QualType type = vd->getType(); 3818 3819 if (!type->isDependentType() && 3820 !type->isObjCLifetimeType()) { 3821 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type) 3822 << type; 3823 return; 3824 } 3825 3826 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 3827 3828 // If we have no lifetime yet, check the lifetime we're presumably 3829 // going to infer. 3830 if (lifetime == Qualifiers::OCL_None && !type->isDependentType()) 3831 lifetime = type->getObjCARCImplicitLifetime(); 3832 3833 switch (lifetime) { 3834 case Qualifiers::OCL_None: 3835 assert(type->isDependentType() && 3836 "didn't infer lifetime for non-dependent type?"); 3837 break; 3838 3839 case Qualifiers::OCL_Weak: // meaningful 3840 case Qualifiers::OCL_Strong: // meaningful 3841 break; 3842 3843 case Qualifiers::OCL_ExplicitNone: 3844 case Qualifiers::OCL_Autoreleasing: 3845 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless) 3846 << (lifetime == Qualifiers::OCL_Autoreleasing); 3847 break; 3848 } 3849 3850 D->addAttr(::new (S.Context) 3851 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context, 3852 Attr.getAttributeSpellingListIndex())); 3853 } 3854 3855 //===----------------------------------------------------------------------===// 3856 // Microsoft specific attribute handlers. 3857 //===----------------------------------------------------------------------===// 3858 3859 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3860 if (!S.LangOpts.CPlusPlus) { 3861 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang) 3862 << Attr.getName() << AttributeLangSupport::C; 3863 return; 3864 } 3865 3866 if (!isa<CXXRecordDecl>(D)) { 3867 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 3868 << Attr.getName() << ExpectedClass; 3869 return; 3870 } 3871 3872 StringRef StrRef; 3873 SourceLocation LiteralLoc; 3874 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc)) 3875 return; 3876 3877 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or 3878 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former. 3879 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}') 3880 StrRef = StrRef.drop_front().drop_back(); 3881 3882 // Validate GUID length. 3883 if (StrRef.size() != 36) { 3884 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 3885 return; 3886 } 3887 3888 for (unsigned i = 0; i < 36; ++i) { 3889 if (i == 8 || i == 13 || i == 18 || i == 23) { 3890 if (StrRef[i] != '-') { 3891 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 3892 return; 3893 } 3894 } else if (!isHexDigit(StrRef[i])) { 3895 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 3896 return; 3897 } 3898 } 3899 3900 D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context, StrRef, 3901 Attr.getAttributeSpellingListIndex())); 3902 } 3903 3904 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3905 if (!S.LangOpts.CPlusPlus) { 3906 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang) 3907 << Attr.getName() << AttributeLangSupport::C; 3908 return; 3909 } 3910 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr( 3911 D, Attr.getRange(), /*BestCase=*/true, 3912 Attr.getAttributeSpellingListIndex(), 3913 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling()); 3914 if (IA) 3915 D->addAttr(IA); 3916 } 3917 3918 static void handleDeclspecThreadAttr(Sema &S, Decl *D, 3919 const AttributeList &Attr) { 3920 VarDecl *VD = cast<VarDecl>(D); 3921 if (!S.Context.getTargetInfo().isTLSSupported()) { 3922 S.Diag(Attr.getLoc(), diag::err_thread_unsupported); 3923 return; 3924 } 3925 if (VD->getTSCSpec() != TSCS_unspecified) { 3926 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable); 3927 return; 3928 } 3929 if (VD->hasLocalStorage()) { 3930 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)"; 3931 return; 3932 } 3933 VD->addAttr(::new (S.Context) ThreadAttr( 3934 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 3935 } 3936 3937 static void handleARMInterruptAttr(Sema &S, Decl *D, 3938 const AttributeList &Attr) { 3939 // Check the attribute arguments. 3940 if (Attr.getNumArgs() > 1) { 3941 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) 3942 << Attr.getName() << 1; 3943 return; 3944 } 3945 3946 StringRef Str; 3947 SourceLocation ArgLoc; 3948 3949 if (Attr.getNumArgs() == 0) 3950 Str = ""; 3951 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc)) 3952 return; 3953 3954 ARMInterruptAttr::InterruptType Kind; 3955 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { 3956 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 3957 << Attr.getName() << Str << ArgLoc; 3958 return; 3959 } 3960 3961 unsigned Index = Attr.getAttributeSpellingListIndex(); 3962 D->addAttr(::new (S.Context) 3963 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index)); 3964 } 3965 3966 static void handleMSP430InterruptAttr(Sema &S, Decl *D, 3967 const AttributeList &Attr) { 3968 if (!checkAttributeNumArgs(S, Attr, 1)) 3969 return; 3970 3971 if (!Attr.isArgExpr(0)) { 3972 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName() 3973 << AANT_ArgumentIntegerConstant; 3974 return; 3975 } 3976 3977 // FIXME: Check for decl - it should be void ()(void). 3978 3979 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 3980 llvm::APSInt NumParams(32); 3981 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) { 3982 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 3983 << Attr.getName() << AANT_ArgumentIntegerConstant 3984 << NumParamsExpr->getSourceRange(); 3985 return; 3986 } 3987 3988 unsigned Num = NumParams.getLimitedValue(255); 3989 if ((Num & 1) || Num > 30) { 3990 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 3991 << Attr.getName() << (int)NumParams.getSExtValue() 3992 << NumParamsExpr->getSourceRange(); 3993 return; 3994 } 3995 3996 D->addAttr(::new (S.Context) 3997 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num, 3998 Attr.getAttributeSpellingListIndex())); 3999 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 4000 } 4001 4002 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4003 // Dispatch the interrupt attribute based on the current target. 4004 if (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::msp430) 4005 handleMSP430InterruptAttr(S, D, Attr); 4006 else 4007 handleARMInterruptAttr(S, D, Attr); 4008 } 4009 4010 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, 4011 const AttributeList &Attr) { 4012 uint32_t NumRegs; 4013 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 4014 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs)) 4015 return; 4016 4017 D->addAttr(::new (S.Context) 4018 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context, 4019 NumRegs, 4020 Attr.getAttributeSpellingListIndex())); 4021 } 4022 4023 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, 4024 const AttributeList &Attr) { 4025 uint32_t NumRegs; 4026 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 4027 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs)) 4028 return; 4029 4030 D->addAttr(::new (S.Context) 4031 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context, 4032 NumRegs, 4033 Attr.getAttributeSpellingListIndex())); 4034 } 4035 4036 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D, 4037 const AttributeList& Attr) { 4038 // If we try to apply it to a function pointer, don't warn, but don't 4039 // do anything, either. It doesn't matter anyway, because there's nothing 4040 // special about calling a force_align_arg_pointer function. 4041 ValueDecl *VD = dyn_cast<ValueDecl>(D); 4042 if (VD && VD->getType()->isFunctionPointerType()) 4043 return; 4044 // Also don't warn on function pointer typedefs. 4045 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D); 4046 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() || 4047 TD->getUnderlyingType()->isFunctionType())) 4048 return; 4049 // Attribute can only be applied to function types. 4050 if (!isa<FunctionDecl>(D)) { 4051 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 4052 << Attr.getName() << /* function */0; 4053 return; 4054 } 4055 4056 D->addAttr(::new (S.Context) 4057 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context, 4058 Attr.getAttributeSpellingListIndex())); 4059 } 4060 4061 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range, 4062 unsigned AttrSpellingListIndex) { 4063 if (D->hasAttr<DLLExportAttr>()) { 4064 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'"; 4065 return nullptr; 4066 } 4067 4068 if (D->hasAttr<DLLImportAttr>()) 4069 return nullptr; 4070 4071 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex); 4072 } 4073 4074 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range, 4075 unsigned AttrSpellingListIndex) { 4076 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) { 4077 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import; 4078 D->dropAttr<DLLImportAttr>(); 4079 } 4080 4081 if (D->hasAttr<DLLExportAttr>()) 4082 return nullptr; 4083 4084 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex); 4085 } 4086 4087 static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) { 4088 if (isa<ClassTemplatePartialSpecializationDecl>(D) && 4089 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4090 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) 4091 << A.getName(); 4092 return; 4093 } 4094 4095 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 4096 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport && 4097 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4098 // MinGW doesn't allow dllimport on inline functions. 4099 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline) 4100 << A.getName(); 4101 return; 4102 } 4103 } 4104 4105 unsigned Index = A.getAttributeSpellingListIndex(); 4106 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport 4107 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index) 4108 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index); 4109 if (NewAttr) 4110 D->addAttr(NewAttr); 4111 } 4112 4113 MSInheritanceAttr * 4114 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase, 4115 unsigned AttrSpellingListIndex, 4116 MSInheritanceAttr::Spelling SemanticSpelling) { 4117 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) { 4118 if (IA->getSemanticSpelling() == SemanticSpelling) 4119 return nullptr; 4120 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance) 4121 << 1 /*previous declaration*/; 4122 Diag(Range.getBegin(), diag::note_previous_ms_inheritance); 4123 D->dropAttr<MSInheritanceAttr>(); 4124 } 4125 4126 CXXRecordDecl *RD = cast<CXXRecordDecl>(D); 4127 if (RD->hasDefinition()) { 4128 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase, 4129 SemanticSpelling)) { 4130 return nullptr; 4131 } 4132 } else { 4133 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) { 4134 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance) 4135 << 1 /*partial specialization*/; 4136 return nullptr; 4137 } 4138 if (RD->getDescribedClassTemplate()) { 4139 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance) 4140 << 0 /*primary template*/; 4141 return nullptr; 4142 } 4143 } 4144 4145 return ::new (Context) 4146 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex); 4147 } 4148 4149 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4150 // The capability attributes take a single string parameter for the name of 4151 // the capability they represent. The lockable attribute does not take any 4152 // parameters. However, semantically, both attributes represent the same 4153 // concept, and so they use the same semantic attribute. Eventually, the 4154 // lockable attribute will be removed. 4155 // 4156 // For backward compatibility, any capability which has no specified string 4157 // literal will be considered a "mutex." 4158 StringRef N("mutex"); 4159 SourceLocation LiteralLoc; 4160 if (Attr.getKind() == AttributeList::AT_Capability && 4161 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc)) 4162 return; 4163 4164 // Currently, there are only two names allowed for a capability: role and 4165 // mutex (case insensitive). Diagnose other capability names. 4166 if (!N.equals_lower("mutex") && !N.equals_lower("role")) 4167 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N; 4168 4169 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N, 4170 Attr.getAttributeSpellingListIndex())); 4171 } 4172 4173 static void handleAssertCapabilityAttr(Sema &S, Decl *D, 4174 const AttributeList &Attr) { 4175 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context, 4176 Attr.getArgAsExpr(0), 4177 Attr.getAttributeSpellingListIndex())); 4178 } 4179 4180 static void handleAcquireCapabilityAttr(Sema &S, Decl *D, 4181 const AttributeList &Attr) { 4182 SmallVector<Expr*, 1> Args; 4183 if (!checkLockFunAttrCommon(S, D, Attr, Args)) 4184 return; 4185 4186 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(), 4187 S.Context, 4188 Args.data(), Args.size(), 4189 Attr.getAttributeSpellingListIndex())); 4190 } 4191 4192 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D, 4193 const AttributeList &Attr) { 4194 SmallVector<Expr*, 2> Args; 4195 if (!checkTryLockFunAttrCommon(S, D, Attr, Args)) 4196 return; 4197 4198 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(), 4199 S.Context, 4200 Attr.getArgAsExpr(0), 4201 Args.data(), 4202 Args.size(), 4203 Attr.getAttributeSpellingListIndex())); 4204 } 4205 4206 static void handleReleaseCapabilityAttr(Sema &S, Decl *D, 4207 const AttributeList &Attr) { 4208 // Check that all arguments are lockable objects. 4209 SmallVector<Expr *, 1> Args; 4210 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true); 4211 4212 D->addAttr(::new (S.Context) ReleaseCapabilityAttr( 4213 Attr.getRange(), S.Context, Args.data(), Args.size(), 4214 Attr.getAttributeSpellingListIndex())); 4215 } 4216 4217 static void handleRequiresCapabilityAttr(Sema &S, Decl *D, 4218 const AttributeList &Attr) { 4219 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 4220 return; 4221 4222 // check that all arguments are lockable objects 4223 SmallVector<Expr*, 1> Args; 4224 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 4225 if (Args.empty()) 4226 return; 4227 4228 RequiresCapabilityAttr *RCA = ::new (S.Context) 4229 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(), 4230 Args.size(), Attr.getAttributeSpellingListIndex()); 4231 4232 D->addAttr(RCA); 4233 } 4234 4235 static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4236 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) { 4237 if (NSD->isAnonymousNamespace()) { 4238 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace); 4239 // Do not want to attach the attribute to the namespace because that will 4240 // cause confusing diagnostic reports for uses of declarations within the 4241 // namespace. 4242 return; 4243 } 4244 } 4245 handleAttrWithMessage<DeprecatedAttr>(S, D, Attr); 4246 } 4247 4248 /// Handles semantic checking for features that are common to all attributes, 4249 /// such as checking whether a parameter was properly specified, or the correct 4250 /// number of arguments were passed, etc. 4251 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D, 4252 const AttributeList &Attr) { 4253 // Several attributes carry different semantics than the parsing requires, so 4254 // those are opted out of the common handling. 4255 // 4256 // We also bail on unknown and ignored attributes because those are handled 4257 // as part of the target-specific handling logic. 4258 if (Attr.hasCustomParsing() || 4259 Attr.getKind() == AttributeList::UnknownAttribute) 4260 return false; 4261 4262 // Check whether the attribute requires specific language extensions to be 4263 // enabled. 4264 if (!Attr.diagnoseLangOpts(S)) 4265 return true; 4266 4267 if (Attr.getMinArgs() == Attr.getMaxArgs()) { 4268 // If there are no optional arguments, then checking for the argument count 4269 // is trivial. 4270 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs())) 4271 return true; 4272 } else { 4273 // There are optional arguments, so checking is slightly more involved. 4274 if (Attr.getMinArgs() && 4275 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs())) 4276 return true; 4277 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() && 4278 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs())) 4279 return true; 4280 } 4281 4282 // Check whether the attribute appertains to the given subject. 4283 if (!Attr.diagnoseAppertainsTo(S, D)) 4284 return true; 4285 4286 return false; 4287 } 4288 4289 //===----------------------------------------------------------------------===// 4290 // Top Level Sema Entry Points 4291 //===----------------------------------------------------------------------===// 4292 4293 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if 4294 /// the attribute applies to decls. If the attribute is a type attribute, just 4295 /// silently ignore it if a GNU attribute. 4296 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, 4297 const AttributeList &Attr, 4298 bool IncludeCXX11Attributes) { 4299 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute) 4300 return; 4301 4302 // Ignore C++11 attributes on declarator chunks: they appertain to the type 4303 // instead. 4304 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes) 4305 return; 4306 4307 // Unknown attributes are automatically warned on. Target-specific attributes 4308 // which do not apply to the current target architecture are treated as 4309 // though they were unknown attributes. 4310 if (Attr.getKind() == AttributeList::UnknownAttribute || 4311 !Attr.existsInTarget(S.Context.getTargetInfo().getTriple())) { 4312 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute() 4313 ? diag::warn_unhandled_ms_attribute_ignored 4314 : diag::warn_unknown_attribute_ignored) 4315 << Attr.getName(); 4316 return; 4317 } 4318 4319 if (handleCommonAttributeFeatures(S, scope, D, Attr)) 4320 return; 4321 4322 switch (Attr.getKind()) { 4323 default: 4324 // Type attributes are handled elsewhere; silently move on. 4325 assert(Attr.isTypeAttr() && "Non-type attribute not handled"); 4326 break; 4327 case AttributeList::AT_Interrupt: 4328 handleInterruptAttr(S, D, Attr); 4329 break; 4330 case AttributeList::AT_X86ForceAlignArgPointer: 4331 handleX86ForceAlignArgPointerAttr(S, D, Attr); 4332 break; 4333 case AttributeList::AT_DLLExport: 4334 case AttributeList::AT_DLLImport: 4335 handleDLLAttr(S, D, Attr); 4336 break; 4337 case AttributeList::AT_Mips16: 4338 handleSimpleAttribute<Mips16Attr>(S, D, Attr); 4339 break; 4340 case AttributeList::AT_NoMips16: 4341 handleSimpleAttribute<NoMips16Attr>(S, D, Attr); 4342 break; 4343 case AttributeList::AT_AMDGPUNumVGPR: 4344 handleAMDGPUNumVGPRAttr(S, D, Attr); 4345 break; 4346 case AttributeList::AT_AMDGPUNumSGPR: 4347 handleAMDGPUNumSGPRAttr(S, D, Attr); 4348 break; 4349 case AttributeList::AT_IBAction: 4350 handleSimpleAttribute<IBActionAttr>(S, D, Attr); 4351 break; 4352 case AttributeList::AT_IBOutlet: 4353 handleIBOutlet(S, D, Attr); 4354 break; 4355 case AttributeList::AT_IBOutletCollection: 4356 handleIBOutletCollection(S, D, Attr); 4357 break; 4358 case AttributeList::AT_Alias: 4359 handleAliasAttr(S, D, Attr); 4360 break; 4361 case AttributeList::AT_Aligned: 4362 handleAlignedAttr(S, D, Attr); 4363 break; 4364 case AttributeList::AT_AlignValue: 4365 handleAlignValueAttr(S, D, Attr); 4366 break; 4367 case AttributeList::AT_AlwaysInline: 4368 handleAlwaysInlineAttr(S, D, Attr); 4369 break; 4370 case AttributeList::AT_AnalyzerNoReturn: 4371 handleAnalyzerNoReturnAttr(S, D, Attr); 4372 break; 4373 case AttributeList::AT_TLSModel: 4374 handleTLSModelAttr(S, D, Attr); 4375 break; 4376 case AttributeList::AT_Annotate: 4377 handleAnnotateAttr(S, D, Attr); 4378 break; 4379 case AttributeList::AT_Availability: 4380 handleAvailabilityAttr(S, D, Attr); 4381 break; 4382 case AttributeList::AT_CarriesDependency: 4383 handleDependencyAttr(S, scope, D, Attr); 4384 break; 4385 case AttributeList::AT_Common: 4386 handleCommonAttr(S, D, Attr); 4387 break; 4388 case AttributeList::AT_CUDAConstant: 4389 handleSimpleAttribute<CUDAConstantAttr>(S, D, Attr); 4390 break; 4391 case AttributeList::AT_Constructor: 4392 handleConstructorAttr(S, D, Attr); 4393 break; 4394 case AttributeList::AT_CXX11NoReturn: 4395 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr); 4396 break; 4397 case AttributeList::AT_Deprecated: 4398 handleDeprecatedAttr(S, D, Attr); 4399 break; 4400 case AttributeList::AT_Destructor: 4401 handleDestructorAttr(S, D, Attr); 4402 break; 4403 case AttributeList::AT_EnableIf: 4404 handleEnableIfAttr(S, D, Attr); 4405 break; 4406 case AttributeList::AT_ExtVectorType: 4407 handleExtVectorTypeAttr(S, scope, D, Attr); 4408 break; 4409 case AttributeList::AT_MinSize: 4410 handleMinSizeAttr(S, D, Attr); 4411 break; 4412 case AttributeList::AT_OptimizeNone: 4413 handleOptimizeNoneAttr(S, D, Attr); 4414 break; 4415 case AttributeList::AT_FlagEnum: 4416 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr); 4417 break; 4418 case AttributeList::AT_Flatten: 4419 handleSimpleAttribute<FlattenAttr>(S, D, Attr); 4420 break; 4421 case AttributeList::AT_Format: 4422 handleFormatAttr(S, D, Attr); 4423 break; 4424 case AttributeList::AT_FormatArg: 4425 handleFormatArgAttr(S, D, Attr); 4426 break; 4427 case AttributeList::AT_CUDAGlobal: 4428 handleGlobalAttr(S, D, Attr); 4429 break; 4430 case AttributeList::AT_CUDADevice: 4431 handleSimpleAttribute<CUDADeviceAttr>(S, D, Attr); 4432 break; 4433 case AttributeList::AT_CUDAHost: 4434 handleSimpleAttribute<CUDAHostAttr>(S, D, Attr); 4435 break; 4436 case AttributeList::AT_GNUInline: 4437 handleGNUInlineAttr(S, D, Attr); 4438 break; 4439 case AttributeList::AT_CUDALaunchBounds: 4440 handleLaunchBoundsAttr(S, D, Attr); 4441 break; 4442 case AttributeList::AT_Malloc: 4443 handleMallocAttr(S, D, Attr); 4444 break; 4445 case AttributeList::AT_MayAlias: 4446 handleSimpleAttribute<MayAliasAttr>(S, D, Attr); 4447 break; 4448 case AttributeList::AT_Mode: 4449 handleModeAttr(S, D, Attr); 4450 break; 4451 case AttributeList::AT_NoCommon: 4452 handleSimpleAttribute<NoCommonAttr>(S, D, Attr); 4453 break; 4454 case AttributeList::AT_NoSplitStack: 4455 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr); 4456 break; 4457 case AttributeList::AT_NonNull: 4458 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D)) 4459 handleNonNullAttrParameter(S, PVD, Attr); 4460 else 4461 handleNonNullAttr(S, D, Attr); 4462 break; 4463 case AttributeList::AT_ReturnsNonNull: 4464 handleReturnsNonNullAttr(S, D, Attr); 4465 break; 4466 case AttributeList::AT_AssumeAligned: 4467 handleAssumeAlignedAttr(S, D, Attr); 4468 break; 4469 case AttributeList::AT_Overloadable: 4470 handleSimpleAttribute<OverloadableAttr>(S, D, Attr); 4471 break; 4472 case AttributeList::AT_Ownership: 4473 handleOwnershipAttr(S, D, Attr); 4474 break; 4475 case AttributeList::AT_Cold: 4476 handleColdAttr(S, D, Attr); 4477 break; 4478 case AttributeList::AT_Hot: 4479 handleHotAttr(S, D, Attr); 4480 break; 4481 case AttributeList::AT_Naked: 4482 handleSimpleAttribute<NakedAttr>(S, D, Attr); 4483 break; 4484 case AttributeList::AT_NoReturn: 4485 handleNoReturnAttr(S, D, Attr); 4486 break; 4487 case AttributeList::AT_NoThrow: 4488 handleSimpleAttribute<NoThrowAttr>(S, D, Attr); 4489 break; 4490 case AttributeList::AT_CUDAShared: 4491 handleSimpleAttribute<CUDASharedAttr>(S, D, Attr); 4492 break; 4493 case AttributeList::AT_VecReturn: 4494 handleVecReturnAttr(S, D, Attr); 4495 break; 4496 4497 case AttributeList::AT_ObjCOwnership: 4498 handleObjCOwnershipAttr(S, D, Attr); 4499 break; 4500 case AttributeList::AT_ObjCPreciseLifetime: 4501 handleObjCPreciseLifetimeAttr(S, D, Attr); 4502 break; 4503 4504 case AttributeList::AT_ObjCReturnsInnerPointer: 4505 handleObjCReturnsInnerPointerAttr(S, D, Attr); 4506 break; 4507 4508 case AttributeList::AT_ObjCRequiresSuper: 4509 handleObjCRequiresSuperAttr(S, D, Attr); 4510 break; 4511 4512 case AttributeList::AT_ObjCBridge: 4513 handleObjCBridgeAttr(S, scope, D, Attr); 4514 break; 4515 4516 case AttributeList::AT_ObjCBridgeMutable: 4517 handleObjCBridgeMutableAttr(S, scope, D, Attr); 4518 break; 4519 4520 case AttributeList::AT_ObjCBridgeRelated: 4521 handleObjCBridgeRelatedAttr(S, scope, D, Attr); 4522 break; 4523 4524 case AttributeList::AT_ObjCDesignatedInitializer: 4525 handleObjCDesignatedInitializer(S, D, Attr); 4526 break; 4527 4528 case AttributeList::AT_ObjCRuntimeName: 4529 handleObjCRuntimeName(S, D, Attr); 4530 break; 4531 4532 case AttributeList::AT_CFAuditedTransfer: 4533 handleCFAuditedTransferAttr(S, D, Attr); 4534 break; 4535 case AttributeList::AT_CFUnknownTransfer: 4536 handleCFUnknownTransferAttr(S, D, Attr); 4537 break; 4538 4539 case AttributeList::AT_CFConsumed: 4540 case AttributeList::AT_NSConsumed: 4541 handleNSConsumedAttr(S, D, Attr); 4542 break; 4543 case AttributeList::AT_NSConsumesSelf: 4544 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr); 4545 break; 4546 4547 case AttributeList::AT_NSReturnsAutoreleased: 4548 case AttributeList::AT_NSReturnsNotRetained: 4549 case AttributeList::AT_CFReturnsNotRetained: 4550 case AttributeList::AT_NSReturnsRetained: 4551 case AttributeList::AT_CFReturnsRetained: 4552 handleNSReturnsRetainedAttr(S, D, Attr); 4553 break; 4554 case AttributeList::AT_WorkGroupSizeHint: 4555 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr); 4556 break; 4557 case AttributeList::AT_ReqdWorkGroupSize: 4558 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr); 4559 break; 4560 case AttributeList::AT_VecTypeHint: 4561 handleVecTypeHint(S, D, Attr); 4562 break; 4563 4564 case AttributeList::AT_InitPriority: 4565 handleInitPriorityAttr(S, D, Attr); 4566 break; 4567 4568 case AttributeList::AT_Packed: 4569 handlePackedAttr(S, D, Attr); 4570 break; 4571 case AttributeList::AT_Section: 4572 handleSectionAttr(S, D, Attr); 4573 break; 4574 case AttributeList::AT_Unavailable: 4575 handleAttrWithMessage<UnavailableAttr>(S, D, Attr); 4576 break; 4577 case AttributeList::AT_ArcWeakrefUnavailable: 4578 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr); 4579 break; 4580 case AttributeList::AT_ObjCRootClass: 4581 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr); 4582 break; 4583 case AttributeList::AT_ObjCExplicitProtocolImpl: 4584 handleObjCSuppresProtocolAttr(S, D, Attr); 4585 break; 4586 case AttributeList::AT_ObjCRequiresPropertyDefs: 4587 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr); 4588 break; 4589 case AttributeList::AT_Unused: 4590 handleSimpleAttribute<UnusedAttr>(S, D, Attr); 4591 break; 4592 case AttributeList::AT_ReturnsTwice: 4593 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr); 4594 break; 4595 case AttributeList::AT_Used: 4596 handleUsedAttr(S, D, Attr); 4597 break; 4598 case AttributeList::AT_Visibility: 4599 handleVisibilityAttr(S, D, Attr, false); 4600 break; 4601 case AttributeList::AT_TypeVisibility: 4602 handleVisibilityAttr(S, D, Attr, true); 4603 break; 4604 case AttributeList::AT_WarnUnused: 4605 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr); 4606 break; 4607 case AttributeList::AT_WarnUnusedResult: 4608 handleWarnUnusedResult(S, D, Attr); 4609 break; 4610 case AttributeList::AT_Weak: 4611 handleSimpleAttribute<WeakAttr>(S, D, Attr); 4612 break; 4613 case AttributeList::AT_WeakRef: 4614 handleWeakRefAttr(S, D, Attr); 4615 break; 4616 case AttributeList::AT_WeakImport: 4617 handleWeakImportAttr(S, D, Attr); 4618 break; 4619 case AttributeList::AT_TransparentUnion: 4620 handleTransparentUnionAttr(S, D, Attr); 4621 break; 4622 case AttributeList::AT_ObjCException: 4623 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr); 4624 break; 4625 case AttributeList::AT_ObjCMethodFamily: 4626 handleObjCMethodFamilyAttr(S, D, Attr); 4627 break; 4628 case AttributeList::AT_ObjCNSObject: 4629 handleObjCNSObject(S, D, Attr); 4630 break; 4631 case AttributeList::AT_Blocks: 4632 handleBlocksAttr(S, D, Attr); 4633 break; 4634 case AttributeList::AT_Sentinel: 4635 handleSentinelAttr(S, D, Attr); 4636 break; 4637 case AttributeList::AT_Const: 4638 handleSimpleAttribute<ConstAttr>(S, D, Attr); 4639 break; 4640 case AttributeList::AT_Pure: 4641 handleSimpleAttribute<PureAttr>(S, D, Attr); 4642 break; 4643 case AttributeList::AT_Cleanup: 4644 handleCleanupAttr(S, D, Attr); 4645 break; 4646 case AttributeList::AT_NoDebug: 4647 handleNoDebugAttr(S, D, Attr); 4648 break; 4649 case AttributeList::AT_NoDuplicate: 4650 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr); 4651 break; 4652 case AttributeList::AT_NoInline: 4653 handleSimpleAttribute<NoInlineAttr>(S, D, Attr); 4654 break; 4655 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg. 4656 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr); 4657 break; 4658 case AttributeList::AT_StdCall: 4659 case AttributeList::AT_CDecl: 4660 case AttributeList::AT_FastCall: 4661 case AttributeList::AT_ThisCall: 4662 case AttributeList::AT_Pascal: 4663 case AttributeList::AT_VectorCall: 4664 case AttributeList::AT_MSABI: 4665 case AttributeList::AT_SysVABI: 4666 case AttributeList::AT_Pcs: 4667 case AttributeList::AT_PnaclCall: 4668 case AttributeList::AT_IntelOclBicc: 4669 handleCallConvAttr(S, D, Attr); 4670 break; 4671 case AttributeList::AT_OpenCLKernel: 4672 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr); 4673 break; 4674 case AttributeList::AT_OpenCLImageAccess: 4675 handleSimpleAttribute<OpenCLImageAccessAttr>(S, D, Attr); 4676 break; 4677 4678 // Microsoft attributes: 4679 case AttributeList::AT_MsStruct: 4680 handleSimpleAttribute<MsStructAttr>(S, D, Attr); 4681 break; 4682 case AttributeList::AT_Uuid: 4683 handleUuidAttr(S, D, Attr); 4684 break; 4685 case AttributeList::AT_MSInheritance: 4686 handleMSInheritanceAttr(S, D, Attr); 4687 break; 4688 case AttributeList::AT_SelectAny: 4689 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr); 4690 break; 4691 case AttributeList::AT_Thread: 4692 handleDeclspecThreadAttr(S, D, Attr); 4693 break; 4694 4695 // Thread safety attributes: 4696 case AttributeList::AT_AssertExclusiveLock: 4697 handleAssertExclusiveLockAttr(S, D, Attr); 4698 break; 4699 case AttributeList::AT_AssertSharedLock: 4700 handleAssertSharedLockAttr(S, D, Attr); 4701 break; 4702 case AttributeList::AT_GuardedVar: 4703 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr); 4704 break; 4705 case AttributeList::AT_PtGuardedVar: 4706 handlePtGuardedVarAttr(S, D, Attr); 4707 break; 4708 case AttributeList::AT_ScopedLockable: 4709 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr); 4710 break; 4711 case AttributeList::AT_NoSanitizeAddress: 4712 handleSimpleAttribute<NoSanitizeAddressAttr>(S, D, Attr); 4713 break; 4714 case AttributeList::AT_NoThreadSafetyAnalysis: 4715 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr); 4716 break; 4717 case AttributeList::AT_NoSanitizeThread: 4718 handleSimpleAttribute<NoSanitizeThreadAttr>(S, D, Attr); 4719 break; 4720 case AttributeList::AT_NoSanitizeMemory: 4721 handleSimpleAttribute<NoSanitizeMemoryAttr>(S, D, Attr); 4722 break; 4723 case AttributeList::AT_GuardedBy: 4724 handleGuardedByAttr(S, D, Attr); 4725 break; 4726 case AttributeList::AT_PtGuardedBy: 4727 handlePtGuardedByAttr(S, D, Attr); 4728 break; 4729 case AttributeList::AT_ExclusiveTrylockFunction: 4730 handleExclusiveTrylockFunctionAttr(S, D, Attr); 4731 break; 4732 case AttributeList::AT_LockReturned: 4733 handleLockReturnedAttr(S, D, Attr); 4734 break; 4735 case AttributeList::AT_LocksExcluded: 4736 handleLocksExcludedAttr(S, D, Attr); 4737 break; 4738 case AttributeList::AT_SharedTrylockFunction: 4739 handleSharedTrylockFunctionAttr(S, D, Attr); 4740 break; 4741 case AttributeList::AT_AcquiredBefore: 4742 handleAcquiredBeforeAttr(S, D, Attr); 4743 break; 4744 case AttributeList::AT_AcquiredAfter: 4745 handleAcquiredAfterAttr(S, D, Attr); 4746 break; 4747 4748 // Capability analysis attributes. 4749 case AttributeList::AT_Capability: 4750 case AttributeList::AT_Lockable: 4751 handleCapabilityAttr(S, D, Attr); 4752 break; 4753 case AttributeList::AT_RequiresCapability: 4754 handleRequiresCapabilityAttr(S, D, Attr); 4755 break; 4756 4757 case AttributeList::AT_AssertCapability: 4758 handleAssertCapabilityAttr(S, D, Attr); 4759 break; 4760 case AttributeList::AT_AcquireCapability: 4761 handleAcquireCapabilityAttr(S, D, Attr); 4762 break; 4763 case AttributeList::AT_ReleaseCapability: 4764 handleReleaseCapabilityAttr(S, D, Attr); 4765 break; 4766 case AttributeList::AT_TryAcquireCapability: 4767 handleTryAcquireCapabilityAttr(S, D, Attr); 4768 break; 4769 4770 // Consumed analysis attributes. 4771 case AttributeList::AT_Consumable: 4772 handleConsumableAttr(S, D, Attr); 4773 break; 4774 case AttributeList::AT_ConsumableAutoCast: 4775 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr); 4776 break; 4777 case AttributeList::AT_ConsumableSetOnRead: 4778 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr); 4779 break; 4780 case AttributeList::AT_CallableWhen: 4781 handleCallableWhenAttr(S, D, Attr); 4782 break; 4783 case AttributeList::AT_ParamTypestate: 4784 handleParamTypestateAttr(S, D, Attr); 4785 break; 4786 case AttributeList::AT_ReturnTypestate: 4787 handleReturnTypestateAttr(S, D, Attr); 4788 break; 4789 case AttributeList::AT_SetTypestate: 4790 handleSetTypestateAttr(S, D, Attr); 4791 break; 4792 case AttributeList::AT_TestTypestate: 4793 handleTestTypestateAttr(S, D, Attr); 4794 break; 4795 4796 // Type safety attributes. 4797 case AttributeList::AT_ArgumentWithTypeTag: 4798 handleArgumentWithTypeTagAttr(S, D, Attr); 4799 break; 4800 case AttributeList::AT_TypeTagForDatatype: 4801 handleTypeTagForDatatypeAttr(S, D, Attr); 4802 break; 4803 } 4804 } 4805 4806 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified 4807 /// attribute list to the specified decl, ignoring any type attributes. 4808 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D, 4809 const AttributeList *AttrList, 4810 bool IncludeCXX11Attributes) { 4811 for (const AttributeList* l = AttrList; l; l = l->getNext()) 4812 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes); 4813 4814 // FIXME: We should be able to handle these cases in TableGen. 4815 // GCC accepts 4816 // static int a9 __attribute__((weakref)); 4817 // but that looks really pointless. We reject it. 4818 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) { 4819 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias) 4820 << cast<NamedDecl>(D); 4821 D->dropAttr<WeakRefAttr>(); 4822 return; 4823 } 4824 4825 // FIXME: We should be able to handle this in TableGen as well. It would be 4826 // good to have a way to specify "these attributes must appear as a group", 4827 // for these. Additionally, it would be good to have a way to specify "these 4828 // attribute must never appear as a group" for attributes like cold and hot. 4829 if (!D->hasAttr<OpenCLKernelAttr>()) { 4830 // These attributes cannot be applied to a non-kernel function. 4831 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) { 4832 // FIXME: This emits a different error message than 4833 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction. 4834 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 4835 D->setInvalidDecl(); 4836 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) { 4837 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 4838 D->setInvalidDecl(); 4839 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) { 4840 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 4841 D->setInvalidDecl(); 4842 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) { 4843 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 4844 << A << ExpectedKernelFunction; 4845 D->setInvalidDecl(); 4846 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) { 4847 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 4848 << A << ExpectedKernelFunction; 4849 D->setInvalidDecl(); 4850 } 4851 } 4852 } 4853 4854 // Annotation attributes are the only attributes allowed after an access 4855 // specifier. 4856 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, 4857 const AttributeList *AttrList) { 4858 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 4859 if (l->getKind() == AttributeList::AT_Annotate) { 4860 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute()); 4861 } else { 4862 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec); 4863 return true; 4864 } 4865 } 4866 4867 return false; 4868 } 4869 4870 /// checkUnusedDeclAttributes - Check a list of attributes to see if it 4871 /// contains any decl attributes that we should warn about. 4872 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) { 4873 for ( ; A; A = A->getNext()) { 4874 // Only warn if the attribute is an unignored, non-type attribute. 4875 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue; 4876 if (A->getKind() == AttributeList::IgnoredAttribute) continue; 4877 4878 if (A->getKind() == AttributeList::UnknownAttribute) { 4879 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored) 4880 << A->getName() << A->getRange(); 4881 } else { 4882 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl) 4883 << A->getName() << A->getRange(); 4884 } 4885 } 4886 } 4887 4888 /// checkUnusedDeclAttributes - Given a declarator which is not being 4889 /// used to build a declaration, complain about any decl attributes 4890 /// which might be lying around on it. 4891 void Sema::checkUnusedDeclAttributes(Declarator &D) { 4892 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList()); 4893 ::checkUnusedDeclAttributes(*this, D.getAttributes()); 4894 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) 4895 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs()); 4896 } 4897 4898 /// DeclClonePragmaWeak - clone existing decl (maybe definition), 4899 /// \#pragma weak needs a non-definition decl and source may not have one. 4900 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 4901 SourceLocation Loc) { 4902 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND)); 4903 NamedDecl *NewD = nullptr; 4904 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 4905 FunctionDecl *NewFD; 4906 // FIXME: Missing call to CheckFunctionDeclaration(). 4907 // FIXME: Mangling? 4908 // FIXME: Is the qualifier info correct? 4909 // FIXME: Is the DeclContext correct? 4910 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(), 4911 Loc, Loc, DeclarationName(II), 4912 FD->getType(), FD->getTypeSourceInfo(), 4913 SC_None, false/*isInlineSpecified*/, 4914 FD->hasPrototype(), 4915 false/*isConstexprSpecified*/); 4916 NewD = NewFD; 4917 4918 if (FD->getQualifier()) 4919 NewFD->setQualifierInfo(FD->getQualifierLoc()); 4920 4921 // Fake up parameter variables; they are declared as if this were 4922 // a typedef. 4923 QualType FDTy = FD->getType(); 4924 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) { 4925 SmallVector<ParmVarDecl*, 16> Params; 4926 for (const auto &AI : FT->param_types()) { 4927 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI); 4928 Param->setScopeInfo(0, Params.size()); 4929 Params.push_back(Param); 4930 } 4931 NewFD->setParams(Params); 4932 } 4933 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) { 4934 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(), 4935 VD->getInnerLocStart(), VD->getLocation(), II, 4936 VD->getType(), VD->getTypeSourceInfo(), 4937 VD->getStorageClass()); 4938 if (VD->getQualifier()) { 4939 VarDecl *NewVD = cast<VarDecl>(NewD); 4940 NewVD->setQualifierInfo(VD->getQualifierLoc()); 4941 } 4942 } 4943 return NewD; 4944 } 4945 4946 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak 4947 /// applied to it, possibly with an alias. 4948 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) { 4949 if (W.getUsed()) return; // only do this once 4950 W.setUsed(true); 4951 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...)) 4952 IdentifierInfo *NDId = ND->getIdentifier(); 4953 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation()); 4954 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(), 4955 W.getLocation())); 4956 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation())); 4957 WeakTopLevelDecl.push_back(NewD); 4958 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin 4959 // to insert Decl at TU scope, sorry. 4960 DeclContext *SavedContext = CurContext; 4961 CurContext = Context.getTranslationUnitDecl(); 4962 NewD->setDeclContext(CurContext); 4963 NewD->setLexicalDeclContext(CurContext); 4964 PushOnScopeChains(NewD, S); 4965 CurContext = SavedContext; 4966 } else { // just add weak to existing 4967 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation())); 4968 } 4969 } 4970 4971 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) { 4972 // It's valid to "forward-declare" #pragma weak, in which case we 4973 // have to do this. 4974 LoadExternalWeakUndeclaredIdentifiers(); 4975 if (!WeakUndeclaredIdentifiers.empty()) { 4976 NamedDecl *ND = nullptr; 4977 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 4978 if (VD->isExternC()) 4979 ND = VD; 4980 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 4981 if (FD->isExternC()) 4982 ND = FD; 4983 if (ND) { 4984 if (IdentifierInfo *Id = ND->getIdentifier()) { 4985 llvm::DenseMap<IdentifierInfo*,WeakInfo>::iterator I 4986 = WeakUndeclaredIdentifiers.find(Id); 4987 if (I != WeakUndeclaredIdentifiers.end()) { 4988 WeakInfo W = I->second; 4989 DeclApplyPragmaWeak(S, ND, W); 4990 WeakUndeclaredIdentifiers[Id] = W; 4991 } 4992 } 4993 } 4994 } 4995 } 4996 4997 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in 4998 /// it, apply them to D. This is a bit tricky because PD can have attributes 4999 /// specified in many different places, and we need to find and apply them all. 5000 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) { 5001 // Apply decl attributes from the DeclSpec if present. 5002 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList()) 5003 ProcessDeclAttributeList(S, D, Attrs); 5004 5005 // Walk the declarator structure, applying decl attributes that were in a type 5006 // position to the decl itself. This handles cases like: 5007 // int *__attr__(x)** D; 5008 // when X is a decl attribute. 5009 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i) 5010 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs()) 5011 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false); 5012 5013 // Finally, apply any attributes on the decl itself. 5014 if (const AttributeList *Attrs = PD.getAttributes()) 5015 ProcessDeclAttributeList(S, D, Attrs); 5016 } 5017 5018 /// Is the given declaration allowed to use a forbidden type? 5019 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl) { 5020 // Private ivars are always okay. Unfortunately, people don't 5021 // always properly make their ivars private, even in system headers. 5022 // Plus we need to make fields okay, too. 5023 // Function declarations in sys headers will be marked unavailable. 5024 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) && 5025 !isa<FunctionDecl>(decl)) 5026 return false; 5027 5028 // Require it to be declared in a system header. 5029 return S.Context.getSourceManager().isInSystemHeader(decl->getLocation()); 5030 } 5031 5032 /// Handle a delayed forbidden-type diagnostic. 5033 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag, 5034 Decl *decl) { 5035 if (decl && isForbiddenTypeAllowed(S, decl)) { 5036 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, 5037 "this system declaration uses an unsupported type", 5038 diag.Loc)); 5039 return; 5040 } 5041 if (S.getLangOpts().ObjCAutoRefCount) 5042 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) { 5043 // FIXME: we may want to suppress diagnostics for all 5044 // kind of forbidden type messages on unavailable functions. 5045 if (FD->hasAttr<UnavailableAttr>() && 5046 diag.getForbiddenTypeDiagnostic() == 5047 diag::err_arc_array_param_no_ownership) { 5048 diag.Triggered = true; 5049 return; 5050 } 5051 } 5052 5053 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic()) 5054 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument(); 5055 diag.Triggered = true; 5056 } 5057 5058 5059 static bool isDeclDeprecated(Decl *D) { 5060 do { 5061 if (D->isDeprecated()) 5062 return true; 5063 // A category implicitly has the availability of the interface. 5064 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D)) 5065 return CatD->getClassInterface()->isDeprecated(); 5066 } while ((D = cast_or_null<Decl>(D->getDeclContext()))); 5067 return false; 5068 } 5069 5070 static bool isDeclUnavailable(Decl *D) { 5071 do { 5072 if (D->isUnavailable()) 5073 return true; 5074 // A category implicitly has the availability of the interface. 5075 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D)) 5076 return CatD->getClassInterface()->isUnavailable(); 5077 } while ((D = cast_or_null<Decl>(D->getDeclContext()))); 5078 return false; 5079 } 5080 5081 static void DoEmitAvailabilityWarning(Sema &S, DelayedDiagnostic::DDKind K, 5082 Decl *Ctx, const NamedDecl *D, 5083 StringRef Message, SourceLocation Loc, 5084 const ObjCInterfaceDecl *UnknownObjCClass, 5085 const ObjCPropertyDecl *ObjCProperty, 5086 bool ObjCPropertyAccess) { 5087 // Diagnostics for deprecated or unavailable. 5088 unsigned diag, diag_message, diag_fwdclass_message; 5089 5090 // Matches 'diag::note_property_attribute' options. 5091 unsigned property_note_select; 5092 5093 // Matches diag::note_availability_specified_here. 5094 unsigned available_here_select_kind; 5095 5096 // Don't warn if our current context is deprecated or unavailable. 5097 switch (K) { 5098 case DelayedDiagnostic::Deprecation: 5099 if (isDeclDeprecated(Ctx)) 5100 return; 5101 diag = !ObjCPropertyAccess ? diag::warn_deprecated 5102 : diag::warn_property_method_deprecated; 5103 diag_message = diag::warn_deprecated_message; 5104 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message; 5105 property_note_select = /* deprecated */ 0; 5106 available_here_select_kind = /* deprecated */ 2; 5107 break; 5108 5109 case DelayedDiagnostic::Unavailable: 5110 if (isDeclUnavailable(Ctx)) 5111 return; 5112 diag = !ObjCPropertyAccess ? diag::err_unavailable 5113 : diag::err_property_method_unavailable; 5114 diag_message = diag::err_unavailable_message; 5115 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message; 5116 property_note_select = /* unavailable */ 1; 5117 available_here_select_kind = /* unavailable */ 0; 5118 break; 5119 5120 default: 5121 llvm_unreachable("Neither a deprecation or unavailable kind"); 5122 } 5123 5124 if (!Message.empty()) { 5125 S.Diag(Loc, diag_message) << D << Message; 5126 if (ObjCProperty) 5127 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute) 5128 << ObjCProperty->getDeclName() << property_note_select; 5129 } else if (!UnknownObjCClass) { 5130 S.Diag(Loc, diag) << D; 5131 if (ObjCProperty) 5132 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute) 5133 << ObjCProperty->getDeclName() << property_note_select; 5134 } else { 5135 S.Diag(Loc, diag_fwdclass_message) << D; 5136 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class); 5137 } 5138 5139 S.Diag(D->getLocation(), diag::note_availability_specified_here) 5140 << D << available_here_select_kind; 5141 } 5142 5143 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD, 5144 Decl *Ctx) { 5145 DD.Triggered = true; 5146 DoEmitAvailabilityWarning(S, (DelayedDiagnostic::DDKind)DD.Kind, Ctx, 5147 DD.getDeprecationDecl(), DD.getDeprecationMessage(), 5148 DD.Loc, DD.getUnknownObjCClass(), 5149 DD.getObjCProperty(), false); 5150 } 5151 5152 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) { 5153 assert(DelayedDiagnostics.getCurrentPool()); 5154 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool(); 5155 DelayedDiagnostics.popWithoutEmitting(state); 5156 5157 // When delaying diagnostics to run in the context of a parsed 5158 // declaration, we only want to actually emit anything if parsing 5159 // succeeds. 5160 if (!decl) return; 5161 5162 // We emit all the active diagnostics in this pool or any of its 5163 // parents. In general, we'll get one pool for the decl spec 5164 // and a child pool for each declarator; in a decl group like: 5165 // deprecated_typedef foo, *bar, baz(); 5166 // only the declarator pops will be passed decls. This is correct; 5167 // we really do need to consider delayed diagnostics from the decl spec 5168 // for each of the different declarations. 5169 const DelayedDiagnosticPool *pool = &poppedPool; 5170 do { 5171 for (DelayedDiagnosticPool::pool_iterator 5172 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) { 5173 // This const_cast is a bit lame. Really, Triggered should be mutable. 5174 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i); 5175 if (diag.Triggered) 5176 continue; 5177 5178 switch (diag.Kind) { 5179 case DelayedDiagnostic::Deprecation: 5180 case DelayedDiagnostic::Unavailable: 5181 // Don't bother giving deprecation/unavailable diagnostics if 5182 // the decl is invalid. 5183 if (!decl->isInvalidDecl()) 5184 handleDelayedAvailabilityCheck(*this, diag, decl); 5185 break; 5186 5187 case DelayedDiagnostic::Access: 5188 HandleDelayedAccessCheck(diag, decl); 5189 break; 5190 5191 case DelayedDiagnostic::ForbiddenType: 5192 handleDelayedForbiddenType(*this, diag, decl); 5193 break; 5194 } 5195 } 5196 } while ((pool = pool->getParent())); 5197 } 5198 5199 /// Given a set of delayed diagnostics, re-emit them as if they had 5200 /// been delayed in the current context instead of in the given pool. 5201 /// Essentially, this just moves them to the current pool. 5202 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) { 5203 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool(); 5204 assert(curPool && "re-emitting in undelayed context not supported"); 5205 curPool->steal(pool); 5206 } 5207 5208 void Sema::EmitAvailabilityWarning(AvailabilityDiagnostic AD, 5209 NamedDecl *D, StringRef Message, 5210 SourceLocation Loc, 5211 const ObjCInterfaceDecl *UnknownObjCClass, 5212 const ObjCPropertyDecl *ObjCProperty, 5213 bool ObjCPropertyAccess) { 5214 // Delay if we're currently parsing a declaration. 5215 if (DelayedDiagnostics.shouldDelayDiagnostics()) { 5216 DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability(AD, Loc, D, 5217 UnknownObjCClass, 5218 ObjCProperty, 5219 Message, 5220 ObjCPropertyAccess)); 5221 return; 5222 } 5223 5224 Decl *Ctx = cast<Decl>(getCurLexicalContext()); 5225 DelayedDiagnostic::DDKind K; 5226 switch (AD) { 5227 case AD_Deprecation: 5228 K = DelayedDiagnostic::Deprecation; 5229 break; 5230 case AD_Unavailable: 5231 K = DelayedDiagnostic::Unavailable; 5232 break; 5233 } 5234 5235 DoEmitAvailabilityWarning(*this, K, Ctx, D, Message, Loc, 5236 UnknownObjCClass, ObjCProperty, ObjCPropertyAccess); 5237 } 5238