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