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