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