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/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/DeclCXX.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/Mangle.h" 24 #include "clang/AST/ASTMutationListener.h" 25 #include "clang/Basic/CharInfo.h" 26 #include "clang/Basic/SourceManager.h" 27 #include "clang/Basic/TargetInfo.h" 28 #include "clang/Lex/Preprocessor.h" 29 #include "clang/Sema/DeclSpec.h" 30 #include "clang/Sema/DelayedDiagnostic.h" 31 #include "clang/Sema/Lookup.h" 32 #include "clang/Sema/Scope.h" 33 #include "llvm/ADT/StringExtras.h" 34 #include "llvm/Support/MathExtras.h" 35 36 using namespace clang; 37 using namespace sema; 38 39 namespace AttributeLangSupport { 40 enum LANG { 41 C, 42 Cpp, 43 ObjC 44 }; 45 } // end namespace AttributeLangSupport 46 47 //===----------------------------------------------------------------------===// 48 // Helper functions 49 //===----------------------------------------------------------------------===// 50 51 /// isFunctionOrMethod - Return true if the given decl has function 52 /// type (function or function-typed variable) or an Objective-C 53 /// method. 54 static bool isFunctionOrMethod(const Decl *D) { 55 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D); 56 } 57 58 /// \brief Return true if the given decl has function type (function or 59 /// function-typed variable) or an Objective-C method or a block. 60 static bool isFunctionOrMethodOrBlock(const Decl *D) { 61 return isFunctionOrMethod(D) || isa<BlockDecl>(D); 62 } 63 64 /// Return true if the given decl has a declarator that should have 65 /// been processed by Sema::GetTypeForDeclarator. 66 static bool hasDeclarator(const Decl *D) { 67 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl. 68 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) || 69 isa<ObjCPropertyDecl>(D); 70 } 71 72 /// hasFunctionProto - Return true if the given decl has a argument 73 /// information. This decl should have already passed 74 /// isFunctionOrMethod or isFunctionOrMethodOrBlock. 75 static bool hasFunctionProto(const Decl *D) { 76 if (const FunctionType *FnTy = D->getFunctionType()) 77 return isa<FunctionProtoType>(FnTy); 78 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D); 79 } 80 81 /// getFunctionOrMethodNumParams - Return number of function or method 82 /// parameters. It is an error to call this on a K&R function (use 83 /// hasFunctionProto first). 84 static unsigned getFunctionOrMethodNumParams(const Decl *D) { 85 if (const FunctionType *FnTy = D->getFunctionType()) 86 return cast<FunctionProtoType>(FnTy)->getNumParams(); 87 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) 88 return BD->getNumParams(); 89 return cast<ObjCMethodDecl>(D)->param_size(); 90 } 91 92 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) { 93 if (const FunctionType *FnTy = D->getFunctionType()) 94 return cast<FunctionProtoType>(FnTy)->getParamType(Idx); 95 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) 96 return BD->getParamDecl(Idx)->getType(); 97 98 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType(); 99 } 100 101 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) { 102 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 103 return FD->getParamDecl(Idx)->getSourceRange(); 104 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 105 return MD->parameters()[Idx]->getSourceRange(); 106 if (const auto *BD = dyn_cast<BlockDecl>(D)) 107 return BD->getParamDecl(Idx)->getSourceRange(); 108 return SourceRange(); 109 } 110 111 static QualType getFunctionOrMethodResultType(const Decl *D) { 112 if (const FunctionType *FnTy = D->getFunctionType()) 113 return cast<FunctionType>(FnTy)->getReturnType(); 114 return cast<ObjCMethodDecl>(D)->getReturnType(); 115 } 116 117 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) { 118 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 119 return FD->getReturnTypeSourceRange(); 120 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 121 return MD->getReturnTypeSourceRange(); 122 return SourceRange(); 123 } 124 125 static bool isFunctionOrMethodVariadic(const Decl *D) { 126 if (const FunctionType *FnTy = D->getFunctionType()) { 127 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy); 128 return proto->isVariadic(); 129 } 130 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) 131 return BD->isVariadic(); 132 133 return cast<ObjCMethodDecl>(D)->isVariadic(); 134 } 135 136 static bool isInstanceMethod(const Decl *D) { 137 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) 138 return MethodDecl->isInstance(); 139 return false; 140 } 141 142 static inline bool isNSStringType(QualType T, ASTContext &Ctx) { 143 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>(); 144 if (!PT) 145 return false; 146 147 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface(); 148 if (!Cls) 149 return false; 150 151 IdentifierInfo* ClsName = Cls->getIdentifier(); 152 153 // FIXME: Should we walk the chain of classes? 154 return ClsName == &Ctx.Idents.get("NSString") || 155 ClsName == &Ctx.Idents.get("NSMutableString"); 156 } 157 158 static inline bool isCFStringType(QualType T, ASTContext &Ctx) { 159 const PointerType *PT = T->getAs<PointerType>(); 160 if (!PT) 161 return false; 162 163 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>(); 164 if (!RT) 165 return false; 166 167 const RecordDecl *RD = RT->getDecl(); 168 if (RD->getTagKind() != TTK_Struct) 169 return false; 170 171 return RD->getIdentifier() == &Ctx.Idents.get("__CFString"); 172 } 173 174 static unsigned getNumAttributeArgs(const AttributeList &Attr) { 175 // FIXME: Include the type in the argument list. 176 return Attr.getNumArgs() + Attr.hasParsedType(); 177 } 178 179 template <typename Compare> 180 static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr, 181 unsigned Num, unsigned Diag, 182 Compare Comp) { 183 if (Comp(getNumAttributeArgs(Attr), Num)) { 184 S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num; 185 return false; 186 } 187 188 return true; 189 } 190 191 /// \brief Check if the attribute has exactly as many args as Num. May 192 /// output an error. 193 static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr, 194 unsigned Num) { 195 return checkAttributeNumArgsImpl(S, Attr, Num, 196 diag::err_attribute_wrong_number_arguments, 197 std::not_equal_to<unsigned>()); 198 } 199 200 /// \brief Check if the attribute has at least as many args as Num. May 201 /// output an error. 202 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr, 203 unsigned Num) { 204 return checkAttributeNumArgsImpl(S, Attr, Num, 205 diag::err_attribute_too_few_arguments, 206 std::less<unsigned>()); 207 } 208 209 /// \brief Check if the attribute has at most as many args as Num. May 210 /// output an error. 211 static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr, 212 unsigned Num) { 213 return checkAttributeNumArgsImpl(S, Attr, Num, 214 diag::err_attribute_too_many_arguments, 215 std::greater<unsigned>()); 216 } 217 218 /// \brief If Expr is a valid integer constant, get the value of the integer 219 /// expression and return success or failure. May output an error. 220 static bool checkUInt32Argument(Sema &S, const AttributeList &Attr, 221 const Expr *Expr, uint32_t &Val, 222 unsigned Idx = UINT_MAX) { 223 llvm::APSInt I(32); 224 if (Expr->isTypeDependent() || Expr->isValueDependent() || 225 !Expr->isIntegerConstantExpr(I, S.Context)) { 226 if (Idx != UINT_MAX) 227 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 228 << Attr.getName() << Idx << AANT_ArgumentIntegerConstant 229 << Expr->getSourceRange(); 230 else 231 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 232 << Attr.getName() << AANT_ArgumentIntegerConstant 233 << Expr->getSourceRange(); 234 return false; 235 } 236 237 if (!I.isIntN(32)) { 238 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large) 239 << I.toString(10, false) << 32 << /* Unsigned */ 1; 240 return false; 241 } 242 243 Val = (uint32_t)I.getZExtValue(); 244 return true; 245 } 246 247 /// \brief Diagnose mutually exclusive attributes when present on a given 248 /// declaration. Returns true if diagnosed. 249 template <typename AttrTy> 250 static bool checkAttrMutualExclusion(Sema &S, Decl *D, SourceRange Range, 251 IdentifierInfo *Ident) { 252 if (AttrTy *A = D->getAttr<AttrTy>()) { 253 S.Diag(Range.getBegin(), diag::err_attributes_are_not_compatible) << Ident 254 << A; 255 S.Diag(A->getLocation(), diag::note_conflicting_attribute); 256 return true; 257 } 258 return false; 259 } 260 261 /// \brief Check if IdxExpr is a valid parameter index for a function or 262 /// instance method D. May output an error. 263 /// 264 /// \returns true if IdxExpr is a valid index. 265 static bool checkFunctionOrMethodParameterIndex(Sema &S, const Decl *D, 266 const AttributeList &Attr, 267 unsigned AttrArgNum, 268 const Expr *IdxExpr, 269 uint64_t &Idx) { 270 assert(isFunctionOrMethodOrBlock(D)); 271 272 // In C++ the implicit 'this' function parameter also counts. 273 // Parameters are counted from one. 274 bool HP = hasFunctionProto(D); 275 bool HasImplicitThisParam = isInstanceMethod(D); 276 bool IV = HP && isFunctionOrMethodVariadic(D); 277 unsigned NumParams = 278 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam; 279 280 llvm::APSInt IdxInt; 281 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() || 282 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) { 283 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 284 << Attr.getName() << AttrArgNum << AANT_ArgumentIntegerConstant 285 << IdxExpr->getSourceRange(); 286 return false; 287 } 288 289 Idx = IdxInt.getLimitedValue(); 290 if (Idx < 1 || (!IV && Idx > NumParams)) { 291 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 292 << Attr.getName() << AttrArgNum << IdxExpr->getSourceRange(); 293 return false; 294 } 295 Idx--; // Convert to zero-based. 296 if (HasImplicitThisParam) { 297 if (Idx == 0) { 298 S.Diag(Attr.getLoc(), 299 diag::err_attribute_invalid_implicit_this_argument) 300 << Attr.getName() << IdxExpr->getSourceRange(); 301 return false; 302 } 303 --Idx; 304 } 305 306 return true; 307 } 308 309 /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal. 310 /// If not emit an error and return false. If the argument is an identifier it 311 /// will emit an error with a fixit hint and treat it as if it was a string 312 /// literal. 313 bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr, 314 unsigned ArgNum, StringRef &Str, 315 SourceLocation *ArgLocation) { 316 // Look for identifiers. If we have one emit a hint to fix it to a literal. 317 if (Attr.isArgIdent(ArgNum)) { 318 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum); 319 Diag(Loc->Loc, diag::err_attribute_argument_type) 320 << Attr.getName() << AANT_ArgumentString 321 << FixItHint::CreateInsertion(Loc->Loc, "\"") 322 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\""); 323 Str = Loc->Ident->getName(); 324 if (ArgLocation) 325 *ArgLocation = Loc->Loc; 326 return true; 327 } 328 329 // Now check for an actual string literal. 330 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum); 331 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts()); 332 if (ArgLocation) 333 *ArgLocation = ArgExpr->getLocStart(); 334 335 if (!Literal || !Literal->isAscii()) { 336 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type) 337 << Attr.getName() << AANT_ArgumentString; 338 return false; 339 } 340 341 Str = Literal->getString(); 342 return true; 343 } 344 345 /// \brief Applies the given attribute to the Decl without performing any 346 /// additional semantic checking. 347 template <typename AttrType> 348 static void handleSimpleAttribute(Sema &S, Decl *D, 349 const AttributeList &Attr) { 350 D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context, 351 Attr.getAttributeSpellingListIndex())); 352 } 353 354 template <typename AttrType> 355 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D, 356 const AttributeList &Attr) { 357 handleSimpleAttribute<AttrType>(S, D, Attr); 358 } 359 360 /// \brief Applies the given attribute to the Decl so long as the Decl doesn't 361 /// already have one of the given incompatible attributes. 362 template <typename AttrType, typename IncompatibleAttrType, 363 typename... IncompatibleAttrTypes> 364 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D, 365 const AttributeList &Attr) { 366 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, Attr.getRange(), 367 Attr.getName())) 368 return; 369 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D, 370 Attr); 371 } 372 373 /// \brief Check if the passed-in expression is of type int or bool. 374 static bool isIntOrBool(Expr *Exp) { 375 QualType QT = Exp->getType(); 376 return QT->isBooleanType() || QT->isIntegerType(); 377 } 378 379 380 // Check to see if the type is a smart pointer of some kind. We assume 381 // it's a smart pointer if it defines both operator-> and operator*. 382 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) { 383 DeclContextLookupResult Res1 = RT->getDecl()->lookup( 384 S.Context.DeclarationNames.getCXXOperatorName(OO_Star)); 385 if (Res1.empty()) 386 return false; 387 388 DeclContextLookupResult Res2 = RT->getDecl()->lookup( 389 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow)); 390 if (Res2.empty()) 391 return false; 392 393 return true; 394 } 395 396 /// \brief Check if passed in Decl is a pointer type. 397 /// Note that this function may produce an error message. 398 /// \return true if the Decl is a pointer type; false otherwise 399 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D, 400 const AttributeList &Attr) { 401 const ValueDecl *vd = cast<ValueDecl>(D); 402 QualType QT = vd->getType(); 403 if (QT->isAnyPointerType()) 404 return true; 405 406 if (const RecordType *RT = QT->getAs<RecordType>()) { 407 // If it's an incomplete type, it could be a smart pointer; skip it. 408 // (We don't want to force template instantiation if we can avoid it, 409 // since that would alter the order in which templates are instantiated.) 410 if (RT->isIncompleteType()) 411 return true; 412 413 if (threadSafetyCheckIsSmartPointer(S, RT)) 414 return true; 415 } 416 417 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer) 418 << Attr.getName() << QT; 419 return false; 420 } 421 422 /// \brief Checks that the passed in QualType either is of RecordType or points 423 /// to RecordType. Returns the relevant RecordType, null if it does not exit. 424 static const RecordType *getRecordType(QualType QT) { 425 if (const RecordType *RT = QT->getAs<RecordType>()) 426 return RT; 427 428 // Now check if we point to record type. 429 if (const PointerType *PT = QT->getAs<PointerType>()) 430 return PT->getPointeeType()->getAs<RecordType>(); 431 432 return nullptr; 433 } 434 435 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) { 436 const RecordType *RT = getRecordType(Ty); 437 438 if (!RT) 439 return false; 440 441 // Don't check for the capability if the class hasn't been defined yet. 442 if (RT->isIncompleteType()) 443 return true; 444 445 // Allow smart pointers to be used as capability objects. 446 // FIXME -- Check the type that the smart pointer points to. 447 if (threadSafetyCheckIsSmartPointer(S, RT)) 448 return true; 449 450 // Check if the record itself has a capability. 451 RecordDecl *RD = RT->getDecl(); 452 if (RD->hasAttr<CapabilityAttr>()) 453 return true; 454 455 // Else check if any base classes have a capability. 456 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 457 CXXBasePaths BPaths(false, false); 458 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) { 459 const auto *Type = BS->getType()->getAs<RecordType>(); 460 return Type->getDecl()->hasAttr<CapabilityAttr>(); 461 }, BPaths)) 462 return true; 463 } 464 return false; 465 } 466 467 static bool checkTypedefTypeForCapability(QualType Ty) { 468 const auto *TD = Ty->getAs<TypedefType>(); 469 if (!TD) 470 return false; 471 472 TypedefNameDecl *TN = TD->getDecl(); 473 if (!TN) 474 return false; 475 476 return TN->hasAttr<CapabilityAttr>(); 477 } 478 479 static bool typeHasCapability(Sema &S, QualType Ty) { 480 if (checkTypedefTypeForCapability(Ty)) 481 return true; 482 483 if (checkRecordTypeForCapability(S, Ty)) 484 return true; 485 486 return false; 487 } 488 489 static bool isCapabilityExpr(Sema &S, const Expr *Ex) { 490 // Capability expressions are simple expressions involving the boolean logic 491 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once 492 // a DeclRefExpr is found, its type should be checked to determine whether it 493 // is a capability or not. 494 495 if (const auto *E = dyn_cast<DeclRefExpr>(Ex)) 496 return typeHasCapability(S, E->getType()); 497 else if (const auto *E = dyn_cast<CastExpr>(Ex)) 498 return isCapabilityExpr(S, E->getSubExpr()); 499 else if (const auto *E = dyn_cast<ParenExpr>(Ex)) 500 return isCapabilityExpr(S, E->getSubExpr()); 501 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) { 502 if (E->getOpcode() == UO_LNot) 503 return isCapabilityExpr(S, E->getSubExpr()); 504 return false; 505 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) { 506 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr) 507 return isCapabilityExpr(S, E->getLHS()) && 508 isCapabilityExpr(S, E->getRHS()); 509 return false; 510 } 511 512 return false; 513 } 514 515 /// \brief Checks that all attribute arguments, starting from Sidx, resolve to 516 /// a capability object. 517 /// \param Sidx The attribute argument index to start checking with. 518 /// \param ParamIdxOk Whether an argument can be indexing into a function 519 /// parameter list. 520 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D, 521 const AttributeList &Attr, 522 SmallVectorImpl<Expr *> &Args, 523 int Sidx = 0, 524 bool ParamIdxOk = false) { 525 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) { 526 Expr *ArgExp = Attr.getArgAsExpr(Idx); 527 528 if (ArgExp->isTypeDependent()) { 529 // FIXME -- need to check this again on template instantiation 530 Args.push_back(ArgExp); 531 continue; 532 } 533 534 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) { 535 if (StrLit->getLength() == 0 || 536 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) { 537 // Pass empty strings to the analyzer without warnings. 538 // Treat "*" as the universal lock. 539 Args.push_back(ArgExp); 540 continue; 541 } 542 543 // We allow constant strings to be used as a placeholder for expressions 544 // that are not valid C++ syntax, but warn that they are ignored. 545 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) << 546 Attr.getName(); 547 Args.push_back(ArgExp); 548 continue; 549 } 550 551 QualType ArgTy = ArgExp->getType(); 552 553 // A pointer to member expression of the form &MyClass::mu is treated 554 // specially -- we need to look at the type of the member. 555 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp)) 556 if (UOp->getOpcode() == UO_AddrOf) 557 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr())) 558 if (DRE->getDecl()->isCXXInstanceMember()) 559 ArgTy = DRE->getDecl()->getType(); 560 561 // First see if we can just cast to record type, or pointer to record type. 562 const RecordType *RT = getRecordType(ArgTy); 563 564 // Now check if we index into a record type function param. 565 if(!RT && ParamIdxOk) { 566 FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 567 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp); 568 if(FD && IL) { 569 unsigned int NumParams = FD->getNumParams(); 570 llvm::APInt ArgValue = IL->getValue(); 571 uint64_t ParamIdxFromOne = ArgValue.getZExtValue(); 572 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1; 573 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) { 574 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range) 575 << Attr.getName() << Idx + 1 << NumParams; 576 continue; 577 } 578 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType(); 579 } 580 } 581 582 // If the type does not have a capability, see if the components of the 583 // expression have capabilities. This allows for writing C code where the 584 // capability may be on the type, and the expression is a capability 585 // boolean logic expression. Eg) requires_capability(A || B && !C) 586 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp)) 587 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable) 588 << Attr.getName() << ArgTy; 589 590 Args.push_back(ArgExp); 591 } 592 } 593 594 //===----------------------------------------------------------------------===// 595 // Attribute Implementations 596 //===----------------------------------------------------------------------===// 597 598 static void handlePtGuardedVarAttr(Sema &S, Decl *D, 599 const AttributeList &Attr) { 600 if (!threadSafetyCheckIsPointer(S, D, Attr)) 601 return; 602 603 D->addAttr(::new (S.Context) 604 PtGuardedVarAttr(Attr.getRange(), S.Context, 605 Attr.getAttributeSpellingListIndex())); 606 } 607 608 static bool checkGuardedByAttrCommon(Sema &S, Decl *D, 609 const AttributeList &Attr, 610 Expr* &Arg) { 611 SmallVector<Expr*, 1> Args; 612 // check that all arguments are lockable objects 613 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 614 unsigned Size = Args.size(); 615 if (Size != 1) 616 return false; 617 618 Arg = Args[0]; 619 620 return true; 621 } 622 623 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) { 624 Expr *Arg = nullptr; 625 if (!checkGuardedByAttrCommon(S, D, Attr, Arg)) 626 return; 627 628 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg, 629 Attr.getAttributeSpellingListIndex())); 630 } 631 632 static void handlePtGuardedByAttr(Sema &S, Decl *D, 633 const AttributeList &Attr) { 634 Expr *Arg = nullptr; 635 if (!checkGuardedByAttrCommon(S, D, Attr, Arg)) 636 return; 637 638 if (!threadSafetyCheckIsPointer(S, D, Attr)) 639 return; 640 641 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(), 642 S.Context, Arg, 643 Attr.getAttributeSpellingListIndex())); 644 } 645 646 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, 647 const AttributeList &Attr, 648 SmallVectorImpl<Expr *> &Args) { 649 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 650 return false; 651 652 // Check that this attribute only applies to lockable types. 653 QualType QT = cast<ValueDecl>(D)->getType(); 654 if (!QT->isDependentType() && !typeHasCapability(S, QT)) { 655 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable) 656 << Attr.getName(); 657 return false; 658 } 659 660 // Check that all arguments are lockable objects. 661 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 662 if (Args.empty()) 663 return false; 664 665 return true; 666 } 667 668 static void handleAcquiredAfterAttr(Sema &S, Decl *D, 669 const AttributeList &Attr) { 670 SmallVector<Expr*, 1> Args; 671 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args)) 672 return; 673 674 Expr **StartArg = &Args[0]; 675 D->addAttr(::new (S.Context) 676 AcquiredAfterAttr(Attr.getRange(), S.Context, 677 StartArg, Args.size(), 678 Attr.getAttributeSpellingListIndex())); 679 } 680 681 static void handleAcquiredBeforeAttr(Sema &S, Decl *D, 682 const AttributeList &Attr) { 683 SmallVector<Expr*, 1> Args; 684 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args)) 685 return; 686 687 Expr **StartArg = &Args[0]; 688 D->addAttr(::new (S.Context) 689 AcquiredBeforeAttr(Attr.getRange(), S.Context, 690 StartArg, Args.size(), 691 Attr.getAttributeSpellingListIndex())); 692 } 693 694 static bool checkLockFunAttrCommon(Sema &S, Decl *D, 695 const AttributeList &Attr, 696 SmallVectorImpl<Expr *> &Args) { 697 // zero or more arguments ok 698 // check that all arguments are lockable objects 699 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true); 700 701 return true; 702 } 703 704 static void handleAssertSharedLockAttr(Sema &S, Decl *D, 705 const AttributeList &Attr) { 706 SmallVector<Expr*, 1> Args; 707 if (!checkLockFunAttrCommon(S, D, Attr, Args)) 708 return; 709 710 unsigned Size = Args.size(); 711 Expr **StartArg = Size == 0 ? nullptr : &Args[0]; 712 D->addAttr(::new (S.Context) 713 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size, 714 Attr.getAttributeSpellingListIndex())); 715 } 716 717 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D, 718 const AttributeList &Attr) { 719 SmallVector<Expr*, 1> Args; 720 if (!checkLockFunAttrCommon(S, D, Attr, Args)) 721 return; 722 723 unsigned Size = Args.size(); 724 Expr **StartArg = Size == 0 ? nullptr : &Args[0]; 725 D->addAttr(::new (S.Context) 726 AssertExclusiveLockAttr(Attr.getRange(), S.Context, 727 StartArg, Size, 728 Attr.getAttributeSpellingListIndex())); 729 } 730 731 732 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, 733 const AttributeList &Attr, 734 SmallVectorImpl<Expr *> &Args) { 735 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 736 return false; 737 738 if (!isIntOrBool(Attr.getArgAsExpr(0))) { 739 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 740 << Attr.getName() << 1 << AANT_ArgumentIntOrBool; 741 return false; 742 } 743 744 // check that all arguments are lockable objects 745 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1); 746 747 return true; 748 } 749 750 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D, 751 const AttributeList &Attr) { 752 SmallVector<Expr*, 2> Args; 753 if (!checkTryLockFunAttrCommon(S, D, Attr, Args)) 754 return; 755 756 D->addAttr(::new (S.Context) 757 SharedTrylockFunctionAttr(Attr.getRange(), S.Context, 758 Attr.getArgAsExpr(0), 759 Args.data(), Args.size(), 760 Attr.getAttributeSpellingListIndex())); 761 } 762 763 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D, 764 const AttributeList &Attr) { 765 SmallVector<Expr*, 2> Args; 766 if (!checkTryLockFunAttrCommon(S, D, Attr, Args)) 767 return; 768 769 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr( 770 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(), 771 Args.size(), Attr.getAttributeSpellingListIndex())); 772 } 773 774 static void handleLockReturnedAttr(Sema &S, Decl *D, 775 const AttributeList &Attr) { 776 // check that the argument is lockable object 777 SmallVector<Expr*, 1> Args; 778 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 779 unsigned Size = Args.size(); 780 if (Size == 0) 781 return; 782 783 D->addAttr(::new (S.Context) 784 LockReturnedAttr(Attr.getRange(), S.Context, Args[0], 785 Attr.getAttributeSpellingListIndex())); 786 } 787 788 static void handleLocksExcludedAttr(Sema &S, Decl *D, 789 const AttributeList &Attr) { 790 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 791 return; 792 793 // check that all arguments are lockable objects 794 SmallVector<Expr*, 1> Args; 795 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 796 unsigned Size = Args.size(); 797 if (Size == 0) 798 return; 799 Expr **StartArg = &Args[0]; 800 801 D->addAttr(::new (S.Context) 802 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size, 803 Attr.getAttributeSpellingListIndex())); 804 } 805 806 static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) { 807 S.Diag(Attr.getLoc(), diag::ext_clang_enable_if); 808 809 Expr *Cond = Attr.getArgAsExpr(0); 810 if (!Cond->isTypeDependent()) { 811 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond); 812 if (Converted.isInvalid()) 813 return; 814 Cond = Converted.get(); 815 } 816 817 StringRef Msg; 818 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg)) 819 return; 820 821 SmallVector<PartialDiagnosticAt, 8> Diags; 822 if (!Cond->isValueDependent() && 823 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D), 824 Diags)) { 825 S.Diag(Attr.getLoc(), diag::err_enable_if_never_constant_expr); 826 for (int I = 0, N = Diags.size(); I != N; ++I) 827 S.Diag(Diags[I].first, Diags[I].second); 828 return; 829 } 830 831 D->addAttr(::new (S.Context) 832 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg, 833 Attr.getAttributeSpellingListIndex())); 834 } 835 836 static void handlePassObjectSizeAttr(Sema &S, Decl *D, 837 const AttributeList &Attr) { 838 if (D->hasAttr<PassObjectSizeAttr>()) { 839 S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter) 840 << Attr.getName(); 841 return; 842 } 843 844 Expr *E = Attr.getArgAsExpr(0); 845 uint32_t Type; 846 if (!checkUInt32Argument(S, Attr, E, Type, /*Idx=*/1)) 847 return; 848 849 // pass_object_size's argument is passed in as the second argument of 850 // __builtin_object_size. So, it has the same constraints as that second 851 // argument; namely, it must be in the range [0, 3]. 852 if (Type > 3) { 853 S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range) 854 << Attr.getName() << 0 << 3 << E->getSourceRange(); 855 return; 856 } 857 858 // pass_object_size is only supported on constant pointer parameters; as a 859 // kindness to users, we allow the parameter to be non-const for declarations. 860 // At this point, we have no clue if `D` belongs to a function declaration or 861 // definition, so we defer the constness check until later. 862 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) { 863 S.Diag(D->getLocStart(), diag::err_attribute_pointers_only) 864 << Attr.getName() << 1; 865 return; 866 } 867 868 D->addAttr(::new (S.Context) 869 PassObjectSizeAttr(Attr.getRange(), S.Context, (int)Type, 870 Attr.getAttributeSpellingListIndex())); 871 } 872 873 static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) { 874 ConsumableAttr::ConsumedState DefaultState; 875 876 if (Attr.isArgIdent(0)) { 877 IdentifierLoc *IL = Attr.getArgAsIdent(0); 878 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(), 879 DefaultState)) { 880 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) 881 << Attr.getName() << IL->Ident; 882 return; 883 } 884 } else { 885 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 886 << Attr.getName() << AANT_ArgumentIdentifier; 887 return; 888 } 889 890 D->addAttr(::new (S.Context) 891 ConsumableAttr(Attr.getRange(), S.Context, DefaultState, 892 Attr.getAttributeSpellingListIndex())); 893 } 894 895 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD, 896 const AttributeList &Attr) { 897 ASTContext &CurrContext = S.getASTContext(); 898 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType(); 899 900 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) { 901 if (!RD->hasAttr<ConsumableAttr>()) { 902 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) << 903 RD->getNameAsString(); 904 905 return false; 906 } 907 } 908 909 return true; 910 } 911 912 static void handleCallableWhenAttr(Sema &S, Decl *D, 913 const AttributeList &Attr) { 914 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 915 return; 916 917 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr)) 918 return; 919 920 SmallVector<CallableWhenAttr::ConsumedState, 3> States; 921 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) { 922 CallableWhenAttr::ConsumedState CallableState; 923 924 StringRef StateString; 925 SourceLocation Loc; 926 if (Attr.isArgIdent(ArgIndex)) { 927 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex); 928 StateString = Ident->Ident->getName(); 929 Loc = Ident->Loc; 930 } else { 931 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc)) 932 return; 933 } 934 935 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString, 936 CallableState)) { 937 S.Diag(Loc, diag::warn_attribute_type_not_supported) 938 << Attr.getName() << StateString; 939 return; 940 } 941 942 States.push_back(CallableState); 943 } 944 945 D->addAttr(::new (S.Context) 946 CallableWhenAttr(Attr.getRange(), S.Context, States.data(), 947 States.size(), Attr.getAttributeSpellingListIndex())); 948 } 949 950 static void handleParamTypestateAttr(Sema &S, Decl *D, 951 const AttributeList &Attr) { 952 ParamTypestateAttr::ConsumedState ParamState; 953 954 if (Attr.isArgIdent(0)) { 955 IdentifierLoc *Ident = Attr.getArgAsIdent(0); 956 StringRef StateString = Ident->Ident->getName(); 957 958 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString, 959 ParamState)) { 960 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) 961 << Attr.getName() << StateString; 962 return; 963 } 964 } else { 965 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << 966 Attr.getName() << AANT_ArgumentIdentifier; 967 return; 968 } 969 970 // FIXME: This check is currently being done in the analysis. It can be 971 // enabled here only after the parser propagates attributes at 972 // template specialization definition, not declaration. 973 //QualType ReturnType = cast<ParmVarDecl>(D)->getType(); 974 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); 975 // 976 //if (!RD || !RD->hasAttr<ConsumableAttr>()) { 977 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) << 978 // ReturnType.getAsString(); 979 // return; 980 //} 981 982 D->addAttr(::new (S.Context) 983 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState, 984 Attr.getAttributeSpellingListIndex())); 985 } 986 987 static void handleReturnTypestateAttr(Sema &S, Decl *D, 988 const AttributeList &Attr) { 989 ReturnTypestateAttr::ConsumedState ReturnState; 990 991 if (Attr.isArgIdent(0)) { 992 IdentifierLoc *IL = Attr.getArgAsIdent(0); 993 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(), 994 ReturnState)) { 995 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) 996 << Attr.getName() << IL->Ident; 997 return; 998 } 999 } else { 1000 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << 1001 Attr.getName() << AANT_ArgumentIdentifier; 1002 return; 1003 } 1004 1005 // FIXME: This check is currently being done in the analysis. It can be 1006 // enabled here only after the parser propagates attributes at 1007 // template specialization definition, not declaration. 1008 //QualType ReturnType; 1009 // 1010 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) { 1011 // ReturnType = Param->getType(); 1012 // 1013 //} else if (const CXXConstructorDecl *Constructor = 1014 // dyn_cast<CXXConstructorDecl>(D)) { 1015 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType(); 1016 // 1017 //} else { 1018 // 1019 // ReturnType = cast<FunctionDecl>(D)->getCallResultType(); 1020 //} 1021 // 1022 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); 1023 // 1024 //if (!RD || !RD->hasAttr<ConsumableAttr>()) { 1025 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) << 1026 // ReturnType.getAsString(); 1027 // return; 1028 //} 1029 1030 D->addAttr(::new (S.Context) 1031 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState, 1032 Attr.getAttributeSpellingListIndex())); 1033 } 1034 1035 static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1036 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr)) 1037 return; 1038 1039 SetTypestateAttr::ConsumedState NewState; 1040 if (Attr.isArgIdent(0)) { 1041 IdentifierLoc *Ident = Attr.getArgAsIdent(0); 1042 StringRef Param = Ident->Ident->getName(); 1043 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) { 1044 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) 1045 << Attr.getName() << Param; 1046 return; 1047 } 1048 } else { 1049 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << 1050 Attr.getName() << AANT_ArgumentIdentifier; 1051 return; 1052 } 1053 1054 D->addAttr(::new (S.Context) 1055 SetTypestateAttr(Attr.getRange(), S.Context, NewState, 1056 Attr.getAttributeSpellingListIndex())); 1057 } 1058 1059 static void handleTestTypestateAttr(Sema &S, Decl *D, 1060 const AttributeList &Attr) { 1061 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr)) 1062 return; 1063 1064 TestTypestateAttr::ConsumedState TestState; 1065 if (Attr.isArgIdent(0)) { 1066 IdentifierLoc *Ident = Attr.getArgAsIdent(0); 1067 StringRef Param = Ident->Ident->getName(); 1068 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) { 1069 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) 1070 << Attr.getName() << Param; 1071 return; 1072 } 1073 } else { 1074 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << 1075 Attr.getName() << AANT_ArgumentIdentifier; 1076 return; 1077 } 1078 1079 D->addAttr(::new (S.Context) 1080 TestTypestateAttr(Attr.getRange(), S.Context, TestState, 1081 Attr.getAttributeSpellingListIndex())); 1082 } 1083 1084 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D, 1085 const AttributeList &Attr) { 1086 // Remember this typedef decl, we will need it later for diagnostics. 1087 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D)); 1088 } 1089 1090 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1091 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 1092 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context, 1093 Attr.getAttributeSpellingListIndex())); 1094 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1095 // Report warning about changed offset in the newer compiler versions. 1096 if (!FD->getType()->isDependentType() && 1097 !FD->getType()->isIncompleteType() && FD->isBitField() && 1098 S.Context.getTypeAlign(FD->getType()) <= 8) 1099 S.Diag(Attr.getLoc(), diag::warn_attribute_packed_for_bitfield); 1100 1101 FD->addAttr(::new (S.Context) PackedAttr( 1102 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 1103 } else 1104 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 1105 } 1106 1107 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) { 1108 // The IBOutlet/IBOutletCollection attributes only apply to instance 1109 // variables or properties of Objective-C classes. The outlet must also 1110 // have an object reference type. 1111 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) { 1112 if (!VD->getType()->getAs<ObjCObjectPointerType>()) { 1113 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type) 1114 << Attr.getName() << VD->getType() << 0; 1115 return false; 1116 } 1117 } 1118 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) { 1119 if (!PD->getType()->getAs<ObjCObjectPointerType>()) { 1120 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type) 1121 << Attr.getName() << PD->getType() << 1; 1122 return false; 1123 } 1124 } 1125 else { 1126 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName(); 1127 return false; 1128 } 1129 1130 return true; 1131 } 1132 1133 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) { 1134 if (!checkIBOutletCommon(S, D, Attr)) 1135 return; 1136 1137 D->addAttr(::new (S.Context) 1138 IBOutletAttr(Attr.getRange(), S.Context, 1139 Attr.getAttributeSpellingListIndex())); 1140 } 1141 1142 static void handleIBOutletCollection(Sema &S, Decl *D, 1143 const AttributeList &Attr) { 1144 1145 // The iboutletcollection attribute can have zero or one arguments. 1146 if (Attr.getNumArgs() > 1) { 1147 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 1148 << Attr.getName() << 1; 1149 return; 1150 } 1151 1152 if (!checkIBOutletCommon(S, D, Attr)) 1153 return; 1154 1155 ParsedType PT; 1156 1157 if (Attr.hasParsedType()) 1158 PT = Attr.getTypeArg(); 1159 else { 1160 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(), 1161 S.getScopeForContext(D->getDeclContext()->getParent())); 1162 if (!PT) { 1163 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject"; 1164 return; 1165 } 1166 } 1167 1168 TypeSourceInfo *QTLoc = nullptr; 1169 QualType QT = S.GetTypeFromParser(PT, &QTLoc); 1170 if (!QTLoc) 1171 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc()); 1172 1173 // Diagnose use of non-object type in iboutletcollection attribute. 1174 // FIXME. Gnu attribute extension ignores use of builtin types in 1175 // attributes. So, __attribute__((iboutletcollection(char))) will be 1176 // treated as __attribute__((iboutletcollection())). 1177 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) { 1178 S.Diag(Attr.getLoc(), 1179 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype 1180 : diag::err_iboutletcollection_type) << QT; 1181 return; 1182 } 1183 1184 D->addAttr(::new (S.Context) 1185 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc, 1186 Attr.getAttributeSpellingListIndex())); 1187 } 1188 1189 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) { 1190 if (RefOkay) { 1191 if (T->isReferenceType()) 1192 return true; 1193 } else { 1194 T = T.getNonReferenceType(); 1195 } 1196 1197 // The nonnull attribute, and other similar attributes, can be applied to a 1198 // transparent union that contains a pointer type. 1199 if (const RecordType *UT = T->getAsUnionType()) { 1200 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) { 1201 RecordDecl *UD = UT->getDecl(); 1202 for (const auto *I : UD->fields()) { 1203 QualType QT = I->getType(); 1204 if (QT->isAnyPointerType() || QT->isBlockPointerType()) 1205 return true; 1206 } 1207 } 1208 } 1209 1210 return T->isAnyPointerType() || T->isBlockPointerType(); 1211 } 1212 1213 static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr, 1214 SourceRange AttrParmRange, 1215 SourceRange TypeRange, 1216 bool isReturnValue = false) { 1217 if (!S.isValidPointerAttrType(T)) { 1218 if (isReturnValue) 1219 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only) 1220 << Attr.getName() << AttrParmRange << TypeRange; 1221 else 1222 S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only) 1223 << Attr.getName() << AttrParmRange << TypeRange << 0; 1224 return false; 1225 } 1226 return true; 1227 } 1228 1229 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1230 SmallVector<unsigned, 8> NonNullArgs; 1231 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) { 1232 Expr *Ex = Attr.getArgAsExpr(I); 1233 uint64_t Idx; 1234 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx)) 1235 return; 1236 1237 // Is the function argument a pointer type? 1238 if (Idx < getFunctionOrMethodNumParams(D) && 1239 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr, 1240 Ex->getSourceRange(), 1241 getFunctionOrMethodParamRange(D, Idx))) 1242 continue; 1243 1244 NonNullArgs.push_back(Idx); 1245 } 1246 1247 // If no arguments were specified to __attribute__((nonnull)) then all pointer 1248 // arguments have a nonnull attribute; warn if there aren't any. Skip this 1249 // check if the attribute came from a macro expansion or a template 1250 // instantiation. 1251 if (NonNullArgs.empty() && Attr.getLoc().isFileID() && 1252 S.ActiveTemplateInstantiations.empty()) { 1253 bool AnyPointers = isFunctionOrMethodVariadic(D); 1254 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); 1255 I != E && !AnyPointers; ++I) { 1256 QualType T = getFunctionOrMethodParamType(D, I); 1257 if (T->isDependentType() || S.isValidPointerAttrType(T)) 1258 AnyPointers = true; 1259 } 1260 1261 if (!AnyPointers) 1262 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers); 1263 } 1264 1265 unsigned *Start = NonNullArgs.data(); 1266 unsigned Size = NonNullArgs.size(); 1267 llvm::array_pod_sort(Start, Start + Size); 1268 D->addAttr(::new (S.Context) 1269 NonNullAttr(Attr.getRange(), S.Context, Start, Size, 1270 Attr.getAttributeSpellingListIndex())); 1271 } 1272 1273 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D, 1274 const AttributeList &Attr) { 1275 if (Attr.getNumArgs() > 0) { 1276 if (D->getFunctionType()) { 1277 handleNonNullAttr(S, D, Attr); 1278 } else { 1279 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args) 1280 << D->getSourceRange(); 1281 } 1282 return; 1283 } 1284 1285 // Is the argument a pointer type? 1286 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(), 1287 D->getSourceRange())) 1288 return; 1289 1290 D->addAttr(::new (S.Context) 1291 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0, 1292 Attr.getAttributeSpellingListIndex())); 1293 } 1294 1295 static void handleReturnsNonNullAttr(Sema &S, Decl *D, 1296 const AttributeList &Attr) { 1297 QualType ResultType = getFunctionOrMethodResultType(D); 1298 SourceRange SR = getFunctionOrMethodResultSourceRange(D); 1299 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR, 1300 /* isReturnValue */ true)) 1301 return; 1302 1303 D->addAttr(::new (S.Context) 1304 ReturnsNonNullAttr(Attr.getRange(), S.Context, 1305 Attr.getAttributeSpellingListIndex())); 1306 } 1307 1308 static void handleAssumeAlignedAttr(Sema &S, Decl *D, 1309 const AttributeList &Attr) { 1310 Expr *E = Attr.getArgAsExpr(0), 1311 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr; 1312 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE, 1313 Attr.getAttributeSpellingListIndex()); 1314 } 1315 1316 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, 1317 Expr *OE, unsigned SpellingListIndex) { 1318 QualType ResultType = getFunctionOrMethodResultType(D); 1319 SourceRange SR = getFunctionOrMethodResultSourceRange(D); 1320 1321 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex); 1322 SourceLocation AttrLoc = AttrRange.getBegin(); 1323 1324 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) { 1325 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only) 1326 << &TmpAttr << AttrRange << SR; 1327 return; 1328 } 1329 1330 if (!E->isValueDependent()) { 1331 llvm::APSInt I(64); 1332 if (!E->isIntegerConstantExpr(I, Context)) { 1333 if (OE) 1334 Diag(AttrLoc, diag::err_attribute_argument_n_type) 1335 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant 1336 << E->getSourceRange(); 1337 else 1338 Diag(AttrLoc, diag::err_attribute_argument_type) 1339 << &TmpAttr << AANT_ArgumentIntegerConstant 1340 << E->getSourceRange(); 1341 return; 1342 } 1343 1344 if (!I.isPowerOf2()) { 1345 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 1346 << E->getSourceRange(); 1347 return; 1348 } 1349 } 1350 1351 if (OE) { 1352 if (!OE->isValueDependent()) { 1353 llvm::APSInt I(64); 1354 if (!OE->isIntegerConstantExpr(I, Context)) { 1355 Diag(AttrLoc, diag::err_attribute_argument_n_type) 1356 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant 1357 << OE->getSourceRange(); 1358 return; 1359 } 1360 } 1361 } 1362 1363 D->addAttr(::new (Context) 1364 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex)); 1365 } 1366 1367 /// Normalize the attribute, __foo__ becomes foo. 1368 /// Returns true if normalization was applied. 1369 static bool normalizeName(StringRef &AttrName) { 1370 if (AttrName.size() > 4 && AttrName.startswith("__") && 1371 AttrName.endswith("__")) { 1372 AttrName = AttrName.drop_front(2).drop_back(2); 1373 return true; 1374 } 1375 return false; 1376 } 1377 1378 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) { 1379 // This attribute must be applied to a function declaration. The first 1380 // argument to the attribute must be an identifier, the name of the resource, 1381 // for example: malloc. The following arguments must be argument indexes, the 1382 // arguments must be of integer type for Returns, otherwise of pointer type. 1383 // The difference between Holds and Takes is that a pointer may still be used 1384 // after being held. free() should be __attribute((ownership_takes)), whereas 1385 // a list append function may well be __attribute((ownership_holds)). 1386 1387 if (!AL.isArgIdent(0)) { 1388 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 1389 << AL.getName() << 1 << AANT_ArgumentIdentifier; 1390 return; 1391 } 1392 1393 // Figure out our Kind. 1394 OwnershipAttr::OwnershipKind K = 1395 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0, 1396 AL.getAttributeSpellingListIndex()).getOwnKind(); 1397 1398 // Check arguments. 1399 switch (K) { 1400 case OwnershipAttr::Takes: 1401 case OwnershipAttr::Holds: 1402 if (AL.getNumArgs() < 2) { 1403 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) 1404 << AL.getName() << 2; 1405 return; 1406 } 1407 break; 1408 case OwnershipAttr::Returns: 1409 if (AL.getNumArgs() > 2) { 1410 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) 1411 << AL.getName() << 1; 1412 return; 1413 } 1414 break; 1415 } 1416 1417 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident; 1418 1419 StringRef ModuleName = Module->getName(); 1420 if (normalizeName(ModuleName)) { 1421 Module = &S.PP.getIdentifierTable().get(ModuleName); 1422 } 1423 1424 SmallVector<unsigned, 8> OwnershipArgs; 1425 for (unsigned i = 1; i < AL.getNumArgs(); ++i) { 1426 Expr *Ex = AL.getArgAsExpr(i); 1427 uint64_t Idx; 1428 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx)) 1429 return; 1430 1431 // Is the function argument a pointer type? 1432 QualType T = getFunctionOrMethodParamType(D, Idx); 1433 int Err = -1; // No error 1434 switch (K) { 1435 case OwnershipAttr::Takes: 1436 case OwnershipAttr::Holds: 1437 if (!T->isAnyPointerType() && !T->isBlockPointerType()) 1438 Err = 0; 1439 break; 1440 case OwnershipAttr::Returns: 1441 if (!T->isIntegerType()) 1442 Err = 1; 1443 break; 1444 } 1445 if (-1 != Err) { 1446 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err 1447 << Ex->getSourceRange(); 1448 return; 1449 } 1450 1451 // Check we don't have a conflict with another ownership attribute. 1452 for (const auto *I : D->specific_attrs<OwnershipAttr>()) { 1453 // Cannot have two ownership attributes of different kinds for the same 1454 // index. 1455 if (I->getOwnKind() != K && I->args_end() != 1456 std::find(I->args_begin(), I->args_end(), Idx)) { 1457 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) 1458 << AL.getName() << I; 1459 return; 1460 } else if (K == OwnershipAttr::Returns && 1461 I->getOwnKind() == OwnershipAttr::Returns) { 1462 // A returns attribute conflicts with any other returns attribute using 1463 // a different index. Note, diagnostic reporting is 1-based, but stored 1464 // argument indexes are 0-based. 1465 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) { 1466 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch) 1467 << *(I->args_begin()) + 1; 1468 if (I->args_size()) 1469 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch) 1470 << (unsigned)Idx + 1 << Ex->getSourceRange(); 1471 return; 1472 } 1473 } 1474 } 1475 OwnershipArgs.push_back(Idx); 1476 } 1477 1478 unsigned* start = OwnershipArgs.data(); 1479 unsigned size = OwnershipArgs.size(); 1480 llvm::array_pod_sort(start, start + size); 1481 1482 D->addAttr(::new (S.Context) 1483 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size, 1484 AL.getAttributeSpellingListIndex())); 1485 } 1486 1487 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1488 // Check the attribute arguments. 1489 if (Attr.getNumArgs() > 1) { 1490 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 1491 << Attr.getName() << 1; 1492 return; 1493 } 1494 1495 NamedDecl *nd = cast<NamedDecl>(D); 1496 1497 // gcc rejects 1498 // class c { 1499 // static int a __attribute__((weakref ("v2"))); 1500 // static int b() __attribute__((weakref ("f3"))); 1501 // }; 1502 // and ignores the attributes of 1503 // void f(void) { 1504 // static int a __attribute__((weakref ("v2"))); 1505 // } 1506 // we reject them 1507 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext(); 1508 if (!Ctx->isFileContext()) { 1509 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context) 1510 << nd; 1511 return; 1512 } 1513 1514 // The GCC manual says 1515 // 1516 // At present, a declaration to which `weakref' is attached can only 1517 // be `static'. 1518 // 1519 // It also says 1520 // 1521 // Without a TARGET, 1522 // given as an argument to `weakref' or to `alias', `weakref' is 1523 // equivalent to `weak'. 1524 // 1525 // gcc 4.4.1 will accept 1526 // int a7 __attribute__((weakref)); 1527 // as 1528 // int a7 __attribute__((weak)); 1529 // This looks like a bug in gcc. We reject that for now. We should revisit 1530 // it if this behaviour is actually used. 1531 1532 // GCC rejects 1533 // static ((alias ("y"), weakref)). 1534 // Should we? How to check that weakref is before or after alias? 1535 1536 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead 1537 // of transforming it into an AliasAttr. The WeakRefAttr never uses the 1538 // StringRef parameter it was given anyway. 1539 StringRef Str; 1540 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 1541 // GCC will accept anything as the argument of weakref. Should we 1542 // check for an existing decl? 1543 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str, 1544 Attr.getAttributeSpellingListIndex())); 1545 1546 D->addAttr(::new (S.Context) 1547 WeakRefAttr(Attr.getRange(), S.Context, 1548 Attr.getAttributeSpellingListIndex())); 1549 } 1550 1551 static void handleIFuncAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1552 StringRef Str; 1553 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 1554 return; 1555 1556 // Aliases should be on declarations, not definitions. 1557 const auto *FD = cast<FunctionDecl>(D); 1558 if (FD->isThisDeclarationADefinition()) { 1559 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 1; 1560 return; 1561 } 1562 // FIXME: it should be handled as a target specific attribute. 1563 if (S.Context.getTargetInfo().getTriple().getObjectFormat() != 1564 llvm::Triple::ELF) { 1565 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 1566 return; 1567 } 1568 1569 D->addAttr(::new (S.Context) IFuncAttr(Attr.getRange(), S.Context, Str, 1570 Attr.getAttributeSpellingListIndex())); 1571 } 1572 1573 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1574 StringRef Str; 1575 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 1576 return; 1577 1578 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 1579 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin); 1580 return; 1581 } 1582 if (S.Context.getTargetInfo().getTriple().isNVPTX()) { 1583 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_nvptx); 1584 } 1585 1586 // Aliases should be on declarations, not definitions. 1587 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 1588 if (FD->isThisDeclarationADefinition()) { 1589 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 0; 1590 return; 1591 } 1592 } else { 1593 const auto *VD = cast<VarDecl>(D); 1594 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) { 1595 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD << 0; 1596 return; 1597 } 1598 } 1599 1600 // FIXME: check if target symbol exists in current file 1601 1602 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str, 1603 Attr.getAttributeSpellingListIndex())); 1604 } 1605 1606 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1607 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName())) 1608 return; 1609 1610 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context, 1611 Attr.getAttributeSpellingListIndex())); 1612 } 1613 1614 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1615 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName())) 1616 return; 1617 1618 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context, 1619 Attr.getAttributeSpellingListIndex())); 1620 } 1621 1622 static void handleTLSModelAttr(Sema &S, Decl *D, 1623 const AttributeList &Attr) { 1624 StringRef Model; 1625 SourceLocation LiteralLoc; 1626 // Check that it is a string. 1627 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc)) 1628 return; 1629 1630 // Check that the value. 1631 if (Model != "global-dynamic" && Model != "local-dynamic" 1632 && Model != "initial-exec" && Model != "local-exec") { 1633 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg); 1634 return; 1635 } 1636 1637 D->addAttr(::new (S.Context) 1638 TLSModelAttr(Attr.getRange(), S.Context, Model, 1639 Attr.getAttributeSpellingListIndex())); 1640 } 1641 1642 static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1643 QualType ResultType = getFunctionOrMethodResultType(D); 1644 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) { 1645 D->addAttr(::new (S.Context) RestrictAttr( 1646 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 1647 return; 1648 } 1649 1650 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only) 1651 << Attr.getName() << getFunctionOrMethodResultSourceRange(D); 1652 } 1653 1654 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1655 if (S.LangOpts.CPlusPlus) { 1656 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang) 1657 << Attr.getName() << AttributeLangSupport::Cpp; 1658 return; 1659 } 1660 1661 if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(), 1662 Attr.getAttributeSpellingListIndex())) 1663 D->addAttr(CA); 1664 } 1665 1666 static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1667 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(), 1668 Attr.getName())) 1669 return; 1670 1671 D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context, 1672 Attr.getAttributeSpellingListIndex())); 1673 } 1674 1675 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) { 1676 if (hasDeclarator(D)) return; 1677 1678 if (S.CheckNoReturnAttr(attr)) return; 1679 1680 if (!isa<ObjCMethodDecl>(D)) { 1681 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type) 1682 << attr.getName() << ExpectedFunctionOrMethod; 1683 return; 1684 } 1685 1686 D->addAttr(::new (S.Context) 1687 NoReturnAttr(attr.getRange(), S.Context, 1688 attr.getAttributeSpellingListIndex())); 1689 } 1690 1691 bool Sema::CheckNoReturnAttr(const AttributeList &attr) { 1692 if (!checkAttributeNumArgs(*this, attr, 0)) { 1693 attr.setInvalid(); 1694 return true; 1695 } 1696 1697 return false; 1698 } 1699 1700 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, 1701 const AttributeList &Attr) { 1702 1703 // The checking path for 'noreturn' and 'analyzer_noreturn' are different 1704 // because 'analyzer_noreturn' does not impact the type. 1705 if (!isFunctionOrMethodOrBlock(D)) { 1706 ValueDecl *VD = dyn_cast<ValueDecl>(D); 1707 if (!VD || (!VD->getType()->isBlockPointerType() && 1708 !VD->getType()->isFunctionPointerType())) { 1709 S.Diag(Attr.getLoc(), 1710 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type 1711 : diag::warn_attribute_wrong_decl_type) 1712 << Attr.getName() << ExpectedFunctionMethodOrBlock; 1713 return; 1714 } 1715 } 1716 1717 D->addAttr(::new (S.Context) 1718 AnalyzerNoReturnAttr(Attr.getRange(), S.Context, 1719 Attr.getAttributeSpellingListIndex())); 1720 } 1721 1722 // PS3 PPU-specific. 1723 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1724 /* 1725 Returning a Vector Class in Registers 1726 1727 According to the PPU ABI specifications, a class with a single member of 1728 vector type is returned in memory when used as the return value of a function. 1729 This results in inefficient code when implementing vector classes. To return 1730 the value in a single vector register, add the vecreturn attribute to the 1731 class definition. This attribute is also applicable to struct types. 1732 1733 Example: 1734 1735 struct Vector 1736 { 1737 __vector float xyzw; 1738 } __attribute__((vecreturn)); 1739 1740 Vector Add(Vector lhs, Vector rhs) 1741 { 1742 Vector result; 1743 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw); 1744 return result; // This will be returned in a register 1745 } 1746 */ 1747 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) { 1748 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A; 1749 return; 1750 } 1751 1752 RecordDecl *record = cast<RecordDecl>(D); 1753 int count = 0; 1754 1755 if (!isa<CXXRecordDecl>(record)) { 1756 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member); 1757 return; 1758 } 1759 1760 if (!cast<CXXRecordDecl>(record)->isPOD()) { 1761 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record); 1762 return; 1763 } 1764 1765 for (const auto *I : record->fields()) { 1766 if ((count == 1) || !I->getType()->isVectorType()) { 1767 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member); 1768 return; 1769 } 1770 count++; 1771 } 1772 1773 D->addAttr(::new (S.Context) 1774 VecReturnAttr(Attr.getRange(), S.Context, 1775 Attr.getAttributeSpellingListIndex())); 1776 } 1777 1778 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D, 1779 const AttributeList &Attr) { 1780 if (isa<ParmVarDecl>(D)) { 1781 // [[carries_dependency]] can only be applied to a parameter if it is a 1782 // parameter of a function declaration or lambda. 1783 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) { 1784 S.Diag(Attr.getLoc(), 1785 diag::err_carries_dependency_param_not_function_decl); 1786 return; 1787 } 1788 } 1789 1790 D->addAttr(::new (S.Context) CarriesDependencyAttr( 1791 Attr.getRange(), S.Context, 1792 Attr.getAttributeSpellingListIndex())); 1793 } 1794 1795 static void handleNotTailCalledAttr(Sema &S, Decl *D, 1796 const AttributeList &Attr) { 1797 if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(), 1798 Attr.getName())) 1799 return; 1800 1801 D->addAttr(::new (S.Context) NotTailCalledAttr( 1802 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 1803 } 1804 1805 static void handleDisableTailCallsAttr(Sema &S, Decl *D, 1806 const AttributeList &Attr) { 1807 if (checkAttrMutualExclusion<NakedAttr>(S, D, Attr.getRange(), 1808 Attr.getName())) 1809 return; 1810 1811 D->addAttr(::new (S.Context) DisableTailCallsAttr( 1812 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 1813 } 1814 1815 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1816 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1817 if (VD->hasLocalStorage()) { 1818 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 1819 return; 1820 } 1821 } else if (!isFunctionOrMethod(D)) { 1822 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 1823 << Attr.getName() << ExpectedVariableOrFunction; 1824 return; 1825 } 1826 1827 D->addAttr(::new (S.Context) 1828 UsedAttr(Attr.getRange(), S.Context, 1829 Attr.getAttributeSpellingListIndex())); 1830 } 1831 1832 static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1833 bool IsCXX1zAttr = Attr.isCXX11Attribute() && !Attr.getScopeName(); 1834 1835 if (IsCXX1zAttr && isa<VarDecl>(D)) { 1836 // The C++1z spelling of this attribute cannot be applied to a static data 1837 // member per [dcl.attr.unused]p2. 1838 if (cast<VarDecl>(D)->isStaticDataMember()) { 1839 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 1840 << Attr.getName() << ExpectedForMaybeUnused; 1841 return; 1842 } 1843 } 1844 1845 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn 1846 // about using it as an extension. 1847 if (!S.getLangOpts().CPlusPlus1z && IsCXX1zAttr) 1848 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName(); 1849 1850 D->addAttr(::new (S.Context) UnusedAttr( 1851 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 1852 } 1853 1854 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1855 uint32_t priority = ConstructorAttr::DefaultPriority; 1856 if (Attr.getNumArgs() && 1857 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority)) 1858 return; 1859 1860 D->addAttr(::new (S.Context) 1861 ConstructorAttr(Attr.getRange(), S.Context, priority, 1862 Attr.getAttributeSpellingListIndex())); 1863 } 1864 1865 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1866 uint32_t priority = DestructorAttr::DefaultPriority; 1867 if (Attr.getNumArgs() && 1868 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority)) 1869 return; 1870 1871 D->addAttr(::new (S.Context) 1872 DestructorAttr(Attr.getRange(), S.Context, priority, 1873 Attr.getAttributeSpellingListIndex())); 1874 } 1875 1876 template <typename AttrTy> 1877 static void handleAttrWithMessage(Sema &S, Decl *D, 1878 const AttributeList &Attr) { 1879 // Handle the case where the attribute has a text message. 1880 StringRef Str; 1881 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 1882 return; 1883 1884 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str, 1885 Attr.getAttributeSpellingListIndex())); 1886 } 1887 1888 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D, 1889 const AttributeList &Attr) { 1890 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) { 1891 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition) 1892 << Attr.getName() << Attr.getRange(); 1893 return; 1894 } 1895 1896 D->addAttr(::new (S.Context) 1897 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context, 1898 Attr.getAttributeSpellingListIndex())); 1899 } 1900 1901 static bool checkAvailabilityAttr(Sema &S, SourceRange Range, 1902 IdentifierInfo *Platform, 1903 VersionTuple Introduced, 1904 VersionTuple Deprecated, 1905 VersionTuple Obsoleted) { 1906 StringRef PlatformName 1907 = AvailabilityAttr::getPrettyPlatformName(Platform->getName()); 1908 if (PlatformName.empty()) 1909 PlatformName = Platform->getName(); 1910 1911 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all 1912 // of these steps are needed). 1913 if (!Introduced.empty() && !Deprecated.empty() && 1914 !(Introduced <= Deprecated)) { 1915 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 1916 << 1 << PlatformName << Deprecated.getAsString() 1917 << 0 << Introduced.getAsString(); 1918 return true; 1919 } 1920 1921 if (!Introduced.empty() && !Obsoleted.empty() && 1922 !(Introduced <= Obsoleted)) { 1923 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 1924 << 2 << PlatformName << Obsoleted.getAsString() 1925 << 0 << Introduced.getAsString(); 1926 return true; 1927 } 1928 1929 if (!Deprecated.empty() && !Obsoleted.empty() && 1930 !(Deprecated <= Obsoleted)) { 1931 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 1932 << 2 << PlatformName << Obsoleted.getAsString() 1933 << 1 << Deprecated.getAsString(); 1934 return true; 1935 } 1936 1937 return false; 1938 } 1939 1940 /// \brief Check whether the two versions match. 1941 /// 1942 /// If either version tuple is empty, then they are assumed to match. If 1943 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y. 1944 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y, 1945 bool BeforeIsOkay) { 1946 if (X.empty() || Y.empty()) 1947 return true; 1948 1949 if (X == Y) 1950 return true; 1951 1952 if (BeforeIsOkay && X < Y) 1953 return true; 1954 1955 return false; 1956 } 1957 1958 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range, 1959 IdentifierInfo *Platform, 1960 VersionTuple Introduced, 1961 VersionTuple Deprecated, 1962 VersionTuple Obsoleted, 1963 bool IsUnavailable, 1964 StringRef Message, 1965 bool IsStrict, 1966 StringRef Replacement, 1967 AvailabilityMergeKind AMK, 1968 unsigned AttrSpellingListIndex) { 1969 VersionTuple MergedIntroduced = Introduced; 1970 VersionTuple MergedDeprecated = Deprecated; 1971 VersionTuple MergedObsoleted = Obsoleted; 1972 bool FoundAny = false; 1973 bool OverrideOrImpl = false; 1974 switch (AMK) { 1975 case AMK_None: 1976 case AMK_Redeclaration: 1977 OverrideOrImpl = false; 1978 break; 1979 1980 case AMK_Override: 1981 case AMK_ProtocolImplementation: 1982 OverrideOrImpl = true; 1983 break; 1984 } 1985 1986 if (D->hasAttrs()) { 1987 AttrVec &Attrs = D->getAttrs(); 1988 for (unsigned i = 0, e = Attrs.size(); i != e;) { 1989 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]); 1990 if (!OldAA) { 1991 ++i; 1992 continue; 1993 } 1994 1995 IdentifierInfo *OldPlatform = OldAA->getPlatform(); 1996 if (OldPlatform != Platform) { 1997 ++i; 1998 continue; 1999 } 2000 2001 // If there is an existing availability attribute for this platform that 2002 // is explicit and the new one is implicit use the explicit one and 2003 // discard the new implicit attribute. 2004 if (OldAA->getRange().isValid() && Range.isInvalid()) { 2005 return nullptr; 2006 } 2007 2008 // If there is an existing attribute for this platform that is implicit 2009 // and the new attribute is explicit then erase the old one and 2010 // continue processing the attributes. 2011 if (Range.isValid() && OldAA->getRange().isInvalid()) { 2012 Attrs.erase(Attrs.begin() + i); 2013 --e; 2014 continue; 2015 } 2016 2017 FoundAny = true; 2018 VersionTuple OldIntroduced = OldAA->getIntroduced(); 2019 VersionTuple OldDeprecated = OldAA->getDeprecated(); 2020 VersionTuple OldObsoleted = OldAA->getObsoleted(); 2021 bool OldIsUnavailable = OldAA->getUnavailable(); 2022 2023 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) || 2024 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) || 2025 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) || 2026 !(OldIsUnavailable == IsUnavailable || 2027 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) { 2028 if (OverrideOrImpl) { 2029 int Which = -1; 2030 VersionTuple FirstVersion; 2031 VersionTuple SecondVersion; 2032 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) { 2033 Which = 0; 2034 FirstVersion = OldIntroduced; 2035 SecondVersion = Introduced; 2036 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) { 2037 Which = 1; 2038 FirstVersion = Deprecated; 2039 SecondVersion = OldDeprecated; 2040 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) { 2041 Which = 2; 2042 FirstVersion = Obsoleted; 2043 SecondVersion = OldObsoleted; 2044 } 2045 2046 if (Which == -1) { 2047 Diag(OldAA->getLocation(), 2048 diag::warn_mismatched_availability_override_unavail) 2049 << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) 2050 << (AMK == AMK_Override); 2051 } else { 2052 Diag(OldAA->getLocation(), 2053 diag::warn_mismatched_availability_override) 2054 << Which 2055 << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) 2056 << FirstVersion.getAsString() << SecondVersion.getAsString() 2057 << (AMK == AMK_Override); 2058 } 2059 if (AMK == AMK_Override) 2060 Diag(Range.getBegin(), diag::note_overridden_method); 2061 else 2062 Diag(Range.getBegin(), diag::note_protocol_method); 2063 } else { 2064 Diag(OldAA->getLocation(), diag::warn_mismatched_availability); 2065 Diag(Range.getBegin(), diag::note_previous_attribute); 2066 } 2067 2068 Attrs.erase(Attrs.begin() + i); 2069 --e; 2070 continue; 2071 } 2072 2073 VersionTuple MergedIntroduced2 = MergedIntroduced; 2074 VersionTuple MergedDeprecated2 = MergedDeprecated; 2075 VersionTuple MergedObsoleted2 = MergedObsoleted; 2076 2077 if (MergedIntroduced2.empty()) 2078 MergedIntroduced2 = OldIntroduced; 2079 if (MergedDeprecated2.empty()) 2080 MergedDeprecated2 = OldDeprecated; 2081 if (MergedObsoleted2.empty()) 2082 MergedObsoleted2 = OldObsoleted; 2083 2084 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform, 2085 MergedIntroduced2, MergedDeprecated2, 2086 MergedObsoleted2)) { 2087 Attrs.erase(Attrs.begin() + i); 2088 --e; 2089 continue; 2090 } 2091 2092 MergedIntroduced = MergedIntroduced2; 2093 MergedDeprecated = MergedDeprecated2; 2094 MergedObsoleted = MergedObsoleted2; 2095 ++i; 2096 } 2097 } 2098 2099 if (FoundAny && 2100 MergedIntroduced == Introduced && 2101 MergedDeprecated == Deprecated && 2102 MergedObsoleted == Obsoleted) 2103 return nullptr; 2104 2105 // Only create a new attribute if !OverrideOrImpl, but we want to do 2106 // the checking. 2107 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced, 2108 MergedDeprecated, MergedObsoleted) && 2109 !OverrideOrImpl) { 2110 return ::new (Context) AvailabilityAttr(Range, Context, Platform, 2111 Introduced, Deprecated, 2112 Obsoleted, IsUnavailable, Message, 2113 IsStrict, Replacement, 2114 AttrSpellingListIndex); 2115 } 2116 return nullptr; 2117 } 2118 2119 static void handleAvailabilityAttr(Sema &S, Decl *D, 2120 const AttributeList &Attr) { 2121 if (!checkAttributeNumArgs(S, Attr, 1)) 2122 return; 2123 IdentifierLoc *Platform = Attr.getArgAsIdent(0); 2124 unsigned Index = Attr.getAttributeSpellingListIndex(); 2125 2126 IdentifierInfo *II = Platform->Ident; 2127 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty()) 2128 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform) 2129 << Platform->Ident; 2130 2131 NamedDecl *ND = dyn_cast<NamedDecl>(D); 2132 if (!ND) { 2133 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 2134 return; 2135 } 2136 2137 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced(); 2138 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated(); 2139 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted(); 2140 bool IsUnavailable = Attr.getUnavailableLoc().isValid(); 2141 bool IsStrict = Attr.getStrictLoc().isValid(); 2142 StringRef Str; 2143 if (const StringLiteral *SE = 2144 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr())) 2145 Str = SE->getString(); 2146 StringRef Replacement; 2147 if (const StringLiteral *SE = 2148 dyn_cast_or_null<StringLiteral>(Attr.getReplacementExpr())) 2149 Replacement = SE->getString(); 2150 2151 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II, 2152 Introduced.Version, 2153 Deprecated.Version, 2154 Obsoleted.Version, 2155 IsUnavailable, Str, 2156 IsStrict, Replacement, 2157 Sema::AMK_None, 2158 Index); 2159 if (NewAttr) 2160 D->addAttr(NewAttr); 2161 2162 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning 2163 // matches before the start of the watchOS platform. 2164 if (S.Context.getTargetInfo().getTriple().isWatchOS()) { 2165 IdentifierInfo *NewII = nullptr; 2166 if (II->getName() == "ios") 2167 NewII = &S.Context.Idents.get("watchos"); 2168 else if (II->getName() == "ios_app_extension") 2169 NewII = &S.Context.Idents.get("watchos_app_extension"); 2170 2171 if (NewII) { 2172 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple { 2173 if (Version.empty()) 2174 return Version; 2175 auto Major = Version.getMajor(); 2176 auto NewMajor = Major >= 9 ? Major - 7 : 0; 2177 if (NewMajor >= 2) { 2178 if (Version.getMinor().hasValue()) { 2179 if (Version.getSubminor().hasValue()) 2180 return VersionTuple(NewMajor, Version.getMinor().getValue(), 2181 Version.getSubminor().getValue()); 2182 else 2183 return VersionTuple(NewMajor, Version.getMinor().getValue()); 2184 } 2185 } 2186 2187 return VersionTuple(2, 0); 2188 }; 2189 2190 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version); 2191 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version); 2192 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version); 2193 2194 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, 2195 SourceRange(), 2196 NewII, 2197 NewIntroduced, 2198 NewDeprecated, 2199 NewObsoleted, 2200 IsUnavailable, Str, 2201 IsStrict, 2202 Replacement, 2203 Sema::AMK_None, 2204 Index); 2205 if (NewAttr) 2206 D->addAttr(NewAttr); 2207 } 2208 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) { 2209 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning 2210 // matches before the start of the tvOS platform. 2211 IdentifierInfo *NewII = nullptr; 2212 if (II->getName() == "ios") 2213 NewII = &S.Context.Idents.get("tvos"); 2214 else if (II->getName() == "ios_app_extension") 2215 NewII = &S.Context.Idents.get("tvos_app_extension"); 2216 2217 if (NewII) { 2218 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, 2219 SourceRange(), 2220 NewII, 2221 Introduced.Version, 2222 Deprecated.Version, 2223 Obsoleted.Version, 2224 IsUnavailable, Str, 2225 IsStrict, 2226 Replacement, 2227 Sema::AMK_None, 2228 Index); 2229 if (NewAttr) 2230 D->addAttr(NewAttr); 2231 } 2232 } 2233 } 2234 2235 template <class T> 2236 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range, 2237 typename T::VisibilityType value, 2238 unsigned attrSpellingListIndex) { 2239 T *existingAttr = D->getAttr<T>(); 2240 if (existingAttr) { 2241 typename T::VisibilityType existingValue = existingAttr->getVisibility(); 2242 if (existingValue == value) 2243 return nullptr; 2244 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility); 2245 S.Diag(range.getBegin(), diag::note_previous_attribute); 2246 D->dropAttr<T>(); 2247 } 2248 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex); 2249 } 2250 2251 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range, 2252 VisibilityAttr::VisibilityType Vis, 2253 unsigned AttrSpellingListIndex) { 2254 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis, 2255 AttrSpellingListIndex); 2256 } 2257 2258 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range, 2259 TypeVisibilityAttr::VisibilityType Vis, 2260 unsigned AttrSpellingListIndex) { 2261 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis, 2262 AttrSpellingListIndex); 2263 } 2264 2265 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr, 2266 bool isTypeVisibility) { 2267 // Visibility attributes don't mean anything on a typedef. 2268 if (isa<TypedefNameDecl>(D)) { 2269 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored) 2270 << Attr.getName(); 2271 return; 2272 } 2273 2274 // 'type_visibility' can only go on a type or namespace. 2275 if (isTypeVisibility && 2276 !(isa<TagDecl>(D) || 2277 isa<ObjCInterfaceDecl>(D) || 2278 isa<NamespaceDecl>(D))) { 2279 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type) 2280 << Attr.getName() << ExpectedTypeOrNamespace; 2281 return; 2282 } 2283 2284 // Check that the argument is a string literal. 2285 StringRef TypeStr; 2286 SourceLocation LiteralLoc; 2287 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc)) 2288 return; 2289 2290 VisibilityAttr::VisibilityType type; 2291 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) { 2292 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) 2293 << Attr.getName() << TypeStr; 2294 return; 2295 } 2296 2297 // Complain about attempts to use protected visibility on targets 2298 // (like Darwin) that don't support it. 2299 if (type == VisibilityAttr::Protected && 2300 !S.Context.getTargetInfo().hasProtectedVisibility()) { 2301 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility); 2302 type = VisibilityAttr::Default; 2303 } 2304 2305 unsigned Index = Attr.getAttributeSpellingListIndex(); 2306 clang::Attr *newAttr; 2307 if (isTypeVisibility) { 2308 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(), 2309 (TypeVisibilityAttr::VisibilityType) type, 2310 Index); 2311 } else { 2312 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index); 2313 } 2314 if (newAttr) 2315 D->addAttr(newAttr); 2316 } 2317 2318 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl, 2319 const AttributeList &Attr) { 2320 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl); 2321 if (!Attr.isArgIdent(0)) { 2322 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2323 << Attr.getName() << 1 << AANT_ArgumentIdentifier; 2324 return; 2325 } 2326 2327 IdentifierLoc *IL = Attr.getArgAsIdent(0); 2328 ObjCMethodFamilyAttr::FamilyKind F; 2329 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) { 2330 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName() 2331 << IL->Ident; 2332 return; 2333 } 2334 2335 if (F == ObjCMethodFamilyAttr::OMF_init && 2336 !method->getReturnType()->isObjCObjectPointerType()) { 2337 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type) 2338 << method->getReturnType(); 2339 // Ignore the attribute. 2340 return; 2341 } 2342 2343 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(), 2344 S.Context, F, 2345 Attr.getAttributeSpellingListIndex())); 2346 } 2347 2348 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) { 2349 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 2350 QualType T = TD->getUnderlyingType(); 2351 if (!T->isCARCBridgableType()) { 2352 S.Diag(TD->getLocation(), diag::err_nsobject_attribute); 2353 return; 2354 } 2355 } 2356 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) { 2357 QualType T = PD->getType(); 2358 if (!T->isCARCBridgableType()) { 2359 S.Diag(PD->getLocation(), diag::err_nsobject_attribute); 2360 return; 2361 } 2362 } 2363 else { 2364 // It is okay to include this attribute on properties, e.g.: 2365 // 2366 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject)); 2367 // 2368 // In this case it follows tradition and suppresses an error in the above 2369 // case. 2370 S.Diag(D->getLocation(), diag::warn_nsobject_attribute); 2371 } 2372 D->addAttr(::new (S.Context) 2373 ObjCNSObjectAttr(Attr.getRange(), S.Context, 2374 Attr.getAttributeSpellingListIndex())); 2375 } 2376 2377 static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) { 2378 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 2379 QualType T = TD->getUnderlyingType(); 2380 if (!T->isObjCObjectPointerType()) { 2381 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute); 2382 return; 2383 } 2384 } else { 2385 S.Diag(D->getLocation(), diag::warn_independentclass_attribute); 2386 return; 2387 } 2388 D->addAttr(::new (S.Context) 2389 ObjCIndependentClassAttr(Attr.getRange(), S.Context, 2390 Attr.getAttributeSpellingListIndex())); 2391 } 2392 2393 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2394 if (!Attr.isArgIdent(0)) { 2395 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2396 << Attr.getName() << 1 << AANT_ArgumentIdentifier; 2397 return; 2398 } 2399 2400 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident; 2401 BlocksAttr::BlockType type; 2402 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) { 2403 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 2404 << Attr.getName() << II; 2405 return; 2406 } 2407 2408 D->addAttr(::new (S.Context) 2409 BlocksAttr(Attr.getRange(), S.Context, type, 2410 Attr.getAttributeSpellingListIndex())); 2411 } 2412 2413 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2414 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel; 2415 if (Attr.getNumArgs() > 0) { 2416 Expr *E = Attr.getArgAsExpr(0); 2417 llvm::APSInt Idx(32); 2418 if (E->isTypeDependent() || E->isValueDependent() || 2419 !E->isIntegerConstantExpr(Idx, S.Context)) { 2420 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2421 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant 2422 << E->getSourceRange(); 2423 return; 2424 } 2425 2426 if (Idx.isSigned() && Idx.isNegative()) { 2427 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero) 2428 << E->getSourceRange(); 2429 return; 2430 } 2431 2432 sentinel = Idx.getZExtValue(); 2433 } 2434 2435 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos; 2436 if (Attr.getNumArgs() > 1) { 2437 Expr *E = Attr.getArgAsExpr(1); 2438 llvm::APSInt Idx(32); 2439 if (E->isTypeDependent() || E->isValueDependent() || 2440 !E->isIntegerConstantExpr(Idx, S.Context)) { 2441 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2442 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant 2443 << E->getSourceRange(); 2444 return; 2445 } 2446 nullPos = Idx.getZExtValue(); 2447 2448 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) { 2449 // FIXME: This error message could be improved, it would be nice 2450 // to say what the bounds actually are. 2451 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one) 2452 << E->getSourceRange(); 2453 return; 2454 } 2455 } 2456 2457 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2458 const FunctionType *FT = FD->getType()->castAs<FunctionType>(); 2459 if (isa<FunctionNoProtoType>(FT)) { 2460 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments); 2461 return; 2462 } 2463 2464 if (!cast<FunctionProtoType>(FT)->isVariadic()) { 2465 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; 2466 return; 2467 } 2468 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 2469 if (!MD->isVariadic()) { 2470 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; 2471 return; 2472 } 2473 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 2474 if (!BD->isVariadic()) { 2475 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1; 2476 return; 2477 } 2478 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) { 2479 QualType Ty = V->getType(); 2480 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) { 2481 const FunctionType *FT = Ty->isFunctionPointerType() 2482 ? D->getFunctionType() 2483 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>(); 2484 if (!cast<FunctionProtoType>(FT)->isVariadic()) { 2485 int m = Ty->isFunctionPointerType() ? 0 : 1; 2486 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m; 2487 return; 2488 } 2489 } else { 2490 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 2491 << Attr.getName() << ExpectedFunctionMethodOrBlock; 2492 return; 2493 } 2494 } else { 2495 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 2496 << Attr.getName() << ExpectedFunctionMethodOrBlock; 2497 return; 2498 } 2499 D->addAttr(::new (S.Context) 2500 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos, 2501 Attr.getAttributeSpellingListIndex())); 2502 } 2503 2504 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) { 2505 if (D->getFunctionType() && 2506 D->getFunctionType()->getReturnType()->isVoidType()) { 2507 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method) 2508 << Attr.getName() << 0; 2509 return; 2510 } 2511 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 2512 if (MD->getReturnType()->isVoidType()) { 2513 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method) 2514 << Attr.getName() << 1; 2515 return; 2516 } 2517 2518 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn 2519 // about using it as an extension. 2520 if (!S.getLangOpts().CPlusPlus1z && Attr.isCXX11Attribute() && 2521 !Attr.getScopeName()) 2522 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName(); 2523 2524 D->addAttr(::new (S.Context) 2525 WarnUnusedResultAttr(Attr.getRange(), S.Context, 2526 Attr.getAttributeSpellingListIndex())); 2527 } 2528 2529 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2530 // weak_import only applies to variable & function declarations. 2531 bool isDef = false; 2532 if (!D->canBeWeakImported(isDef)) { 2533 if (isDef) 2534 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition) 2535 << "weak_import"; 2536 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) || 2537 (S.Context.getTargetInfo().getTriple().isOSDarwin() && 2538 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) { 2539 // Nothing to warn about here. 2540 } else 2541 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 2542 << Attr.getName() << ExpectedVariableOrFunction; 2543 2544 return; 2545 } 2546 2547 D->addAttr(::new (S.Context) 2548 WeakImportAttr(Attr.getRange(), S.Context, 2549 Attr.getAttributeSpellingListIndex())); 2550 } 2551 2552 // Handles reqd_work_group_size and work_group_size_hint. 2553 template <typename WorkGroupAttr> 2554 static void handleWorkGroupSize(Sema &S, Decl *D, 2555 const AttributeList &Attr) { 2556 uint32_t WGSize[3]; 2557 for (unsigned i = 0; i < 3; ++i) { 2558 const Expr *E = Attr.getArgAsExpr(i); 2559 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i)) 2560 return; 2561 if (WGSize[i] == 0) { 2562 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero) 2563 << Attr.getName() << E->getSourceRange(); 2564 return; 2565 } 2566 } 2567 2568 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>(); 2569 if (Existing && !(Existing->getXDim() == WGSize[0] && 2570 Existing->getYDim() == WGSize[1] && 2571 Existing->getZDim() == WGSize[2])) 2572 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName(); 2573 2574 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context, 2575 WGSize[0], WGSize[1], WGSize[2], 2576 Attr.getAttributeSpellingListIndex())); 2577 } 2578 2579 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) { 2580 if (!Attr.hasParsedType()) { 2581 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 2582 << Attr.getName() << 1; 2583 return; 2584 } 2585 2586 TypeSourceInfo *ParmTSI = nullptr; 2587 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI); 2588 assert(ParmTSI && "no type source info for attribute argument"); 2589 2590 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() && 2591 (ParmType->isBooleanType() || 2592 !ParmType->isIntegralType(S.getASTContext()))) { 2593 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint) 2594 << ParmType; 2595 return; 2596 } 2597 2598 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) { 2599 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) { 2600 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName(); 2601 return; 2602 } 2603 } 2604 2605 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context, 2606 ParmTSI, 2607 Attr.getAttributeSpellingListIndex())); 2608 } 2609 2610 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range, 2611 StringRef Name, 2612 unsigned AttrSpellingListIndex) { 2613 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) { 2614 if (ExistingAttr->getName() == Name) 2615 return nullptr; 2616 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section); 2617 Diag(Range.getBegin(), diag::note_previous_attribute); 2618 return nullptr; 2619 } 2620 return ::new (Context) SectionAttr(Range, Context, Name, 2621 AttrSpellingListIndex); 2622 } 2623 2624 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) { 2625 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName); 2626 if (!Error.empty()) { 2627 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error; 2628 return false; 2629 } 2630 return true; 2631 } 2632 2633 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2634 // Make sure that there is a string literal as the sections's single 2635 // argument. 2636 StringRef Str; 2637 SourceLocation LiteralLoc; 2638 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc)) 2639 return; 2640 2641 if (!S.checkSectionName(LiteralLoc, Str)) 2642 return; 2643 2644 // If the target wants to validate the section specifier, make it happen. 2645 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str); 2646 if (!Error.empty()) { 2647 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) 2648 << Error; 2649 return; 2650 } 2651 2652 unsigned Index = Attr.getAttributeSpellingListIndex(); 2653 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index); 2654 if (NewAttr) 2655 D->addAttr(NewAttr); 2656 } 2657 2658 // Check for things we'd like to warn about, no errors or validation for now. 2659 // TODO: Validation should use a backend target library that specifies 2660 // the allowable subtarget features and cpus. We could use something like a 2661 // TargetCodeGenInfo hook here to do validation. 2662 void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) { 2663 for (auto Str : {"tune=", "fpmath="}) 2664 if (AttrStr.find(Str) != StringRef::npos) 2665 Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str; 2666 } 2667 2668 static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2669 StringRef Str; 2670 SourceLocation LiteralLoc; 2671 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc)) 2672 return; 2673 S.checkTargetAttr(LiteralLoc, Str); 2674 unsigned Index = Attr.getAttributeSpellingListIndex(); 2675 TargetAttr *NewAttr = 2676 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index); 2677 D->addAttr(NewAttr); 2678 } 2679 2680 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2681 VarDecl *VD = cast<VarDecl>(D); 2682 if (!VD->hasLocalStorage()) { 2683 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 2684 return; 2685 } 2686 2687 Expr *E = Attr.getArgAsExpr(0); 2688 SourceLocation Loc = E->getExprLoc(); 2689 FunctionDecl *FD = nullptr; 2690 DeclarationNameInfo NI; 2691 2692 // gcc only allows for simple identifiers. Since we support more than gcc, we 2693 // will warn the user. 2694 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 2695 if (DRE->hasQualifier()) 2696 S.Diag(Loc, diag::warn_cleanup_ext); 2697 FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 2698 NI = DRE->getNameInfo(); 2699 if (!FD) { 2700 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1 2701 << NI.getName(); 2702 return; 2703 } 2704 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 2705 if (ULE->hasExplicitTemplateArgs()) 2706 S.Diag(Loc, diag::warn_cleanup_ext); 2707 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true); 2708 NI = ULE->getNameInfo(); 2709 if (!FD) { 2710 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2 2711 << NI.getName(); 2712 if (ULE->getType() == S.Context.OverloadTy) 2713 S.NoteAllOverloadCandidates(ULE); 2714 return; 2715 } 2716 } else { 2717 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0; 2718 return; 2719 } 2720 2721 if (FD->getNumParams() != 1) { 2722 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg) 2723 << NI.getName(); 2724 return; 2725 } 2726 2727 // We're currently more strict than GCC about what function types we accept. 2728 // If this ever proves to be a problem it should be easy to fix. 2729 QualType Ty = S.Context.getPointerType(VD->getType()); 2730 QualType ParamTy = FD->getParamDecl(0)->getType(); 2731 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(), 2732 ParamTy, Ty) != Sema::Compatible) { 2733 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type) 2734 << NI.getName() << ParamTy << Ty; 2735 return; 2736 } 2737 2738 D->addAttr(::new (S.Context) 2739 CleanupAttr(Attr.getRange(), S.Context, FD, 2740 Attr.getAttributeSpellingListIndex())); 2741 } 2742 2743 /// Handle __attribute__((format_arg((idx)))) attribute based on 2744 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 2745 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2746 Expr *IdxExpr = Attr.getArgAsExpr(0); 2747 uint64_t Idx; 2748 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx)) 2749 return; 2750 2751 // Make sure the format string is really a string. 2752 QualType Ty = getFunctionOrMethodParamType(D, Idx); 2753 2754 bool NotNSStringTy = !isNSStringType(Ty, S.Context); 2755 if (NotNSStringTy && 2756 !isCFStringType(Ty, S.Context) && 2757 (!Ty->isPointerType() || 2758 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) { 2759 S.Diag(Attr.getLoc(), diag::err_format_attribute_not) 2760 << "a string type" << IdxExpr->getSourceRange() 2761 << getFunctionOrMethodParamRange(D, 0); 2762 return; 2763 } 2764 Ty = getFunctionOrMethodResultType(D); 2765 if (!isNSStringType(Ty, S.Context) && 2766 !isCFStringType(Ty, S.Context) && 2767 (!Ty->isPointerType() || 2768 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) { 2769 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not) 2770 << (NotNSStringTy ? "string type" : "NSString") 2771 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0); 2772 return; 2773 } 2774 2775 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex 2776 // because that has corrected for the implicit this parameter, and is zero- 2777 // based. The attribute expects what the user wrote explicitly. 2778 llvm::APSInt Val; 2779 IdxExpr->EvaluateAsInt(Val, S.Context); 2780 2781 D->addAttr(::new (S.Context) 2782 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(), 2783 Attr.getAttributeSpellingListIndex())); 2784 } 2785 2786 enum FormatAttrKind { 2787 CFStringFormat, 2788 NSStringFormat, 2789 StrftimeFormat, 2790 SupportedFormat, 2791 IgnoredFormat, 2792 InvalidFormat 2793 }; 2794 2795 /// getFormatAttrKind - Map from format attribute names to supported format 2796 /// types. 2797 static FormatAttrKind getFormatAttrKind(StringRef Format) { 2798 return llvm::StringSwitch<FormatAttrKind>(Format) 2799 // Check for formats that get handled specially. 2800 .Case("NSString", NSStringFormat) 2801 .Case("CFString", CFStringFormat) 2802 .Case("strftime", StrftimeFormat) 2803 2804 // Otherwise, check for supported formats. 2805 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat) 2806 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat) 2807 .Case("kprintf", SupportedFormat) // OpenBSD. 2808 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD. 2809 .Case("os_trace", SupportedFormat) 2810 2811 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat) 2812 .Default(InvalidFormat); 2813 } 2814 2815 /// Handle __attribute__((init_priority(priority))) attributes based on 2816 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html 2817 static void handleInitPriorityAttr(Sema &S, Decl *D, 2818 const AttributeList &Attr) { 2819 if (!S.getLangOpts().CPlusPlus) { 2820 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 2821 return; 2822 } 2823 2824 if (S.getCurFunctionOrMethodDecl()) { 2825 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr); 2826 Attr.setInvalid(); 2827 return; 2828 } 2829 QualType T = cast<VarDecl>(D)->getType(); 2830 if (S.Context.getAsArrayType(T)) 2831 T = S.Context.getBaseElementType(T); 2832 if (!T->getAs<RecordType>()) { 2833 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr); 2834 Attr.setInvalid(); 2835 return; 2836 } 2837 2838 Expr *E = Attr.getArgAsExpr(0); 2839 uint32_t prioritynum; 2840 if (!checkUInt32Argument(S, Attr, E, prioritynum)) { 2841 Attr.setInvalid(); 2842 return; 2843 } 2844 2845 if (prioritynum < 101 || prioritynum > 65535) { 2846 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range) 2847 << E->getSourceRange() << Attr.getName() << 101 << 65535; 2848 Attr.setInvalid(); 2849 return; 2850 } 2851 D->addAttr(::new (S.Context) 2852 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum, 2853 Attr.getAttributeSpellingListIndex())); 2854 } 2855 2856 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range, 2857 IdentifierInfo *Format, int FormatIdx, 2858 int FirstArg, 2859 unsigned AttrSpellingListIndex) { 2860 // Check whether we already have an equivalent format attribute. 2861 for (auto *F : D->specific_attrs<FormatAttr>()) { 2862 if (F->getType() == Format && 2863 F->getFormatIdx() == FormatIdx && 2864 F->getFirstArg() == FirstArg) { 2865 // If we don't have a valid location for this attribute, adopt the 2866 // location. 2867 if (F->getLocation().isInvalid()) 2868 F->setRange(Range); 2869 return nullptr; 2870 } 2871 } 2872 2873 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx, 2874 FirstArg, AttrSpellingListIndex); 2875 } 2876 2877 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on 2878 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 2879 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2880 if (!Attr.isArgIdent(0)) { 2881 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2882 << Attr.getName() << 1 << AANT_ArgumentIdentifier; 2883 return; 2884 } 2885 2886 // In C++ the implicit 'this' function parameter also counts, and they are 2887 // counted from one. 2888 bool HasImplicitThisParam = isInstanceMethod(D); 2889 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam; 2890 2891 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident; 2892 StringRef Format = II->getName(); 2893 2894 if (normalizeName(Format)) { 2895 // If we've modified the string name, we need a new identifier for it. 2896 II = &S.Context.Idents.get(Format); 2897 } 2898 2899 // Check for supported formats. 2900 FormatAttrKind Kind = getFormatAttrKind(Format); 2901 2902 if (Kind == IgnoredFormat) 2903 return; 2904 2905 if (Kind == InvalidFormat) { 2906 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 2907 << Attr.getName() << II->getName(); 2908 return; 2909 } 2910 2911 // checks for the 2nd argument 2912 Expr *IdxExpr = Attr.getArgAsExpr(1); 2913 uint32_t Idx; 2914 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2)) 2915 return; 2916 2917 if (Idx < 1 || Idx > NumArgs) { 2918 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 2919 << Attr.getName() << 2 << IdxExpr->getSourceRange(); 2920 return; 2921 } 2922 2923 // FIXME: Do we need to bounds check? 2924 unsigned ArgIdx = Idx - 1; 2925 2926 if (HasImplicitThisParam) { 2927 if (ArgIdx == 0) { 2928 S.Diag(Attr.getLoc(), 2929 diag::err_format_attribute_implicit_this_format_string) 2930 << IdxExpr->getSourceRange(); 2931 return; 2932 } 2933 ArgIdx--; 2934 } 2935 2936 // make sure the format string is really a string 2937 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx); 2938 2939 if (Kind == CFStringFormat) { 2940 if (!isCFStringType(Ty, S.Context)) { 2941 S.Diag(Attr.getLoc(), diag::err_format_attribute_not) 2942 << "a CFString" << IdxExpr->getSourceRange() 2943 << getFunctionOrMethodParamRange(D, ArgIdx); 2944 return; 2945 } 2946 } else if (Kind == NSStringFormat) { 2947 // FIXME: do we need to check if the type is NSString*? What are the 2948 // semantics? 2949 if (!isNSStringType(Ty, S.Context)) { 2950 S.Diag(Attr.getLoc(), diag::err_format_attribute_not) 2951 << "an NSString" << IdxExpr->getSourceRange() 2952 << getFunctionOrMethodParamRange(D, ArgIdx); 2953 return; 2954 } 2955 } else if (!Ty->isPointerType() || 2956 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) { 2957 S.Diag(Attr.getLoc(), diag::err_format_attribute_not) 2958 << "a string type" << IdxExpr->getSourceRange() 2959 << getFunctionOrMethodParamRange(D, ArgIdx); 2960 return; 2961 } 2962 2963 // check the 3rd argument 2964 Expr *FirstArgExpr = Attr.getArgAsExpr(2); 2965 uint32_t FirstArg; 2966 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3)) 2967 return; 2968 2969 // check if the function is variadic if the 3rd argument non-zero 2970 if (FirstArg != 0) { 2971 if (isFunctionOrMethodVariadic(D)) { 2972 ++NumArgs; // +1 for ... 2973 } else { 2974 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic); 2975 return; 2976 } 2977 } 2978 2979 // strftime requires FirstArg to be 0 because it doesn't read from any 2980 // variable the input is just the current time + the format string. 2981 if (Kind == StrftimeFormat) { 2982 if (FirstArg != 0) { 2983 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter) 2984 << FirstArgExpr->getSourceRange(); 2985 return; 2986 } 2987 // if 0 it disables parameter checking (to use with e.g. va_list) 2988 } else if (FirstArg != 0 && FirstArg != NumArgs) { 2989 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 2990 << Attr.getName() << 3 << FirstArgExpr->getSourceRange(); 2991 return; 2992 } 2993 2994 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II, 2995 Idx, FirstArg, 2996 Attr.getAttributeSpellingListIndex()); 2997 if (NewAttr) 2998 D->addAttr(NewAttr); 2999 } 3000 3001 static void handleTransparentUnionAttr(Sema &S, Decl *D, 3002 const AttributeList &Attr) { 3003 // Try to find the underlying union declaration. 3004 RecordDecl *RD = nullptr; 3005 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D); 3006 if (TD && TD->getUnderlyingType()->isUnionType()) 3007 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl(); 3008 else 3009 RD = dyn_cast<RecordDecl>(D); 3010 3011 if (!RD || !RD->isUnion()) { 3012 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 3013 << Attr.getName() << ExpectedUnion; 3014 return; 3015 } 3016 3017 if (!RD->isCompleteDefinition()) { 3018 S.Diag(Attr.getLoc(), 3019 diag::warn_transparent_union_attribute_not_definition); 3020 return; 3021 } 3022 3023 RecordDecl::field_iterator Field = RD->field_begin(), 3024 FieldEnd = RD->field_end(); 3025 if (Field == FieldEnd) { 3026 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields); 3027 return; 3028 } 3029 3030 FieldDecl *FirstField = *Field; 3031 QualType FirstType = FirstField->getType(); 3032 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) { 3033 S.Diag(FirstField->getLocation(), 3034 diag::warn_transparent_union_attribute_floating) 3035 << FirstType->isVectorType() << FirstType; 3036 return; 3037 } 3038 3039 uint64_t FirstSize = S.Context.getTypeSize(FirstType); 3040 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType); 3041 for (; Field != FieldEnd; ++Field) { 3042 QualType FieldType = Field->getType(); 3043 // FIXME: this isn't fully correct; we also need to test whether the 3044 // members of the union would all have the same calling convention as the 3045 // first member of the union. Checking just the size and alignment isn't 3046 // sufficient (consider structs passed on the stack instead of in registers 3047 // as an example). 3048 if (S.Context.getTypeSize(FieldType) != FirstSize || 3049 S.Context.getTypeAlign(FieldType) > FirstAlign) { 3050 // Warn if we drop the attribute. 3051 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize; 3052 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType) 3053 : S.Context.getTypeAlign(FieldType); 3054 S.Diag(Field->getLocation(), 3055 diag::warn_transparent_union_attribute_field_size_align) 3056 << isSize << Field->getDeclName() << FieldBits; 3057 unsigned FirstBits = isSize? FirstSize : FirstAlign; 3058 S.Diag(FirstField->getLocation(), 3059 diag::note_transparent_union_first_field_size_align) 3060 << isSize << FirstBits; 3061 return; 3062 } 3063 } 3064 3065 RD->addAttr(::new (S.Context) 3066 TransparentUnionAttr(Attr.getRange(), S.Context, 3067 Attr.getAttributeSpellingListIndex())); 3068 } 3069 3070 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3071 // Make sure that there is a string literal as the annotation's single 3072 // argument. 3073 StringRef Str; 3074 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 3075 return; 3076 3077 // Don't duplicate annotations that are already set. 3078 for (const auto *I : D->specific_attrs<AnnotateAttr>()) { 3079 if (I->getAnnotation() == Str) 3080 return; 3081 } 3082 3083 D->addAttr(::new (S.Context) 3084 AnnotateAttr(Attr.getRange(), S.Context, Str, 3085 Attr.getAttributeSpellingListIndex())); 3086 } 3087 3088 static void handleAlignValueAttr(Sema &S, Decl *D, 3089 const AttributeList &Attr) { 3090 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0), 3091 Attr.getAttributeSpellingListIndex()); 3092 } 3093 3094 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E, 3095 unsigned SpellingListIndex) { 3096 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex); 3097 SourceLocation AttrLoc = AttrRange.getBegin(); 3098 3099 QualType T; 3100 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) 3101 T = TD->getUnderlyingType(); 3102 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) 3103 T = VD->getType(); 3104 else 3105 llvm_unreachable("Unknown decl type for align_value"); 3106 3107 if (!T->isDependentType() && !T->isAnyPointerType() && 3108 !T->isReferenceType() && !T->isMemberPointerType()) { 3109 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only) 3110 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange(); 3111 return; 3112 } 3113 3114 if (!E->isValueDependent()) { 3115 llvm::APSInt Alignment; 3116 ExprResult ICE 3117 = VerifyIntegerConstantExpression(E, &Alignment, 3118 diag::err_align_value_attribute_argument_not_int, 3119 /*AllowFold*/ false); 3120 if (ICE.isInvalid()) 3121 return; 3122 3123 if (!Alignment.isPowerOf2()) { 3124 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 3125 << E->getSourceRange(); 3126 return; 3127 } 3128 3129 D->addAttr(::new (Context) 3130 AlignValueAttr(AttrRange, Context, ICE.get(), 3131 SpellingListIndex)); 3132 return; 3133 } 3134 3135 // Save dependent expressions in the AST to be instantiated. 3136 D->addAttr(::new (Context) AlignValueAttr(TmpAttr)); 3137 } 3138 3139 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3140 // check the attribute arguments. 3141 if (Attr.getNumArgs() > 1) { 3142 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 3143 << Attr.getName() << 1; 3144 return; 3145 } 3146 3147 if (Attr.getNumArgs() == 0) { 3148 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context, 3149 true, nullptr, Attr.getAttributeSpellingListIndex())); 3150 return; 3151 } 3152 3153 Expr *E = Attr.getArgAsExpr(0); 3154 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) { 3155 S.Diag(Attr.getEllipsisLoc(), 3156 diag::err_pack_expansion_without_parameter_packs); 3157 return; 3158 } 3159 3160 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E)) 3161 return; 3162 3163 if (E->isValueDependent()) { 3164 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) { 3165 if (!TND->getUnderlyingType()->isDependentType()) { 3166 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name) 3167 << E->getSourceRange(); 3168 return; 3169 } 3170 } 3171 } 3172 3173 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(), 3174 Attr.isPackExpansion()); 3175 } 3176 3177 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, 3178 unsigned SpellingListIndex, bool IsPackExpansion) { 3179 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex); 3180 SourceLocation AttrLoc = AttrRange.getBegin(); 3181 3182 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements. 3183 if (TmpAttr.isAlignas()) { 3184 // C++11 [dcl.align]p1: 3185 // An alignment-specifier may be applied to a variable or to a class 3186 // data member, but it shall not be applied to a bit-field, a function 3187 // parameter, the formal parameter of a catch clause, or a variable 3188 // declared with the register storage class specifier. An 3189 // alignment-specifier may also be applied to the declaration of a class 3190 // or enumeration type. 3191 // C11 6.7.5/2: 3192 // An alignment attribute shall not be specified in a declaration of 3193 // a typedef, or a bit-field, or a function, or a parameter, or an 3194 // object declared with the register storage-class specifier. 3195 int DiagKind = -1; 3196 if (isa<ParmVarDecl>(D)) { 3197 DiagKind = 0; 3198 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 3199 if (VD->getStorageClass() == SC_Register) 3200 DiagKind = 1; 3201 if (VD->isExceptionVariable()) 3202 DiagKind = 2; 3203 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 3204 if (FD->isBitField()) 3205 DiagKind = 3; 3206 } else if (!isa<TagDecl>(D)) { 3207 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr 3208 << (TmpAttr.isC11() ? ExpectedVariableOrField 3209 : ExpectedVariableFieldOrTag); 3210 return; 3211 } 3212 if (DiagKind != -1) { 3213 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type) 3214 << &TmpAttr << DiagKind; 3215 return; 3216 } 3217 } 3218 3219 if (E->isTypeDependent() || E->isValueDependent()) { 3220 // Save dependent expressions in the AST to be instantiated. 3221 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr); 3222 AA->setPackExpansion(IsPackExpansion); 3223 D->addAttr(AA); 3224 return; 3225 } 3226 3227 // FIXME: Cache the number on the Attr object? 3228 llvm::APSInt Alignment; 3229 ExprResult ICE 3230 = VerifyIntegerConstantExpression(E, &Alignment, 3231 diag::err_aligned_attribute_argument_not_int, 3232 /*AllowFold*/ false); 3233 if (ICE.isInvalid()) 3234 return; 3235 3236 uint64_t AlignVal = Alignment.getZExtValue(); 3237 3238 // C++11 [dcl.align]p2: 3239 // -- if the constant expression evaluates to zero, the alignment 3240 // specifier shall have no effect 3241 // C11 6.7.5p6: 3242 // An alignment specification of zero has no effect. 3243 if (!(TmpAttr.isAlignas() && !Alignment)) { 3244 if (!llvm::isPowerOf2_64(AlignVal)) { 3245 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 3246 << E->getSourceRange(); 3247 return; 3248 } 3249 } 3250 3251 // Alignment calculations can wrap around if it's greater than 2**28. 3252 unsigned MaxValidAlignment = 3253 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192 3254 : 268435456; 3255 if (AlignVal > MaxValidAlignment) { 3256 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment 3257 << E->getSourceRange(); 3258 return; 3259 } 3260 3261 if (Context.getTargetInfo().isTLSSupported()) { 3262 unsigned MaxTLSAlign = 3263 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign()) 3264 .getQuantity(); 3265 auto *VD = dyn_cast<VarDecl>(D); 3266 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD && 3267 VD->getTLSKind() != VarDecl::TLS_None) { 3268 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 3269 << (unsigned)AlignVal << VD << MaxTLSAlign; 3270 return; 3271 } 3272 } 3273 3274 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true, 3275 ICE.get(), SpellingListIndex); 3276 AA->setPackExpansion(IsPackExpansion); 3277 D->addAttr(AA); 3278 } 3279 3280 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS, 3281 unsigned SpellingListIndex, bool IsPackExpansion) { 3282 // FIXME: Cache the number on the Attr object if non-dependent? 3283 // FIXME: Perform checking of type validity 3284 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS, 3285 SpellingListIndex); 3286 AA->setPackExpansion(IsPackExpansion); 3287 D->addAttr(AA); 3288 } 3289 3290 void Sema::CheckAlignasUnderalignment(Decl *D) { 3291 assert(D->hasAttrs() && "no attributes on decl"); 3292 3293 QualType UnderlyingTy, DiagTy; 3294 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 3295 UnderlyingTy = DiagTy = VD->getType(); 3296 } else { 3297 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D)); 3298 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) 3299 UnderlyingTy = ED->getIntegerType(); 3300 } 3301 if (DiagTy->isDependentType() || DiagTy->isIncompleteType()) 3302 return; 3303 3304 // C++11 [dcl.align]p5, C11 6.7.5/4: 3305 // The combined effect of all alignment attributes in a declaration shall 3306 // not specify an alignment that is less strict than the alignment that 3307 // would otherwise be required for the entity being declared. 3308 AlignedAttr *AlignasAttr = nullptr; 3309 unsigned Align = 0; 3310 for (auto *I : D->specific_attrs<AlignedAttr>()) { 3311 if (I->isAlignmentDependent()) 3312 return; 3313 if (I->isAlignas()) 3314 AlignasAttr = I; 3315 Align = std::max(Align, I->getAlignment(Context)); 3316 } 3317 3318 if (AlignasAttr && Align) { 3319 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align); 3320 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy); 3321 if (NaturalAlign > RequestedAlign) 3322 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned) 3323 << DiagTy << (unsigned)NaturalAlign.getQuantity(); 3324 } 3325 } 3326 3327 bool Sema::checkMSInheritanceAttrOnDefinition( 3328 CXXRecordDecl *RD, SourceRange Range, bool BestCase, 3329 MSInheritanceAttr::Spelling SemanticSpelling) { 3330 assert(RD->hasDefinition() && "RD has no definition!"); 3331 3332 // We may not have seen base specifiers or any virtual methods yet. We will 3333 // have to wait until the record is defined to catch any mismatches. 3334 if (!RD->getDefinition()->isCompleteDefinition()) 3335 return false; 3336 3337 // The unspecified model never matches what a definition could need. 3338 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance) 3339 return false; 3340 3341 if (BestCase) { 3342 if (RD->calculateInheritanceModel() == SemanticSpelling) 3343 return false; 3344 } else { 3345 if (RD->calculateInheritanceModel() <= SemanticSpelling) 3346 return false; 3347 } 3348 3349 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance) 3350 << 0 /*definition*/; 3351 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) 3352 << RD->getNameAsString(); 3353 return true; 3354 } 3355 3356 /// parseModeAttrArg - Parses attribute mode string and returns parsed type 3357 /// attribute. 3358 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth, 3359 bool &IntegerMode, bool &ComplexMode) { 3360 IntegerMode = true; 3361 ComplexMode = false; 3362 switch (Str.size()) { 3363 case 2: 3364 switch (Str[0]) { 3365 case 'Q': 3366 DestWidth = 8; 3367 break; 3368 case 'H': 3369 DestWidth = 16; 3370 break; 3371 case 'S': 3372 DestWidth = 32; 3373 break; 3374 case 'D': 3375 DestWidth = 64; 3376 break; 3377 case 'X': 3378 DestWidth = 96; 3379 break; 3380 case 'T': 3381 DestWidth = 128; 3382 break; 3383 } 3384 if (Str[1] == 'F') { 3385 IntegerMode = false; 3386 } else if (Str[1] == 'C') { 3387 IntegerMode = false; 3388 ComplexMode = true; 3389 } else if (Str[1] != 'I') { 3390 DestWidth = 0; 3391 } 3392 break; 3393 case 4: 3394 // FIXME: glibc uses 'word' to define register_t; this is narrower than a 3395 // pointer on PIC16 and other embedded platforms. 3396 if (Str == "word") 3397 DestWidth = S.Context.getTargetInfo().getRegisterWidth(); 3398 else if (Str == "byte") 3399 DestWidth = S.Context.getTargetInfo().getCharWidth(); 3400 break; 3401 case 7: 3402 if (Str == "pointer") 3403 DestWidth = S.Context.getTargetInfo().getPointerWidth(0); 3404 break; 3405 case 11: 3406 if (Str == "unwind_word") 3407 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth(); 3408 break; 3409 } 3410 } 3411 3412 /// handleModeAttr - This attribute modifies the width of a decl with primitive 3413 /// type. 3414 /// 3415 /// Despite what would be logical, the mode attribute is a decl attribute, not a 3416 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be 3417 /// HImode, not an intermediate pointer. 3418 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3419 // This attribute isn't documented, but glibc uses it. It changes 3420 // the width of an int or unsigned int to the specified size. 3421 if (!Attr.isArgIdent(0)) { 3422 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName() 3423 << AANT_ArgumentIdentifier; 3424 return; 3425 } 3426 3427 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident; 3428 3429 S.AddModeAttr(Attr.getRange(), D, Name, Attr.getAttributeSpellingListIndex()); 3430 } 3431 3432 void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name, 3433 unsigned SpellingListIndex, bool InInstantiation) { 3434 StringRef Str = Name->getName(); 3435 normalizeName(Str); 3436 SourceLocation AttrLoc = AttrRange.getBegin(); 3437 3438 unsigned DestWidth = 0; 3439 bool IntegerMode = true; 3440 bool ComplexMode = false; 3441 llvm::APInt VectorSize(64, 0); 3442 if (Str.size() >= 4 && Str[0] == 'V') { 3443 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2). 3444 size_t StrSize = Str.size(); 3445 size_t VectorStringLength = 0; 3446 while ((VectorStringLength + 1) < StrSize && 3447 isdigit(Str[VectorStringLength + 1])) 3448 ++VectorStringLength; 3449 if (VectorStringLength && 3450 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) && 3451 VectorSize.isPowerOf2()) { 3452 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth, 3453 IntegerMode, ComplexMode); 3454 // Avoid duplicate warning from template instantiation. 3455 if (!InInstantiation) 3456 Diag(AttrLoc, diag::warn_vector_mode_deprecated); 3457 } else { 3458 VectorSize = 0; 3459 } 3460 } 3461 3462 if (!VectorSize) 3463 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode); 3464 3465 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t 3466 // and friends, at least with glibc. 3467 // FIXME: Make sure floating-point mappings are accurate 3468 // FIXME: Support XF and TF types 3469 if (!DestWidth) { 3470 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name; 3471 return; 3472 } 3473 3474 QualType OldTy; 3475 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) 3476 OldTy = TD->getUnderlyingType(); 3477 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 3478 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'. 3479 // Try to get type from enum declaration, default to int. 3480 OldTy = ED->getIntegerType(); 3481 if (OldTy.isNull()) 3482 OldTy = Context.IntTy; 3483 } else 3484 OldTy = cast<ValueDecl>(D)->getType(); 3485 3486 if (OldTy->isDependentType()) { 3487 D->addAttr(::new (Context) 3488 ModeAttr(AttrRange, Context, Name, SpellingListIndex)); 3489 return; 3490 } 3491 3492 // Base type can also be a vector type (see PR17453). 3493 // Distinguish between base type and base element type. 3494 QualType OldElemTy = OldTy; 3495 if (const VectorType *VT = OldTy->getAs<VectorType>()) 3496 OldElemTy = VT->getElementType(); 3497 3498 // GCC allows 'mode' attribute on enumeration types (even incomplete), except 3499 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete 3500 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected. 3501 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) && 3502 VectorSize.getBoolValue()) { 3503 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange; 3504 return; 3505 } 3506 bool IntegralOrAnyEnumType = 3507 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>(); 3508 3509 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() && 3510 !IntegralOrAnyEnumType) 3511 Diag(AttrLoc, diag::err_mode_not_primitive); 3512 else if (IntegerMode) { 3513 if (!IntegralOrAnyEnumType) 3514 Diag(AttrLoc, diag::err_mode_wrong_type); 3515 } else if (ComplexMode) { 3516 if (!OldElemTy->isComplexType()) 3517 Diag(AttrLoc, diag::err_mode_wrong_type); 3518 } else { 3519 if (!OldElemTy->isFloatingType()) 3520 Diag(AttrLoc, diag::err_mode_wrong_type); 3521 } 3522 3523 QualType NewElemTy; 3524 3525 if (IntegerMode) 3526 NewElemTy = Context.getIntTypeForBitwidth(DestWidth, 3527 OldElemTy->isSignedIntegerType()); 3528 else 3529 NewElemTy = Context.getRealTypeForBitwidth(DestWidth); 3530 3531 if (NewElemTy.isNull()) { 3532 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name; 3533 return; 3534 } 3535 3536 if (ComplexMode) { 3537 NewElemTy = Context.getComplexType(NewElemTy); 3538 } 3539 3540 QualType NewTy = NewElemTy; 3541 if (VectorSize.getBoolValue()) { 3542 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(), 3543 VectorType::GenericVector); 3544 } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) { 3545 // Complex machine mode does not support base vector types. 3546 if (ComplexMode) { 3547 Diag(AttrLoc, diag::err_complex_mode_vector_type); 3548 return; 3549 } 3550 unsigned NumElements = Context.getTypeSize(OldElemTy) * 3551 OldVT->getNumElements() / 3552 Context.getTypeSize(NewElemTy); 3553 NewTy = 3554 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind()); 3555 } 3556 3557 if (NewTy.isNull()) { 3558 Diag(AttrLoc, diag::err_mode_wrong_type); 3559 return; 3560 } 3561 3562 // Install the new type. 3563 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) 3564 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy); 3565 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) 3566 ED->setIntegerType(NewTy); 3567 else 3568 cast<ValueDecl>(D)->setType(NewTy); 3569 3570 D->addAttr(::new (Context) 3571 ModeAttr(AttrRange, Context, Name, SpellingListIndex)); 3572 } 3573 3574 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3575 D->addAttr(::new (S.Context) 3576 NoDebugAttr(Attr.getRange(), S.Context, 3577 Attr.getAttributeSpellingListIndex())); 3578 } 3579 3580 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range, 3581 IdentifierInfo *Ident, 3582 unsigned AttrSpellingListIndex) { 3583 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) { 3584 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident; 3585 Diag(Optnone->getLocation(), diag::note_conflicting_attribute); 3586 return nullptr; 3587 } 3588 3589 if (D->hasAttr<AlwaysInlineAttr>()) 3590 return nullptr; 3591 3592 return ::new (Context) AlwaysInlineAttr(Range, Context, 3593 AttrSpellingListIndex); 3594 } 3595 3596 CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range, 3597 IdentifierInfo *Ident, 3598 unsigned AttrSpellingListIndex) { 3599 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident)) 3600 return nullptr; 3601 3602 return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex); 3603 } 3604 3605 InternalLinkageAttr * 3606 Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range, 3607 IdentifierInfo *Ident, 3608 unsigned AttrSpellingListIndex) { 3609 if (auto VD = dyn_cast<VarDecl>(D)) { 3610 // Attribute applies to Var but not any subclass of it (like ParmVar, 3611 // ImplicitParm or VarTemplateSpecialization). 3612 if (VD->getKind() != Decl::Var) { 3613 Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type) 3614 << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass 3615 : ExpectedVariableOrFunction); 3616 return nullptr; 3617 } 3618 // Attribute does not apply to non-static local variables. 3619 if (VD->hasLocalStorage()) { 3620 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage); 3621 return nullptr; 3622 } 3623 } 3624 3625 if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident)) 3626 return nullptr; 3627 3628 return ::new (Context) 3629 InternalLinkageAttr(Range, Context, AttrSpellingListIndex); 3630 } 3631 3632 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range, 3633 unsigned AttrSpellingListIndex) { 3634 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) { 3635 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'"; 3636 Diag(Optnone->getLocation(), diag::note_conflicting_attribute); 3637 return nullptr; 3638 } 3639 3640 if (D->hasAttr<MinSizeAttr>()) 3641 return nullptr; 3642 3643 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex); 3644 } 3645 3646 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range, 3647 unsigned AttrSpellingListIndex) { 3648 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) { 3649 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline; 3650 Diag(Range.getBegin(), diag::note_conflicting_attribute); 3651 D->dropAttr<AlwaysInlineAttr>(); 3652 } 3653 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) { 3654 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize; 3655 Diag(Range.getBegin(), diag::note_conflicting_attribute); 3656 D->dropAttr<MinSizeAttr>(); 3657 } 3658 3659 if (D->hasAttr<OptimizeNoneAttr>()) 3660 return nullptr; 3661 3662 return ::new (Context) OptimizeNoneAttr(Range, Context, 3663 AttrSpellingListIndex); 3664 } 3665 3666 static void handleAlwaysInlineAttr(Sema &S, Decl *D, 3667 const AttributeList &Attr) { 3668 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(), 3669 Attr.getName())) 3670 return; 3671 3672 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr( 3673 D, Attr.getRange(), Attr.getName(), 3674 Attr.getAttributeSpellingListIndex())) 3675 D->addAttr(Inline); 3676 } 3677 3678 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3679 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr( 3680 D, Attr.getRange(), Attr.getAttributeSpellingListIndex())) 3681 D->addAttr(MinSize); 3682 } 3683 3684 static void handleOptimizeNoneAttr(Sema &S, Decl *D, 3685 const AttributeList &Attr) { 3686 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr( 3687 D, Attr.getRange(), Attr.getAttributeSpellingListIndex())) 3688 D->addAttr(Optnone); 3689 } 3690 3691 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3692 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(), 3693 Attr.getName()) || 3694 checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(), 3695 Attr.getName())) { 3696 return; 3697 } 3698 FunctionDecl *FD = cast<FunctionDecl>(D); 3699 if (!FD->getReturnType()->isVoidType()) { 3700 SourceRange RTRange = FD->getReturnTypeSourceRange(); 3701 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return) 3702 << FD->getType() 3703 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 3704 : FixItHint()); 3705 return; 3706 } 3707 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) { 3708 if (Method->isInstance()) { 3709 S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method) 3710 << Method; 3711 return; 3712 } 3713 S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method; 3714 } 3715 // Only warn for "inline" when compiling for host, to cut down on noise. 3716 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice) 3717 S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD; 3718 3719 D->addAttr(::new (S.Context) 3720 CUDAGlobalAttr(Attr.getRange(), S.Context, 3721 Attr.getAttributeSpellingListIndex())); 3722 } 3723 3724 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3725 FunctionDecl *Fn = cast<FunctionDecl>(D); 3726 if (!Fn->isInlineSpecified()) { 3727 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline); 3728 return; 3729 } 3730 3731 D->addAttr(::new (S.Context) 3732 GNUInlineAttr(Attr.getRange(), S.Context, 3733 Attr.getAttributeSpellingListIndex())); 3734 } 3735 3736 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3737 if (hasDeclarator(D)) return; 3738 3739 // Diagnostic is emitted elsewhere: here we store the (valid) Attr 3740 // in the Decl node for syntactic reasoning, e.g., pretty-printing. 3741 CallingConv CC; 3742 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr)) 3743 return; 3744 3745 if (!isa<ObjCMethodDecl>(D)) { 3746 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 3747 << Attr.getName() << ExpectedFunctionOrMethod; 3748 return; 3749 } 3750 3751 switch (Attr.getKind()) { 3752 case AttributeList::AT_FastCall: 3753 D->addAttr(::new (S.Context) 3754 FastCallAttr(Attr.getRange(), S.Context, 3755 Attr.getAttributeSpellingListIndex())); 3756 return; 3757 case AttributeList::AT_StdCall: 3758 D->addAttr(::new (S.Context) 3759 StdCallAttr(Attr.getRange(), S.Context, 3760 Attr.getAttributeSpellingListIndex())); 3761 return; 3762 case AttributeList::AT_ThisCall: 3763 D->addAttr(::new (S.Context) 3764 ThisCallAttr(Attr.getRange(), S.Context, 3765 Attr.getAttributeSpellingListIndex())); 3766 return; 3767 case AttributeList::AT_CDecl: 3768 D->addAttr(::new (S.Context) 3769 CDeclAttr(Attr.getRange(), S.Context, 3770 Attr.getAttributeSpellingListIndex())); 3771 return; 3772 case AttributeList::AT_Pascal: 3773 D->addAttr(::new (S.Context) 3774 PascalAttr(Attr.getRange(), S.Context, 3775 Attr.getAttributeSpellingListIndex())); 3776 return; 3777 case AttributeList::AT_SwiftCall: 3778 D->addAttr(::new (S.Context) 3779 SwiftCallAttr(Attr.getRange(), S.Context, 3780 Attr.getAttributeSpellingListIndex())); 3781 return; 3782 case AttributeList::AT_VectorCall: 3783 D->addAttr(::new (S.Context) 3784 VectorCallAttr(Attr.getRange(), S.Context, 3785 Attr.getAttributeSpellingListIndex())); 3786 return; 3787 case AttributeList::AT_MSABI: 3788 D->addAttr(::new (S.Context) 3789 MSABIAttr(Attr.getRange(), S.Context, 3790 Attr.getAttributeSpellingListIndex())); 3791 return; 3792 case AttributeList::AT_SysVABI: 3793 D->addAttr(::new (S.Context) 3794 SysVABIAttr(Attr.getRange(), S.Context, 3795 Attr.getAttributeSpellingListIndex())); 3796 return; 3797 case AttributeList::AT_Pcs: { 3798 PcsAttr::PCSType PCS; 3799 switch (CC) { 3800 case CC_AAPCS: 3801 PCS = PcsAttr::AAPCS; 3802 break; 3803 case CC_AAPCS_VFP: 3804 PCS = PcsAttr::AAPCS_VFP; 3805 break; 3806 default: 3807 llvm_unreachable("unexpected calling convention in pcs attribute"); 3808 } 3809 3810 D->addAttr(::new (S.Context) 3811 PcsAttr(Attr.getRange(), S.Context, PCS, 3812 Attr.getAttributeSpellingListIndex())); 3813 return; 3814 } 3815 case AttributeList::AT_IntelOclBicc: 3816 D->addAttr(::new (S.Context) 3817 IntelOclBiccAttr(Attr.getRange(), S.Context, 3818 Attr.getAttributeSpellingListIndex())); 3819 return; 3820 case AttributeList::AT_PreserveMost: 3821 D->addAttr(::new (S.Context) PreserveMostAttr( 3822 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 3823 return; 3824 case AttributeList::AT_PreserveAll: 3825 D->addAttr(::new (S.Context) PreserveAllAttr( 3826 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 3827 return; 3828 default: 3829 llvm_unreachable("unexpected attribute kind"); 3830 } 3831 } 3832 3833 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC, 3834 const FunctionDecl *FD) { 3835 if (attr.isInvalid()) 3836 return true; 3837 3838 if (attr.hasProcessingCache()) { 3839 CC = (CallingConv) attr.getProcessingCache(); 3840 return false; 3841 } 3842 3843 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0; 3844 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) { 3845 attr.setInvalid(); 3846 return true; 3847 } 3848 3849 // TODO: diagnose uses of these conventions on the wrong target. 3850 switch (attr.getKind()) { 3851 case AttributeList::AT_CDecl: CC = CC_C; break; 3852 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break; 3853 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break; 3854 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break; 3855 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break; 3856 case AttributeList::AT_SwiftCall: CC = CC_Swift; break; 3857 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break; 3858 case AttributeList::AT_MSABI: 3859 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C : 3860 CC_X86_64Win64; 3861 break; 3862 case AttributeList::AT_SysVABI: 3863 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV : 3864 CC_C; 3865 break; 3866 case AttributeList::AT_Pcs: { 3867 StringRef StrRef; 3868 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) { 3869 attr.setInvalid(); 3870 return true; 3871 } 3872 if (StrRef == "aapcs") { 3873 CC = CC_AAPCS; 3874 break; 3875 } else if (StrRef == "aapcs-vfp") { 3876 CC = CC_AAPCS_VFP; 3877 break; 3878 } 3879 3880 attr.setInvalid(); 3881 Diag(attr.getLoc(), diag::err_invalid_pcs); 3882 return true; 3883 } 3884 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break; 3885 case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break; 3886 case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break; 3887 default: llvm_unreachable("unexpected attribute kind"); 3888 } 3889 3890 const TargetInfo &TI = Context.getTargetInfo(); 3891 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC); 3892 if (A != TargetInfo::CCCR_OK) { 3893 if (A == TargetInfo::CCCR_Warning) 3894 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName(); 3895 3896 // This convention is not valid for the target. Use the default function or 3897 // method calling convention. 3898 TargetInfo::CallingConvMethodType MT = TargetInfo::CCMT_Unknown; 3899 if (FD) 3900 MT = FD->isCXXInstanceMember() ? TargetInfo::CCMT_Member : 3901 TargetInfo::CCMT_NonMember; 3902 CC = TI.getDefaultCallingConv(MT); 3903 } 3904 3905 attr.setProcessingCache((unsigned) CC); 3906 return false; 3907 } 3908 3909 /// Pointer-like types in the default address space. 3910 static bool isValidSwiftContextType(QualType type) { 3911 if (!type->hasPointerRepresentation()) 3912 return type->isDependentType(); 3913 return type->getPointeeType().getAddressSpace() == 0; 3914 } 3915 3916 /// Pointers and references in the default address space. 3917 static bool isValidSwiftIndirectResultType(QualType type) { 3918 if (auto ptrType = type->getAs<PointerType>()) { 3919 type = ptrType->getPointeeType(); 3920 } else if (auto refType = type->getAs<ReferenceType>()) { 3921 type = refType->getPointeeType(); 3922 } else { 3923 return type->isDependentType(); 3924 } 3925 return type.getAddressSpace() == 0; 3926 } 3927 3928 /// Pointers and references to pointers in the default address space. 3929 static bool isValidSwiftErrorResultType(QualType type) { 3930 if (auto ptrType = type->getAs<PointerType>()) { 3931 type = ptrType->getPointeeType(); 3932 } else if (auto refType = type->getAs<ReferenceType>()) { 3933 type = refType->getPointeeType(); 3934 } else { 3935 return type->isDependentType(); 3936 } 3937 if (!type.getQualifiers().empty()) 3938 return false; 3939 return isValidSwiftContextType(type); 3940 } 3941 3942 static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &attr, 3943 ParameterABI abi) { 3944 S.AddParameterABIAttr(attr.getRange(), D, abi, 3945 attr.getAttributeSpellingListIndex()); 3946 } 3947 3948 void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi, 3949 unsigned spellingIndex) { 3950 3951 QualType type = cast<ParmVarDecl>(D)->getType(); 3952 3953 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) { 3954 if (existingAttr->getABI() != abi) { 3955 Diag(range.getBegin(), diag::err_attributes_are_not_compatible) 3956 << getParameterABISpelling(abi) << existingAttr; 3957 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute); 3958 return; 3959 } 3960 } 3961 3962 switch (abi) { 3963 case ParameterABI::Ordinary: 3964 llvm_unreachable("explicit attribute for ordinary parameter ABI?"); 3965 3966 case ParameterABI::SwiftContext: 3967 if (!isValidSwiftContextType(type)) { 3968 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) 3969 << getParameterABISpelling(abi) 3970 << /*pointer to pointer */ 0 << type; 3971 } 3972 D->addAttr(::new (Context) 3973 SwiftContextAttr(range, Context, spellingIndex)); 3974 return; 3975 3976 case ParameterABI::SwiftErrorResult: 3977 if (!isValidSwiftErrorResultType(type)) { 3978 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) 3979 << getParameterABISpelling(abi) 3980 << /*pointer to pointer */ 1 << type; 3981 } 3982 D->addAttr(::new (Context) 3983 SwiftErrorResultAttr(range, Context, spellingIndex)); 3984 return; 3985 3986 case ParameterABI::SwiftIndirectResult: 3987 if (!isValidSwiftIndirectResultType(type)) { 3988 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) 3989 << getParameterABISpelling(abi) 3990 << /*pointer*/ 0 << type; 3991 } 3992 D->addAttr(::new (Context) 3993 SwiftIndirectResultAttr(range, Context, spellingIndex)); 3994 return; 3995 } 3996 llvm_unreachable("bad parameter ABI attribute"); 3997 } 3998 3999 /// Checks a regparm attribute, returning true if it is ill-formed and 4000 /// otherwise setting numParams to the appropriate value. 4001 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) { 4002 if (Attr.isInvalid()) 4003 return true; 4004 4005 if (!checkAttributeNumArgs(*this, Attr, 1)) { 4006 Attr.setInvalid(); 4007 return true; 4008 } 4009 4010 uint32_t NP; 4011 Expr *NumParamsExpr = Attr.getArgAsExpr(0); 4012 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) { 4013 Attr.setInvalid(); 4014 return true; 4015 } 4016 4017 if (Context.getTargetInfo().getRegParmMax() == 0) { 4018 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform) 4019 << NumParamsExpr->getSourceRange(); 4020 Attr.setInvalid(); 4021 return true; 4022 } 4023 4024 numParams = NP; 4025 if (numParams > Context.getTargetInfo().getRegParmMax()) { 4026 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number) 4027 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange(); 4028 Attr.setInvalid(); 4029 return true; 4030 } 4031 4032 return false; 4033 } 4034 4035 // Checks whether an argument of launch_bounds attribute is acceptable 4036 // May output an error. 4037 static bool checkLaunchBoundsArgument(Sema &S, Expr *E, 4038 const CUDALaunchBoundsAttr &Attr, 4039 const unsigned Idx) { 4040 if (S.DiagnoseUnexpandedParameterPack(E)) 4041 return false; 4042 4043 // Accept template arguments for now as they depend on something else. 4044 // We'll get to check them when they eventually get instantiated. 4045 if (E->isValueDependent()) 4046 return true; 4047 4048 llvm::APSInt I(64); 4049 if (!E->isIntegerConstantExpr(I, S.Context)) { 4050 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type) 4051 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange(); 4052 return false; 4053 } 4054 // Make sure we can fit it in 32 bits. 4055 if (!I.isIntN(32)) { 4056 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false) 4057 << 32 << /* Unsigned */ 1; 4058 return false; 4059 } 4060 if (I < 0) 4061 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative) 4062 << &Attr << Idx << E->getSourceRange(); 4063 4064 return true; 4065 } 4066 4067 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads, 4068 Expr *MinBlocks, unsigned SpellingListIndex) { 4069 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks, 4070 SpellingListIndex); 4071 4072 if (!checkLaunchBoundsArgument(*this, MaxThreads, TmpAttr, 0)) 4073 return; 4074 4075 if (MinBlocks && !checkLaunchBoundsArgument(*this, MinBlocks, TmpAttr, 1)) 4076 return; 4077 4078 D->addAttr(::new (Context) CUDALaunchBoundsAttr( 4079 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex)); 4080 } 4081 4082 static void handleLaunchBoundsAttr(Sema &S, Decl *D, 4083 const AttributeList &Attr) { 4084 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) || 4085 !checkAttributeAtMostNumArgs(S, Attr, 2)) 4086 return; 4087 4088 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0), 4089 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr, 4090 Attr.getAttributeSpellingListIndex()); 4091 } 4092 4093 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D, 4094 const AttributeList &Attr) { 4095 if (!Attr.isArgIdent(0)) { 4096 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 4097 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier; 4098 return; 4099 } 4100 4101 if (!checkAttributeNumArgs(S, Attr, 3)) 4102 return; 4103 4104 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident; 4105 4106 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) { 4107 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type) 4108 << Attr.getName() << ExpectedFunctionOrMethod; 4109 return; 4110 } 4111 4112 uint64_t ArgumentIdx; 4113 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1), 4114 ArgumentIdx)) 4115 return; 4116 4117 uint64_t TypeTagIdx; 4118 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2), 4119 TypeTagIdx)) 4120 return; 4121 4122 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag"); 4123 if (IsPointer) { 4124 // Ensure that buffer has a pointer type. 4125 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx); 4126 if (!BufferTy->isPointerType()) { 4127 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only) 4128 << Attr.getName() << 0; 4129 } 4130 } 4131 4132 D->addAttr(::new (S.Context) 4133 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind, 4134 ArgumentIdx, TypeTagIdx, IsPointer, 4135 Attr.getAttributeSpellingListIndex())); 4136 } 4137 4138 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D, 4139 const AttributeList &Attr) { 4140 if (!Attr.isArgIdent(0)) { 4141 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 4142 << Attr.getName() << 1 << AANT_ArgumentIdentifier; 4143 return; 4144 } 4145 4146 if (!checkAttributeNumArgs(S, Attr, 1)) 4147 return; 4148 4149 if (!isa<VarDecl>(D)) { 4150 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type) 4151 << Attr.getName() << ExpectedVariable; 4152 return; 4153 } 4154 4155 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident; 4156 TypeSourceInfo *MatchingCTypeLoc = nullptr; 4157 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc); 4158 assert(MatchingCTypeLoc && "no type source info for attribute argument"); 4159 4160 D->addAttr(::new (S.Context) 4161 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind, 4162 MatchingCTypeLoc, 4163 Attr.getLayoutCompatible(), 4164 Attr.getMustBeNull(), 4165 Attr.getAttributeSpellingListIndex())); 4166 } 4167 4168 //===----------------------------------------------------------------------===// 4169 // Checker-specific attribute handlers. 4170 //===----------------------------------------------------------------------===// 4171 4172 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) { 4173 return type->isDependentType() || 4174 type->isObjCRetainableType(); 4175 } 4176 4177 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) { 4178 return type->isDependentType() || 4179 type->isObjCObjectPointerType() || 4180 S.Context.isObjCNSObjectType(type); 4181 } 4182 4183 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) { 4184 return type->isDependentType() || 4185 type->isPointerType() || 4186 isValidSubjectOfNSAttribute(S, type); 4187 } 4188 4189 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4190 S.AddNSConsumedAttr(Attr.getRange(), D, Attr.getAttributeSpellingListIndex(), 4191 Attr.getKind() == AttributeList::AT_NSConsumed, 4192 /*template instantiation*/ false); 4193 } 4194 4195 void Sema::AddNSConsumedAttr(SourceRange attrRange, Decl *D, 4196 unsigned spellingIndex, bool isNSConsumed, 4197 bool isTemplateInstantiation) { 4198 ParmVarDecl *param = cast<ParmVarDecl>(D); 4199 bool typeOK; 4200 4201 if (isNSConsumed) { 4202 typeOK = isValidSubjectOfNSAttribute(*this, param->getType()); 4203 } else { 4204 typeOK = isValidSubjectOfCFAttribute(*this, param->getType()); 4205 } 4206 4207 if (!typeOK) { 4208 // These attributes are normally just advisory, but in ARC, ns_consumed 4209 // is significant. Allow non-dependent code to contain inappropriate 4210 // attributes even in ARC, but require template instantiations to be 4211 // set up correctly. 4212 Diag(D->getLocStart(), 4213 (isTemplateInstantiation && isNSConsumed && 4214 getLangOpts().ObjCAutoRefCount 4215 ? diag::err_ns_attribute_wrong_parameter_type 4216 : diag::warn_ns_attribute_wrong_parameter_type)) 4217 << attrRange 4218 << (isNSConsumed ? "ns_consumed" : "cf_consumed") 4219 << (isNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1); 4220 return; 4221 } 4222 4223 if (isNSConsumed) 4224 param->addAttr(::new (Context) 4225 NSConsumedAttr(attrRange, Context, spellingIndex)); 4226 else 4227 param->addAttr(::new (Context) 4228 CFConsumedAttr(attrRange, Context, spellingIndex)); 4229 } 4230 4231 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D, 4232 const AttributeList &Attr) { 4233 QualType returnType; 4234 4235 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 4236 returnType = MD->getReturnType(); 4237 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) && 4238 (Attr.getKind() == AttributeList::AT_NSReturnsRetained)) 4239 return; // ignore: was handled as a type attribute 4240 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) 4241 returnType = PD->getType(); 4242 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 4243 returnType = FD->getReturnType(); 4244 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) { 4245 returnType = Param->getType()->getPointeeType(); 4246 if (returnType.isNull()) { 4247 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type) 4248 << Attr.getName() << /*pointer-to-CF*/2 4249 << Attr.getRange(); 4250 return; 4251 } 4252 } else { 4253 AttributeDeclKind ExpectedDeclKind; 4254 switch (Attr.getKind()) { 4255 default: llvm_unreachable("invalid ownership attribute"); 4256 case AttributeList::AT_NSReturnsRetained: 4257 case AttributeList::AT_NSReturnsAutoreleased: 4258 case AttributeList::AT_NSReturnsNotRetained: 4259 ExpectedDeclKind = ExpectedFunctionOrMethod; 4260 break; 4261 4262 case AttributeList::AT_CFReturnsRetained: 4263 case AttributeList::AT_CFReturnsNotRetained: 4264 ExpectedDeclKind = ExpectedFunctionMethodOrParameter; 4265 break; 4266 } 4267 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type) 4268 << Attr.getRange() << Attr.getName() << ExpectedDeclKind; 4269 return; 4270 } 4271 4272 bool typeOK; 4273 bool cf; 4274 switch (Attr.getKind()) { 4275 default: llvm_unreachable("invalid ownership attribute"); 4276 case AttributeList::AT_NSReturnsRetained: 4277 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType); 4278 cf = false; 4279 break; 4280 4281 case AttributeList::AT_NSReturnsAutoreleased: 4282 case AttributeList::AT_NSReturnsNotRetained: 4283 typeOK = isValidSubjectOfNSAttribute(S, returnType); 4284 cf = false; 4285 break; 4286 4287 case AttributeList::AT_CFReturnsRetained: 4288 case AttributeList::AT_CFReturnsNotRetained: 4289 typeOK = isValidSubjectOfCFAttribute(S, returnType); 4290 cf = true; 4291 break; 4292 } 4293 4294 if (!typeOK) { 4295 if (isa<ParmVarDecl>(D)) { 4296 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type) 4297 << Attr.getName() << /*pointer-to-CF*/2 4298 << Attr.getRange(); 4299 } else { 4300 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type. 4301 enum : unsigned { 4302 Function, 4303 Method, 4304 Property 4305 } SubjectKind = Function; 4306 if (isa<ObjCMethodDecl>(D)) 4307 SubjectKind = Method; 4308 else if (isa<ObjCPropertyDecl>(D)) 4309 SubjectKind = Property; 4310 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type) 4311 << Attr.getName() << SubjectKind << cf 4312 << Attr.getRange(); 4313 } 4314 return; 4315 } 4316 4317 switch (Attr.getKind()) { 4318 default: 4319 llvm_unreachable("invalid ownership attribute"); 4320 case AttributeList::AT_NSReturnsAutoreleased: 4321 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr( 4322 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 4323 return; 4324 case AttributeList::AT_CFReturnsNotRetained: 4325 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr( 4326 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 4327 return; 4328 case AttributeList::AT_NSReturnsNotRetained: 4329 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr( 4330 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 4331 return; 4332 case AttributeList::AT_CFReturnsRetained: 4333 D->addAttr(::new (S.Context) CFReturnsRetainedAttr( 4334 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 4335 return; 4336 case AttributeList::AT_NSReturnsRetained: 4337 D->addAttr(::new (S.Context) NSReturnsRetainedAttr( 4338 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 4339 return; 4340 }; 4341 } 4342 4343 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D, 4344 const AttributeList &attr) { 4345 const int EP_ObjCMethod = 1; 4346 const int EP_ObjCProperty = 2; 4347 4348 SourceLocation loc = attr.getLoc(); 4349 QualType resultType; 4350 if (isa<ObjCMethodDecl>(D)) 4351 resultType = cast<ObjCMethodDecl>(D)->getReturnType(); 4352 else 4353 resultType = cast<ObjCPropertyDecl>(D)->getType(); 4354 4355 if (!resultType->isReferenceType() && 4356 (!resultType->isPointerType() || resultType->isObjCRetainableType())) { 4357 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type) 4358 << SourceRange(loc) 4359 << attr.getName() 4360 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty) 4361 << /*non-retainable pointer*/ 2; 4362 4363 // Drop the attribute. 4364 return; 4365 } 4366 4367 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr( 4368 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex())); 4369 } 4370 4371 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D, 4372 const AttributeList &attr) { 4373 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D); 4374 4375 DeclContext *DC = method->getDeclContext(); 4376 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) { 4377 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol) 4378 << attr.getName() << 0; 4379 S.Diag(PDecl->getLocation(), diag::note_protocol_decl); 4380 return; 4381 } 4382 if (method->getMethodFamily() == OMF_dealloc) { 4383 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol) 4384 << attr.getName() << 1; 4385 return; 4386 } 4387 4388 method->addAttr(::new (S.Context) 4389 ObjCRequiresSuperAttr(attr.getRange(), S.Context, 4390 attr.getAttributeSpellingListIndex())); 4391 } 4392 4393 static void handleCFAuditedTransferAttr(Sema &S, Decl *D, 4394 const AttributeList &Attr) { 4395 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(), 4396 Attr.getName())) 4397 return; 4398 4399 D->addAttr(::new (S.Context) 4400 CFAuditedTransferAttr(Attr.getRange(), S.Context, 4401 Attr.getAttributeSpellingListIndex())); 4402 } 4403 4404 static void handleCFUnknownTransferAttr(Sema &S, Decl *D, 4405 const AttributeList &Attr) { 4406 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(), 4407 Attr.getName())) 4408 return; 4409 4410 D->addAttr(::new (S.Context) 4411 CFUnknownTransferAttr(Attr.getRange(), S.Context, 4412 Attr.getAttributeSpellingListIndex())); 4413 } 4414 4415 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D, 4416 const AttributeList &Attr) { 4417 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr; 4418 4419 if (!Parm) { 4420 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0; 4421 return; 4422 } 4423 4424 // Typedefs only allow objc_bridge(id) and have some additional checking. 4425 if (auto TD = dyn_cast<TypedefNameDecl>(D)) { 4426 if (!Parm->Ident->isStr("id")) { 4427 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id) 4428 << Attr.getName(); 4429 return; 4430 } 4431 4432 // Only allow 'cv void *'. 4433 QualType T = TD->getUnderlyingType(); 4434 if (!T->isVoidPointerType()) { 4435 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer); 4436 return; 4437 } 4438 } 4439 4440 D->addAttr(::new (S.Context) 4441 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident, 4442 Attr.getAttributeSpellingListIndex())); 4443 } 4444 4445 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D, 4446 const AttributeList &Attr) { 4447 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr; 4448 4449 if (!Parm) { 4450 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0; 4451 return; 4452 } 4453 4454 D->addAttr(::new (S.Context) 4455 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident, 4456 Attr.getAttributeSpellingListIndex())); 4457 } 4458 4459 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D, 4460 const AttributeList &Attr) { 4461 IdentifierInfo *RelatedClass = 4462 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr; 4463 if (!RelatedClass) { 4464 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0; 4465 return; 4466 } 4467 IdentifierInfo *ClassMethod = 4468 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr; 4469 IdentifierInfo *InstanceMethod = 4470 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr; 4471 D->addAttr(::new (S.Context) 4472 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass, 4473 ClassMethod, InstanceMethod, 4474 Attr.getAttributeSpellingListIndex())); 4475 } 4476 4477 static void handleObjCDesignatedInitializer(Sema &S, Decl *D, 4478 const AttributeList &Attr) { 4479 ObjCInterfaceDecl *IFace; 4480 if (ObjCCategoryDecl *CatDecl = 4481 dyn_cast<ObjCCategoryDecl>(D->getDeclContext())) 4482 IFace = CatDecl->getClassInterface(); 4483 else 4484 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext()); 4485 4486 if (!IFace) 4487 return; 4488 4489 IFace->setHasDesignatedInitializers(); 4490 D->addAttr(::new (S.Context) 4491 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context, 4492 Attr.getAttributeSpellingListIndex())); 4493 } 4494 4495 static void handleObjCRuntimeName(Sema &S, Decl *D, 4496 const AttributeList &Attr) { 4497 StringRef MetaDataName; 4498 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName)) 4499 return; 4500 D->addAttr(::new (S.Context) 4501 ObjCRuntimeNameAttr(Attr.getRange(), S.Context, 4502 MetaDataName, 4503 Attr.getAttributeSpellingListIndex())); 4504 } 4505 4506 // when a user wants to use objc_boxable with a union or struct 4507 // but she doesn't have access to the declaration (legacy/third-party code) 4508 // then she can 'enable' this feature via trick with a typedef 4509 // e.g.: 4510 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct; 4511 static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) { 4512 bool notify = false; 4513 4514 RecordDecl *RD = dyn_cast<RecordDecl>(D); 4515 if (RD && RD->getDefinition()) { 4516 RD = RD->getDefinition(); 4517 notify = true; 4518 } 4519 4520 if (RD) { 4521 ObjCBoxableAttr *BoxableAttr = ::new (S.Context) 4522 ObjCBoxableAttr(Attr.getRange(), S.Context, 4523 Attr.getAttributeSpellingListIndex()); 4524 RD->addAttr(BoxableAttr); 4525 if (notify) { 4526 // we need to notify ASTReader/ASTWriter about 4527 // modification of existing declaration 4528 if (ASTMutationListener *L = S.getASTMutationListener()) 4529 L->AddedAttributeToRecord(BoxableAttr, RD); 4530 } 4531 } 4532 } 4533 4534 static void handleObjCOwnershipAttr(Sema &S, Decl *D, 4535 const AttributeList &Attr) { 4536 if (hasDeclarator(D)) return; 4537 4538 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type) 4539 << Attr.getRange() << Attr.getName() << ExpectedVariable; 4540 } 4541 4542 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D, 4543 const AttributeList &Attr) { 4544 ValueDecl *vd = cast<ValueDecl>(D); 4545 QualType type = vd->getType(); 4546 4547 if (!type->isDependentType() && 4548 !type->isObjCLifetimeType()) { 4549 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type) 4550 << type; 4551 return; 4552 } 4553 4554 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4555 4556 // If we have no lifetime yet, check the lifetime we're presumably 4557 // going to infer. 4558 if (lifetime == Qualifiers::OCL_None && !type->isDependentType()) 4559 lifetime = type->getObjCARCImplicitLifetime(); 4560 4561 switch (lifetime) { 4562 case Qualifiers::OCL_None: 4563 assert(type->isDependentType() && 4564 "didn't infer lifetime for non-dependent type?"); 4565 break; 4566 4567 case Qualifiers::OCL_Weak: // meaningful 4568 case Qualifiers::OCL_Strong: // meaningful 4569 break; 4570 4571 case Qualifiers::OCL_ExplicitNone: 4572 case Qualifiers::OCL_Autoreleasing: 4573 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless) 4574 << (lifetime == Qualifiers::OCL_Autoreleasing); 4575 break; 4576 } 4577 4578 D->addAttr(::new (S.Context) 4579 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context, 4580 Attr.getAttributeSpellingListIndex())); 4581 } 4582 4583 //===----------------------------------------------------------------------===// 4584 // Microsoft specific attribute handlers. 4585 //===----------------------------------------------------------------------===// 4586 4587 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4588 if (!S.LangOpts.CPlusPlus) { 4589 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang) 4590 << Attr.getName() << AttributeLangSupport::C; 4591 return; 4592 } 4593 4594 if (!isa<CXXRecordDecl>(D)) { 4595 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 4596 << Attr.getName() << ExpectedClass; 4597 return; 4598 } 4599 4600 StringRef StrRef; 4601 SourceLocation LiteralLoc; 4602 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc)) 4603 return; 4604 4605 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or 4606 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former. 4607 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}') 4608 StrRef = StrRef.drop_front().drop_back(); 4609 4610 // Validate GUID length. 4611 if (StrRef.size() != 36) { 4612 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 4613 return; 4614 } 4615 4616 for (unsigned i = 0; i < 36; ++i) { 4617 if (i == 8 || i == 13 || i == 18 || i == 23) { 4618 if (StrRef[i] != '-') { 4619 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 4620 return; 4621 } 4622 } else if (!isHexDigit(StrRef[i])) { 4623 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 4624 return; 4625 } 4626 } 4627 4628 D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context, StrRef, 4629 Attr.getAttributeSpellingListIndex())); 4630 } 4631 4632 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4633 if (!S.LangOpts.CPlusPlus) { 4634 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang) 4635 << Attr.getName() << AttributeLangSupport::C; 4636 return; 4637 } 4638 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr( 4639 D, Attr.getRange(), /*BestCase=*/true, 4640 Attr.getAttributeSpellingListIndex(), 4641 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling()); 4642 if (IA) { 4643 D->addAttr(IA); 4644 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 4645 } 4646 } 4647 4648 static void handleDeclspecThreadAttr(Sema &S, Decl *D, 4649 const AttributeList &Attr) { 4650 VarDecl *VD = cast<VarDecl>(D); 4651 if (!S.Context.getTargetInfo().isTLSSupported()) { 4652 S.Diag(Attr.getLoc(), diag::err_thread_unsupported); 4653 return; 4654 } 4655 if (VD->getTSCSpec() != TSCS_unspecified) { 4656 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable); 4657 return; 4658 } 4659 if (VD->hasLocalStorage()) { 4660 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)"; 4661 return; 4662 } 4663 VD->addAttr(::new (S.Context) ThreadAttr( 4664 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 4665 } 4666 4667 static void handleAbiTagAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4668 SmallVector<StringRef, 4> Tags; 4669 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) { 4670 StringRef Tag; 4671 if (!S.checkStringLiteralArgumentAttr(Attr, I, Tag)) 4672 return; 4673 Tags.push_back(Tag); 4674 } 4675 4676 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) { 4677 if (!NS->isInline()) { 4678 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 0; 4679 return; 4680 } 4681 if (NS->isAnonymousNamespace()) { 4682 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 1; 4683 return; 4684 } 4685 if (Attr.getNumArgs() == 0) 4686 Tags.push_back(NS->getName()); 4687 } else if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 4688 return; 4689 4690 // Store tags sorted and without duplicates. 4691 std::sort(Tags.begin(), Tags.end()); 4692 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end()); 4693 4694 D->addAttr(::new (S.Context) 4695 AbiTagAttr(Attr.getRange(), S.Context, Tags.data(), Tags.size(), 4696 Attr.getAttributeSpellingListIndex())); 4697 4698 // FIXME: remove this warning as soon as mangled part is ready. 4699 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored) 4700 << Attr.getName(); 4701 } 4702 4703 static void handleARMInterruptAttr(Sema &S, Decl *D, 4704 const AttributeList &Attr) { 4705 // Check the attribute arguments. 4706 if (Attr.getNumArgs() > 1) { 4707 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) 4708 << Attr.getName() << 1; 4709 return; 4710 } 4711 4712 StringRef Str; 4713 SourceLocation ArgLoc; 4714 4715 if (Attr.getNumArgs() == 0) 4716 Str = ""; 4717 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc)) 4718 return; 4719 4720 ARMInterruptAttr::InterruptType Kind; 4721 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { 4722 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 4723 << Attr.getName() << Str << ArgLoc; 4724 return; 4725 } 4726 4727 unsigned Index = Attr.getAttributeSpellingListIndex(); 4728 D->addAttr(::new (S.Context) 4729 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index)); 4730 } 4731 4732 static void handleMSP430InterruptAttr(Sema &S, Decl *D, 4733 const AttributeList &Attr) { 4734 if (!checkAttributeNumArgs(S, Attr, 1)) 4735 return; 4736 4737 if (!Attr.isArgExpr(0)) { 4738 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName() 4739 << AANT_ArgumentIntegerConstant; 4740 return; 4741 } 4742 4743 // FIXME: Check for decl - it should be void ()(void). 4744 4745 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 4746 llvm::APSInt NumParams(32); 4747 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) { 4748 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 4749 << Attr.getName() << AANT_ArgumentIntegerConstant 4750 << NumParamsExpr->getSourceRange(); 4751 return; 4752 } 4753 4754 unsigned Num = NumParams.getLimitedValue(255); 4755 if ((Num & 1) || Num > 30) { 4756 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 4757 << Attr.getName() << (int)NumParams.getSExtValue() 4758 << NumParamsExpr->getSourceRange(); 4759 return; 4760 } 4761 4762 D->addAttr(::new (S.Context) 4763 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num, 4764 Attr.getAttributeSpellingListIndex())); 4765 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 4766 } 4767 4768 static void handleMipsInterruptAttr(Sema &S, Decl *D, 4769 const AttributeList &Attr) { 4770 // Only one optional argument permitted. 4771 if (Attr.getNumArgs() > 1) { 4772 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) 4773 << Attr.getName() << 1; 4774 return; 4775 } 4776 4777 StringRef Str; 4778 SourceLocation ArgLoc; 4779 4780 if (Attr.getNumArgs() == 0) 4781 Str = ""; 4782 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc)) 4783 return; 4784 4785 // Semantic checks for a function with the 'interrupt' attribute for MIPS: 4786 // a) Must be a function. 4787 // b) Must have no parameters. 4788 // c) Must have the 'void' return type. 4789 // d) Cannot have the 'mips16' attribute, as that instruction set 4790 // lacks the 'eret' instruction. 4791 // e) The attribute itself must either have no argument or one of the 4792 // valid interrupt types, see [MipsInterruptDocs]. 4793 4794 if (!isFunctionOrMethod(D)) { 4795 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 4796 << "'interrupt'" << ExpectedFunctionOrMethod; 4797 return; 4798 } 4799 4800 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) { 4801 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute) 4802 << 0; 4803 return; 4804 } 4805 4806 if (!getFunctionOrMethodResultType(D)->isVoidType()) { 4807 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute) 4808 << 1; 4809 return; 4810 } 4811 4812 if (checkAttrMutualExclusion<Mips16Attr>(S, D, Attr.getRange(), 4813 Attr.getName())) 4814 return; 4815 4816 MipsInterruptAttr::InterruptType Kind; 4817 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { 4818 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 4819 << Attr.getName() << "'" + std::string(Str) + "'"; 4820 return; 4821 } 4822 4823 D->addAttr(::new (S.Context) MipsInterruptAttr( 4824 Attr.getLoc(), S.Context, Kind, Attr.getAttributeSpellingListIndex())); 4825 } 4826 4827 static void handleAnyX86InterruptAttr(Sema &S, Decl *D, 4828 const AttributeList &Attr) { 4829 // Semantic checks for a function with the 'interrupt' attribute. 4830 // a) Must be a function. 4831 // b) Must have the 'void' return type. 4832 // c) Must take 1 or 2 arguments. 4833 // d) The 1st argument must be a pointer. 4834 // e) The 2nd argument (if any) must be an unsigned integer. 4835 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) || 4836 CXXMethodDecl::isStaticOverloadedOperator( 4837 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) { 4838 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 4839 << Attr.getName() << ExpectedFunctionWithProtoType; 4840 return; 4841 } 4842 // Interrupt handler must have void return type. 4843 if (!getFunctionOrMethodResultType(D)->isVoidType()) { 4844 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(), 4845 diag::err_anyx86_interrupt_attribute) 4846 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 4847 ? 0 4848 : 1) 4849 << 0; 4850 return; 4851 } 4852 // Interrupt handler must have 1 or 2 parameters. 4853 unsigned NumParams = getFunctionOrMethodNumParams(D); 4854 if (NumParams < 1 || NumParams > 2) { 4855 S.Diag(D->getLocStart(), diag::err_anyx86_interrupt_attribute) 4856 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 4857 ? 0 4858 : 1) 4859 << 1; 4860 return; 4861 } 4862 // The first argument must be a pointer. 4863 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) { 4864 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(), 4865 diag::err_anyx86_interrupt_attribute) 4866 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 4867 ? 0 4868 : 1) 4869 << 2; 4870 return; 4871 } 4872 // The second argument, if present, must be an unsigned integer. 4873 unsigned TypeSize = 4874 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64 4875 ? 64 4876 : 32; 4877 if (NumParams == 2 && 4878 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() || 4879 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) { 4880 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(), 4881 diag::err_anyx86_interrupt_attribute) 4882 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 4883 ? 0 4884 : 1) 4885 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false); 4886 return; 4887 } 4888 D->addAttr(::new (S.Context) AnyX86InterruptAttr( 4889 Attr.getLoc(), S.Context, Attr.getAttributeSpellingListIndex())); 4890 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 4891 } 4892 4893 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4894 // Dispatch the interrupt attribute based on the current target. 4895 switch (S.Context.getTargetInfo().getTriple().getArch()) { 4896 case llvm::Triple::msp430: 4897 handleMSP430InterruptAttr(S, D, Attr); 4898 break; 4899 case llvm::Triple::mipsel: 4900 case llvm::Triple::mips: 4901 handleMipsInterruptAttr(S, D, Attr); 4902 break; 4903 case llvm::Triple::x86: 4904 case llvm::Triple::x86_64: 4905 handleAnyX86InterruptAttr(S, D, Attr); 4906 break; 4907 default: 4908 handleARMInterruptAttr(S, D, Attr); 4909 break; 4910 } 4911 } 4912 4913 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, 4914 const AttributeList &Attr) { 4915 uint32_t NumRegs; 4916 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 4917 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs)) 4918 return; 4919 4920 D->addAttr(::new (S.Context) 4921 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context, 4922 NumRegs, 4923 Attr.getAttributeSpellingListIndex())); 4924 } 4925 4926 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, 4927 const AttributeList &Attr) { 4928 uint32_t NumRegs; 4929 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 4930 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs)) 4931 return; 4932 4933 D->addAttr(::new (S.Context) 4934 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context, 4935 NumRegs, 4936 Attr.getAttributeSpellingListIndex())); 4937 } 4938 4939 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D, 4940 const AttributeList& Attr) { 4941 // If we try to apply it to a function pointer, don't warn, but don't 4942 // do anything, either. It doesn't matter anyway, because there's nothing 4943 // special about calling a force_align_arg_pointer function. 4944 ValueDecl *VD = dyn_cast<ValueDecl>(D); 4945 if (VD && VD->getType()->isFunctionPointerType()) 4946 return; 4947 // Also don't warn on function pointer typedefs. 4948 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D); 4949 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() || 4950 TD->getUnderlyingType()->isFunctionType())) 4951 return; 4952 // Attribute can only be applied to function types. 4953 if (!isa<FunctionDecl>(D)) { 4954 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 4955 << Attr.getName() << /* function */0; 4956 return; 4957 } 4958 4959 D->addAttr(::new (S.Context) 4960 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context, 4961 Attr.getAttributeSpellingListIndex())); 4962 } 4963 4964 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range, 4965 unsigned AttrSpellingListIndex) { 4966 if (D->hasAttr<DLLExportAttr>()) { 4967 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'"; 4968 return nullptr; 4969 } 4970 4971 if (D->hasAttr<DLLImportAttr>()) 4972 return nullptr; 4973 4974 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex); 4975 } 4976 4977 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range, 4978 unsigned AttrSpellingListIndex) { 4979 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) { 4980 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import; 4981 D->dropAttr<DLLImportAttr>(); 4982 } 4983 4984 if (D->hasAttr<DLLExportAttr>()) 4985 return nullptr; 4986 4987 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex); 4988 } 4989 4990 static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) { 4991 if (isa<ClassTemplatePartialSpecializationDecl>(D) && 4992 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4993 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) 4994 << A.getName(); 4995 return; 4996 } 4997 4998 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 4999 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport && 5000 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5001 // MinGW doesn't allow dllimport on inline functions. 5002 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline) 5003 << A.getName(); 5004 return; 5005 } 5006 } 5007 5008 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 5009 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && 5010 MD->getParent()->isLambda()) { 5011 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName(); 5012 return; 5013 } 5014 } 5015 5016 unsigned Index = A.getAttributeSpellingListIndex(); 5017 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport 5018 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index) 5019 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index); 5020 if (NewAttr) 5021 D->addAttr(NewAttr); 5022 } 5023 5024 MSInheritanceAttr * 5025 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase, 5026 unsigned AttrSpellingListIndex, 5027 MSInheritanceAttr::Spelling SemanticSpelling) { 5028 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) { 5029 if (IA->getSemanticSpelling() == SemanticSpelling) 5030 return nullptr; 5031 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance) 5032 << 1 /*previous declaration*/; 5033 Diag(Range.getBegin(), diag::note_previous_ms_inheritance); 5034 D->dropAttr<MSInheritanceAttr>(); 5035 } 5036 5037 CXXRecordDecl *RD = cast<CXXRecordDecl>(D); 5038 if (RD->hasDefinition()) { 5039 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase, 5040 SemanticSpelling)) { 5041 return nullptr; 5042 } 5043 } else { 5044 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) { 5045 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance) 5046 << 1 /*partial specialization*/; 5047 return nullptr; 5048 } 5049 if (RD->getDescribedClassTemplate()) { 5050 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance) 5051 << 0 /*primary template*/; 5052 return nullptr; 5053 } 5054 } 5055 5056 return ::new (Context) 5057 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex); 5058 } 5059 5060 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) { 5061 // The capability attributes take a single string parameter for the name of 5062 // the capability they represent. The lockable attribute does not take any 5063 // parameters. However, semantically, both attributes represent the same 5064 // concept, and so they use the same semantic attribute. Eventually, the 5065 // lockable attribute will be removed. 5066 // 5067 // For backward compatibility, any capability which has no specified string 5068 // literal will be considered a "mutex." 5069 StringRef N("mutex"); 5070 SourceLocation LiteralLoc; 5071 if (Attr.getKind() == AttributeList::AT_Capability && 5072 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc)) 5073 return; 5074 5075 // Currently, there are only two names allowed for a capability: role and 5076 // mutex (case insensitive). Diagnose other capability names. 5077 if (!N.equals_lower("mutex") && !N.equals_lower("role")) 5078 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N; 5079 5080 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N, 5081 Attr.getAttributeSpellingListIndex())); 5082 } 5083 5084 static void handleAssertCapabilityAttr(Sema &S, Decl *D, 5085 const AttributeList &Attr) { 5086 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context, 5087 Attr.getArgAsExpr(0), 5088 Attr.getAttributeSpellingListIndex())); 5089 } 5090 5091 static void handleAcquireCapabilityAttr(Sema &S, Decl *D, 5092 const AttributeList &Attr) { 5093 SmallVector<Expr*, 1> Args; 5094 if (!checkLockFunAttrCommon(S, D, Attr, Args)) 5095 return; 5096 5097 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(), 5098 S.Context, 5099 Args.data(), Args.size(), 5100 Attr.getAttributeSpellingListIndex())); 5101 } 5102 5103 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D, 5104 const AttributeList &Attr) { 5105 SmallVector<Expr*, 2> Args; 5106 if (!checkTryLockFunAttrCommon(S, D, Attr, Args)) 5107 return; 5108 5109 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(), 5110 S.Context, 5111 Attr.getArgAsExpr(0), 5112 Args.data(), 5113 Args.size(), 5114 Attr.getAttributeSpellingListIndex())); 5115 } 5116 5117 static void handleReleaseCapabilityAttr(Sema &S, Decl *D, 5118 const AttributeList &Attr) { 5119 // Check that all arguments are lockable objects. 5120 SmallVector<Expr *, 1> Args; 5121 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true); 5122 5123 D->addAttr(::new (S.Context) ReleaseCapabilityAttr( 5124 Attr.getRange(), S.Context, Args.data(), Args.size(), 5125 Attr.getAttributeSpellingListIndex())); 5126 } 5127 5128 static void handleRequiresCapabilityAttr(Sema &S, Decl *D, 5129 const AttributeList &Attr) { 5130 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 5131 return; 5132 5133 // check that all arguments are lockable objects 5134 SmallVector<Expr*, 1> Args; 5135 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 5136 if (Args.empty()) 5137 return; 5138 5139 RequiresCapabilityAttr *RCA = ::new (S.Context) 5140 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(), 5141 Args.size(), Attr.getAttributeSpellingListIndex()); 5142 5143 D->addAttr(RCA); 5144 } 5145 5146 static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 5147 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) { 5148 if (NSD->isAnonymousNamespace()) { 5149 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace); 5150 // Do not want to attach the attribute to the namespace because that will 5151 // cause confusing diagnostic reports for uses of declarations within the 5152 // namespace. 5153 return; 5154 } 5155 } 5156 5157 // Handle the cases where the attribute has a text message. 5158 StringRef Str, Replacement; 5159 if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0) && 5160 !S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 5161 return; 5162 5163 // Only support a single optional message for Declspec and CXX11. 5164 if (Attr.isDeclspecAttribute() || Attr.isCXX11Attribute()) 5165 checkAttributeAtMostNumArgs(S, Attr, 1); 5166 else if (Attr.isArgExpr(1) && Attr.getArgAsExpr(1) && 5167 !S.checkStringLiteralArgumentAttr(Attr, 1, Replacement)) 5168 return; 5169 5170 if (!S.getLangOpts().CPlusPlus14) 5171 if (Attr.isCXX11Attribute() && 5172 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu"))) 5173 S.Diag(Attr.getLoc(), diag::ext_cxx14_attr) << Attr.getName(); 5174 5175 D->addAttr(::new (S.Context) DeprecatedAttr(Attr.getRange(), S.Context, Str, 5176 Replacement, 5177 Attr.getAttributeSpellingListIndex())); 5178 } 5179 5180 static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) { 5181 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 5182 return; 5183 5184 std::vector<StringRef> Sanitizers; 5185 5186 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) { 5187 StringRef SanitizerName; 5188 SourceLocation LiteralLoc; 5189 5190 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc)) 5191 return; 5192 5193 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0) 5194 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName; 5195 5196 Sanitizers.push_back(SanitizerName); 5197 } 5198 5199 D->addAttr(::new (S.Context) NoSanitizeAttr( 5200 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(), 5201 Attr.getAttributeSpellingListIndex())); 5202 } 5203 5204 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D, 5205 const AttributeList &Attr) { 5206 StringRef AttrName = Attr.getName()->getName(); 5207 normalizeName(AttrName); 5208 StringRef SanitizerName = 5209 llvm::StringSwitch<StringRef>(AttrName) 5210 .Case("no_address_safety_analysis", "address") 5211 .Case("no_sanitize_address", "address") 5212 .Case("no_sanitize_thread", "thread") 5213 .Case("no_sanitize_memory", "memory"); 5214 D->addAttr(::new (S.Context) 5215 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1, 5216 Attr.getAttributeSpellingListIndex())); 5217 } 5218 5219 static void handleInternalLinkageAttr(Sema &S, Decl *D, 5220 const AttributeList &Attr) { 5221 if (InternalLinkageAttr *Internal = 5222 S.mergeInternalLinkageAttr(D, Attr.getRange(), Attr.getName(), 5223 Attr.getAttributeSpellingListIndex())) 5224 D->addAttr(Internal); 5225 } 5226 5227 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const AttributeList &Attr) { 5228 if (S.LangOpts.OpenCLVersion != 200) 5229 S.Diag(Attr.getLoc(), diag::err_attribute_requires_opencl_version) 5230 << Attr.getName() << "2.0" << 0; 5231 else 5232 S.Diag(Attr.getLoc(), diag::warn_opencl_attr_deprecated_ignored) 5233 << Attr.getName() << "2.0"; 5234 } 5235 5236 /// Handles semantic checking for features that are common to all attributes, 5237 /// such as checking whether a parameter was properly specified, or the correct 5238 /// number of arguments were passed, etc. 5239 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D, 5240 const AttributeList &Attr) { 5241 // Several attributes carry different semantics than the parsing requires, so 5242 // those are opted out of the common handling. 5243 // 5244 // We also bail on unknown and ignored attributes because those are handled 5245 // as part of the target-specific handling logic. 5246 if (Attr.hasCustomParsing() || 5247 Attr.getKind() == AttributeList::UnknownAttribute) 5248 return false; 5249 5250 // Check whether the attribute requires specific language extensions to be 5251 // enabled. 5252 if (!Attr.diagnoseLangOpts(S)) 5253 return true; 5254 5255 if (Attr.getMinArgs() == Attr.getMaxArgs()) { 5256 // If there are no optional arguments, then checking for the argument count 5257 // is trivial. 5258 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs())) 5259 return true; 5260 } else { 5261 // There are optional arguments, so checking is slightly more involved. 5262 if (Attr.getMinArgs() && 5263 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs())) 5264 return true; 5265 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() && 5266 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs())) 5267 return true; 5268 } 5269 5270 // Check whether the attribute appertains to the given subject. 5271 if (!Attr.diagnoseAppertainsTo(S, D)) 5272 return true; 5273 5274 return false; 5275 } 5276 5277 static void handleOpenCLAccessAttr(Sema &S, Decl *D, 5278 const AttributeList &Attr) { 5279 if (D->isInvalidDecl()) 5280 return; 5281 5282 // Check if there is only one access qualifier. 5283 if (D->hasAttr<OpenCLAccessAttr>()) { 5284 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers) 5285 << D->getSourceRange(); 5286 D->setInvalidDecl(true); 5287 return; 5288 } 5289 5290 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an 5291 // image object can be read and written. 5292 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe 5293 // object. Using the read_write (or __read_write) qualifier with the pipe 5294 // qualifier is a compilation error. 5295 if (const ParmVarDecl *PDecl = dyn_cast<ParmVarDecl>(D)) { 5296 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr(); 5297 if (Attr.getName()->getName().find("read_write") != StringRef::npos) { 5298 if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) { 5299 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_read_write) 5300 << Attr.getName() << PDecl->getType() << DeclTy->isImageType(); 5301 D->setInvalidDecl(true); 5302 return; 5303 } 5304 } 5305 } 5306 5307 D->addAttr(::new (S.Context) OpenCLAccessAttr( 5308 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 5309 } 5310 5311 //===----------------------------------------------------------------------===// 5312 // Top Level Sema Entry Points 5313 //===----------------------------------------------------------------------===// 5314 5315 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if 5316 /// the attribute applies to decls. If the attribute is a type attribute, just 5317 /// silently ignore it if a GNU attribute. 5318 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, 5319 const AttributeList &Attr, 5320 bool IncludeCXX11Attributes) { 5321 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute) 5322 return; 5323 5324 // Ignore C++11 attributes on declarator chunks: they appertain to the type 5325 // instead. 5326 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes) 5327 return; 5328 5329 // Unknown attributes are automatically warned on. Target-specific attributes 5330 // which do not apply to the current target architecture are treated as 5331 // though they were unknown attributes. 5332 if (Attr.getKind() == AttributeList::UnknownAttribute || 5333 !Attr.existsInTarget(S.Context.getTargetInfo())) { 5334 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute() 5335 ? diag::warn_unhandled_ms_attribute_ignored 5336 : diag::warn_unknown_attribute_ignored) 5337 << Attr.getName(); 5338 return; 5339 } 5340 5341 if (handleCommonAttributeFeatures(S, scope, D, Attr)) 5342 return; 5343 5344 switch (Attr.getKind()) { 5345 default: 5346 if (!Attr.isStmtAttr()) { 5347 // Type attributes are handled elsewhere; silently move on. 5348 assert(Attr.isTypeAttr() && "Non-type attribute not handled"); 5349 break; 5350 } 5351 S.Diag(Attr.getLoc(), diag::err_stmt_attribute_invalid_on_decl) 5352 << Attr.getName() << D->getLocation(); 5353 break; 5354 case AttributeList::AT_Interrupt: 5355 handleInterruptAttr(S, D, Attr); 5356 break; 5357 case AttributeList::AT_X86ForceAlignArgPointer: 5358 handleX86ForceAlignArgPointerAttr(S, D, Attr); 5359 break; 5360 case AttributeList::AT_DLLExport: 5361 case AttributeList::AT_DLLImport: 5362 handleDLLAttr(S, D, Attr); 5363 break; 5364 case AttributeList::AT_Mips16: 5365 handleSimpleAttributeWithExclusions<Mips16Attr, MipsInterruptAttr>(S, D, 5366 Attr); 5367 break; 5368 case AttributeList::AT_NoMips16: 5369 handleSimpleAttribute<NoMips16Attr>(S, D, Attr); 5370 break; 5371 case AttributeList::AT_AMDGPUNumVGPR: 5372 handleAMDGPUNumVGPRAttr(S, D, Attr); 5373 break; 5374 case AttributeList::AT_AMDGPUNumSGPR: 5375 handleAMDGPUNumSGPRAttr(S, D, Attr); 5376 break; 5377 case AttributeList::AT_IBAction: 5378 handleSimpleAttribute<IBActionAttr>(S, D, Attr); 5379 break; 5380 case AttributeList::AT_IBOutlet: 5381 handleIBOutlet(S, D, Attr); 5382 break; 5383 case AttributeList::AT_IBOutletCollection: 5384 handleIBOutletCollection(S, D, Attr); 5385 break; 5386 case AttributeList::AT_IFunc: 5387 handleIFuncAttr(S, D, Attr); 5388 break; 5389 case AttributeList::AT_Alias: 5390 handleAliasAttr(S, D, Attr); 5391 break; 5392 case AttributeList::AT_Aligned: 5393 handleAlignedAttr(S, D, Attr); 5394 break; 5395 case AttributeList::AT_AlignValue: 5396 handleAlignValueAttr(S, D, Attr); 5397 break; 5398 case AttributeList::AT_AlwaysInline: 5399 handleAlwaysInlineAttr(S, D, Attr); 5400 break; 5401 case AttributeList::AT_AnalyzerNoReturn: 5402 handleAnalyzerNoReturnAttr(S, D, Attr); 5403 break; 5404 case AttributeList::AT_TLSModel: 5405 handleTLSModelAttr(S, D, Attr); 5406 break; 5407 case AttributeList::AT_Annotate: 5408 handleAnnotateAttr(S, D, Attr); 5409 break; 5410 case AttributeList::AT_Availability: 5411 handleAvailabilityAttr(S, D, Attr); 5412 break; 5413 case AttributeList::AT_CarriesDependency: 5414 handleDependencyAttr(S, scope, D, Attr); 5415 break; 5416 case AttributeList::AT_Common: 5417 handleCommonAttr(S, D, Attr); 5418 break; 5419 case AttributeList::AT_CUDAConstant: 5420 handleSimpleAttributeWithExclusions<CUDAConstantAttr, CUDASharedAttr>(S, D, 5421 Attr); 5422 break; 5423 case AttributeList::AT_PassObjectSize: 5424 handlePassObjectSizeAttr(S, D, Attr); 5425 break; 5426 case AttributeList::AT_Constructor: 5427 handleConstructorAttr(S, D, Attr); 5428 break; 5429 case AttributeList::AT_CXX11NoReturn: 5430 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr); 5431 break; 5432 case AttributeList::AT_Deprecated: 5433 handleDeprecatedAttr(S, D, Attr); 5434 break; 5435 case AttributeList::AT_Destructor: 5436 handleDestructorAttr(S, D, Attr); 5437 break; 5438 case AttributeList::AT_EnableIf: 5439 handleEnableIfAttr(S, D, Attr); 5440 break; 5441 case AttributeList::AT_ExtVectorType: 5442 handleExtVectorTypeAttr(S, scope, D, Attr); 5443 break; 5444 case AttributeList::AT_MinSize: 5445 handleMinSizeAttr(S, D, Attr); 5446 break; 5447 case AttributeList::AT_OptimizeNone: 5448 handleOptimizeNoneAttr(S, D, Attr); 5449 break; 5450 case AttributeList::AT_FlagEnum: 5451 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr); 5452 break; 5453 case AttributeList::AT_Flatten: 5454 handleSimpleAttribute<FlattenAttr>(S, D, Attr); 5455 break; 5456 case AttributeList::AT_Format: 5457 handleFormatAttr(S, D, Attr); 5458 break; 5459 case AttributeList::AT_FormatArg: 5460 handleFormatArgAttr(S, D, Attr); 5461 break; 5462 case AttributeList::AT_CUDAGlobal: 5463 handleGlobalAttr(S, D, Attr); 5464 break; 5465 case AttributeList::AT_CUDADevice: 5466 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D, 5467 Attr); 5468 break; 5469 case AttributeList::AT_CUDAHost: 5470 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D, 5471 Attr); 5472 break; 5473 case AttributeList::AT_GNUInline: 5474 handleGNUInlineAttr(S, D, Attr); 5475 break; 5476 case AttributeList::AT_CUDALaunchBounds: 5477 handleLaunchBoundsAttr(S, D, Attr); 5478 break; 5479 case AttributeList::AT_Restrict: 5480 handleRestrictAttr(S, D, Attr); 5481 break; 5482 case AttributeList::AT_MayAlias: 5483 handleSimpleAttribute<MayAliasAttr>(S, D, Attr); 5484 break; 5485 case AttributeList::AT_Mode: 5486 handleModeAttr(S, D, Attr); 5487 break; 5488 case AttributeList::AT_NoAlias: 5489 handleSimpleAttribute<NoAliasAttr>(S, D, Attr); 5490 break; 5491 case AttributeList::AT_NoCommon: 5492 handleSimpleAttribute<NoCommonAttr>(S, D, Attr); 5493 break; 5494 case AttributeList::AT_NoSplitStack: 5495 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr); 5496 break; 5497 case AttributeList::AT_NonNull: 5498 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D)) 5499 handleNonNullAttrParameter(S, PVD, Attr); 5500 else 5501 handleNonNullAttr(S, D, Attr); 5502 break; 5503 case AttributeList::AT_ReturnsNonNull: 5504 handleReturnsNonNullAttr(S, D, Attr); 5505 break; 5506 case AttributeList::AT_AssumeAligned: 5507 handleAssumeAlignedAttr(S, D, Attr); 5508 break; 5509 case AttributeList::AT_Overloadable: 5510 handleSimpleAttribute<OverloadableAttr>(S, D, Attr); 5511 break; 5512 case AttributeList::AT_Ownership: 5513 handleOwnershipAttr(S, D, Attr); 5514 break; 5515 case AttributeList::AT_Cold: 5516 handleColdAttr(S, D, Attr); 5517 break; 5518 case AttributeList::AT_Hot: 5519 handleHotAttr(S, D, Attr); 5520 break; 5521 case AttributeList::AT_Naked: 5522 handleNakedAttr(S, D, Attr); 5523 break; 5524 case AttributeList::AT_NoReturn: 5525 handleNoReturnAttr(S, D, Attr); 5526 break; 5527 case AttributeList::AT_NoThrow: 5528 handleSimpleAttribute<NoThrowAttr>(S, D, Attr); 5529 break; 5530 case AttributeList::AT_CUDAShared: 5531 handleSimpleAttributeWithExclusions<CUDASharedAttr, CUDAConstantAttr>(S, D, 5532 Attr); 5533 break; 5534 case AttributeList::AT_VecReturn: 5535 handleVecReturnAttr(S, D, Attr); 5536 break; 5537 case AttributeList::AT_ObjCOwnership: 5538 handleObjCOwnershipAttr(S, D, Attr); 5539 break; 5540 case AttributeList::AT_ObjCPreciseLifetime: 5541 handleObjCPreciseLifetimeAttr(S, D, Attr); 5542 break; 5543 case AttributeList::AT_ObjCReturnsInnerPointer: 5544 handleObjCReturnsInnerPointerAttr(S, D, Attr); 5545 break; 5546 case AttributeList::AT_ObjCRequiresSuper: 5547 handleObjCRequiresSuperAttr(S, D, Attr); 5548 break; 5549 case AttributeList::AT_ObjCBridge: 5550 handleObjCBridgeAttr(S, scope, D, Attr); 5551 break; 5552 case AttributeList::AT_ObjCBridgeMutable: 5553 handleObjCBridgeMutableAttr(S, scope, D, Attr); 5554 break; 5555 case AttributeList::AT_ObjCBridgeRelated: 5556 handleObjCBridgeRelatedAttr(S, scope, D, Attr); 5557 break; 5558 case AttributeList::AT_ObjCDesignatedInitializer: 5559 handleObjCDesignatedInitializer(S, D, Attr); 5560 break; 5561 case AttributeList::AT_ObjCRuntimeName: 5562 handleObjCRuntimeName(S, D, Attr); 5563 break; 5564 case AttributeList::AT_ObjCRuntimeVisible: 5565 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, Attr); 5566 break; 5567 case AttributeList::AT_ObjCBoxable: 5568 handleObjCBoxable(S, D, Attr); 5569 break; 5570 case AttributeList::AT_CFAuditedTransfer: 5571 handleCFAuditedTransferAttr(S, D, Attr); 5572 break; 5573 case AttributeList::AT_CFUnknownTransfer: 5574 handleCFUnknownTransferAttr(S, D, Attr); 5575 break; 5576 case AttributeList::AT_CFConsumed: 5577 case AttributeList::AT_NSConsumed: 5578 handleNSConsumedAttr(S, D, Attr); 5579 break; 5580 case AttributeList::AT_NSConsumesSelf: 5581 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr); 5582 break; 5583 case AttributeList::AT_NSReturnsAutoreleased: 5584 case AttributeList::AT_NSReturnsNotRetained: 5585 case AttributeList::AT_CFReturnsNotRetained: 5586 case AttributeList::AT_NSReturnsRetained: 5587 case AttributeList::AT_CFReturnsRetained: 5588 handleNSReturnsRetainedAttr(S, D, Attr); 5589 break; 5590 case AttributeList::AT_WorkGroupSizeHint: 5591 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr); 5592 break; 5593 case AttributeList::AT_ReqdWorkGroupSize: 5594 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr); 5595 break; 5596 case AttributeList::AT_VecTypeHint: 5597 handleVecTypeHint(S, D, Attr); 5598 break; 5599 case AttributeList::AT_InitPriority: 5600 handleInitPriorityAttr(S, D, Attr); 5601 break; 5602 case AttributeList::AT_Packed: 5603 handlePackedAttr(S, D, Attr); 5604 break; 5605 case AttributeList::AT_Section: 5606 handleSectionAttr(S, D, Attr); 5607 break; 5608 case AttributeList::AT_Target: 5609 handleTargetAttr(S, D, Attr); 5610 break; 5611 case AttributeList::AT_Unavailable: 5612 handleAttrWithMessage<UnavailableAttr>(S, D, Attr); 5613 break; 5614 case AttributeList::AT_ArcWeakrefUnavailable: 5615 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr); 5616 break; 5617 case AttributeList::AT_ObjCRootClass: 5618 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr); 5619 break; 5620 case AttributeList::AT_ObjCExplicitProtocolImpl: 5621 handleObjCSuppresProtocolAttr(S, D, Attr); 5622 break; 5623 case AttributeList::AT_ObjCRequiresPropertyDefs: 5624 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr); 5625 break; 5626 case AttributeList::AT_Unused: 5627 handleUnusedAttr(S, D, Attr); 5628 break; 5629 case AttributeList::AT_ReturnsTwice: 5630 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr); 5631 break; 5632 case AttributeList::AT_NotTailCalled: 5633 handleNotTailCalledAttr(S, D, Attr); 5634 break; 5635 case AttributeList::AT_DisableTailCalls: 5636 handleDisableTailCallsAttr(S, D, Attr); 5637 break; 5638 case AttributeList::AT_Used: 5639 handleUsedAttr(S, D, Attr); 5640 break; 5641 case AttributeList::AT_Visibility: 5642 handleVisibilityAttr(S, D, Attr, false); 5643 break; 5644 case AttributeList::AT_TypeVisibility: 5645 handleVisibilityAttr(S, D, Attr, true); 5646 break; 5647 case AttributeList::AT_WarnUnused: 5648 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr); 5649 break; 5650 case AttributeList::AT_WarnUnusedResult: 5651 handleWarnUnusedResult(S, D, Attr); 5652 break; 5653 case AttributeList::AT_Weak: 5654 handleSimpleAttribute<WeakAttr>(S, D, Attr); 5655 break; 5656 case AttributeList::AT_WeakRef: 5657 handleWeakRefAttr(S, D, Attr); 5658 break; 5659 case AttributeList::AT_WeakImport: 5660 handleWeakImportAttr(S, D, Attr); 5661 break; 5662 case AttributeList::AT_TransparentUnion: 5663 handleTransparentUnionAttr(S, D, Attr); 5664 break; 5665 case AttributeList::AT_ObjCException: 5666 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr); 5667 break; 5668 case AttributeList::AT_ObjCMethodFamily: 5669 handleObjCMethodFamilyAttr(S, D, Attr); 5670 break; 5671 case AttributeList::AT_ObjCNSObject: 5672 handleObjCNSObject(S, D, Attr); 5673 break; 5674 case AttributeList::AT_ObjCIndependentClass: 5675 handleObjCIndependentClass(S, D, Attr); 5676 break; 5677 case AttributeList::AT_Blocks: 5678 handleBlocksAttr(S, D, Attr); 5679 break; 5680 case AttributeList::AT_Sentinel: 5681 handleSentinelAttr(S, D, Attr); 5682 break; 5683 case AttributeList::AT_Const: 5684 handleSimpleAttribute<ConstAttr>(S, D, Attr); 5685 break; 5686 case AttributeList::AT_Pure: 5687 handleSimpleAttribute<PureAttr>(S, D, Attr); 5688 break; 5689 case AttributeList::AT_Cleanup: 5690 handleCleanupAttr(S, D, Attr); 5691 break; 5692 case AttributeList::AT_NoDebug: 5693 handleNoDebugAttr(S, D, Attr); 5694 break; 5695 case AttributeList::AT_NoDuplicate: 5696 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr); 5697 break; 5698 case AttributeList::AT_NoInline: 5699 handleSimpleAttribute<NoInlineAttr>(S, D, Attr); 5700 break; 5701 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg. 5702 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr); 5703 break; 5704 case AttributeList::AT_StdCall: 5705 case AttributeList::AT_CDecl: 5706 case AttributeList::AT_FastCall: 5707 case AttributeList::AT_ThisCall: 5708 case AttributeList::AT_Pascal: 5709 case AttributeList::AT_SwiftCall: 5710 case AttributeList::AT_VectorCall: 5711 case AttributeList::AT_MSABI: 5712 case AttributeList::AT_SysVABI: 5713 case AttributeList::AT_Pcs: 5714 case AttributeList::AT_IntelOclBicc: 5715 case AttributeList::AT_PreserveMost: 5716 case AttributeList::AT_PreserveAll: 5717 handleCallConvAttr(S, D, Attr); 5718 break; 5719 case AttributeList::AT_OpenCLKernel: 5720 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr); 5721 break; 5722 case AttributeList::AT_OpenCLAccess: 5723 handleOpenCLAccessAttr(S, D, Attr); 5724 break; 5725 case AttributeList::AT_OpenCLNoSVM: 5726 handleOpenCLNoSVMAttr(S, D, Attr); 5727 break; 5728 case AttributeList::AT_SwiftContext: 5729 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftContext); 5730 break; 5731 case AttributeList::AT_SwiftErrorResult: 5732 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftErrorResult); 5733 break; 5734 case AttributeList::AT_SwiftIndirectResult: 5735 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftIndirectResult); 5736 break; 5737 case AttributeList::AT_InternalLinkage: 5738 handleInternalLinkageAttr(S, D, Attr); 5739 break; 5740 case AttributeList::AT_LTOVisibilityPublic: 5741 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, Attr); 5742 break; 5743 5744 // Microsoft attributes: 5745 case AttributeList::AT_MSNoVTable: 5746 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr); 5747 break; 5748 case AttributeList::AT_MSStruct: 5749 handleSimpleAttribute<MSStructAttr>(S, D, Attr); 5750 break; 5751 case AttributeList::AT_Uuid: 5752 handleUuidAttr(S, D, Attr); 5753 break; 5754 case AttributeList::AT_MSInheritance: 5755 handleMSInheritanceAttr(S, D, Attr); 5756 break; 5757 case AttributeList::AT_SelectAny: 5758 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr); 5759 break; 5760 case AttributeList::AT_Thread: 5761 handleDeclspecThreadAttr(S, D, Attr); 5762 break; 5763 case AttributeList::AT_AbiTag: 5764 handleAbiTagAttr(S, D, Attr); 5765 break; 5766 5767 // Thread safety attributes: 5768 case AttributeList::AT_AssertExclusiveLock: 5769 handleAssertExclusiveLockAttr(S, D, Attr); 5770 break; 5771 case AttributeList::AT_AssertSharedLock: 5772 handleAssertSharedLockAttr(S, D, Attr); 5773 break; 5774 case AttributeList::AT_GuardedVar: 5775 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr); 5776 break; 5777 case AttributeList::AT_PtGuardedVar: 5778 handlePtGuardedVarAttr(S, D, Attr); 5779 break; 5780 case AttributeList::AT_ScopedLockable: 5781 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr); 5782 break; 5783 case AttributeList::AT_NoSanitize: 5784 handleNoSanitizeAttr(S, D, Attr); 5785 break; 5786 case AttributeList::AT_NoSanitizeSpecific: 5787 handleNoSanitizeSpecificAttr(S, D, Attr); 5788 break; 5789 case AttributeList::AT_NoThreadSafetyAnalysis: 5790 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr); 5791 break; 5792 case AttributeList::AT_GuardedBy: 5793 handleGuardedByAttr(S, D, Attr); 5794 break; 5795 case AttributeList::AT_PtGuardedBy: 5796 handlePtGuardedByAttr(S, D, Attr); 5797 break; 5798 case AttributeList::AT_ExclusiveTrylockFunction: 5799 handleExclusiveTrylockFunctionAttr(S, D, Attr); 5800 break; 5801 case AttributeList::AT_LockReturned: 5802 handleLockReturnedAttr(S, D, Attr); 5803 break; 5804 case AttributeList::AT_LocksExcluded: 5805 handleLocksExcludedAttr(S, D, Attr); 5806 break; 5807 case AttributeList::AT_SharedTrylockFunction: 5808 handleSharedTrylockFunctionAttr(S, D, Attr); 5809 break; 5810 case AttributeList::AT_AcquiredBefore: 5811 handleAcquiredBeforeAttr(S, D, Attr); 5812 break; 5813 case AttributeList::AT_AcquiredAfter: 5814 handleAcquiredAfterAttr(S, D, Attr); 5815 break; 5816 5817 // Capability analysis attributes. 5818 case AttributeList::AT_Capability: 5819 case AttributeList::AT_Lockable: 5820 handleCapabilityAttr(S, D, Attr); 5821 break; 5822 case AttributeList::AT_RequiresCapability: 5823 handleRequiresCapabilityAttr(S, D, Attr); 5824 break; 5825 5826 case AttributeList::AT_AssertCapability: 5827 handleAssertCapabilityAttr(S, D, Attr); 5828 break; 5829 case AttributeList::AT_AcquireCapability: 5830 handleAcquireCapabilityAttr(S, D, Attr); 5831 break; 5832 case AttributeList::AT_ReleaseCapability: 5833 handleReleaseCapabilityAttr(S, D, Attr); 5834 break; 5835 case AttributeList::AT_TryAcquireCapability: 5836 handleTryAcquireCapabilityAttr(S, D, Attr); 5837 break; 5838 5839 // Consumed analysis attributes. 5840 case AttributeList::AT_Consumable: 5841 handleConsumableAttr(S, D, Attr); 5842 break; 5843 case AttributeList::AT_ConsumableAutoCast: 5844 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr); 5845 break; 5846 case AttributeList::AT_ConsumableSetOnRead: 5847 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr); 5848 break; 5849 case AttributeList::AT_CallableWhen: 5850 handleCallableWhenAttr(S, D, Attr); 5851 break; 5852 case AttributeList::AT_ParamTypestate: 5853 handleParamTypestateAttr(S, D, Attr); 5854 break; 5855 case AttributeList::AT_ReturnTypestate: 5856 handleReturnTypestateAttr(S, D, Attr); 5857 break; 5858 case AttributeList::AT_SetTypestate: 5859 handleSetTypestateAttr(S, D, Attr); 5860 break; 5861 case AttributeList::AT_TestTypestate: 5862 handleTestTypestateAttr(S, D, Attr); 5863 break; 5864 5865 // Type safety attributes. 5866 case AttributeList::AT_ArgumentWithTypeTag: 5867 handleArgumentWithTypeTagAttr(S, D, Attr); 5868 break; 5869 case AttributeList::AT_TypeTagForDatatype: 5870 handleTypeTagForDatatypeAttr(S, D, Attr); 5871 break; 5872 } 5873 } 5874 5875 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified 5876 /// attribute list to the specified decl, ignoring any type attributes. 5877 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D, 5878 const AttributeList *AttrList, 5879 bool IncludeCXX11Attributes) { 5880 for (const AttributeList* l = AttrList; l; l = l->getNext()) 5881 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes); 5882 5883 // FIXME: We should be able to handle these cases in TableGen. 5884 // GCC accepts 5885 // static int a9 __attribute__((weakref)); 5886 // but that looks really pointless. We reject it. 5887 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) { 5888 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias) 5889 << cast<NamedDecl>(D); 5890 D->dropAttr<WeakRefAttr>(); 5891 return; 5892 } 5893 5894 // FIXME: We should be able to handle this in TableGen as well. It would be 5895 // good to have a way to specify "these attributes must appear as a group", 5896 // for these. Additionally, it would be good to have a way to specify "these 5897 // attribute must never appear as a group" for attributes like cold and hot. 5898 if (!D->hasAttr<OpenCLKernelAttr>()) { 5899 // These attributes cannot be applied to a non-kernel function. 5900 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) { 5901 // FIXME: This emits a different error message than 5902 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction. 5903 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 5904 D->setInvalidDecl(); 5905 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) { 5906 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 5907 D->setInvalidDecl(); 5908 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) { 5909 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 5910 D->setInvalidDecl(); 5911 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) { 5912 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 5913 << A << ExpectedKernelFunction; 5914 D->setInvalidDecl(); 5915 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) { 5916 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 5917 << A << ExpectedKernelFunction; 5918 D->setInvalidDecl(); 5919 } 5920 } 5921 } 5922 5923 // Annotation attributes are the only attributes allowed after an access 5924 // specifier. 5925 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, 5926 const AttributeList *AttrList) { 5927 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5928 if (l->getKind() == AttributeList::AT_Annotate) { 5929 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute()); 5930 } else { 5931 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec); 5932 return true; 5933 } 5934 } 5935 5936 return false; 5937 } 5938 5939 /// checkUnusedDeclAttributes - Check a list of attributes to see if it 5940 /// contains any decl attributes that we should warn about. 5941 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) { 5942 for ( ; A; A = A->getNext()) { 5943 // Only warn if the attribute is an unignored, non-type attribute. 5944 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue; 5945 if (A->getKind() == AttributeList::IgnoredAttribute) continue; 5946 5947 if (A->getKind() == AttributeList::UnknownAttribute) { 5948 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored) 5949 << A->getName() << A->getRange(); 5950 } else { 5951 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl) 5952 << A->getName() << A->getRange(); 5953 } 5954 } 5955 } 5956 5957 /// checkUnusedDeclAttributes - Given a declarator which is not being 5958 /// used to build a declaration, complain about any decl attributes 5959 /// which might be lying around on it. 5960 void Sema::checkUnusedDeclAttributes(Declarator &D) { 5961 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList()); 5962 ::checkUnusedDeclAttributes(*this, D.getAttributes()); 5963 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) 5964 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs()); 5965 } 5966 5967 /// DeclClonePragmaWeak - clone existing decl (maybe definition), 5968 /// \#pragma weak needs a non-definition decl and source may not have one. 5969 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 5970 SourceLocation Loc) { 5971 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND)); 5972 NamedDecl *NewD = nullptr; 5973 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 5974 FunctionDecl *NewFD; 5975 // FIXME: Missing call to CheckFunctionDeclaration(). 5976 // FIXME: Mangling? 5977 // FIXME: Is the qualifier info correct? 5978 // FIXME: Is the DeclContext correct? 5979 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(), 5980 Loc, Loc, DeclarationName(II), 5981 FD->getType(), FD->getTypeSourceInfo(), 5982 SC_None, false/*isInlineSpecified*/, 5983 FD->hasPrototype(), 5984 false/*isConstexprSpecified*/); 5985 NewD = NewFD; 5986 5987 if (FD->getQualifier()) 5988 NewFD->setQualifierInfo(FD->getQualifierLoc()); 5989 5990 // Fake up parameter variables; they are declared as if this were 5991 // a typedef. 5992 QualType FDTy = FD->getType(); 5993 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) { 5994 SmallVector<ParmVarDecl*, 16> Params; 5995 for (const auto &AI : FT->param_types()) { 5996 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI); 5997 Param->setScopeInfo(0, Params.size()); 5998 Params.push_back(Param); 5999 } 6000 NewFD->setParams(Params); 6001 } 6002 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) { 6003 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(), 6004 VD->getInnerLocStart(), VD->getLocation(), II, 6005 VD->getType(), VD->getTypeSourceInfo(), 6006 VD->getStorageClass()); 6007 if (VD->getQualifier()) { 6008 VarDecl *NewVD = cast<VarDecl>(NewD); 6009 NewVD->setQualifierInfo(VD->getQualifierLoc()); 6010 } 6011 } 6012 return NewD; 6013 } 6014 6015 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak 6016 /// applied to it, possibly with an alias. 6017 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) { 6018 if (W.getUsed()) return; // only do this once 6019 W.setUsed(true); 6020 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...)) 6021 IdentifierInfo *NDId = ND->getIdentifier(); 6022 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation()); 6023 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(), 6024 W.getLocation())); 6025 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation())); 6026 WeakTopLevelDecl.push_back(NewD); 6027 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin 6028 // to insert Decl at TU scope, sorry. 6029 DeclContext *SavedContext = CurContext; 6030 CurContext = Context.getTranslationUnitDecl(); 6031 NewD->setDeclContext(CurContext); 6032 NewD->setLexicalDeclContext(CurContext); 6033 PushOnScopeChains(NewD, S); 6034 CurContext = SavedContext; 6035 } else { // just add weak to existing 6036 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation())); 6037 } 6038 } 6039 6040 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) { 6041 // It's valid to "forward-declare" #pragma weak, in which case we 6042 // have to do this. 6043 LoadExternalWeakUndeclaredIdentifiers(); 6044 if (!WeakUndeclaredIdentifiers.empty()) { 6045 NamedDecl *ND = nullptr; 6046 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 6047 if (VD->isExternC()) 6048 ND = VD; 6049 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 6050 if (FD->isExternC()) 6051 ND = FD; 6052 if (ND) { 6053 if (IdentifierInfo *Id = ND->getIdentifier()) { 6054 auto I = WeakUndeclaredIdentifiers.find(Id); 6055 if (I != WeakUndeclaredIdentifiers.end()) { 6056 WeakInfo W = I->second; 6057 DeclApplyPragmaWeak(S, ND, W); 6058 WeakUndeclaredIdentifiers[Id] = W; 6059 } 6060 } 6061 } 6062 } 6063 } 6064 6065 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in 6066 /// it, apply them to D. This is a bit tricky because PD can have attributes 6067 /// specified in many different places, and we need to find and apply them all. 6068 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) { 6069 // Apply decl attributes from the DeclSpec if present. 6070 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList()) 6071 ProcessDeclAttributeList(S, D, Attrs); 6072 6073 // Walk the declarator structure, applying decl attributes that were in a type 6074 // position to the decl itself. This handles cases like: 6075 // int *__attr__(x)** D; 6076 // when X is a decl attribute. 6077 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i) 6078 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs()) 6079 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false); 6080 6081 // Finally, apply any attributes on the decl itself. 6082 if (const AttributeList *Attrs = PD.getAttributes()) 6083 ProcessDeclAttributeList(S, D, Attrs); 6084 } 6085 6086 /// Is the given declaration allowed to use a forbidden type? 6087 /// If so, it'll still be annotated with an attribute that makes it 6088 /// illegal to actually use. 6089 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl, 6090 const DelayedDiagnostic &diag, 6091 UnavailableAttr::ImplicitReason &reason) { 6092 // Private ivars are always okay. Unfortunately, people don't 6093 // always properly make their ivars private, even in system headers. 6094 // Plus we need to make fields okay, too. 6095 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) && 6096 !isa<FunctionDecl>(decl)) 6097 return false; 6098 6099 // Silently accept unsupported uses of __weak in both user and system 6100 // declarations when it's been disabled, for ease of integration with 6101 // -fno-objc-arc files. We do have to take some care against attempts 6102 // to define such things; for now, we've only done that for ivars 6103 // and properties. 6104 if ((isa<ObjCIvarDecl>(decl) || isa<ObjCPropertyDecl>(decl))) { 6105 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled || 6106 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) { 6107 reason = UnavailableAttr::IR_ForbiddenWeak; 6108 return true; 6109 } 6110 } 6111 6112 // Allow all sorts of things in system headers. 6113 if (S.Context.getSourceManager().isInSystemHeader(decl->getLocation())) { 6114 // Currently, all the failures dealt with this way are due to ARC 6115 // restrictions. 6116 reason = UnavailableAttr::IR_ARCForbiddenType; 6117 return true; 6118 } 6119 6120 return false; 6121 } 6122 6123 /// Handle a delayed forbidden-type diagnostic. 6124 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag, 6125 Decl *decl) { 6126 auto reason = UnavailableAttr::IR_None; 6127 if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) { 6128 assert(reason && "didn't set reason?"); 6129 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason, 6130 diag.Loc)); 6131 return; 6132 } 6133 if (S.getLangOpts().ObjCAutoRefCount) 6134 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) { 6135 // FIXME: we may want to suppress diagnostics for all 6136 // kind of forbidden type messages on unavailable functions. 6137 if (FD->hasAttr<UnavailableAttr>() && 6138 diag.getForbiddenTypeDiagnostic() == 6139 diag::err_arc_array_param_no_ownership) { 6140 diag.Triggered = true; 6141 return; 6142 } 6143 } 6144 6145 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic()) 6146 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument(); 6147 diag.Triggered = true; 6148 } 6149 6150 static bool isDeclDeprecated(Decl *D) { 6151 do { 6152 if (D->isDeprecated()) 6153 return true; 6154 // A category implicitly has the availability of the interface. 6155 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D)) 6156 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface()) 6157 return Interface->isDeprecated(); 6158 } while ((D = cast_or_null<Decl>(D->getDeclContext()))); 6159 return false; 6160 } 6161 6162 static bool isDeclUnavailable(Decl *D) { 6163 do { 6164 if (D->isUnavailable()) 6165 return true; 6166 // A category implicitly has the availability of the interface. 6167 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D)) 6168 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface()) 6169 return Interface->isUnavailable(); 6170 } while ((D = cast_or_null<Decl>(D->getDeclContext()))); 6171 return false; 6172 } 6173 6174 static void DoEmitAvailabilityWarning(Sema &S, Sema::AvailabilityDiagnostic K, 6175 Decl *Ctx, const NamedDecl *D, 6176 StringRef Message, SourceLocation Loc, 6177 const ObjCInterfaceDecl *UnknownObjCClass, 6178 const ObjCPropertyDecl *ObjCProperty, 6179 bool ObjCPropertyAccess) { 6180 // Diagnostics for deprecated or unavailable. 6181 unsigned diag, diag_message, diag_fwdclass_message; 6182 unsigned diag_available_here = diag::note_availability_specified_here; 6183 6184 // Matches 'diag::note_property_attribute' options. 6185 unsigned property_note_select; 6186 6187 // Matches diag::note_availability_specified_here. 6188 unsigned available_here_select_kind; 6189 6190 // Don't warn if our current context is deprecated or unavailable. 6191 switch (K) { 6192 case Sema::AD_Deprecation: 6193 if (isDeclDeprecated(Ctx) || isDeclUnavailable(Ctx)) 6194 return; 6195 diag = !ObjCPropertyAccess ? diag::warn_deprecated 6196 : diag::warn_property_method_deprecated; 6197 diag_message = diag::warn_deprecated_message; 6198 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message; 6199 property_note_select = /* deprecated */ 0; 6200 available_here_select_kind = /* deprecated */ 2; 6201 break; 6202 6203 case Sema::AD_Unavailable: 6204 if (isDeclUnavailable(Ctx)) 6205 return; 6206 diag = !ObjCPropertyAccess ? diag::err_unavailable 6207 : diag::err_property_method_unavailable; 6208 diag_message = diag::err_unavailable_message; 6209 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message; 6210 property_note_select = /* unavailable */ 1; 6211 available_here_select_kind = /* unavailable */ 0; 6212 6213 if (auto attr = D->getAttr<UnavailableAttr>()) { 6214 if (attr->isImplicit() && attr->getImplicitReason()) { 6215 // Most of these failures are due to extra restrictions in ARC; 6216 // reflect that in the primary diagnostic when applicable. 6217 auto flagARCError = [&] { 6218 if (S.getLangOpts().ObjCAutoRefCount && 6219 S.getSourceManager().isInSystemHeader(D->getLocation())) 6220 diag = diag::err_unavailable_in_arc; 6221 }; 6222 6223 switch (attr->getImplicitReason()) { 6224 case UnavailableAttr::IR_None: break; 6225 6226 case UnavailableAttr::IR_ARCForbiddenType: 6227 flagARCError(); 6228 diag_available_here = diag::note_arc_forbidden_type; 6229 break; 6230 6231 case UnavailableAttr::IR_ForbiddenWeak: 6232 if (S.getLangOpts().ObjCWeakRuntime) 6233 diag_available_here = diag::note_arc_weak_disabled; 6234 else 6235 diag_available_here = diag::note_arc_weak_no_runtime; 6236 break; 6237 6238 case UnavailableAttr::IR_ARCForbiddenConversion: 6239 flagARCError(); 6240 diag_available_here = diag::note_performs_forbidden_arc_conversion; 6241 break; 6242 6243 case UnavailableAttr::IR_ARCInitReturnsUnrelated: 6244 flagARCError(); 6245 diag_available_here = diag::note_arc_init_returns_unrelated; 6246 break; 6247 6248 case UnavailableAttr::IR_ARCFieldWithOwnership: 6249 flagARCError(); 6250 diag_available_here = diag::note_arc_field_with_ownership; 6251 break; 6252 } 6253 } 6254 } 6255 break; 6256 6257 case Sema::AD_Partial: 6258 diag = diag::warn_partial_availability; 6259 diag_message = diag::warn_partial_message; 6260 diag_fwdclass_message = diag::warn_partial_fwdclass_message; 6261 property_note_select = /* partial */ 2; 6262 available_here_select_kind = /* partial */ 3; 6263 break; 6264 } 6265 6266 CharSourceRange UseRange; 6267 StringRef Replacement; 6268 if (K == Sema::AD_Deprecation) { 6269 if (auto attr = D->getAttr<DeprecatedAttr>()) 6270 Replacement = attr->getReplacement(); 6271 if (auto attr = D->getAttr<AvailabilityAttr>()) 6272 Replacement = attr->getReplacement(); 6273 6274 if (!Replacement.empty()) 6275 UseRange = 6276 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 6277 } 6278 6279 if (!Message.empty()) { 6280 S.Diag(Loc, diag_message) << D << Message 6281 << (UseRange.isValid() ? 6282 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint()); 6283 if (ObjCProperty) 6284 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute) 6285 << ObjCProperty->getDeclName() << property_note_select; 6286 } else if (!UnknownObjCClass) { 6287 S.Diag(Loc, diag) << D 6288 << (UseRange.isValid() ? 6289 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint()); 6290 if (ObjCProperty) 6291 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute) 6292 << ObjCProperty->getDeclName() << property_note_select; 6293 } else { 6294 S.Diag(Loc, diag_fwdclass_message) << D 6295 << (UseRange.isValid() ? 6296 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint()); 6297 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class); 6298 } 6299 6300 S.Diag(D->getLocation(), diag_available_here) 6301 << D << available_here_select_kind; 6302 if (K == Sema::AD_Partial) 6303 S.Diag(Loc, diag::note_partial_availability_silence) << D; 6304 } 6305 6306 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD, 6307 Decl *Ctx) { 6308 assert(DD.Kind == DelayedDiagnostic::Deprecation || 6309 DD.Kind == DelayedDiagnostic::Unavailable); 6310 Sema::AvailabilityDiagnostic AD = DD.Kind == DelayedDiagnostic::Deprecation 6311 ? Sema::AD_Deprecation 6312 : Sema::AD_Unavailable; 6313 DD.Triggered = true; 6314 DoEmitAvailabilityWarning( 6315 S, AD, Ctx, DD.getDeprecationDecl(), DD.getDeprecationMessage(), DD.Loc, 6316 DD.getUnknownObjCClass(), DD.getObjCProperty(), false); 6317 } 6318 6319 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) { 6320 assert(DelayedDiagnostics.getCurrentPool()); 6321 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool(); 6322 DelayedDiagnostics.popWithoutEmitting(state); 6323 6324 // When delaying diagnostics to run in the context of a parsed 6325 // declaration, we only want to actually emit anything if parsing 6326 // succeeds. 6327 if (!decl) return; 6328 6329 // We emit all the active diagnostics in this pool or any of its 6330 // parents. In general, we'll get one pool for the decl spec 6331 // and a child pool for each declarator; in a decl group like: 6332 // deprecated_typedef foo, *bar, baz(); 6333 // only the declarator pops will be passed decls. This is correct; 6334 // we really do need to consider delayed diagnostics from the decl spec 6335 // for each of the different declarations. 6336 const DelayedDiagnosticPool *pool = &poppedPool; 6337 do { 6338 for (DelayedDiagnosticPool::pool_iterator 6339 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) { 6340 // This const_cast is a bit lame. Really, Triggered should be mutable. 6341 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i); 6342 if (diag.Triggered) 6343 continue; 6344 6345 switch (diag.Kind) { 6346 case DelayedDiagnostic::Deprecation: 6347 case DelayedDiagnostic::Unavailable: 6348 // Don't bother giving deprecation/unavailable diagnostics if 6349 // the decl is invalid. 6350 if (!decl->isInvalidDecl()) 6351 handleDelayedAvailabilityCheck(*this, diag, decl); 6352 break; 6353 6354 case DelayedDiagnostic::Access: 6355 HandleDelayedAccessCheck(diag, decl); 6356 break; 6357 6358 case DelayedDiagnostic::ForbiddenType: 6359 handleDelayedForbiddenType(*this, diag, decl); 6360 break; 6361 } 6362 } 6363 } while ((pool = pool->getParent())); 6364 } 6365 6366 /// Given a set of delayed diagnostics, re-emit them as if they had 6367 /// been delayed in the current context instead of in the given pool. 6368 /// Essentially, this just moves them to the current pool. 6369 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) { 6370 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool(); 6371 assert(curPool && "re-emitting in undelayed context not supported"); 6372 curPool->steal(pool); 6373 } 6374 6375 void Sema::EmitAvailabilityWarning(AvailabilityDiagnostic AD, 6376 NamedDecl *D, StringRef Message, 6377 SourceLocation Loc, 6378 const ObjCInterfaceDecl *UnknownObjCClass, 6379 const ObjCPropertyDecl *ObjCProperty, 6380 bool ObjCPropertyAccess) { 6381 // Delay if we're currently parsing a declaration. 6382 if (DelayedDiagnostics.shouldDelayDiagnostics() && AD != AD_Partial) { 6383 DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability( 6384 AD, Loc, D, UnknownObjCClass, ObjCProperty, Message, 6385 ObjCPropertyAccess)); 6386 return; 6387 } 6388 6389 Decl *Ctx = cast<Decl>(getCurLexicalContext()); 6390 DoEmitAvailabilityWarning(*this, AD, Ctx, D, Message, Loc, UnknownObjCClass, 6391 ObjCProperty, ObjCPropertyAccess); 6392 } 6393