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