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