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