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