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