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