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