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