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