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