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 handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) { 2179 if (!S.getLangOpts().CFProtectionBranch) 2180 S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored); 2181 else 2182 handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs); 2183 } 2184 2185 bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) { 2186 if (!Attrs.checkExactlyNumArgs(*this, 0)) { 2187 Attrs.setInvalid(); 2188 return true; 2189 } 2190 2191 return false; 2192 } 2193 2194 bool Sema::CheckAttrTarget(const ParsedAttr &AL) { 2195 // Check whether the attribute is valid on the current target. 2196 if (!AL.existsInTarget(Context.getTargetInfo())) { 2197 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) 2198 << AL << AL.getRange(); 2199 AL.setInvalid(); 2200 return true; 2201 } 2202 2203 return false; 2204 } 2205 2206 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2207 2208 // The checking path for 'noreturn' and 'analyzer_noreturn' are different 2209 // because 'analyzer_noreturn' does not impact the type. 2210 if (!isFunctionOrMethodOrBlock(D)) { 2211 ValueDecl *VD = dyn_cast<ValueDecl>(D); 2212 if (!VD || (!VD->getType()->isBlockPointerType() && 2213 !VD->getType()->isFunctionPointerType())) { 2214 S.Diag(AL.getLoc(), AL.isStandardAttributeSyntax() 2215 ? diag::err_attribute_wrong_decl_type 2216 : diag::warn_attribute_wrong_decl_type) 2217 << AL << ExpectedFunctionMethodOrBlock; 2218 return; 2219 } 2220 } 2221 2222 D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(S.Context, AL)); 2223 } 2224 2225 // PS3 PPU-specific. 2226 static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2227 /* 2228 Returning a Vector Class in Registers 2229 2230 According to the PPU ABI specifications, a class with a single member of 2231 vector type is returned in memory when used as the return value of a 2232 function. 2233 This results in inefficient code when implementing vector classes. To return 2234 the value in a single vector register, add the vecreturn attribute to the 2235 class definition. This attribute is also applicable to struct types. 2236 2237 Example: 2238 2239 struct Vector 2240 { 2241 __vector float xyzw; 2242 } __attribute__((vecreturn)); 2243 2244 Vector Add(Vector lhs, Vector rhs) 2245 { 2246 Vector result; 2247 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw); 2248 return result; // This will be returned in a register 2249 } 2250 */ 2251 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) { 2252 S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A; 2253 return; 2254 } 2255 2256 const auto *R = cast<RecordDecl>(D); 2257 int count = 0; 2258 2259 if (!isa<CXXRecordDecl>(R)) { 2260 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member); 2261 return; 2262 } 2263 2264 if (!cast<CXXRecordDecl>(R)->isPOD()) { 2265 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record); 2266 return; 2267 } 2268 2269 for (const auto *I : R->fields()) { 2270 if ((count == 1) || !I->getType()->isVectorType()) { 2271 S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member); 2272 return; 2273 } 2274 count++; 2275 } 2276 2277 D->addAttr(::new (S.Context) VecReturnAttr(S.Context, AL)); 2278 } 2279 2280 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D, 2281 const ParsedAttr &AL) { 2282 if (isa<ParmVarDecl>(D)) { 2283 // [[carries_dependency]] can only be applied to a parameter if it is a 2284 // parameter of a function declaration or lambda. 2285 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) { 2286 S.Diag(AL.getLoc(), 2287 diag::err_carries_dependency_param_not_function_decl); 2288 return; 2289 } 2290 } 2291 2292 D->addAttr(::new (S.Context) CarriesDependencyAttr(S.Context, AL)); 2293 } 2294 2295 static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2296 bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName(); 2297 2298 // If this is spelled as the standard C++17 attribute, but not in C++17, warn 2299 // about using it as an extension. 2300 if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr) 2301 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL; 2302 2303 D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL)); 2304 } 2305 2306 static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2307 uint32_t priority = ConstructorAttr::DefaultPriority; 2308 if (AL.getNumArgs() && 2309 !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority)) 2310 return; 2311 2312 D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority)); 2313 } 2314 2315 static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2316 uint32_t priority = DestructorAttr::DefaultPriority; 2317 if (AL.getNumArgs() && 2318 !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority)) 2319 return; 2320 2321 D->addAttr(::new (S.Context) DestructorAttr(S.Context, AL, priority)); 2322 } 2323 2324 template <typename AttrTy> 2325 static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) { 2326 // Handle the case where the attribute has a text message. 2327 StringRef Str; 2328 if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str)) 2329 return; 2330 2331 D->addAttr(::new (S.Context) AttrTy(S.Context, AL, Str)); 2332 } 2333 2334 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D, 2335 const ParsedAttr &AL) { 2336 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) { 2337 S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition) 2338 << AL << AL.getRange(); 2339 return; 2340 } 2341 2342 D->addAttr(::new (S.Context) ObjCExplicitProtocolImplAttr(S.Context, AL)); 2343 } 2344 2345 static bool checkAvailabilityAttr(Sema &S, SourceRange Range, 2346 IdentifierInfo *Platform, 2347 VersionTuple Introduced, 2348 VersionTuple Deprecated, 2349 VersionTuple Obsoleted) { 2350 StringRef PlatformName 2351 = AvailabilityAttr::getPrettyPlatformName(Platform->getName()); 2352 if (PlatformName.empty()) 2353 PlatformName = Platform->getName(); 2354 2355 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all 2356 // of these steps are needed). 2357 if (!Introduced.empty() && !Deprecated.empty() && 2358 !(Introduced <= Deprecated)) { 2359 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 2360 << 1 << PlatformName << Deprecated.getAsString() 2361 << 0 << Introduced.getAsString(); 2362 return true; 2363 } 2364 2365 if (!Introduced.empty() && !Obsoleted.empty() && 2366 !(Introduced <= Obsoleted)) { 2367 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 2368 << 2 << PlatformName << Obsoleted.getAsString() 2369 << 0 << Introduced.getAsString(); 2370 return true; 2371 } 2372 2373 if (!Deprecated.empty() && !Obsoleted.empty() && 2374 !(Deprecated <= Obsoleted)) { 2375 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 2376 << 2 << PlatformName << Obsoleted.getAsString() 2377 << 1 << Deprecated.getAsString(); 2378 return true; 2379 } 2380 2381 return false; 2382 } 2383 2384 /// Check whether the two versions match. 2385 /// 2386 /// If either version tuple is empty, then they are assumed to match. If 2387 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y. 2388 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y, 2389 bool BeforeIsOkay) { 2390 if (X.empty() || Y.empty()) 2391 return true; 2392 2393 if (X == Y) 2394 return true; 2395 2396 if (BeforeIsOkay && X < Y) 2397 return true; 2398 2399 return false; 2400 } 2401 2402 AvailabilityAttr *Sema::mergeAvailabilityAttr( 2403 NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, 2404 bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, 2405 VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, 2406 bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, 2407 int Priority) { 2408 VersionTuple MergedIntroduced = Introduced; 2409 VersionTuple MergedDeprecated = Deprecated; 2410 VersionTuple MergedObsoleted = Obsoleted; 2411 bool FoundAny = false; 2412 bool OverrideOrImpl = false; 2413 switch (AMK) { 2414 case AMK_None: 2415 case AMK_Redeclaration: 2416 OverrideOrImpl = false; 2417 break; 2418 2419 case AMK_Override: 2420 case AMK_ProtocolImplementation: 2421 case AMK_OptionalProtocolImplementation: 2422 OverrideOrImpl = true; 2423 break; 2424 } 2425 2426 if (D->hasAttrs()) { 2427 AttrVec &Attrs = D->getAttrs(); 2428 for (unsigned i = 0, e = Attrs.size(); i != e;) { 2429 const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]); 2430 if (!OldAA) { 2431 ++i; 2432 continue; 2433 } 2434 2435 IdentifierInfo *OldPlatform = OldAA->getPlatform(); 2436 if (OldPlatform != Platform) { 2437 ++i; 2438 continue; 2439 } 2440 2441 // If there is an existing availability attribute for this platform that 2442 // has a lower priority use the existing one and discard the new 2443 // attribute. 2444 if (OldAA->getPriority() < Priority) 2445 return nullptr; 2446 2447 // If there is an existing attribute for this platform that has a higher 2448 // priority than the new attribute then erase the old one and continue 2449 // processing the attributes. 2450 if (OldAA->getPriority() > Priority) { 2451 Attrs.erase(Attrs.begin() + i); 2452 --e; 2453 continue; 2454 } 2455 2456 FoundAny = true; 2457 VersionTuple OldIntroduced = OldAA->getIntroduced(); 2458 VersionTuple OldDeprecated = OldAA->getDeprecated(); 2459 VersionTuple OldObsoleted = OldAA->getObsoleted(); 2460 bool OldIsUnavailable = OldAA->getUnavailable(); 2461 2462 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) || 2463 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) || 2464 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) || 2465 !(OldIsUnavailable == IsUnavailable || 2466 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) { 2467 if (OverrideOrImpl) { 2468 int Which = -1; 2469 VersionTuple FirstVersion; 2470 VersionTuple SecondVersion; 2471 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) { 2472 Which = 0; 2473 FirstVersion = OldIntroduced; 2474 SecondVersion = Introduced; 2475 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) { 2476 Which = 1; 2477 FirstVersion = Deprecated; 2478 SecondVersion = OldDeprecated; 2479 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) { 2480 Which = 2; 2481 FirstVersion = Obsoleted; 2482 SecondVersion = OldObsoleted; 2483 } 2484 2485 if (Which == -1) { 2486 Diag(OldAA->getLocation(), 2487 diag::warn_mismatched_availability_override_unavail) 2488 << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) 2489 << (AMK == AMK_Override); 2490 } else if (Which != 1 && AMK == AMK_OptionalProtocolImplementation) { 2491 // Allow different 'introduced' / 'obsoleted' availability versions 2492 // on a method that implements an optional protocol requirement. It 2493 // makes less sense to allow this for 'deprecated' as the user can't 2494 // see if the method is 'deprecated' as 'respondsToSelector' will 2495 // still return true when the method is deprecated. 2496 ++i; 2497 continue; 2498 } else { 2499 Diag(OldAA->getLocation(), 2500 diag::warn_mismatched_availability_override) 2501 << Which 2502 << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) 2503 << FirstVersion.getAsString() << SecondVersion.getAsString() 2504 << (AMK == AMK_Override); 2505 } 2506 if (AMK == AMK_Override) 2507 Diag(CI.getLoc(), diag::note_overridden_method); 2508 else 2509 Diag(CI.getLoc(), diag::note_protocol_method); 2510 } else { 2511 Diag(OldAA->getLocation(), diag::warn_mismatched_availability); 2512 Diag(CI.getLoc(), diag::note_previous_attribute); 2513 } 2514 2515 Attrs.erase(Attrs.begin() + i); 2516 --e; 2517 continue; 2518 } 2519 2520 VersionTuple MergedIntroduced2 = MergedIntroduced; 2521 VersionTuple MergedDeprecated2 = MergedDeprecated; 2522 VersionTuple MergedObsoleted2 = MergedObsoleted; 2523 2524 if (MergedIntroduced2.empty()) 2525 MergedIntroduced2 = OldIntroduced; 2526 if (MergedDeprecated2.empty()) 2527 MergedDeprecated2 = OldDeprecated; 2528 if (MergedObsoleted2.empty()) 2529 MergedObsoleted2 = OldObsoleted; 2530 2531 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform, 2532 MergedIntroduced2, MergedDeprecated2, 2533 MergedObsoleted2)) { 2534 Attrs.erase(Attrs.begin() + i); 2535 --e; 2536 continue; 2537 } 2538 2539 MergedIntroduced = MergedIntroduced2; 2540 MergedDeprecated = MergedDeprecated2; 2541 MergedObsoleted = MergedObsoleted2; 2542 ++i; 2543 } 2544 } 2545 2546 if (FoundAny && 2547 MergedIntroduced == Introduced && 2548 MergedDeprecated == Deprecated && 2549 MergedObsoleted == Obsoleted) 2550 return nullptr; 2551 2552 // Only create a new attribute if !OverrideOrImpl, but we want to do 2553 // the checking. 2554 if (!checkAvailabilityAttr(*this, CI.getRange(), Platform, MergedIntroduced, 2555 MergedDeprecated, MergedObsoleted) && 2556 !OverrideOrImpl) { 2557 auto *Avail = ::new (Context) AvailabilityAttr( 2558 Context, CI, Platform, Introduced, Deprecated, Obsoleted, IsUnavailable, 2559 Message, IsStrict, Replacement, Priority); 2560 Avail->setImplicit(Implicit); 2561 return Avail; 2562 } 2563 return nullptr; 2564 } 2565 2566 static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2567 if (isa<UsingDecl, UnresolvedUsingTypenameDecl, UnresolvedUsingValueDecl>( 2568 D)) { 2569 S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using) 2570 << AL; 2571 return; 2572 } 2573 2574 if (!AL.checkExactlyNumArgs(S, 1)) 2575 return; 2576 IdentifierLoc *Platform = AL.getArgAsIdent(0); 2577 2578 IdentifierInfo *II = Platform->Ident; 2579 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty()) 2580 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform) 2581 << Platform->Ident; 2582 2583 auto *ND = dyn_cast<NamedDecl>(D); 2584 if (!ND) // We warned about this already, so just return. 2585 return; 2586 2587 AvailabilityChange Introduced = AL.getAvailabilityIntroduced(); 2588 AvailabilityChange Deprecated = AL.getAvailabilityDeprecated(); 2589 AvailabilityChange Obsoleted = AL.getAvailabilityObsoleted(); 2590 bool IsUnavailable = AL.getUnavailableLoc().isValid(); 2591 bool IsStrict = AL.getStrictLoc().isValid(); 2592 StringRef Str; 2593 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getMessageExpr())) 2594 Str = SE->getString(); 2595 StringRef Replacement; 2596 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getReplacementExpr())) 2597 Replacement = SE->getString(); 2598 2599 if (II->isStr("swift")) { 2600 if (Introduced.isValid() || Obsoleted.isValid() || 2601 (!IsUnavailable && !Deprecated.isValid())) { 2602 S.Diag(AL.getLoc(), 2603 diag::warn_availability_swift_unavailable_deprecated_only); 2604 return; 2605 } 2606 } 2607 2608 if (II->isStr("fuchsia")) { 2609 Optional<unsigned> Min, Sub; 2610 if ((Min = Introduced.Version.getMinor()) || 2611 (Sub = Introduced.Version.getSubminor())) { 2612 S.Diag(AL.getLoc(), diag::warn_availability_fuchsia_unavailable_minor); 2613 return; 2614 } 2615 } 2616 2617 int PriorityModifier = AL.isPragmaClangAttribute() 2618 ? Sema::AP_PragmaClangAttribute 2619 : Sema::AP_Explicit; 2620 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr( 2621 ND, AL, II, false /*Implicit*/, Introduced.Version, Deprecated.Version, 2622 Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement, 2623 Sema::AMK_None, PriorityModifier); 2624 if (NewAttr) 2625 D->addAttr(NewAttr); 2626 2627 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning 2628 // matches before the start of the watchOS platform. 2629 if (S.Context.getTargetInfo().getTriple().isWatchOS()) { 2630 IdentifierInfo *NewII = nullptr; 2631 if (II->getName() == "ios") 2632 NewII = &S.Context.Idents.get("watchos"); 2633 else if (II->getName() == "ios_app_extension") 2634 NewII = &S.Context.Idents.get("watchos_app_extension"); 2635 2636 if (NewII) { 2637 const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking(); 2638 const auto *IOSToWatchOSMapping = 2639 SDKInfo ? SDKInfo->getVersionMapping( 2640 DarwinSDKInfo::OSEnvPair::iOStoWatchOSPair()) 2641 : nullptr; 2642 2643 auto adjustWatchOSVersion = 2644 [IOSToWatchOSMapping](VersionTuple Version) -> VersionTuple { 2645 if (Version.empty()) 2646 return Version; 2647 auto MinimumWatchOSVersion = VersionTuple(2, 0); 2648 2649 if (IOSToWatchOSMapping) { 2650 if (auto MappedVersion = IOSToWatchOSMapping->map( 2651 Version, MinimumWatchOSVersion, None)) { 2652 return MappedVersion.getValue(); 2653 } 2654 } 2655 2656 auto Major = Version.getMajor(); 2657 auto NewMajor = Major >= 9 ? Major - 7 : 0; 2658 if (NewMajor >= 2) { 2659 if (Version.getMinor().hasValue()) { 2660 if (Version.getSubminor().hasValue()) 2661 return VersionTuple(NewMajor, Version.getMinor().getValue(), 2662 Version.getSubminor().getValue()); 2663 else 2664 return VersionTuple(NewMajor, Version.getMinor().getValue()); 2665 } 2666 return VersionTuple(NewMajor); 2667 } 2668 2669 return MinimumWatchOSVersion; 2670 }; 2671 2672 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version); 2673 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version); 2674 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version); 2675 2676 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr( 2677 ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated, 2678 NewObsoleted, IsUnavailable, Str, IsStrict, Replacement, 2679 Sema::AMK_None, 2680 PriorityModifier + Sema::AP_InferredFromOtherPlatform); 2681 if (NewAttr) 2682 D->addAttr(NewAttr); 2683 } 2684 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) { 2685 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning 2686 // matches before the start of the tvOS platform. 2687 IdentifierInfo *NewII = nullptr; 2688 if (II->getName() == "ios") 2689 NewII = &S.Context.Idents.get("tvos"); 2690 else if (II->getName() == "ios_app_extension") 2691 NewII = &S.Context.Idents.get("tvos_app_extension"); 2692 2693 if (NewII) { 2694 const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking(); 2695 const auto *IOSToTvOSMapping = 2696 SDKInfo ? SDKInfo->getVersionMapping( 2697 DarwinSDKInfo::OSEnvPair::iOStoTvOSPair()) 2698 : nullptr; 2699 2700 auto AdjustTvOSVersion = 2701 [IOSToTvOSMapping](VersionTuple Version) -> VersionTuple { 2702 if (Version.empty()) 2703 return Version; 2704 2705 if (IOSToTvOSMapping) { 2706 if (auto MappedVersion = 2707 IOSToTvOSMapping->map(Version, VersionTuple(0, 0), None)) { 2708 return MappedVersion.getValue(); 2709 } 2710 } 2711 return Version; 2712 }; 2713 2714 auto NewIntroduced = AdjustTvOSVersion(Introduced.Version); 2715 auto NewDeprecated = AdjustTvOSVersion(Deprecated.Version); 2716 auto NewObsoleted = AdjustTvOSVersion(Obsoleted.Version); 2717 2718 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr( 2719 ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated, 2720 NewObsoleted, IsUnavailable, Str, IsStrict, Replacement, 2721 Sema::AMK_None, 2722 PriorityModifier + Sema::AP_InferredFromOtherPlatform); 2723 if (NewAttr) 2724 D->addAttr(NewAttr); 2725 } 2726 } else if (S.Context.getTargetInfo().getTriple().getOS() == 2727 llvm::Triple::IOS && 2728 S.Context.getTargetInfo().getTriple().isMacCatalystEnvironment()) { 2729 auto GetSDKInfo = [&]() { 2730 return S.getDarwinSDKInfoForAvailabilityChecking(AL.getRange().getBegin(), 2731 "macOS"); 2732 }; 2733 2734 // Transcribe "ios" to "maccatalyst" (and add a new attribute). 2735 IdentifierInfo *NewII = nullptr; 2736 if (II->getName() == "ios") 2737 NewII = &S.Context.Idents.get("maccatalyst"); 2738 else if (II->getName() == "ios_app_extension") 2739 NewII = &S.Context.Idents.get("maccatalyst_app_extension"); 2740 if (NewII) { 2741 auto MinMacCatalystVersion = [](const VersionTuple &V) { 2742 if (V.empty()) 2743 return V; 2744 if (V.getMajor() < 13 || 2745 (V.getMajor() == 13 && V.getMinor() && *V.getMinor() < 1)) 2746 return VersionTuple(13, 1); // The min Mac Catalyst version is 13.1. 2747 return V; 2748 }; 2749 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr( 2750 ND, AL.getRange(), NewII, true /*Implicit*/, 2751 MinMacCatalystVersion(Introduced.Version), 2752 MinMacCatalystVersion(Deprecated.Version), 2753 MinMacCatalystVersion(Obsoleted.Version), IsUnavailable, Str, 2754 IsStrict, Replacement, Sema::AMK_None, 2755 PriorityModifier + Sema::AP_InferredFromOtherPlatform); 2756 if (NewAttr) 2757 D->addAttr(NewAttr); 2758 } else if (II->getName() == "macos" && GetSDKInfo() && 2759 (!Introduced.Version.empty() || !Deprecated.Version.empty() || 2760 !Obsoleted.Version.empty())) { 2761 if (const auto *MacOStoMacCatalystMapping = 2762 GetSDKInfo()->getVersionMapping( 2763 DarwinSDKInfo::OSEnvPair::macOStoMacCatalystPair())) { 2764 // Infer Mac Catalyst availability from the macOS availability attribute 2765 // if it has versioned availability. Don't infer 'unavailable'. This 2766 // inferred availability has lower priority than the other availability 2767 // attributes that are inferred from 'ios'. 2768 NewII = &S.Context.Idents.get("maccatalyst"); 2769 auto RemapMacOSVersion = 2770 [&](const VersionTuple &V) -> Optional<VersionTuple> { 2771 if (V.empty()) 2772 return None; 2773 // API_TO_BE_DEPRECATED is 100000. 2774 if (V.getMajor() == 100000) 2775 return VersionTuple(100000); 2776 // The minimum iosmac version is 13.1 2777 return MacOStoMacCatalystMapping->map(V, VersionTuple(13, 1), None); 2778 }; 2779 Optional<VersionTuple> NewIntroduced = 2780 RemapMacOSVersion(Introduced.Version), 2781 NewDeprecated = 2782 RemapMacOSVersion(Deprecated.Version), 2783 NewObsoleted = 2784 RemapMacOSVersion(Obsoleted.Version); 2785 if (NewIntroduced || NewDeprecated || NewObsoleted) { 2786 auto VersionOrEmptyVersion = 2787 [](const Optional<VersionTuple> &V) -> VersionTuple { 2788 return V ? *V : VersionTuple(); 2789 }; 2790 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr( 2791 ND, AL.getRange(), NewII, true /*Implicit*/, 2792 VersionOrEmptyVersion(NewIntroduced), 2793 VersionOrEmptyVersion(NewDeprecated), 2794 VersionOrEmptyVersion(NewObsoleted), /*IsUnavailable=*/false, Str, 2795 IsStrict, Replacement, Sema::AMK_None, 2796 PriorityModifier + Sema::AP_InferredFromOtherPlatform + 2797 Sema::AP_InferredFromOtherPlatform); 2798 if (NewAttr) 2799 D->addAttr(NewAttr); 2800 } 2801 } 2802 } 2803 } 2804 } 2805 2806 static void handleExternalSourceSymbolAttr(Sema &S, Decl *D, 2807 const ParsedAttr &AL) { 2808 if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 3)) 2809 return; 2810 2811 StringRef Language; 2812 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0))) 2813 Language = SE->getString(); 2814 StringRef DefinedIn; 2815 if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1))) 2816 DefinedIn = SE->getString(); 2817 bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr; 2818 2819 D->addAttr(::new (S.Context) ExternalSourceSymbolAttr( 2820 S.Context, AL, Language, DefinedIn, IsGeneratedDeclaration)); 2821 } 2822 2823 template <class T> 2824 static T *mergeVisibilityAttr(Sema &S, Decl *D, const AttributeCommonInfo &CI, 2825 typename T::VisibilityType value) { 2826 T *existingAttr = D->getAttr<T>(); 2827 if (existingAttr) { 2828 typename T::VisibilityType existingValue = existingAttr->getVisibility(); 2829 if (existingValue == value) 2830 return nullptr; 2831 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility); 2832 S.Diag(CI.getLoc(), diag::note_previous_attribute); 2833 D->dropAttr<T>(); 2834 } 2835 return ::new (S.Context) T(S.Context, CI, value); 2836 } 2837 2838 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, 2839 const AttributeCommonInfo &CI, 2840 VisibilityAttr::VisibilityType Vis) { 2841 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, CI, Vis); 2842 } 2843 2844 TypeVisibilityAttr * 2845 Sema::mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, 2846 TypeVisibilityAttr::VisibilityType Vis) { 2847 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, CI, Vis); 2848 } 2849 2850 static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL, 2851 bool isTypeVisibility) { 2852 // Visibility attributes don't mean anything on a typedef. 2853 if (isa<TypedefNameDecl>(D)) { 2854 S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL; 2855 return; 2856 } 2857 2858 // 'type_visibility' can only go on a type or namespace. 2859 if (isTypeVisibility && 2860 !(isa<TagDecl>(D) || 2861 isa<ObjCInterfaceDecl>(D) || 2862 isa<NamespaceDecl>(D))) { 2863 S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type) 2864 << AL << ExpectedTypeOrNamespace; 2865 return; 2866 } 2867 2868 // Check that the argument is a string literal. 2869 StringRef TypeStr; 2870 SourceLocation LiteralLoc; 2871 if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc)) 2872 return; 2873 2874 VisibilityAttr::VisibilityType type; 2875 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) { 2876 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL 2877 << TypeStr; 2878 return; 2879 } 2880 2881 // Complain about attempts to use protected visibility on targets 2882 // (like Darwin) that don't support it. 2883 if (type == VisibilityAttr::Protected && 2884 !S.Context.getTargetInfo().hasProtectedVisibility()) { 2885 S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility); 2886 type = VisibilityAttr::Default; 2887 } 2888 2889 Attr *newAttr; 2890 if (isTypeVisibility) { 2891 newAttr = S.mergeTypeVisibilityAttr( 2892 D, AL, (TypeVisibilityAttr::VisibilityType)type); 2893 } else { 2894 newAttr = S.mergeVisibilityAttr(D, AL, type); 2895 } 2896 if (newAttr) 2897 D->addAttr(newAttr); 2898 } 2899 2900 static void handleObjCDirectAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2901 // objc_direct cannot be set on methods declared in the context of a protocol 2902 if (isa<ObjCProtocolDecl>(D->getDeclContext())) { 2903 S.Diag(AL.getLoc(), diag::err_objc_direct_on_protocol) << false; 2904 return; 2905 } 2906 2907 if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) { 2908 handleSimpleAttribute<ObjCDirectAttr>(S, D, AL); 2909 } else { 2910 S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL; 2911 } 2912 } 2913 2914 static void handleObjCDirectMembersAttr(Sema &S, Decl *D, 2915 const ParsedAttr &AL) { 2916 if (S.getLangOpts().ObjCRuntime.allowsDirectDispatch()) { 2917 handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL); 2918 } else { 2919 S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL; 2920 } 2921 } 2922 2923 static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2924 const auto *M = cast<ObjCMethodDecl>(D); 2925 if (!AL.isArgIdent(0)) { 2926 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 2927 << AL << 1 << AANT_ArgumentIdentifier; 2928 return; 2929 } 2930 2931 IdentifierLoc *IL = AL.getArgAsIdent(0); 2932 ObjCMethodFamilyAttr::FamilyKind F; 2933 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) { 2934 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident; 2935 return; 2936 } 2937 2938 if (F == ObjCMethodFamilyAttr::OMF_init && 2939 !M->getReturnType()->isObjCObjectPointerType()) { 2940 S.Diag(M->getLocation(), diag::err_init_method_bad_return_type) 2941 << M->getReturnType(); 2942 // Ignore the attribute. 2943 return; 2944 } 2945 2946 D->addAttr(new (S.Context) ObjCMethodFamilyAttr(S.Context, AL, F)); 2947 } 2948 2949 static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) { 2950 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 2951 QualType T = TD->getUnderlyingType(); 2952 if (!T->isCARCBridgableType()) { 2953 S.Diag(TD->getLocation(), diag::err_nsobject_attribute); 2954 return; 2955 } 2956 } 2957 else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) { 2958 QualType T = PD->getType(); 2959 if (!T->isCARCBridgableType()) { 2960 S.Diag(PD->getLocation(), diag::err_nsobject_attribute); 2961 return; 2962 } 2963 } 2964 else { 2965 // It is okay to include this attribute on properties, e.g.: 2966 // 2967 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject)); 2968 // 2969 // In this case it follows tradition and suppresses an error in the above 2970 // case. 2971 S.Diag(D->getLocation(), diag::warn_nsobject_attribute); 2972 } 2973 D->addAttr(::new (S.Context) ObjCNSObjectAttr(S.Context, AL)); 2974 } 2975 2976 static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) { 2977 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 2978 QualType T = TD->getUnderlyingType(); 2979 if (!T->isObjCObjectPointerType()) { 2980 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute); 2981 return; 2982 } 2983 } else { 2984 S.Diag(D->getLocation(), diag::warn_independentclass_attribute); 2985 return; 2986 } 2987 D->addAttr(::new (S.Context) ObjCIndependentClassAttr(S.Context, AL)); 2988 } 2989 2990 static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 2991 if (!AL.isArgIdent(0)) { 2992 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 2993 << AL << 1 << AANT_ArgumentIdentifier; 2994 return; 2995 } 2996 2997 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 2998 BlocksAttr::BlockType type; 2999 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) { 3000 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II; 3001 return; 3002 } 3003 3004 D->addAttr(::new (S.Context) BlocksAttr(S.Context, AL, type)); 3005 } 3006 3007 static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3008 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel; 3009 if (AL.getNumArgs() > 0) { 3010 Expr *E = AL.getArgAsExpr(0); 3011 Optional<llvm::APSInt> Idx = llvm::APSInt(32); 3012 if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) { 3013 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 3014 << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange(); 3015 return; 3016 } 3017 3018 if (Idx->isSigned() && Idx->isNegative()) { 3019 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero) 3020 << E->getSourceRange(); 3021 return; 3022 } 3023 3024 sentinel = Idx->getZExtValue(); 3025 } 3026 3027 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos; 3028 if (AL.getNumArgs() > 1) { 3029 Expr *E = AL.getArgAsExpr(1); 3030 Optional<llvm::APSInt> Idx = llvm::APSInt(32); 3031 if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) { 3032 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 3033 << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange(); 3034 return; 3035 } 3036 nullPos = Idx->getZExtValue(); 3037 3038 if ((Idx->isSigned() && Idx->isNegative()) || nullPos > 1) { 3039 // FIXME: This error message could be improved, it would be nice 3040 // to say what the bounds actually are. 3041 S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one) 3042 << E->getSourceRange(); 3043 return; 3044 } 3045 } 3046 3047 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 3048 const FunctionType *FT = FD->getType()->castAs<FunctionType>(); 3049 if (isa<FunctionNoProtoType>(FT)) { 3050 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments); 3051 return; 3052 } 3053 3054 if (!cast<FunctionProtoType>(FT)->isVariadic()) { 3055 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; 3056 return; 3057 } 3058 } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) { 3059 if (!MD->isVariadic()) { 3060 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; 3061 return; 3062 } 3063 } else if (const auto *BD = dyn_cast<BlockDecl>(D)) { 3064 if (!BD->isVariadic()) { 3065 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1; 3066 return; 3067 } 3068 } else if (const auto *V = dyn_cast<VarDecl>(D)) { 3069 QualType Ty = V->getType(); 3070 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) { 3071 const FunctionType *FT = Ty->isFunctionPointerType() 3072 ? D->getFunctionType() 3073 : Ty->castAs<BlockPointerType>() 3074 ->getPointeeType() 3075 ->castAs<FunctionType>(); 3076 if (!cast<FunctionProtoType>(FT)->isVariadic()) { 3077 int m = Ty->isFunctionPointerType() ? 0 : 1; 3078 S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m; 3079 return; 3080 } 3081 } else { 3082 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 3083 << AL << ExpectedFunctionMethodOrBlock; 3084 return; 3085 } 3086 } else { 3087 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 3088 << AL << ExpectedFunctionMethodOrBlock; 3089 return; 3090 } 3091 D->addAttr(::new (S.Context) SentinelAttr(S.Context, AL, sentinel, nullPos)); 3092 } 3093 3094 static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) { 3095 if (D->getFunctionType() && 3096 D->getFunctionType()->getReturnType()->isVoidType() && 3097 !isa<CXXConstructorDecl>(D)) { 3098 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0; 3099 return; 3100 } 3101 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 3102 if (MD->getReturnType()->isVoidType()) { 3103 S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1; 3104 return; 3105 } 3106 3107 StringRef Str; 3108 if (AL.isStandardAttributeSyntax() && !AL.getScopeName()) { 3109 // The standard attribute cannot be applied to variable declarations such 3110 // as a function pointer. 3111 if (isa<VarDecl>(D)) 3112 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str) 3113 << AL << "functions, classes, or enumerations"; 3114 3115 // If this is spelled as the standard C++17 attribute, but not in C++17, 3116 // warn about using it as an extension. If there are attribute arguments, 3117 // then claim it's a C++2a extension instead. 3118 // FIXME: If WG14 does not seem likely to adopt the same feature, add an 3119 // extension warning for C2x mode. 3120 const LangOptions &LO = S.getLangOpts(); 3121 if (AL.getNumArgs() == 1) { 3122 if (LO.CPlusPlus && !LO.CPlusPlus20) 3123 S.Diag(AL.getLoc(), diag::ext_cxx20_attr) << AL; 3124 3125 // Since this this is spelled [[nodiscard]], get the optional string 3126 // literal. If in C++ mode, but not in C++2a mode, diagnose as an 3127 // extension. 3128 // FIXME: C2x should support this feature as well, even as an extension. 3129 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, nullptr)) 3130 return; 3131 } else if (LO.CPlusPlus && !LO.CPlusPlus17) 3132 S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL; 3133 } 3134 3135 D->addAttr(::new (S.Context) WarnUnusedResultAttr(S.Context, AL, Str)); 3136 } 3137 3138 static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3139 // weak_import only applies to variable & function declarations. 3140 bool isDef = false; 3141 if (!D->canBeWeakImported(isDef)) { 3142 if (isDef) 3143 S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition) 3144 << "weak_import"; 3145 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) || 3146 (S.Context.getTargetInfo().getTriple().isOSDarwin() && 3147 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) { 3148 // Nothing to warn about here. 3149 } else 3150 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 3151 << AL << ExpectedVariableOrFunction; 3152 3153 return; 3154 } 3155 3156 D->addAttr(::new (S.Context) WeakImportAttr(S.Context, AL)); 3157 } 3158 3159 // Handles reqd_work_group_size and work_group_size_hint. 3160 template <typename WorkGroupAttr> 3161 static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) { 3162 uint32_t WGSize[3]; 3163 for (unsigned i = 0; i < 3; ++i) { 3164 const Expr *E = AL.getArgAsExpr(i); 3165 if (!checkUInt32Argument(S, AL, E, WGSize[i], i, 3166 /*StrictlyUnsigned=*/true)) 3167 return; 3168 if (WGSize[i] == 0) { 3169 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero) 3170 << AL << E->getSourceRange(); 3171 return; 3172 } 3173 } 3174 3175 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>(); 3176 if (Existing && !(Existing->getXDim() == WGSize[0] && 3177 Existing->getYDim() == WGSize[1] && 3178 Existing->getZDim() == WGSize[2])) 3179 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; 3180 3181 D->addAttr(::new (S.Context) 3182 WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2])); 3183 } 3184 3185 // Handles intel_reqd_sub_group_size. 3186 static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) { 3187 uint32_t SGSize; 3188 const Expr *E = AL.getArgAsExpr(0); 3189 if (!checkUInt32Argument(S, AL, E, SGSize)) 3190 return; 3191 if (SGSize == 0) { 3192 S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero) 3193 << AL << E->getSourceRange(); 3194 return; 3195 } 3196 3197 OpenCLIntelReqdSubGroupSizeAttr *Existing = 3198 D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>(); 3199 if (Existing && Existing->getSubGroupSize() != SGSize) 3200 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; 3201 3202 D->addAttr(::new (S.Context) 3203 OpenCLIntelReqdSubGroupSizeAttr(S.Context, AL, SGSize)); 3204 } 3205 3206 static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) { 3207 if (!AL.hasParsedType()) { 3208 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1; 3209 return; 3210 } 3211 3212 TypeSourceInfo *ParmTSI = nullptr; 3213 QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI); 3214 assert(ParmTSI && "no type source info for attribute argument"); 3215 3216 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() && 3217 (ParmType->isBooleanType() || 3218 !ParmType->isIntegralType(S.getASTContext()))) { 3219 S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) << 2 << AL; 3220 return; 3221 } 3222 3223 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) { 3224 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) { 3225 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; 3226 return; 3227 } 3228 } 3229 3230 D->addAttr(::new (S.Context) VecTypeHintAttr(S.Context, AL, ParmTSI)); 3231 } 3232 3233 SectionAttr *Sema::mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, 3234 StringRef Name) { 3235 // Explicit or partial specializations do not inherit 3236 // the section attribute from the primary template. 3237 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 3238 if (CI.getAttributeSpellingListIndex() == SectionAttr::Declspec_allocate && 3239 FD->isFunctionTemplateSpecialization()) 3240 return nullptr; 3241 } 3242 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) { 3243 if (ExistingAttr->getName() == Name) 3244 return nullptr; 3245 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section) 3246 << 1 /*section*/; 3247 Diag(CI.getLoc(), diag::note_previous_attribute); 3248 return nullptr; 3249 } 3250 return ::new (Context) SectionAttr(Context, CI, Name); 3251 } 3252 3253 /// Used to implement to perform semantic checking on 3254 /// attribute((section("foo"))) specifiers. 3255 /// 3256 /// In this case, "foo" is passed in to be checked. If the section 3257 /// specifier is invalid, return an Error that indicates the problem. 3258 /// 3259 /// This is a simple quality of implementation feature to catch errors 3260 /// and give good diagnostics in cases when the assembler or code generator 3261 /// would otherwise reject the section specifier. 3262 llvm::Error Sema::isValidSectionSpecifier(StringRef SecName) { 3263 if (!Context.getTargetInfo().getTriple().isOSDarwin()) 3264 return llvm::Error::success(); 3265 3266 // Let MCSectionMachO validate this. 3267 StringRef Segment, Section; 3268 unsigned TAA, StubSize; 3269 bool HasTAA; 3270 return llvm::MCSectionMachO::ParseSectionSpecifier(SecName, Segment, Section, 3271 TAA, HasTAA, StubSize); 3272 } 3273 3274 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) { 3275 if (llvm::Error E = isValidSectionSpecifier(SecName)) { 3276 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) 3277 << toString(std::move(E)) << 1 /*'section'*/; 3278 return false; 3279 } 3280 return true; 3281 } 3282 3283 static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3284 // Make sure that there is a string literal as the sections's single 3285 // argument. 3286 StringRef Str; 3287 SourceLocation LiteralLoc; 3288 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc)) 3289 return; 3290 3291 if (!S.checkSectionName(LiteralLoc, Str)) 3292 return; 3293 3294 SectionAttr *NewAttr = S.mergeSectionAttr(D, AL, Str); 3295 if (NewAttr) { 3296 D->addAttr(NewAttr); 3297 if (isa<FunctionDecl, FunctionTemplateDecl, ObjCMethodDecl, 3298 ObjCPropertyDecl>(D)) 3299 S.UnifySection(NewAttr->getName(), 3300 ASTContext::PSF_Execute | ASTContext::PSF_Read, 3301 cast<NamedDecl>(D)); 3302 } 3303 } 3304 3305 // This is used for `__declspec(code_seg("segname"))` on a decl. 3306 // `#pragma code_seg("segname")` uses checkSectionName() instead. 3307 static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc, 3308 StringRef CodeSegName) { 3309 if (llvm::Error E = S.isValidSectionSpecifier(CodeSegName)) { 3310 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) 3311 << toString(std::move(E)) << 0 /*'code-seg'*/; 3312 return false; 3313 } 3314 3315 return true; 3316 } 3317 3318 CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, 3319 StringRef Name) { 3320 // Explicit or partial specializations do not inherit 3321 // the code_seg attribute from the primary template. 3322 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 3323 if (FD->isFunctionTemplateSpecialization()) 3324 return nullptr; 3325 } 3326 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) { 3327 if (ExistingAttr->getName() == Name) 3328 return nullptr; 3329 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section) 3330 << 0 /*codeseg*/; 3331 Diag(CI.getLoc(), diag::note_previous_attribute); 3332 return nullptr; 3333 } 3334 return ::new (Context) CodeSegAttr(Context, CI, Name); 3335 } 3336 3337 static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3338 StringRef Str; 3339 SourceLocation LiteralLoc; 3340 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc)) 3341 return; 3342 if (!checkCodeSegName(S, LiteralLoc, Str)) 3343 return; 3344 if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) { 3345 if (!ExistingAttr->isImplicit()) { 3346 S.Diag(AL.getLoc(), 3347 ExistingAttr->getName() == Str 3348 ? diag::warn_duplicate_codeseg_attribute 3349 : diag::err_conflicting_codeseg_attribute); 3350 return; 3351 } 3352 D->dropAttr<CodeSegAttr>(); 3353 } 3354 if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL, Str)) 3355 D->addAttr(CSA); 3356 } 3357 3358 // Check for things we'd like to warn about. Multiversioning issues are 3359 // handled later in the process, once we know how many exist. 3360 bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) { 3361 enum FirstParam { Unsupported, Duplicate, Unknown }; 3362 enum SecondParam { None, Architecture, Tune }; 3363 enum ThirdParam { Target, TargetClones }; 3364 if (AttrStr.contains("fpmath=")) 3365 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3366 << Unsupported << None << "fpmath=" << Target; 3367 3368 // Diagnose use of tune if target doesn't support it. 3369 if (!Context.getTargetInfo().supportsTargetAttributeTune() && 3370 AttrStr.contains("tune=")) 3371 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3372 << Unsupported << None << "tune=" << Target; 3373 3374 ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr); 3375 3376 if (!ParsedAttrs.Architecture.empty() && 3377 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture)) 3378 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3379 << Unknown << Architecture << ParsedAttrs.Architecture << Target; 3380 3381 if (!ParsedAttrs.Tune.empty() && 3382 !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Tune)) 3383 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3384 << Unknown << Tune << ParsedAttrs.Tune << Target; 3385 3386 if (ParsedAttrs.DuplicateArchitecture) 3387 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3388 << Duplicate << None << "arch=" << Target; 3389 if (ParsedAttrs.DuplicateTune) 3390 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3391 << Duplicate << None << "tune=" << Target; 3392 3393 for (const auto &Feature : ParsedAttrs.Features) { 3394 auto CurFeature = StringRef(Feature).drop_front(); // remove + or -. 3395 if (!Context.getTargetInfo().isValidFeatureName(CurFeature)) 3396 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3397 << Unsupported << None << CurFeature << Target; 3398 } 3399 3400 TargetInfo::BranchProtectionInfo BPI; 3401 StringRef DiagMsg; 3402 if (ParsedAttrs.BranchProtection.empty()) 3403 return false; 3404 if (!Context.getTargetInfo().validateBranchProtection( 3405 ParsedAttrs.BranchProtection, ParsedAttrs.Architecture, BPI, 3406 DiagMsg)) { 3407 if (DiagMsg.empty()) 3408 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3409 << Unsupported << None << "branch-protection" << Target; 3410 return Diag(LiteralLoc, diag::err_invalid_branch_protection_spec) 3411 << DiagMsg; 3412 } 3413 if (!DiagMsg.empty()) 3414 Diag(LiteralLoc, diag::warn_unsupported_branch_protection_spec) << DiagMsg; 3415 3416 return false; 3417 } 3418 3419 static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3420 StringRef Str; 3421 SourceLocation LiteralLoc; 3422 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) || 3423 S.checkTargetAttr(LiteralLoc, Str)) 3424 return; 3425 3426 TargetAttr *NewAttr = ::new (S.Context) TargetAttr(S.Context, AL, Str); 3427 D->addAttr(NewAttr); 3428 } 3429 3430 bool Sema::checkTargetClonesAttrString(SourceLocation LiteralLoc, StringRef Str, 3431 const StringLiteral *Literal, 3432 bool &HasDefault, bool &HasCommas, 3433 SmallVectorImpl<StringRef> &Strings) { 3434 enum FirstParam { Unsupported, Duplicate, Unknown }; 3435 enum SecondParam { None, Architecture, Tune }; 3436 enum ThirdParam { Target, TargetClones }; 3437 HasCommas = HasCommas || Str.contains(','); 3438 // Warn on empty at the beginning of a string. 3439 if (Str.size() == 0) 3440 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3441 << Unsupported << None << "" << TargetClones; 3442 3443 std::pair<StringRef, StringRef> Parts = {{}, Str}; 3444 while (!Parts.second.empty()) { 3445 Parts = Parts.second.split(','); 3446 StringRef Cur = Parts.first.trim(); 3447 SourceLocation CurLoc = Literal->getLocationOfByte( 3448 Cur.data() - Literal->getString().data(), getSourceManager(), 3449 getLangOpts(), Context.getTargetInfo()); 3450 3451 bool DefaultIsDupe = false; 3452 if (Cur.empty()) 3453 return Diag(CurLoc, diag::warn_unsupported_target_attribute) 3454 << Unsupported << None << "" << TargetClones; 3455 3456 if (Cur.startswith("arch=")) { 3457 if (!Context.getTargetInfo().isValidCPUName( 3458 Cur.drop_front(sizeof("arch=") - 1))) 3459 return Diag(CurLoc, diag::warn_unsupported_target_attribute) 3460 << Unsupported << Architecture 3461 << Cur.drop_front(sizeof("arch=") - 1) << TargetClones; 3462 } else if (Cur == "default") { 3463 DefaultIsDupe = HasDefault; 3464 HasDefault = true; 3465 } else if (!Context.getTargetInfo().isValidFeatureName(Cur)) 3466 return Diag(CurLoc, diag::warn_unsupported_target_attribute) 3467 << Unsupported << None << Cur << TargetClones; 3468 3469 if (llvm::find(Strings, Cur) != Strings.end() || DefaultIsDupe) 3470 Diag(CurLoc, diag::warn_target_clone_duplicate_options); 3471 // Note: Add even if there are duplicates, since it changes name mangling. 3472 Strings.push_back(Cur); 3473 } 3474 3475 if (Str.rtrim().endswith(",")) 3476 return Diag(LiteralLoc, diag::warn_unsupported_target_attribute) 3477 << Unsupported << None << "" << TargetClones; 3478 return false; 3479 } 3480 3481 static void handleTargetClonesAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3482 // Ensure we don't combine these with themselves, since that causes some 3483 // confusing behavior. 3484 if (const auto *Other = D->getAttr<TargetClonesAttr>()) { 3485 S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL; 3486 S.Diag(Other->getLocation(), diag::note_conflicting_attribute); 3487 return; 3488 } 3489 if (checkAttrMutualExclusion<TargetClonesAttr>(S, D, AL)) 3490 return; 3491 3492 SmallVector<StringRef, 2> Strings; 3493 bool HasCommas = false, HasDefault = false; 3494 3495 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) { 3496 StringRef CurStr; 3497 SourceLocation LiteralLoc; 3498 if (!S.checkStringLiteralArgumentAttr(AL, I, CurStr, &LiteralLoc) || 3499 S.checkTargetClonesAttrString( 3500 LiteralLoc, CurStr, 3501 cast<StringLiteral>(AL.getArgAsExpr(I)->IgnoreParenCasts()), 3502 HasDefault, HasCommas, Strings)) 3503 return; 3504 } 3505 3506 if (HasCommas && AL.getNumArgs() > 1) 3507 S.Diag(AL.getLoc(), diag::warn_target_clone_mixed_values); 3508 3509 if (!HasDefault) { 3510 S.Diag(AL.getLoc(), diag::err_target_clone_must_have_default); 3511 return; 3512 } 3513 3514 // FIXME: We could probably figure out how to get this to work for lambdas 3515 // someday. 3516 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) { 3517 if (MD->getParent()->isLambda()) { 3518 S.Diag(D->getLocation(), diag::err_multiversion_doesnt_support) 3519 << static_cast<unsigned>(MultiVersionKind::TargetClones) 3520 << /*Lambda*/ 9; 3521 return; 3522 } 3523 } 3524 3525 cast<FunctionDecl>(D)->setIsMultiVersion(); 3526 TargetClonesAttr *NewAttr = ::new (S.Context) 3527 TargetClonesAttr(S.Context, AL, Strings.data(), Strings.size()); 3528 D->addAttr(NewAttr); 3529 } 3530 3531 static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3532 Expr *E = AL.getArgAsExpr(0); 3533 uint32_t VecWidth; 3534 if (!checkUInt32Argument(S, AL, E, VecWidth)) { 3535 AL.setInvalid(); 3536 return; 3537 } 3538 3539 MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>(); 3540 if (Existing && Existing->getVectorWidth() != VecWidth) { 3541 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; 3542 return; 3543 } 3544 3545 D->addAttr(::new (S.Context) MinVectorWidthAttr(S.Context, AL, VecWidth)); 3546 } 3547 3548 static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3549 Expr *E = AL.getArgAsExpr(0); 3550 SourceLocation Loc = E->getExprLoc(); 3551 FunctionDecl *FD = nullptr; 3552 DeclarationNameInfo NI; 3553 3554 // gcc only allows for simple identifiers. Since we support more than gcc, we 3555 // will warn the user. 3556 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) { 3557 if (DRE->hasQualifier()) 3558 S.Diag(Loc, diag::warn_cleanup_ext); 3559 FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 3560 NI = DRE->getNameInfo(); 3561 if (!FD) { 3562 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1 3563 << NI.getName(); 3564 return; 3565 } 3566 } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 3567 if (ULE->hasExplicitTemplateArgs()) 3568 S.Diag(Loc, diag::warn_cleanup_ext); 3569 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true); 3570 NI = ULE->getNameInfo(); 3571 if (!FD) { 3572 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2 3573 << NI.getName(); 3574 if (ULE->getType() == S.Context.OverloadTy) 3575 S.NoteAllOverloadCandidates(ULE); 3576 return; 3577 } 3578 } else { 3579 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0; 3580 return; 3581 } 3582 3583 if (FD->getNumParams() != 1) { 3584 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg) 3585 << NI.getName(); 3586 return; 3587 } 3588 3589 // We're currently more strict than GCC about what function types we accept. 3590 // If this ever proves to be a problem it should be easy to fix. 3591 QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType()); 3592 QualType ParamTy = FD->getParamDecl(0)->getType(); 3593 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(), 3594 ParamTy, Ty) != Sema::Compatible) { 3595 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type) 3596 << NI.getName() << ParamTy << Ty; 3597 return; 3598 } 3599 3600 D->addAttr(::new (S.Context) CleanupAttr(S.Context, AL, FD)); 3601 } 3602 3603 static void handleEnumExtensibilityAttr(Sema &S, Decl *D, 3604 const ParsedAttr &AL) { 3605 if (!AL.isArgIdent(0)) { 3606 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 3607 << AL << 0 << AANT_ArgumentIdentifier; 3608 return; 3609 } 3610 3611 EnumExtensibilityAttr::Kind ExtensibilityKind; 3612 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 3613 if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(), 3614 ExtensibilityKind)) { 3615 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II; 3616 return; 3617 } 3618 3619 D->addAttr(::new (S.Context) 3620 EnumExtensibilityAttr(S.Context, AL, ExtensibilityKind)); 3621 } 3622 3623 /// Handle __attribute__((format_arg((idx)))) attribute based on 3624 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 3625 static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3626 Expr *IdxExpr = AL.getArgAsExpr(0); 3627 ParamIdx Idx; 3628 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx)) 3629 return; 3630 3631 // Make sure the format string is really a string. 3632 QualType Ty = getFunctionOrMethodParamType(D, Idx.getASTIndex()); 3633 3634 bool NotNSStringTy = !isNSStringType(Ty, S.Context); 3635 if (NotNSStringTy && 3636 !isCFStringType(Ty, S.Context) && 3637 (!Ty->isPointerType() || 3638 !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) { 3639 S.Diag(AL.getLoc(), diag::err_format_attribute_not) 3640 << "a string type" << IdxExpr->getSourceRange() 3641 << getFunctionOrMethodParamRange(D, 0); 3642 return; 3643 } 3644 Ty = getFunctionOrMethodResultType(D); 3645 // replace instancetype with the class type 3646 auto Instancetype = S.Context.getObjCInstanceTypeDecl()->getTypeForDecl(); 3647 if (Ty->getAs<TypedefType>() == Instancetype) 3648 if (auto *OMD = dyn_cast<ObjCMethodDecl>(D)) 3649 if (auto *Interface = OMD->getClassInterface()) 3650 Ty = S.Context.getObjCObjectPointerType( 3651 QualType(Interface->getTypeForDecl(), 0)); 3652 if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true) && 3653 !isCFStringType(Ty, S.Context) && 3654 (!Ty->isPointerType() || 3655 !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) { 3656 S.Diag(AL.getLoc(), diag::err_format_attribute_result_not) 3657 << (NotNSStringTy ? "string type" : "NSString") 3658 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0); 3659 return; 3660 } 3661 3662 D->addAttr(::new (S.Context) FormatArgAttr(S.Context, AL, Idx)); 3663 } 3664 3665 enum FormatAttrKind { 3666 CFStringFormat, 3667 NSStringFormat, 3668 StrftimeFormat, 3669 SupportedFormat, 3670 IgnoredFormat, 3671 InvalidFormat 3672 }; 3673 3674 /// getFormatAttrKind - Map from format attribute names to supported format 3675 /// types. 3676 static FormatAttrKind getFormatAttrKind(StringRef Format) { 3677 return llvm::StringSwitch<FormatAttrKind>(Format) 3678 // Check for formats that get handled specially. 3679 .Case("NSString", NSStringFormat) 3680 .Case("CFString", CFStringFormat) 3681 .Case("strftime", StrftimeFormat) 3682 3683 // Otherwise, check for supported formats. 3684 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat) 3685 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat) 3686 .Case("kprintf", SupportedFormat) // OpenBSD. 3687 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD. 3688 .Case("os_trace", SupportedFormat) 3689 .Case("os_log", SupportedFormat) 3690 3691 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat) 3692 .Default(InvalidFormat); 3693 } 3694 3695 /// Handle __attribute__((init_priority(priority))) attributes based on 3696 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html 3697 static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3698 if (!S.getLangOpts().CPlusPlus) { 3699 S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL; 3700 return; 3701 } 3702 3703 if (S.getCurFunctionOrMethodDecl()) { 3704 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr); 3705 AL.setInvalid(); 3706 return; 3707 } 3708 QualType T = cast<VarDecl>(D)->getType(); 3709 if (S.Context.getAsArrayType(T)) 3710 T = S.Context.getBaseElementType(T); 3711 if (!T->getAs<RecordType>()) { 3712 S.Diag(AL.getLoc(), diag::err_init_priority_object_attr); 3713 AL.setInvalid(); 3714 return; 3715 } 3716 3717 Expr *E = AL.getArgAsExpr(0); 3718 uint32_t prioritynum; 3719 if (!checkUInt32Argument(S, AL, E, prioritynum)) { 3720 AL.setInvalid(); 3721 return; 3722 } 3723 3724 // Only perform the priority check if the attribute is outside of a system 3725 // header. Values <= 100 are reserved for the implementation, and libc++ 3726 // benefits from being able to specify values in that range. 3727 if ((prioritynum < 101 || prioritynum > 65535) && 3728 !S.getSourceManager().isInSystemHeader(AL.getLoc())) { 3729 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range) 3730 << E->getSourceRange() << AL << 101 << 65535; 3731 AL.setInvalid(); 3732 return; 3733 } 3734 D->addAttr(::new (S.Context) InitPriorityAttr(S.Context, AL, prioritynum)); 3735 } 3736 3737 ErrorAttr *Sema::mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, 3738 StringRef NewUserDiagnostic) { 3739 if (const auto *EA = D->getAttr<ErrorAttr>()) { 3740 std::string NewAttr = CI.getNormalizedFullName(); 3741 assert((NewAttr == "error" || NewAttr == "warning") && 3742 "unexpected normalized full name"); 3743 bool Match = (EA->isError() && NewAttr == "error") || 3744 (EA->isWarning() && NewAttr == "warning"); 3745 if (!Match) { 3746 Diag(EA->getLocation(), diag::err_attributes_are_not_compatible) 3747 << CI << EA; 3748 Diag(CI.getLoc(), diag::note_conflicting_attribute); 3749 return nullptr; 3750 } 3751 if (EA->getUserDiagnostic() != NewUserDiagnostic) { 3752 Diag(CI.getLoc(), diag::warn_duplicate_attribute) << EA; 3753 Diag(EA->getLoc(), diag::note_previous_attribute); 3754 } 3755 D->dropAttr<ErrorAttr>(); 3756 } 3757 return ::new (Context) ErrorAttr(Context, CI, NewUserDiagnostic); 3758 } 3759 3760 FormatAttr *Sema::mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, 3761 IdentifierInfo *Format, int FormatIdx, 3762 int FirstArg) { 3763 // Check whether we already have an equivalent format attribute. 3764 for (auto *F : D->specific_attrs<FormatAttr>()) { 3765 if (F->getType() == Format && 3766 F->getFormatIdx() == FormatIdx && 3767 F->getFirstArg() == FirstArg) { 3768 // If we don't have a valid location for this attribute, adopt the 3769 // location. 3770 if (F->getLocation().isInvalid()) 3771 F->setRange(CI.getRange()); 3772 return nullptr; 3773 } 3774 } 3775 3776 return ::new (Context) FormatAttr(Context, CI, Format, FormatIdx, FirstArg); 3777 } 3778 3779 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on 3780 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 3781 static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3782 if (!AL.isArgIdent(0)) { 3783 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 3784 << AL << 1 << AANT_ArgumentIdentifier; 3785 return; 3786 } 3787 3788 // In C++ the implicit 'this' function parameter also counts, and they are 3789 // counted from one. 3790 bool HasImplicitThisParam = isInstanceMethod(D); 3791 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam; 3792 3793 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 3794 StringRef Format = II->getName(); 3795 3796 if (normalizeName(Format)) { 3797 // If we've modified the string name, we need a new identifier for it. 3798 II = &S.Context.Idents.get(Format); 3799 } 3800 3801 // Check for supported formats. 3802 FormatAttrKind Kind = getFormatAttrKind(Format); 3803 3804 if (Kind == IgnoredFormat) 3805 return; 3806 3807 if (Kind == InvalidFormat) { 3808 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) 3809 << AL << II->getName(); 3810 return; 3811 } 3812 3813 // checks for the 2nd argument 3814 Expr *IdxExpr = AL.getArgAsExpr(1); 3815 uint32_t Idx; 3816 if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2)) 3817 return; 3818 3819 if (Idx < 1 || Idx > NumArgs) { 3820 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 3821 << AL << 2 << IdxExpr->getSourceRange(); 3822 return; 3823 } 3824 3825 // FIXME: Do we need to bounds check? 3826 unsigned ArgIdx = Idx - 1; 3827 3828 if (HasImplicitThisParam) { 3829 if (ArgIdx == 0) { 3830 S.Diag(AL.getLoc(), 3831 diag::err_format_attribute_implicit_this_format_string) 3832 << IdxExpr->getSourceRange(); 3833 return; 3834 } 3835 ArgIdx--; 3836 } 3837 3838 // make sure the format string is really a string 3839 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx); 3840 3841 if (Kind == CFStringFormat) { 3842 if (!isCFStringType(Ty, S.Context)) { 3843 S.Diag(AL.getLoc(), diag::err_format_attribute_not) 3844 << "a CFString" << IdxExpr->getSourceRange() 3845 << getFunctionOrMethodParamRange(D, ArgIdx); 3846 return; 3847 } 3848 } else if (Kind == NSStringFormat) { 3849 // FIXME: do we need to check if the type is NSString*? What are the 3850 // semantics? 3851 if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true)) { 3852 S.Diag(AL.getLoc(), diag::err_format_attribute_not) 3853 << "an NSString" << IdxExpr->getSourceRange() 3854 << getFunctionOrMethodParamRange(D, ArgIdx); 3855 return; 3856 } 3857 } else if (!Ty->isPointerType() || 3858 !Ty->castAs<PointerType>()->getPointeeType()->isCharType()) { 3859 S.Diag(AL.getLoc(), diag::err_format_attribute_not) 3860 << "a string type" << IdxExpr->getSourceRange() 3861 << getFunctionOrMethodParamRange(D, ArgIdx); 3862 return; 3863 } 3864 3865 // check the 3rd argument 3866 Expr *FirstArgExpr = AL.getArgAsExpr(2); 3867 uint32_t FirstArg; 3868 if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3)) 3869 return; 3870 3871 // check if the function is variadic if the 3rd argument non-zero 3872 if (FirstArg != 0) { 3873 if (isFunctionOrMethodVariadic(D)) { 3874 ++NumArgs; // +1 for ... 3875 } else { 3876 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic); 3877 return; 3878 } 3879 } 3880 3881 // strftime requires FirstArg to be 0 because it doesn't read from any 3882 // variable the input is just the current time + the format string. 3883 if (Kind == StrftimeFormat) { 3884 if (FirstArg != 0) { 3885 S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter) 3886 << FirstArgExpr->getSourceRange(); 3887 return; 3888 } 3889 // if 0 it disables parameter checking (to use with e.g. va_list) 3890 } else if (FirstArg != 0 && FirstArg != NumArgs) { 3891 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 3892 << AL << 3 << FirstArgExpr->getSourceRange(); 3893 return; 3894 } 3895 3896 FormatAttr *NewAttr = S.mergeFormatAttr(D, AL, II, Idx, FirstArg); 3897 if (NewAttr) 3898 D->addAttr(NewAttr); 3899 } 3900 3901 /// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes. 3902 static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 3903 // The index that identifies the callback callee is mandatory. 3904 if (AL.getNumArgs() == 0) { 3905 S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee) 3906 << AL.getRange(); 3907 return; 3908 } 3909 3910 bool HasImplicitThisParam = isInstanceMethod(D); 3911 int32_t NumArgs = getFunctionOrMethodNumParams(D); 3912 3913 FunctionDecl *FD = D->getAsFunction(); 3914 assert(FD && "Expected a function declaration!"); 3915 3916 llvm::StringMap<int> NameIdxMapping; 3917 NameIdxMapping["__"] = -1; 3918 3919 NameIdxMapping["this"] = 0; 3920 3921 int Idx = 1; 3922 for (const ParmVarDecl *PVD : FD->parameters()) 3923 NameIdxMapping[PVD->getName()] = Idx++; 3924 3925 auto UnknownName = NameIdxMapping.end(); 3926 3927 SmallVector<int, 8> EncodingIndices; 3928 for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) { 3929 SourceRange SR; 3930 int32_t ArgIdx; 3931 3932 if (AL.isArgIdent(I)) { 3933 IdentifierLoc *IdLoc = AL.getArgAsIdent(I); 3934 auto It = NameIdxMapping.find(IdLoc->Ident->getName()); 3935 if (It == UnknownName) { 3936 S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown) 3937 << IdLoc->Ident << IdLoc->Loc; 3938 return; 3939 } 3940 3941 SR = SourceRange(IdLoc->Loc); 3942 ArgIdx = It->second; 3943 } else if (AL.isArgExpr(I)) { 3944 Expr *IdxExpr = AL.getArgAsExpr(I); 3945 3946 // If the expression is not parseable as an int32_t we have a problem. 3947 if (!checkUInt32Argument(S, AL, IdxExpr, (uint32_t &)ArgIdx, I + 1, 3948 false)) { 3949 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 3950 << AL << (I + 1) << IdxExpr->getSourceRange(); 3951 return; 3952 } 3953 3954 // Check oob, excluding the special values, 0 and -1. 3955 if (ArgIdx < -1 || ArgIdx > NumArgs) { 3956 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 3957 << AL << (I + 1) << IdxExpr->getSourceRange(); 3958 return; 3959 } 3960 3961 SR = IdxExpr->getSourceRange(); 3962 } else { 3963 llvm_unreachable("Unexpected ParsedAttr argument type!"); 3964 } 3965 3966 if (ArgIdx == 0 && !HasImplicitThisParam) { 3967 S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available) 3968 << (I + 1) << SR; 3969 return; 3970 } 3971 3972 // Adjust for the case we do not have an implicit "this" parameter. In this 3973 // case we decrease all positive values by 1 to get LLVM argument indices. 3974 if (!HasImplicitThisParam && ArgIdx > 0) 3975 ArgIdx -= 1; 3976 3977 EncodingIndices.push_back(ArgIdx); 3978 } 3979 3980 int CalleeIdx = EncodingIndices.front(); 3981 // Check if the callee index is proper, thus not "this" and not "unknown". 3982 // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam" 3983 // is false and positive if "HasImplicitThisParam" is true. 3984 if (CalleeIdx < (int)HasImplicitThisParam) { 3985 S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee) 3986 << AL.getRange(); 3987 return; 3988 } 3989 3990 // Get the callee type, note the index adjustment as the AST doesn't contain 3991 // the this type (which the callee cannot reference anyway!). 3992 const Type *CalleeType = 3993 getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam) 3994 .getTypePtr(); 3995 if (!CalleeType || !CalleeType->isFunctionPointerType()) { 3996 S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type) 3997 << AL.getRange(); 3998 return; 3999 } 4000 4001 const Type *CalleeFnType = 4002 CalleeType->getPointeeType()->getUnqualifiedDesugaredType(); 4003 4004 // TODO: Check the type of the callee arguments. 4005 4006 const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType); 4007 if (!CalleeFnProtoType) { 4008 S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type) 4009 << AL.getRange(); 4010 return; 4011 } 4012 4013 if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) { 4014 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) 4015 << AL << (unsigned)(EncodingIndices.size() - 1); 4016 return; 4017 } 4018 4019 if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) { 4020 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) 4021 << AL << (unsigned)(EncodingIndices.size() - 1); 4022 return; 4023 } 4024 4025 if (CalleeFnProtoType->isVariadic()) { 4026 S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange(); 4027 return; 4028 } 4029 4030 // Do not allow multiple callback attributes. 4031 if (D->hasAttr<CallbackAttr>()) { 4032 S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange(); 4033 return; 4034 } 4035 4036 D->addAttr(::new (S.Context) CallbackAttr( 4037 S.Context, AL, EncodingIndices.data(), EncodingIndices.size())); 4038 } 4039 4040 static bool isFunctionLike(const Type &T) { 4041 // Check for explicit function types. 4042 // 'called_once' is only supported in Objective-C and it has 4043 // function pointers and block pointers. 4044 return T.isFunctionPointerType() || T.isBlockPointerType(); 4045 } 4046 4047 /// Handle 'called_once' attribute. 4048 static void handleCalledOnceAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4049 // 'called_once' only applies to parameters representing functions. 4050 QualType T = cast<ParmVarDecl>(D)->getType(); 4051 4052 if (!isFunctionLike(*T)) { 4053 S.Diag(AL.getLoc(), diag::err_called_once_attribute_wrong_type); 4054 return; 4055 } 4056 4057 D->addAttr(::new (S.Context) CalledOnceAttr(S.Context, AL)); 4058 } 4059 4060 static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4061 // Try to find the underlying union declaration. 4062 RecordDecl *RD = nullptr; 4063 const auto *TD = dyn_cast<TypedefNameDecl>(D); 4064 if (TD && TD->getUnderlyingType()->isUnionType()) 4065 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl(); 4066 else 4067 RD = dyn_cast<RecordDecl>(D); 4068 4069 if (!RD || !RD->isUnion()) { 4070 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL 4071 << ExpectedUnion; 4072 return; 4073 } 4074 4075 if (!RD->isCompleteDefinition()) { 4076 if (!RD->isBeingDefined()) 4077 S.Diag(AL.getLoc(), 4078 diag::warn_transparent_union_attribute_not_definition); 4079 return; 4080 } 4081 4082 RecordDecl::field_iterator Field = RD->field_begin(), 4083 FieldEnd = RD->field_end(); 4084 if (Field == FieldEnd) { 4085 S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields); 4086 return; 4087 } 4088 4089 FieldDecl *FirstField = *Field; 4090 QualType FirstType = FirstField->getType(); 4091 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) { 4092 S.Diag(FirstField->getLocation(), 4093 diag::warn_transparent_union_attribute_floating) 4094 << FirstType->isVectorType() << FirstType; 4095 return; 4096 } 4097 4098 if (FirstType->isIncompleteType()) 4099 return; 4100 uint64_t FirstSize = S.Context.getTypeSize(FirstType); 4101 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType); 4102 for (; Field != FieldEnd; ++Field) { 4103 QualType FieldType = Field->getType(); 4104 if (FieldType->isIncompleteType()) 4105 return; 4106 // FIXME: this isn't fully correct; we also need to test whether the 4107 // members of the union would all have the same calling convention as the 4108 // first member of the union. Checking just the size and alignment isn't 4109 // sufficient (consider structs passed on the stack instead of in registers 4110 // as an example). 4111 if (S.Context.getTypeSize(FieldType) != FirstSize || 4112 S.Context.getTypeAlign(FieldType) > FirstAlign) { 4113 // Warn if we drop the attribute. 4114 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize; 4115 unsigned FieldBits = isSize ? S.Context.getTypeSize(FieldType) 4116 : S.Context.getTypeAlign(FieldType); 4117 S.Diag(Field->getLocation(), 4118 diag::warn_transparent_union_attribute_field_size_align) 4119 << isSize << *Field << FieldBits; 4120 unsigned FirstBits = isSize ? FirstSize : FirstAlign; 4121 S.Diag(FirstField->getLocation(), 4122 diag::note_transparent_union_first_field_size_align) 4123 << isSize << FirstBits; 4124 return; 4125 } 4126 } 4127 4128 RD->addAttr(::new (S.Context) TransparentUnionAttr(S.Context, AL)); 4129 } 4130 4131 void Sema::AddAnnotationAttr(Decl *D, const AttributeCommonInfo &CI, 4132 StringRef Str, MutableArrayRef<Expr *> Args) { 4133 auto *Attr = AnnotateAttr::Create(Context, Str, Args.data(), Args.size(), CI); 4134 llvm::SmallVector<PartialDiagnosticAt, 8> Notes; 4135 for (unsigned Idx = 0; Idx < Attr->args_size(); Idx++) { 4136 Expr *&E = Attr->args_begin()[Idx]; 4137 assert(E && "error are handled before"); 4138 if (E->isValueDependent() || E->isTypeDependent()) 4139 continue; 4140 4141 if (E->getType()->isArrayType()) 4142 E = ImpCastExprToType(E, Context.getPointerType(E->getType()), 4143 clang::CK_ArrayToPointerDecay) 4144 .get(); 4145 if (E->getType()->isFunctionType()) 4146 E = ImplicitCastExpr::Create(Context, 4147 Context.getPointerType(E->getType()), 4148 clang::CK_FunctionToPointerDecay, E, nullptr, 4149 VK_PRValue, FPOptionsOverride()); 4150 if (E->isLValue()) 4151 E = ImplicitCastExpr::Create(Context, E->getType().getNonReferenceType(), 4152 clang::CK_LValueToRValue, E, nullptr, 4153 VK_PRValue, FPOptionsOverride()); 4154 4155 Expr::EvalResult Eval; 4156 Notes.clear(); 4157 Eval.Diag = &Notes; 4158 4159 bool Result = 4160 E->EvaluateAsConstantExpr(Eval, Context); 4161 4162 /// Result means the expression can be folded to a constant. 4163 /// Note.empty() means the expression is a valid constant expression in the 4164 /// current language mode. 4165 if (!Result || !Notes.empty()) { 4166 Diag(E->getBeginLoc(), diag::err_attribute_argument_n_type) 4167 << CI << (Idx + 1) << AANT_ArgumentConstantExpr; 4168 for (auto &Note : Notes) 4169 Diag(Note.first, Note.second); 4170 return; 4171 } 4172 assert(Eval.Val.hasValue()); 4173 E = ConstantExpr::Create(Context, E, Eval.Val); 4174 } 4175 D->addAttr(Attr); 4176 } 4177 4178 static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4179 // Make sure that there is a string literal as the annotation's first 4180 // argument. 4181 StringRef Str; 4182 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str)) 4183 return; 4184 4185 llvm::SmallVector<Expr *, 4> Args; 4186 Args.reserve(AL.getNumArgs() - 1); 4187 for (unsigned Idx = 1; Idx < AL.getNumArgs(); Idx++) { 4188 assert(!AL.isArgIdent(Idx)); 4189 Args.push_back(AL.getArgAsExpr(Idx)); 4190 } 4191 4192 S.AddAnnotationAttr(D, AL, Str, Args); 4193 } 4194 4195 static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4196 S.AddAlignValueAttr(D, AL, AL.getArgAsExpr(0)); 4197 } 4198 4199 void Sema::AddAlignValueAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E) { 4200 AlignValueAttr TmpAttr(Context, CI, E); 4201 SourceLocation AttrLoc = CI.getLoc(); 4202 4203 QualType T; 4204 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) 4205 T = TD->getUnderlyingType(); 4206 else if (const auto *VD = dyn_cast<ValueDecl>(D)) 4207 T = VD->getType(); 4208 else 4209 llvm_unreachable("Unknown decl type for align_value"); 4210 4211 if (!T->isDependentType() && !T->isAnyPointerType() && 4212 !T->isReferenceType() && !T->isMemberPointerType()) { 4213 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only) 4214 << &TmpAttr << T << D->getSourceRange(); 4215 return; 4216 } 4217 4218 if (!E->isValueDependent()) { 4219 llvm::APSInt Alignment; 4220 ExprResult ICE = VerifyIntegerConstantExpression( 4221 E, &Alignment, diag::err_align_value_attribute_argument_not_int); 4222 if (ICE.isInvalid()) 4223 return; 4224 4225 if (!Alignment.isPowerOf2()) { 4226 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 4227 << E->getSourceRange(); 4228 return; 4229 } 4230 4231 D->addAttr(::new (Context) AlignValueAttr(Context, CI, ICE.get())); 4232 return; 4233 } 4234 4235 // Save dependent expressions in the AST to be instantiated. 4236 D->addAttr(::new (Context) AlignValueAttr(Context, CI, E)); 4237 } 4238 4239 static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4240 // check the attribute arguments. 4241 if (AL.getNumArgs() > 1) { 4242 S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1; 4243 return; 4244 } 4245 4246 if (AL.getNumArgs() == 0) { 4247 D->addAttr(::new (S.Context) AlignedAttr(S.Context, AL, true, nullptr)); 4248 return; 4249 } 4250 4251 Expr *E = AL.getArgAsExpr(0); 4252 if (AL.isPackExpansion() && !E->containsUnexpandedParameterPack()) { 4253 S.Diag(AL.getEllipsisLoc(), 4254 diag::err_pack_expansion_without_parameter_packs); 4255 return; 4256 } 4257 4258 if (!AL.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E)) 4259 return; 4260 4261 S.AddAlignedAttr(D, AL, E, AL.isPackExpansion()); 4262 } 4263 4264 void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, Expr *E, 4265 bool IsPackExpansion) { 4266 AlignedAttr TmpAttr(Context, CI, true, E); 4267 SourceLocation AttrLoc = CI.getLoc(); 4268 4269 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements. 4270 if (TmpAttr.isAlignas()) { 4271 // C++11 [dcl.align]p1: 4272 // An alignment-specifier may be applied to a variable or to a class 4273 // data member, but it shall not be applied to a bit-field, a function 4274 // parameter, the formal parameter of a catch clause, or a variable 4275 // declared with the register storage class specifier. An 4276 // alignment-specifier may also be applied to the declaration of a class 4277 // or enumeration type. 4278 // C11 6.7.5/2: 4279 // An alignment attribute shall not be specified in a declaration of 4280 // a typedef, or a bit-field, or a function, or a parameter, or an 4281 // object declared with the register storage-class specifier. 4282 int DiagKind = -1; 4283 if (isa<ParmVarDecl>(D)) { 4284 DiagKind = 0; 4285 } else if (const auto *VD = dyn_cast<VarDecl>(D)) { 4286 if (VD->getStorageClass() == SC_Register) 4287 DiagKind = 1; 4288 if (VD->isExceptionVariable()) 4289 DiagKind = 2; 4290 } else if (const auto *FD = dyn_cast<FieldDecl>(D)) { 4291 if (FD->isBitField()) 4292 DiagKind = 3; 4293 } else if (!isa<TagDecl>(D)) { 4294 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr 4295 << (TmpAttr.isC11() ? ExpectedVariableOrField 4296 : ExpectedVariableFieldOrTag); 4297 return; 4298 } 4299 if (DiagKind != -1) { 4300 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type) 4301 << &TmpAttr << DiagKind; 4302 return; 4303 } 4304 } 4305 4306 if (E->isValueDependent()) { 4307 // We can't support a dependent alignment on a non-dependent type, 4308 // because we have no way to model that a type is "alignment-dependent" 4309 // but not dependent in any other way. 4310 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) { 4311 if (!TND->getUnderlyingType()->isDependentType()) { 4312 Diag(AttrLoc, diag::err_alignment_dependent_typedef_name) 4313 << E->getSourceRange(); 4314 return; 4315 } 4316 } 4317 4318 // Save dependent expressions in the AST to be instantiated. 4319 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, E); 4320 AA->setPackExpansion(IsPackExpansion); 4321 D->addAttr(AA); 4322 return; 4323 } 4324 4325 // FIXME: Cache the number on the AL object? 4326 llvm::APSInt Alignment; 4327 ExprResult ICE = VerifyIntegerConstantExpression( 4328 E, &Alignment, diag::err_aligned_attribute_argument_not_int); 4329 if (ICE.isInvalid()) 4330 return; 4331 4332 uint64_t AlignVal = Alignment.getZExtValue(); 4333 // 16 byte ByVal alignment not due to a vector member is not honoured by XL 4334 // on AIX. Emit a warning here that users are generating binary incompatible 4335 // code to be safe. 4336 if (AlignVal >= 16 && isa<FieldDecl>(D) && 4337 Context.getTargetInfo().getTriple().isOSAIX()) 4338 Diag(AttrLoc, diag::warn_not_xl_compatible) << E->getSourceRange(); 4339 4340 // C++11 [dcl.align]p2: 4341 // -- if the constant expression evaluates to zero, the alignment 4342 // specifier shall have no effect 4343 // C11 6.7.5p6: 4344 // An alignment specification of zero has no effect. 4345 if (!(TmpAttr.isAlignas() && !Alignment)) { 4346 if (!llvm::isPowerOf2_64(AlignVal)) { 4347 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 4348 << E->getSourceRange(); 4349 return; 4350 } 4351 } 4352 4353 uint64_t MaximumAlignment = Sema::MaximumAlignment; 4354 if (Context.getTargetInfo().getTriple().isOSBinFormatCOFF()) 4355 MaximumAlignment = std::min(MaximumAlignment, uint64_t(8192)); 4356 if (AlignVal > MaximumAlignment) { 4357 Diag(AttrLoc, diag::err_attribute_aligned_too_great) 4358 << MaximumAlignment << E->getSourceRange(); 4359 return; 4360 } 4361 4362 const auto *VD = dyn_cast<VarDecl>(D); 4363 if (VD && Context.getTargetInfo().isTLSSupported()) { 4364 unsigned MaxTLSAlign = 4365 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign()) 4366 .getQuantity(); 4367 if (MaxTLSAlign && AlignVal > MaxTLSAlign && 4368 VD->getTLSKind() != VarDecl::TLS_None) { 4369 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 4370 << (unsigned)AlignVal << VD << MaxTLSAlign; 4371 return; 4372 } 4373 } 4374 4375 // On AIX, an aligned attribute can not decrease the alignment when applied 4376 // to a variable declaration with vector type. 4377 if (VD && Context.getTargetInfo().getTriple().isOSAIX()) { 4378 const Type *Ty = VD->getType().getTypePtr(); 4379 if (Ty->isVectorType() && AlignVal < 16) { 4380 Diag(VD->getLocation(), diag::warn_aligned_attr_underaligned) 4381 << VD->getType() << 16; 4382 return; 4383 } 4384 } 4385 4386 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, ICE.get()); 4387 AA->setPackExpansion(IsPackExpansion); 4388 D->addAttr(AA); 4389 } 4390 4391 void Sema::AddAlignedAttr(Decl *D, const AttributeCommonInfo &CI, 4392 TypeSourceInfo *TS, bool IsPackExpansion) { 4393 // FIXME: Cache the number on the AL object if non-dependent? 4394 // FIXME: Perform checking of type validity 4395 AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS); 4396 AA->setPackExpansion(IsPackExpansion); 4397 D->addAttr(AA); 4398 } 4399 4400 void Sema::CheckAlignasUnderalignment(Decl *D) { 4401 assert(D->hasAttrs() && "no attributes on decl"); 4402 4403 QualType UnderlyingTy, DiagTy; 4404 if (const auto *VD = dyn_cast<ValueDecl>(D)) { 4405 UnderlyingTy = DiagTy = VD->getType(); 4406 } else { 4407 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D)); 4408 if (const auto *ED = dyn_cast<EnumDecl>(D)) 4409 UnderlyingTy = ED->getIntegerType(); 4410 } 4411 if (DiagTy->isDependentType() || DiagTy->isIncompleteType()) 4412 return; 4413 4414 // C++11 [dcl.align]p5, C11 6.7.5/4: 4415 // The combined effect of all alignment attributes in a declaration shall 4416 // not specify an alignment that is less strict than the alignment that 4417 // would otherwise be required for the entity being declared. 4418 AlignedAttr *AlignasAttr = nullptr; 4419 AlignedAttr *LastAlignedAttr = nullptr; 4420 unsigned Align = 0; 4421 for (auto *I : D->specific_attrs<AlignedAttr>()) { 4422 if (I->isAlignmentDependent()) 4423 return; 4424 if (I->isAlignas()) 4425 AlignasAttr = I; 4426 Align = std::max(Align, I->getAlignment(Context)); 4427 LastAlignedAttr = I; 4428 } 4429 4430 if (Align && DiagTy->isSizelessType()) { 4431 Diag(LastAlignedAttr->getLocation(), diag::err_attribute_sizeless_type) 4432 << LastAlignedAttr << DiagTy; 4433 } else if (AlignasAttr && Align) { 4434 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align); 4435 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy); 4436 if (NaturalAlign > RequestedAlign) 4437 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned) 4438 << DiagTy << (unsigned)NaturalAlign.getQuantity(); 4439 } 4440 } 4441 4442 bool Sema::checkMSInheritanceAttrOnDefinition( 4443 CXXRecordDecl *RD, SourceRange Range, bool BestCase, 4444 MSInheritanceModel ExplicitModel) { 4445 assert(RD->hasDefinition() && "RD has no definition!"); 4446 4447 // We may not have seen base specifiers or any virtual methods yet. We will 4448 // have to wait until the record is defined to catch any mismatches. 4449 if (!RD->getDefinition()->isCompleteDefinition()) 4450 return false; 4451 4452 // The unspecified model never matches what a definition could need. 4453 if (ExplicitModel == MSInheritanceModel::Unspecified) 4454 return false; 4455 4456 if (BestCase) { 4457 if (RD->calculateInheritanceModel() == ExplicitModel) 4458 return false; 4459 } else { 4460 if (RD->calculateInheritanceModel() <= ExplicitModel) 4461 return false; 4462 } 4463 4464 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance) 4465 << 0 /*definition*/; 4466 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) << RD; 4467 return true; 4468 } 4469 4470 /// parseModeAttrArg - Parses attribute mode string and returns parsed type 4471 /// attribute. 4472 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth, 4473 bool &IntegerMode, bool &ComplexMode, 4474 FloatModeKind &ExplicitType) { 4475 IntegerMode = true; 4476 ComplexMode = false; 4477 ExplicitType = FloatModeKind::NoFloat; 4478 switch (Str.size()) { 4479 case 2: 4480 switch (Str[0]) { 4481 case 'Q': 4482 DestWidth = 8; 4483 break; 4484 case 'H': 4485 DestWidth = 16; 4486 break; 4487 case 'S': 4488 DestWidth = 32; 4489 break; 4490 case 'D': 4491 DestWidth = 64; 4492 break; 4493 case 'X': 4494 DestWidth = 96; 4495 break; 4496 case 'K': // KFmode - IEEE quad precision (__float128) 4497 ExplicitType = FloatModeKind::Float128; 4498 DestWidth = Str[1] == 'I' ? 0 : 128; 4499 break; 4500 case 'T': 4501 ExplicitType = FloatModeKind::LongDouble; 4502 DestWidth = 128; 4503 break; 4504 case 'I': 4505 ExplicitType = FloatModeKind::Ibm128; 4506 DestWidth = Str[1] == 'I' ? 0 : 128; 4507 break; 4508 } 4509 if (Str[1] == 'F') { 4510 IntegerMode = false; 4511 } else if (Str[1] == 'C') { 4512 IntegerMode = false; 4513 ComplexMode = true; 4514 } else if (Str[1] != 'I') { 4515 DestWidth = 0; 4516 } 4517 break; 4518 case 4: 4519 // FIXME: glibc uses 'word' to define register_t; this is narrower than a 4520 // pointer on PIC16 and other embedded platforms. 4521 if (Str == "word") 4522 DestWidth = S.Context.getTargetInfo().getRegisterWidth(); 4523 else if (Str == "byte") 4524 DestWidth = S.Context.getTargetInfo().getCharWidth(); 4525 break; 4526 case 7: 4527 if (Str == "pointer") 4528 DestWidth = S.Context.getTargetInfo().getPointerWidth(0); 4529 break; 4530 case 11: 4531 if (Str == "unwind_word") 4532 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth(); 4533 break; 4534 } 4535 } 4536 4537 /// handleModeAttr - This attribute modifies the width of a decl with primitive 4538 /// type. 4539 /// 4540 /// Despite what would be logical, the mode attribute is a decl attribute, not a 4541 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be 4542 /// HImode, not an intermediate pointer. 4543 static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4544 // This attribute isn't documented, but glibc uses it. It changes 4545 // the width of an int or unsigned int to the specified size. 4546 if (!AL.isArgIdent(0)) { 4547 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 4548 << AL << AANT_ArgumentIdentifier; 4549 return; 4550 } 4551 4552 IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident; 4553 4554 S.AddModeAttr(D, AL, Name); 4555 } 4556 4557 void Sema::AddModeAttr(Decl *D, const AttributeCommonInfo &CI, 4558 IdentifierInfo *Name, bool InInstantiation) { 4559 StringRef Str = Name->getName(); 4560 normalizeName(Str); 4561 SourceLocation AttrLoc = CI.getLoc(); 4562 4563 unsigned DestWidth = 0; 4564 bool IntegerMode = true; 4565 bool ComplexMode = false; 4566 FloatModeKind ExplicitType = FloatModeKind::NoFloat; 4567 llvm::APInt VectorSize(64, 0); 4568 if (Str.size() >= 4 && Str[0] == 'V') { 4569 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2). 4570 size_t StrSize = Str.size(); 4571 size_t VectorStringLength = 0; 4572 while ((VectorStringLength + 1) < StrSize && 4573 isdigit(Str[VectorStringLength + 1])) 4574 ++VectorStringLength; 4575 if (VectorStringLength && 4576 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) && 4577 VectorSize.isPowerOf2()) { 4578 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth, 4579 IntegerMode, ComplexMode, ExplicitType); 4580 // Avoid duplicate warning from template instantiation. 4581 if (!InInstantiation) 4582 Diag(AttrLoc, diag::warn_vector_mode_deprecated); 4583 } else { 4584 VectorSize = 0; 4585 } 4586 } 4587 4588 if (!VectorSize) 4589 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode, 4590 ExplicitType); 4591 4592 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t 4593 // and friends, at least with glibc. 4594 // FIXME: Make sure floating-point mappings are accurate 4595 // FIXME: Support XF and TF types 4596 if (!DestWidth) { 4597 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name; 4598 return; 4599 } 4600 4601 QualType OldTy; 4602 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) 4603 OldTy = TD->getUnderlyingType(); 4604 else if (const auto *ED = dyn_cast<EnumDecl>(D)) { 4605 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'. 4606 // Try to get type from enum declaration, default to int. 4607 OldTy = ED->getIntegerType(); 4608 if (OldTy.isNull()) 4609 OldTy = Context.IntTy; 4610 } else 4611 OldTy = cast<ValueDecl>(D)->getType(); 4612 4613 if (OldTy->isDependentType()) { 4614 D->addAttr(::new (Context) ModeAttr(Context, CI, Name)); 4615 return; 4616 } 4617 4618 // Base type can also be a vector type (see PR17453). 4619 // Distinguish between base type and base element type. 4620 QualType OldElemTy = OldTy; 4621 if (const auto *VT = OldTy->getAs<VectorType>()) 4622 OldElemTy = VT->getElementType(); 4623 4624 // GCC allows 'mode' attribute on enumeration types (even incomplete), except 4625 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete 4626 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected. 4627 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) && 4628 VectorSize.getBoolValue()) { 4629 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << CI.getRange(); 4630 return; 4631 } 4632 bool IntegralOrAnyEnumType = (OldElemTy->isIntegralOrEnumerationType() && 4633 !OldElemTy->isBitIntType()) || 4634 OldElemTy->getAs<EnumType>(); 4635 4636 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() && 4637 !IntegralOrAnyEnumType) 4638 Diag(AttrLoc, diag::err_mode_not_primitive); 4639 else if (IntegerMode) { 4640 if (!IntegralOrAnyEnumType) 4641 Diag(AttrLoc, diag::err_mode_wrong_type); 4642 } else if (ComplexMode) { 4643 if (!OldElemTy->isComplexType()) 4644 Diag(AttrLoc, diag::err_mode_wrong_type); 4645 } else { 4646 if (!OldElemTy->isFloatingType()) 4647 Diag(AttrLoc, diag::err_mode_wrong_type); 4648 } 4649 4650 QualType NewElemTy; 4651 4652 if (IntegerMode) 4653 NewElemTy = Context.getIntTypeForBitwidth(DestWidth, 4654 OldElemTy->isSignedIntegerType()); 4655 else 4656 NewElemTy = Context.getRealTypeForBitwidth(DestWidth, ExplicitType); 4657 4658 if (NewElemTy.isNull()) { 4659 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name; 4660 return; 4661 } 4662 4663 if (ComplexMode) { 4664 NewElemTy = Context.getComplexType(NewElemTy); 4665 } 4666 4667 QualType NewTy = NewElemTy; 4668 if (VectorSize.getBoolValue()) { 4669 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(), 4670 VectorType::GenericVector); 4671 } else if (const auto *OldVT = OldTy->getAs<VectorType>()) { 4672 // Complex machine mode does not support base vector types. 4673 if (ComplexMode) { 4674 Diag(AttrLoc, diag::err_complex_mode_vector_type); 4675 return; 4676 } 4677 unsigned NumElements = Context.getTypeSize(OldElemTy) * 4678 OldVT->getNumElements() / 4679 Context.getTypeSize(NewElemTy); 4680 NewTy = 4681 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind()); 4682 } 4683 4684 if (NewTy.isNull()) { 4685 Diag(AttrLoc, diag::err_mode_wrong_type); 4686 return; 4687 } 4688 4689 // Install the new type. 4690 if (auto *TD = dyn_cast<TypedefNameDecl>(D)) 4691 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy); 4692 else if (auto *ED = dyn_cast<EnumDecl>(D)) 4693 ED->setIntegerType(NewTy); 4694 else 4695 cast<ValueDecl>(D)->setType(NewTy); 4696 4697 D->addAttr(::new (Context) ModeAttr(Context, CI, Name)); 4698 } 4699 4700 static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4701 D->addAttr(::new (S.Context) NoDebugAttr(S.Context, AL)); 4702 } 4703 4704 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, 4705 const AttributeCommonInfo &CI, 4706 const IdentifierInfo *Ident) { 4707 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) { 4708 Diag(CI.getLoc(), diag::warn_attribute_ignored) << Ident; 4709 Diag(Optnone->getLocation(), diag::note_conflicting_attribute); 4710 return nullptr; 4711 } 4712 4713 if (D->hasAttr<AlwaysInlineAttr>()) 4714 return nullptr; 4715 4716 return ::new (Context) AlwaysInlineAttr(Context, CI); 4717 } 4718 4719 InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D, 4720 const ParsedAttr &AL) { 4721 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4722 // Attribute applies to Var but not any subclass of it (like ParmVar, 4723 // ImplicitParm or VarTemplateSpecialization). 4724 if (VD->getKind() != Decl::Var) { 4725 Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 4726 << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass 4727 : ExpectedVariableOrFunction); 4728 return nullptr; 4729 } 4730 // Attribute does not apply to non-static local variables. 4731 if (VD->hasLocalStorage()) { 4732 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage); 4733 return nullptr; 4734 } 4735 } 4736 4737 return ::new (Context) InternalLinkageAttr(Context, AL); 4738 } 4739 InternalLinkageAttr * 4740 Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) { 4741 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4742 // Attribute applies to Var but not any subclass of it (like ParmVar, 4743 // ImplicitParm or VarTemplateSpecialization). 4744 if (VD->getKind() != Decl::Var) { 4745 Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type) 4746 << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass 4747 : ExpectedVariableOrFunction); 4748 return nullptr; 4749 } 4750 // Attribute does not apply to non-static local variables. 4751 if (VD->hasLocalStorage()) { 4752 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage); 4753 return nullptr; 4754 } 4755 } 4756 4757 return ::new (Context) InternalLinkageAttr(Context, AL); 4758 } 4759 4760 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI) { 4761 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) { 4762 Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'minsize'"; 4763 Diag(Optnone->getLocation(), diag::note_conflicting_attribute); 4764 return nullptr; 4765 } 4766 4767 if (D->hasAttr<MinSizeAttr>()) 4768 return nullptr; 4769 4770 return ::new (Context) MinSizeAttr(Context, CI); 4771 } 4772 4773 SwiftNameAttr *Sema::mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, 4774 StringRef Name) { 4775 if (const auto *PrevSNA = D->getAttr<SwiftNameAttr>()) { 4776 if (PrevSNA->getName() != Name && !PrevSNA->isImplicit()) { 4777 Diag(PrevSNA->getLocation(), diag::err_attributes_are_not_compatible) 4778 << PrevSNA << &SNA; 4779 Diag(SNA.getLoc(), diag::note_conflicting_attribute); 4780 } 4781 4782 D->dropAttr<SwiftNameAttr>(); 4783 } 4784 return ::new (Context) SwiftNameAttr(Context, SNA, Name); 4785 } 4786 4787 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, 4788 const AttributeCommonInfo &CI) { 4789 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) { 4790 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline; 4791 Diag(CI.getLoc(), diag::note_conflicting_attribute); 4792 D->dropAttr<AlwaysInlineAttr>(); 4793 } 4794 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) { 4795 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize; 4796 Diag(CI.getLoc(), diag::note_conflicting_attribute); 4797 D->dropAttr<MinSizeAttr>(); 4798 } 4799 4800 if (D->hasAttr<OptimizeNoneAttr>()) 4801 return nullptr; 4802 4803 return ::new (Context) OptimizeNoneAttr(Context, CI); 4804 } 4805 4806 static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4807 if (AlwaysInlineAttr *Inline = 4808 S.mergeAlwaysInlineAttr(D, AL, AL.getAttrName())) 4809 D->addAttr(Inline); 4810 } 4811 4812 static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4813 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(D, AL)) 4814 D->addAttr(MinSize); 4815 } 4816 4817 static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4818 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(D, AL)) 4819 D->addAttr(Optnone); 4820 } 4821 4822 static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4823 const auto *VD = cast<VarDecl>(D); 4824 if (VD->hasLocalStorage()) { 4825 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev); 4826 return; 4827 } 4828 // constexpr variable may already get an implicit constant attr, which should 4829 // be replaced by the explicit constant attr. 4830 if (auto *A = D->getAttr<CUDAConstantAttr>()) { 4831 if (!A->isImplicit()) 4832 return; 4833 D->dropAttr<CUDAConstantAttr>(); 4834 } 4835 D->addAttr(::new (S.Context) CUDAConstantAttr(S.Context, AL)); 4836 } 4837 4838 static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4839 const auto *VD = cast<VarDecl>(D); 4840 // extern __shared__ is only allowed on arrays with no length (e.g. 4841 // "int x[]"). 4842 if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() && 4843 !isa<IncompleteArrayType>(VD->getType())) { 4844 S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD; 4845 return; 4846 } 4847 if (S.getLangOpts().CUDA && VD->hasLocalStorage() && 4848 S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared) 4849 << S.CurrentCUDATarget()) 4850 return; 4851 D->addAttr(::new (S.Context) CUDASharedAttr(S.Context, AL)); 4852 } 4853 4854 static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4855 const auto *FD = cast<FunctionDecl>(D); 4856 if (!FD->getReturnType()->isVoidType() && 4857 !FD->getReturnType()->getAs<AutoType>() && 4858 !FD->getReturnType()->isInstantiationDependentType()) { 4859 SourceRange RTRange = FD->getReturnTypeSourceRange(); 4860 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return) 4861 << FD->getType() 4862 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 4863 : FixItHint()); 4864 return; 4865 } 4866 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) { 4867 if (Method->isInstance()) { 4868 S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method) 4869 << Method; 4870 return; 4871 } 4872 S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method; 4873 } 4874 // Only warn for "inline" when compiling for host, to cut down on noise. 4875 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice) 4876 S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD; 4877 4878 D->addAttr(::new (S.Context) CUDAGlobalAttr(S.Context, AL)); 4879 // In host compilation the kernel is emitted as a stub function, which is 4880 // a helper function for launching the kernel. The instructions in the helper 4881 // function has nothing to do with the source code of the kernel. Do not emit 4882 // debug info for the stub function to avoid confusing the debugger. 4883 if (S.LangOpts.HIP && !S.LangOpts.CUDAIsDevice) 4884 D->addAttr(NoDebugAttr::CreateImplicit(S.Context)); 4885 } 4886 4887 static void handleDeviceAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4888 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4889 if (VD->hasLocalStorage()) { 4890 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev); 4891 return; 4892 } 4893 } 4894 4895 if (auto *A = D->getAttr<CUDADeviceAttr>()) { 4896 if (!A->isImplicit()) 4897 return; 4898 D->dropAttr<CUDADeviceAttr>(); 4899 } 4900 D->addAttr(::new (S.Context) CUDADeviceAttr(S.Context, AL)); 4901 } 4902 4903 static void handleManagedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4904 if (const auto *VD = dyn_cast<VarDecl>(D)) { 4905 if (VD->hasLocalStorage()) { 4906 S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev); 4907 return; 4908 } 4909 } 4910 if (!D->hasAttr<HIPManagedAttr>()) 4911 D->addAttr(::new (S.Context) HIPManagedAttr(S.Context, AL)); 4912 if (!D->hasAttr<CUDADeviceAttr>()) 4913 D->addAttr(CUDADeviceAttr::CreateImplicit(S.Context)); 4914 } 4915 4916 static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4917 const auto *Fn = cast<FunctionDecl>(D); 4918 if (!Fn->isInlineSpecified()) { 4919 S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline); 4920 return; 4921 } 4922 4923 if (S.LangOpts.CPlusPlus && Fn->getStorageClass() != SC_Extern) 4924 S.Diag(AL.getLoc(), diag::warn_gnu_inline_cplusplus_without_extern); 4925 4926 D->addAttr(::new (S.Context) GNUInlineAttr(S.Context, AL)); 4927 } 4928 4929 static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 4930 if (hasDeclarator(D)) return; 4931 4932 // Diagnostic is emitted elsewhere: here we store the (valid) AL 4933 // in the Decl node for syntactic reasoning, e.g., pretty-printing. 4934 CallingConv CC; 4935 if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr)) 4936 return; 4937 4938 if (!isa<ObjCMethodDecl>(D)) { 4939 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 4940 << AL << ExpectedFunctionOrMethod; 4941 return; 4942 } 4943 4944 switch (AL.getKind()) { 4945 case ParsedAttr::AT_FastCall: 4946 D->addAttr(::new (S.Context) FastCallAttr(S.Context, AL)); 4947 return; 4948 case ParsedAttr::AT_StdCall: 4949 D->addAttr(::new (S.Context) StdCallAttr(S.Context, AL)); 4950 return; 4951 case ParsedAttr::AT_ThisCall: 4952 D->addAttr(::new (S.Context) ThisCallAttr(S.Context, AL)); 4953 return; 4954 case ParsedAttr::AT_CDecl: 4955 D->addAttr(::new (S.Context) CDeclAttr(S.Context, AL)); 4956 return; 4957 case ParsedAttr::AT_Pascal: 4958 D->addAttr(::new (S.Context) PascalAttr(S.Context, AL)); 4959 return; 4960 case ParsedAttr::AT_SwiftCall: 4961 D->addAttr(::new (S.Context) SwiftCallAttr(S.Context, AL)); 4962 return; 4963 case ParsedAttr::AT_SwiftAsyncCall: 4964 D->addAttr(::new (S.Context) SwiftAsyncCallAttr(S.Context, AL)); 4965 return; 4966 case ParsedAttr::AT_VectorCall: 4967 D->addAttr(::new (S.Context) VectorCallAttr(S.Context, AL)); 4968 return; 4969 case ParsedAttr::AT_MSABI: 4970 D->addAttr(::new (S.Context) MSABIAttr(S.Context, AL)); 4971 return; 4972 case ParsedAttr::AT_SysVABI: 4973 D->addAttr(::new (S.Context) SysVABIAttr(S.Context, AL)); 4974 return; 4975 case ParsedAttr::AT_RegCall: 4976 D->addAttr(::new (S.Context) RegCallAttr(S.Context, AL)); 4977 return; 4978 case ParsedAttr::AT_Pcs: { 4979 PcsAttr::PCSType PCS; 4980 switch (CC) { 4981 case CC_AAPCS: 4982 PCS = PcsAttr::AAPCS; 4983 break; 4984 case CC_AAPCS_VFP: 4985 PCS = PcsAttr::AAPCS_VFP; 4986 break; 4987 default: 4988 llvm_unreachable("unexpected calling convention in pcs attribute"); 4989 } 4990 4991 D->addAttr(::new (S.Context) PcsAttr(S.Context, AL, PCS)); 4992 return; 4993 } 4994 case ParsedAttr::AT_AArch64VectorPcs: 4995 D->addAttr(::new (S.Context) AArch64VectorPcsAttr(S.Context, AL)); 4996 return; 4997 case ParsedAttr::AT_IntelOclBicc: 4998 D->addAttr(::new (S.Context) IntelOclBiccAttr(S.Context, AL)); 4999 return; 5000 case ParsedAttr::AT_PreserveMost: 5001 D->addAttr(::new (S.Context) PreserveMostAttr(S.Context, AL)); 5002 return; 5003 case ParsedAttr::AT_PreserveAll: 5004 D->addAttr(::new (S.Context) PreserveAllAttr(S.Context, AL)); 5005 return; 5006 default: 5007 llvm_unreachable("unexpected attribute kind"); 5008 } 5009 } 5010 5011 static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 5012 if (!AL.checkAtLeastNumArgs(S, 1)) 5013 return; 5014 5015 std::vector<StringRef> DiagnosticIdentifiers; 5016 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) { 5017 StringRef RuleName; 5018 5019 if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr)) 5020 return; 5021 5022 // FIXME: Warn if the rule name is unknown. This is tricky because only 5023 // clang-tidy knows about available rules. 5024 DiagnosticIdentifiers.push_back(RuleName); 5025 } 5026 D->addAttr(::new (S.Context) 5027 SuppressAttr(S.Context, AL, DiagnosticIdentifiers.data(), 5028 DiagnosticIdentifiers.size())); 5029 } 5030 5031 static void handleLifetimeCategoryAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 5032 TypeSourceInfo *DerefTypeLoc = nullptr; 5033 QualType ParmType; 5034 if (AL.hasParsedType()) { 5035 ParmType = S.GetTypeFromParser(AL.getTypeArg(), &DerefTypeLoc); 5036 5037 unsigned SelectIdx = ~0U; 5038 if (ParmType->isReferenceType()) 5039 SelectIdx = 0; 5040 else if (ParmType->isArrayType()) 5041 SelectIdx = 1; 5042 5043 if (SelectIdx != ~0U) { 5044 S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) 5045 << SelectIdx << AL; 5046 return; 5047 } 5048 } 5049 5050 // To check if earlier decl attributes do not conflict the newly parsed ones 5051 // we always add (and check) the attribute to the canonical decl. We need 5052 // to repeat the check for attribute mutual exclusion because we're attaching 5053 // all of the attributes to the canonical declaration rather than the current 5054 // declaration. 5055 D = D->getCanonicalDecl(); 5056 if (AL.getKind() == ParsedAttr::AT_Owner) { 5057 if (checkAttrMutualExclusion<PointerAttr>(S, D, AL)) 5058 return; 5059 if (const auto *OAttr = D->getAttr<OwnerAttr>()) { 5060 const Type *ExistingDerefType = OAttr->getDerefTypeLoc() 5061 ? OAttr->getDerefType().getTypePtr() 5062 : nullptr; 5063 if (ExistingDerefType != ParmType.getTypePtrOrNull()) { 5064 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) 5065 << AL << OAttr; 5066 S.Diag(OAttr->getLocation(), diag::note_conflicting_attribute); 5067 } 5068 return; 5069 } 5070 for (Decl *Redecl : D->redecls()) { 5071 Redecl->addAttr(::new (S.Context) OwnerAttr(S.Context, AL, DerefTypeLoc)); 5072 } 5073 } else { 5074 if (checkAttrMutualExclusion<OwnerAttr>(S, D, AL)) 5075 return; 5076 if (const auto *PAttr = D->getAttr<PointerAttr>()) { 5077 const Type *ExistingDerefType = PAttr->getDerefTypeLoc() 5078 ? PAttr->getDerefType().getTypePtr() 5079 : nullptr; 5080 if (ExistingDerefType != ParmType.getTypePtrOrNull()) { 5081 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) 5082 << AL << PAttr; 5083 S.Diag(PAttr->getLocation(), diag::note_conflicting_attribute); 5084 } 5085 return; 5086 } 5087 for (Decl *Redecl : D->redecls()) { 5088 Redecl->addAttr(::new (S.Context) 5089 PointerAttr(S.Context, AL, DerefTypeLoc)); 5090 } 5091 } 5092 } 5093 5094 bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC, 5095 const FunctionDecl *FD) { 5096 if (Attrs.isInvalid()) 5097 return true; 5098 5099 if (Attrs.hasProcessingCache()) { 5100 CC = (CallingConv) Attrs.getProcessingCache(); 5101 return false; 5102 } 5103 5104 unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0; 5105 if (!Attrs.checkExactlyNumArgs(*this, ReqArgs)) { 5106 Attrs.setInvalid(); 5107 return true; 5108 } 5109 5110 // TODO: diagnose uses of these conventions on the wrong target. 5111 switch (Attrs.getKind()) { 5112 case ParsedAttr::AT_CDecl: 5113 CC = CC_C; 5114 break; 5115 case ParsedAttr::AT_FastCall: 5116 CC = CC_X86FastCall; 5117 break; 5118 case ParsedAttr::AT_StdCall: 5119 CC = CC_X86StdCall; 5120 break; 5121 case ParsedAttr::AT_ThisCall: 5122 CC = CC_X86ThisCall; 5123 break; 5124 case ParsedAttr::AT_Pascal: 5125 CC = CC_X86Pascal; 5126 break; 5127 case ParsedAttr::AT_SwiftCall: 5128 CC = CC_Swift; 5129 break; 5130 case ParsedAttr::AT_SwiftAsyncCall: 5131 CC = CC_SwiftAsync; 5132 break; 5133 case ParsedAttr::AT_VectorCall: 5134 CC = CC_X86VectorCall; 5135 break; 5136 case ParsedAttr::AT_AArch64VectorPcs: 5137 CC = CC_AArch64VectorCall; 5138 break; 5139 case ParsedAttr::AT_RegCall: 5140 CC = CC_X86RegCall; 5141 break; 5142 case ParsedAttr::AT_MSABI: 5143 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C : 5144 CC_Win64; 5145 break; 5146 case ParsedAttr::AT_SysVABI: 5147 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV : 5148 CC_C; 5149 break; 5150 case ParsedAttr::AT_Pcs: { 5151 StringRef StrRef; 5152 if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) { 5153 Attrs.setInvalid(); 5154 return true; 5155 } 5156 if (StrRef == "aapcs") { 5157 CC = CC_AAPCS; 5158 break; 5159 } else if (StrRef == "aapcs-vfp") { 5160 CC = CC_AAPCS_VFP; 5161 break; 5162 } 5163 5164 Attrs.setInvalid(); 5165 Diag(Attrs.getLoc(), diag::err_invalid_pcs); 5166 return true; 5167 } 5168 case ParsedAttr::AT_IntelOclBicc: 5169 CC = CC_IntelOclBicc; 5170 break; 5171 case ParsedAttr::AT_PreserveMost: 5172 CC = CC_PreserveMost; 5173 break; 5174 case ParsedAttr::AT_PreserveAll: 5175 CC = CC_PreserveAll; 5176 break; 5177 default: llvm_unreachable("unexpected attribute kind"); 5178 } 5179 5180 TargetInfo::CallingConvCheckResult A = TargetInfo::CCCR_OK; 5181 const TargetInfo &TI = Context.getTargetInfo(); 5182 // CUDA functions may have host and/or device attributes which indicate 5183 // their targeted execution environment, therefore the calling convention 5184 // of functions in CUDA should be checked against the target deduced based 5185 // on their host/device attributes. 5186 if (LangOpts.CUDA) { 5187 auto *Aux = Context.getAuxTargetInfo(); 5188 auto CudaTarget = IdentifyCUDATarget(FD); 5189 bool CheckHost = false, CheckDevice = false; 5190 switch (CudaTarget) { 5191 case CFT_HostDevice: 5192 CheckHost = true; 5193 CheckDevice = true; 5194 break; 5195 case CFT_Host: 5196 CheckHost = true; 5197 break; 5198 case CFT_Device: 5199 case CFT_Global: 5200 CheckDevice = true; 5201 break; 5202 case CFT_InvalidTarget: 5203 llvm_unreachable("unexpected cuda target"); 5204 } 5205 auto *HostTI = LangOpts.CUDAIsDevice ? Aux : &TI; 5206 auto *DeviceTI = LangOpts.CUDAIsDevice ? &TI : Aux; 5207 if (CheckHost && HostTI) 5208 A = HostTI->checkCallingConvention(CC); 5209 if (A == TargetInfo::CCCR_OK && CheckDevice && DeviceTI) 5210 A = DeviceTI->checkCallingConvention(CC); 5211 } else { 5212 A = TI.checkCallingConvention(CC); 5213 } 5214 5215 switch (A) { 5216 case TargetInfo::CCCR_OK: 5217 break; 5218 5219 case TargetInfo::CCCR_Ignore: 5220 // Treat an ignored convention as if it was an explicit C calling convention 5221 // attribute. For example, __stdcall on Win x64 functions as __cdecl, so 5222 // that command line flags that change the default convention to 5223 // __vectorcall don't affect declarations marked __stdcall. 5224 CC = CC_C; 5225 break; 5226 5227 case TargetInfo::CCCR_Error: 5228 Diag(Attrs.getLoc(), diag::error_cconv_unsupported) 5229 << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget; 5230 break; 5231 5232 case TargetInfo::CCCR_Warning: { 5233 Diag(Attrs.getLoc(), diag::warn_cconv_unsupported) 5234 << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget; 5235 5236 // This convention is not valid for the target. Use the default function or 5237 // method calling convention. 5238 bool IsCXXMethod = false, IsVariadic = false; 5239 if (FD) { 5240 IsCXXMethod = FD->isCXXInstanceMember(); 5241 IsVariadic = FD->isVariadic(); 5242 } 5243 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod); 5244 break; 5245 } 5246 } 5247 5248 Attrs.setProcessingCache((unsigned) CC); 5249 return false; 5250 } 5251 5252 /// Pointer-like types in the default address space. 5253 static bool isValidSwiftContextType(QualType Ty) { 5254 if (!Ty->hasPointerRepresentation()) 5255 return Ty->isDependentType(); 5256 return Ty->getPointeeType().getAddressSpace() == LangAS::Default; 5257 } 5258 5259 /// Pointers and references in the default address space. 5260 static bool isValidSwiftIndirectResultType(QualType Ty) { 5261 if (const auto *PtrType = Ty->getAs<PointerType>()) { 5262 Ty = PtrType->getPointeeType(); 5263 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) { 5264 Ty = RefType->getPointeeType(); 5265 } else { 5266 return Ty->isDependentType(); 5267 } 5268 return Ty.getAddressSpace() == LangAS::Default; 5269 } 5270 5271 /// Pointers and references to pointers in the default address space. 5272 static bool isValidSwiftErrorResultType(QualType Ty) { 5273 if (const auto *PtrType = Ty->getAs<PointerType>()) { 5274 Ty = PtrType->getPointeeType(); 5275 } else if (const auto *RefType = Ty->getAs<ReferenceType>()) { 5276 Ty = RefType->getPointeeType(); 5277 } else { 5278 return Ty->isDependentType(); 5279 } 5280 if (!Ty.getQualifiers().empty()) 5281 return false; 5282 return isValidSwiftContextType(Ty); 5283 } 5284 5285 void Sema::AddParameterABIAttr(Decl *D, const AttributeCommonInfo &CI, 5286 ParameterABI abi) { 5287 5288 QualType type = cast<ParmVarDecl>(D)->getType(); 5289 5290 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) { 5291 if (existingAttr->getABI() != abi) { 5292 Diag(CI.getLoc(), diag::err_attributes_are_not_compatible) 5293 << getParameterABISpelling(abi) << existingAttr; 5294 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute); 5295 return; 5296 } 5297 } 5298 5299 switch (abi) { 5300 case ParameterABI::Ordinary: 5301 llvm_unreachable("explicit attribute for ordinary parameter ABI?"); 5302 5303 case ParameterABI::SwiftContext: 5304 if (!isValidSwiftContextType(type)) { 5305 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type) 5306 << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type; 5307 } 5308 D->addAttr(::new (Context) SwiftContextAttr(Context, CI)); 5309 return; 5310 5311 case ParameterABI::SwiftAsyncContext: 5312 if (!isValidSwiftContextType(type)) { 5313 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type) 5314 << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type; 5315 } 5316 D->addAttr(::new (Context) SwiftAsyncContextAttr(Context, CI)); 5317 return; 5318 5319 case ParameterABI::SwiftErrorResult: 5320 if (!isValidSwiftErrorResultType(type)) { 5321 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type) 5322 << getParameterABISpelling(abi) << /*pointer to pointer */ 1 << type; 5323 } 5324 D->addAttr(::new (Context) SwiftErrorResultAttr(Context, CI)); 5325 return; 5326 5327 case ParameterABI::SwiftIndirectResult: 5328 if (!isValidSwiftIndirectResultType(type)) { 5329 Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type) 5330 << getParameterABISpelling(abi) << /*pointer*/ 0 << type; 5331 } 5332 D->addAttr(::new (Context) SwiftIndirectResultAttr(Context, CI)); 5333 return; 5334 } 5335 llvm_unreachable("bad parameter ABI attribute"); 5336 } 5337 5338 /// Checks a regparm attribute, returning true if it is ill-formed and 5339 /// otherwise setting numParams to the appropriate value. 5340 bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) { 5341 if (AL.isInvalid()) 5342 return true; 5343 5344 if (!AL.checkExactlyNumArgs(*this, 1)) { 5345 AL.setInvalid(); 5346 return true; 5347 } 5348 5349 uint32_t NP; 5350 Expr *NumParamsExpr = AL.getArgAsExpr(0); 5351 if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) { 5352 AL.setInvalid(); 5353 return true; 5354 } 5355 5356 if (Context.getTargetInfo().getRegParmMax() == 0) { 5357 Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform) 5358 << NumParamsExpr->getSourceRange(); 5359 AL.setInvalid(); 5360 return true; 5361 } 5362 5363 numParams = NP; 5364 if (numParams > Context.getTargetInfo().getRegParmMax()) { 5365 Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number) 5366 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange(); 5367 AL.setInvalid(); 5368 return true; 5369 } 5370 5371 return false; 5372 } 5373 5374 // Checks whether an argument of launch_bounds attribute is 5375 // acceptable, performs implicit conversion to Rvalue, and returns 5376 // non-nullptr Expr result on success. Otherwise, it returns nullptr 5377 // and may output an error. 5378 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E, 5379 const CUDALaunchBoundsAttr &AL, 5380 const unsigned Idx) { 5381 if (S.DiagnoseUnexpandedParameterPack(E)) 5382 return nullptr; 5383 5384 // Accept template arguments for now as they depend on something else. 5385 // We'll get to check them when they eventually get instantiated. 5386 if (E->isValueDependent()) 5387 return E; 5388 5389 Optional<llvm::APSInt> I = llvm::APSInt(64); 5390 if (!(I = E->getIntegerConstantExpr(S.Context))) { 5391 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type) 5392 << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange(); 5393 return nullptr; 5394 } 5395 // Make sure we can fit it in 32 bits. 5396 if (!I->isIntN(32)) { 5397 S.Diag(E->getExprLoc(), diag::err_ice_too_large) 5398 << toString(*I, 10, false) << 32 << /* Unsigned */ 1; 5399 return nullptr; 5400 } 5401 if (*I < 0) 5402 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative) 5403 << &AL << Idx << E->getSourceRange(); 5404 5405 // We may need to perform implicit conversion of the argument. 5406 InitializedEntity Entity = InitializedEntity::InitializeParameter( 5407 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false); 5408 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E); 5409 assert(!ValArg.isInvalid() && 5410 "Unexpected PerformCopyInitialization() failure."); 5411 5412 return ValArg.getAs<Expr>(); 5413 } 5414 5415 void Sema::AddLaunchBoundsAttr(Decl *D, const AttributeCommonInfo &CI, 5416 Expr *MaxThreads, Expr *MinBlocks) { 5417 CUDALaunchBoundsAttr TmpAttr(Context, CI, MaxThreads, MinBlocks); 5418 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0); 5419 if (MaxThreads == nullptr) 5420 return; 5421 5422 if (MinBlocks) { 5423 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1); 5424 if (MinBlocks == nullptr) 5425 return; 5426 } 5427 5428 D->addAttr(::new (Context) 5429 CUDALaunchBoundsAttr(Context, CI, MaxThreads, MinBlocks)); 5430 } 5431 5432 static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 5433 if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2)) 5434 return; 5435 5436 S.AddLaunchBoundsAttr(D, AL, AL.getArgAsExpr(0), 5437 AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr); 5438 } 5439 5440 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D, 5441 const ParsedAttr &AL) { 5442 if (!AL.isArgIdent(0)) { 5443 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 5444 << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier; 5445 return; 5446 } 5447 5448 ParamIdx ArgumentIdx; 5449 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1), 5450 ArgumentIdx)) 5451 return; 5452 5453 ParamIdx TypeTagIdx; 5454 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2), 5455 TypeTagIdx)) 5456 return; 5457 5458 bool IsPointer = AL.getAttrName()->getName() == "pointer_with_type_tag"; 5459 if (IsPointer) { 5460 // Ensure that buffer has a pointer type. 5461 unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex(); 5462 if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) || 5463 !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType()) 5464 S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0; 5465 } 5466 5467 D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr( 5468 S.Context, AL, AL.getArgAsIdent(0)->Ident, ArgumentIdx, TypeTagIdx, 5469 IsPointer)); 5470 } 5471 5472 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D, 5473 const ParsedAttr &AL) { 5474 if (!AL.isArgIdent(0)) { 5475 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 5476 << AL << 1 << AANT_ArgumentIdentifier; 5477 return; 5478 } 5479 5480 if (!AL.checkExactlyNumArgs(S, 1)) 5481 return; 5482 5483 if (!isa<VarDecl>(D)) { 5484 S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type) 5485 << AL << ExpectedVariable; 5486 return; 5487 } 5488 5489 IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident; 5490 TypeSourceInfo *MatchingCTypeLoc = nullptr; 5491 S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc); 5492 assert(MatchingCTypeLoc && "no type source info for attribute argument"); 5493 5494 D->addAttr(::new (S.Context) TypeTagForDatatypeAttr( 5495 S.Context, AL, PointerKind, MatchingCTypeLoc, AL.getLayoutCompatible(), 5496 AL.getMustBeNull())); 5497 } 5498 5499 static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 5500 ParamIdx ArgCount; 5501 5502 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0), 5503 ArgCount, 5504 true /* CanIndexImplicitThis */)) 5505 return; 5506 5507 // ArgCount isn't a parameter index [0;n), it's a count [1;n] 5508 D->addAttr(::new (S.Context) 5509 XRayLogArgsAttr(S.Context, AL, ArgCount.getSourceIndex())); 5510 } 5511 5512 static void handlePatchableFunctionEntryAttr(Sema &S, Decl *D, 5513 const ParsedAttr &AL) { 5514 uint32_t Count = 0, Offset = 0; 5515 if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Count, 0, true)) 5516 return; 5517 if (AL.getNumArgs() == 2) { 5518 Expr *Arg = AL.getArgAsExpr(1); 5519 if (!checkUInt32Argument(S, AL, Arg, Offset, 1, true)) 5520 return; 5521 if (Count < Offset) { 5522 S.Diag(getAttrLoc(AL), diag::err_attribute_argument_out_of_range) 5523 << &AL << 0 << Count << Arg->getBeginLoc(); 5524 return; 5525 } 5526 } 5527 D->addAttr(::new (S.Context) 5528 PatchableFunctionEntryAttr(S.Context, AL, Count, Offset)); 5529 } 5530 5531 namespace { 5532 struct IntrinToName { 5533 uint32_t Id; 5534 int32_t FullName; 5535 int32_t ShortName; 5536 }; 5537 } // unnamed namespace 5538 5539 static bool ArmBuiltinAliasValid(unsigned BuiltinID, StringRef AliasName, 5540 ArrayRef<IntrinToName> Map, 5541 const char *IntrinNames) { 5542 if (AliasName.startswith("__arm_")) 5543 AliasName = AliasName.substr(6); 5544 const IntrinToName *It = std::lower_bound( 5545 Map.begin(), Map.end(), BuiltinID, 5546 [](const IntrinToName &L, unsigned Id) { return L.Id < Id; }); 5547 if (It == Map.end() || It->Id != BuiltinID) 5548 return false; 5549 StringRef FullName(&IntrinNames[It->FullName]); 5550 if (AliasName == FullName) 5551 return true; 5552 if (It->ShortName == -1) 5553 return false; 5554 StringRef ShortName(&IntrinNames[It->ShortName]); 5555 return AliasName == ShortName; 5556 } 5557 5558 static bool ArmMveAliasValid(unsigned BuiltinID, StringRef AliasName) { 5559 #include "clang/Basic/arm_mve_builtin_aliases.inc" 5560 // The included file defines: 5561 // - ArrayRef<IntrinToName> Map 5562 // - const char IntrinNames[] 5563 return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames); 5564 } 5565 5566 static bool ArmCdeAliasValid(unsigned BuiltinID, StringRef AliasName) { 5567 #include "clang/Basic/arm_cde_builtin_aliases.inc" 5568 return ArmBuiltinAliasValid(BuiltinID, AliasName, Map, IntrinNames); 5569 } 5570 5571 static bool ArmSveAliasValid(ASTContext &Context, unsigned BuiltinID, 5572 StringRef AliasName) { 5573 if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) 5574 BuiltinID = Context.BuiltinInfo.getAuxBuiltinID(BuiltinID); 5575 return BuiltinID >= AArch64::FirstSVEBuiltin && 5576 BuiltinID <= AArch64::LastSVEBuiltin; 5577 } 5578 5579 static void handleArmBuiltinAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 5580 if (!AL.isArgIdent(0)) { 5581 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 5582 << AL << 1 << AANT_ArgumentIdentifier; 5583 return; 5584 } 5585 5586 IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident; 5587 unsigned BuiltinID = Ident->getBuiltinID(); 5588 StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName(); 5589 5590 bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 5591 if ((IsAArch64 && !ArmSveAliasValid(S.Context, BuiltinID, AliasName)) || 5592 (!IsAArch64 && !ArmMveAliasValid(BuiltinID, AliasName) && 5593 !ArmCdeAliasValid(BuiltinID, AliasName))) { 5594 S.Diag(AL.getLoc(), diag::err_attribute_arm_builtin_alias); 5595 return; 5596 } 5597 5598 D->addAttr(::new (S.Context) ArmBuiltinAliasAttr(S.Context, AL, Ident)); 5599 } 5600 5601 static bool RISCVAliasValid(unsigned BuiltinID, StringRef AliasName) { 5602 return BuiltinID >= RISCV::FirstRVVBuiltin && 5603 BuiltinID <= RISCV::LastRVVBuiltin; 5604 } 5605 5606 static void handleBuiltinAliasAttr(Sema &S, Decl *D, 5607 const ParsedAttr &AL) { 5608 if (!AL.isArgIdent(0)) { 5609 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 5610 << AL << 1 << AANT_ArgumentIdentifier; 5611 return; 5612 } 5613 5614 IdentifierInfo *Ident = AL.getArgAsIdent(0)->Ident; 5615 unsigned BuiltinID = Ident->getBuiltinID(); 5616 StringRef AliasName = cast<FunctionDecl>(D)->getIdentifier()->getName(); 5617 5618 bool IsAArch64 = S.Context.getTargetInfo().getTriple().isAArch64(); 5619 bool IsARM = S.Context.getTargetInfo().getTriple().isARM(); 5620 bool IsRISCV = S.Context.getTargetInfo().getTriple().isRISCV(); 5621 if ((IsAArch64 && !ArmSveAliasValid(S.Context, BuiltinID, AliasName)) || 5622 (IsARM && !ArmMveAliasValid(BuiltinID, AliasName) && 5623 !ArmCdeAliasValid(BuiltinID, AliasName)) || 5624 (IsRISCV && !RISCVAliasValid(BuiltinID, AliasName)) || 5625 (!IsAArch64 && !IsARM && !IsRISCV)) { 5626 S.Diag(AL.getLoc(), diag::err_attribute_builtin_alias) << AL; 5627 return; 5628 } 5629 5630 D->addAttr(::new (S.Context) BuiltinAliasAttr(S.Context, AL, Ident)); 5631 } 5632 5633 //===----------------------------------------------------------------------===// 5634 // Checker-specific attribute handlers. 5635 //===----------------------------------------------------------------------===// 5636 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) { 5637 return QT->isDependentType() || QT->isObjCRetainableType(); 5638 } 5639 5640 static bool isValidSubjectOfNSAttribute(QualType QT) { 5641 return QT->isDependentType() || QT->isObjCObjectPointerType() || 5642 QT->isObjCNSObjectType(); 5643 } 5644 5645 static bool isValidSubjectOfCFAttribute(QualType QT) { 5646 return QT->isDependentType() || QT->isPointerType() || 5647 isValidSubjectOfNSAttribute(QT); 5648 } 5649 5650 static bool isValidSubjectOfOSAttribute(QualType QT) { 5651 if (QT->isDependentType()) 5652 return true; 5653 QualType PT = QT->getPointeeType(); 5654 return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr; 5655 } 5656 5657 void Sema::AddXConsumedAttr(Decl *D, const AttributeCommonInfo &CI, 5658 RetainOwnershipKind K, 5659 bool IsTemplateInstantiation) { 5660 ValueDecl *VD = cast<ValueDecl>(D); 5661 switch (K) { 5662 case RetainOwnershipKind::OS: 5663 handleSimpleAttributeOrDiagnose<OSConsumedAttr>( 5664 *this, VD, CI, isValidSubjectOfOSAttribute(VD->getType()), 5665 diag::warn_ns_attribute_wrong_parameter_type, 5666 /*ExtraArgs=*/CI.getRange(), "os_consumed", /*pointers*/ 1); 5667 return; 5668 case RetainOwnershipKind::NS: 5669 handleSimpleAttributeOrDiagnose<NSConsumedAttr>( 5670 *this, VD, CI, isValidSubjectOfNSAttribute(VD->getType()), 5671 5672 // These attributes are normally just advisory, but in ARC, ns_consumed 5673 // is significant. Allow non-dependent code to contain inappropriate 5674 // attributes even in ARC, but require template instantiations to be 5675 // set up correctly. 5676 ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount) 5677 ? diag::err_ns_attribute_wrong_parameter_type 5678 : diag::warn_ns_attribute_wrong_parameter_type), 5679 /*ExtraArgs=*/CI.getRange(), "ns_consumed", /*objc pointers*/ 0); 5680 return; 5681 case RetainOwnershipKind::CF: 5682 handleSimpleAttributeOrDiagnose<CFConsumedAttr>( 5683 *this, VD, CI, isValidSubjectOfCFAttribute(VD->getType()), 5684 diag::warn_ns_attribute_wrong_parameter_type, 5685 /*ExtraArgs=*/CI.getRange(), "cf_consumed", /*pointers*/ 1); 5686 return; 5687 } 5688 } 5689 5690 static Sema::RetainOwnershipKind 5691 parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) { 5692 switch (AL.getKind()) { 5693 case ParsedAttr::AT_CFConsumed: 5694 case ParsedAttr::AT_CFReturnsRetained: 5695 case ParsedAttr::AT_CFReturnsNotRetained: 5696 return Sema::RetainOwnershipKind::CF; 5697 case ParsedAttr::AT_OSConsumesThis: 5698 case ParsedAttr::AT_OSConsumed: 5699 case ParsedAttr::AT_OSReturnsRetained: 5700 case ParsedAttr::AT_OSReturnsNotRetained: 5701 case ParsedAttr::AT_OSReturnsRetainedOnZero: 5702 case ParsedAttr::AT_OSReturnsRetainedOnNonZero: 5703 return Sema::RetainOwnershipKind::OS; 5704 case ParsedAttr::AT_NSConsumesSelf: 5705 case ParsedAttr::AT_NSConsumed: 5706 case ParsedAttr::AT_NSReturnsRetained: 5707 case ParsedAttr::AT_NSReturnsNotRetained: 5708 case ParsedAttr::AT_NSReturnsAutoreleased: 5709 return Sema::RetainOwnershipKind::NS; 5710 default: 5711 llvm_unreachable("Wrong argument supplied"); 5712 } 5713 } 5714 5715 bool Sema::checkNSReturnsRetainedReturnType(SourceLocation Loc, QualType QT) { 5716 if (isValidSubjectOfNSReturnsRetainedAttribute(QT)) 5717 return false; 5718 5719 Diag(Loc, diag::warn_ns_attribute_wrong_return_type) 5720 << "'ns_returns_retained'" << 0 << 0; 5721 return true; 5722 } 5723 5724 /// \return whether the parameter is a pointer to OSObject pointer. 5725 static bool isValidOSObjectOutParameter(const Decl *D) { 5726 const auto *PVD = dyn_cast<ParmVarDecl>(D); 5727 if (!PVD) 5728 return false; 5729 QualType QT = PVD->getType(); 5730 QualType PT = QT->getPointeeType(); 5731 return !PT.isNull() && isValidSubjectOfOSAttribute(PT); 5732 } 5733 5734 static void handleXReturnsXRetainedAttr(Sema &S, Decl *D, 5735 const ParsedAttr &AL) { 5736 QualType ReturnType; 5737 Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL); 5738 5739 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) { 5740 ReturnType = MD->getReturnType(); 5741 } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) && 5742 (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) { 5743 return; // ignore: was handled as a type attribute 5744 } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) { 5745 ReturnType = PD->getType(); 5746 } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 5747 ReturnType = FD->getReturnType(); 5748 } else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) { 5749 // Attributes on parameters are used for out-parameters, 5750 // passed as pointers-to-pointers. 5751 unsigned DiagID = K == Sema::RetainOwnershipKind::CF 5752 ? /*pointer-to-CF-pointer*/2 5753 : /*pointer-to-OSObject-pointer*/3; 5754 ReturnType = Param->getType()->getPointeeType(); 5755 if (ReturnType.isNull()) { 5756 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type) 5757 << AL << DiagID << AL.getRange(); 5758 return; 5759 } 5760 } else if (AL.isUsedAsTypeAttr()) { 5761 return; 5762 } else { 5763 AttributeDeclKind ExpectedDeclKind; 5764 switch (AL.getKind()) { 5765 default: llvm_unreachable("invalid ownership attribute"); 5766 case ParsedAttr::AT_NSReturnsRetained: 5767 case ParsedAttr::AT_NSReturnsAutoreleased: 5768 case ParsedAttr::AT_NSReturnsNotRetained: 5769 ExpectedDeclKind = ExpectedFunctionOrMethod; 5770 break; 5771 5772 case ParsedAttr::AT_OSReturnsRetained: 5773 case ParsedAttr::AT_OSReturnsNotRetained: 5774 case ParsedAttr::AT_CFReturnsRetained: 5775 case ParsedAttr::AT_CFReturnsNotRetained: 5776 ExpectedDeclKind = ExpectedFunctionMethodOrParameter; 5777 break; 5778 } 5779 S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type) 5780 << AL.getRange() << AL << ExpectedDeclKind; 5781 return; 5782 } 5783 5784 bool TypeOK; 5785 bool Cf; 5786 unsigned ParmDiagID = 2; // Pointer-to-CF-pointer 5787 switch (AL.getKind()) { 5788 default: llvm_unreachable("invalid ownership attribute"); 5789 case ParsedAttr::AT_NSReturnsRetained: 5790 TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType); 5791 Cf = false; 5792 break; 5793 5794 case ParsedAttr::AT_NSReturnsAutoreleased: 5795 case ParsedAttr::AT_NSReturnsNotRetained: 5796 TypeOK = isValidSubjectOfNSAttribute(ReturnType); 5797 Cf = false; 5798 break; 5799 5800 case ParsedAttr::AT_CFReturnsRetained: 5801 case ParsedAttr::AT_CFReturnsNotRetained: 5802 TypeOK = isValidSubjectOfCFAttribute(ReturnType); 5803 Cf = true; 5804 break; 5805 5806 case ParsedAttr::AT_OSReturnsRetained: 5807 case ParsedAttr::AT_OSReturnsNotRetained: 5808 TypeOK = isValidSubjectOfOSAttribute(ReturnType); 5809 Cf = true; 5810 ParmDiagID = 3; // Pointer-to-OSObject-pointer 5811 break; 5812 } 5813 5814 if (!TypeOK) { 5815 if (AL.isUsedAsTypeAttr()) 5816 return; 5817 5818 if (isa<ParmVarDecl>(D)) { 5819 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type) 5820 << AL << ParmDiagID << AL.getRange(); 5821 } else { 5822 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type. 5823 enum : unsigned { 5824 Function, 5825 Method, 5826 Property 5827 } SubjectKind = Function; 5828 if (isa<ObjCMethodDecl>(D)) 5829 SubjectKind = Method; 5830 else if (isa<ObjCPropertyDecl>(D)) 5831 SubjectKind = Property; 5832 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type) 5833 << AL << SubjectKind << Cf << AL.getRange(); 5834 } 5835 return; 5836 } 5837 5838 switch (AL.getKind()) { 5839 default: 5840 llvm_unreachable("invalid ownership attribute"); 5841 case ParsedAttr::AT_NSReturnsAutoreleased: 5842 handleSimpleAttribute<NSReturnsAutoreleasedAttr>(S, D, AL); 5843 return; 5844 case ParsedAttr::AT_CFReturnsNotRetained: 5845 handleSimpleAttribute<CFReturnsNotRetainedAttr>(S, D, AL); 5846 return; 5847 case ParsedAttr::AT_NSReturnsNotRetained: 5848 handleSimpleAttribute<NSReturnsNotRetainedAttr>(S, D, AL); 5849 return; 5850 case ParsedAttr::AT_CFReturnsRetained: 5851 handleSimpleAttribute<CFReturnsRetainedAttr>(S, D, AL); 5852 return; 5853 case ParsedAttr::AT_NSReturnsRetained: 5854 handleSimpleAttribute<NSReturnsRetainedAttr>(S, D, AL); 5855 return; 5856 case ParsedAttr::AT_OSReturnsRetained: 5857 handleSimpleAttribute<OSReturnsRetainedAttr>(S, D, AL); 5858 return; 5859 case ParsedAttr::AT_OSReturnsNotRetained: 5860 handleSimpleAttribute<OSReturnsNotRetainedAttr>(S, D, AL); 5861 return; 5862 }; 5863 } 5864 5865 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D, 5866 const ParsedAttr &Attrs) { 5867 const int EP_ObjCMethod = 1; 5868 const int EP_ObjCProperty = 2; 5869 5870 SourceLocation loc = Attrs.getLoc(); 5871 QualType resultType; 5872 if (isa<ObjCMethodDecl>(D)) 5873 resultType = cast<ObjCMethodDecl>(D)->getReturnType(); 5874 else 5875 resultType = cast<ObjCPropertyDecl>(D)->getType(); 5876 5877 if (!resultType->isReferenceType() && 5878 (!resultType->isPointerType() || resultType->isObjCRetainableType())) { 5879 S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type) 5880 << SourceRange(loc) << Attrs 5881 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty) 5882 << /*non-retainable pointer*/ 2; 5883 5884 // Drop the attribute. 5885 return; 5886 } 5887 5888 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(S.Context, Attrs)); 5889 } 5890 5891 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D, 5892 const ParsedAttr &Attrs) { 5893 const auto *Method = cast<ObjCMethodDecl>(D); 5894 5895 const DeclContext *DC = Method->getDeclContext(); 5896 if (const auto *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) { 5897 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs 5898 << 0; 5899 S.Diag(PDecl->getLocation(), diag::note_protocol_decl); 5900 return; 5901 } 5902 if (Method->getMethodFamily() == OMF_dealloc) { 5903 S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs 5904 << 1; 5905 return; 5906 } 5907 5908 D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(S.Context, Attrs)); 5909 } 5910 5911 static void handleNSErrorDomain(Sema &S, Decl *D, const ParsedAttr &AL) { 5912 auto *E = AL.getArgAsExpr(0); 5913 auto Loc = E ? E->getBeginLoc() : AL.getLoc(); 5914 5915 auto *DRE = dyn_cast<DeclRefExpr>(AL.getArgAsExpr(0)); 5916 if (!DRE) { 5917 S.Diag(Loc, diag::err_nserrordomain_invalid_decl) << 0; 5918 return; 5919 } 5920 5921 auto *VD = dyn_cast<VarDecl>(DRE->getDecl()); 5922 if (!VD) { 5923 S.Diag(Loc, diag::err_nserrordomain_invalid_decl) << 1 << DRE->getDecl(); 5924 return; 5925 } 5926 5927 if (!isNSStringType(VD->getType(), S.Context) && 5928 !isCFStringType(VD->getType(), S.Context)) { 5929 S.Diag(Loc, diag::err_nserrordomain_wrong_type) << VD; 5930 return; 5931 } 5932 5933 D->addAttr(::new (S.Context) NSErrorDomainAttr(S.Context, AL, VD)); 5934 } 5935 5936 static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 5937 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr; 5938 5939 if (!Parm) { 5940 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0; 5941 return; 5942 } 5943 5944 // Typedefs only allow objc_bridge(id) and have some additional checking. 5945 if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) { 5946 if (!Parm->Ident->isStr("id")) { 5947 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL; 5948 return; 5949 } 5950 5951 // Only allow 'cv void *'. 5952 QualType T = TD->getUnderlyingType(); 5953 if (!T->isVoidPointerType()) { 5954 S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer); 5955 return; 5956 } 5957 } 5958 5959 D->addAttr(::new (S.Context) ObjCBridgeAttr(S.Context, AL, Parm->Ident)); 5960 } 5961 5962 static void handleObjCBridgeMutableAttr(Sema &S, Decl *D, 5963 const ParsedAttr &AL) { 5964 IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr; 5965 5966 if (!Parm) { 5967 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0; 5968 return; 5969 } 5970 5971 D->addAttr(::new (S.Context) 5972 ObjCBridgeMutableAttr(S.Context, AL, Parm->Ident)); 5973 } 5974 5975 static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D, 5976 const ParsedAttr &AL) { 5977 IdentifierInfo *RelatedClass = 5978 AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr; 5979 if (!RelatedClass) { 5980 S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0; 5981 return; 5982 } 5983 IdentifierInfo *ClassMethod = 5984 AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr; 5985 IdentifierInfo *InstanceMethod = 5986 AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr; 5987 D->addAttr(::new (S.Context) ObjCBridgeRelatedAttr( 5988 S.Context, AL, RelatedClass, ClassMethod, InstanceMethod)); 5989 } 5990 5991 static void handleObjCDesignatedInitializer(Sema &S, Decl *D, 5992 const ParsedAttr &AL) { 5993 DeclContext *Ctx = D->getDeclContext(); 5994 5995 // This attribute can only be applied to methods in interfaces or class 5996 // extensions. 5997 if (!isa<ObjCInterfaceDecl>(Ctx) && 5998 !(isa<ObjCCategoryDecl>(Ctx) && 5999 cast<ObjCCategoryDecl>(Ctx)->IsClassExtension())) { 6000 S.Diag(D->getLocation(), diag::err_designated_init_attr_non_init); 6001 return; 6002 } 6003 6004 ObjCInterfaceDecl *IFace; 6005 if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Ctx)) 6006 IFace = CatDecl->getClassInterface(); 6007 else 6008 IFace = cast<ObjCInterfaceDecl>(Ctx); 6009 6010 if (!IFace) 6011 return; 6012 6013 IFace->setHasDesignatedInitializers(); 6014 D->addAttr(::new (S.Context) ObjCDesignatedInitializerAttr(S.Context, AL)); 6015 } 6016 6017 static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) { 6018 StringRef MetaDataName; 6019 if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName)) 6020 return; 6021 D->addAttr(::new (S.Context) 6022 ObjCRuntimeNameAttr(S.Context, AL, MetaDataName)); 6023 } 6024 6025 // When a user wants to use objc_boxable with a union or struct 6026 // but they don't have access to the declaration (legacy/third-party code) 6027 // then they can 'enable' this feature with a typedef: 6028 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct; 6029 static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) { 6030 bool notify = false; 6031 6032 auto *RD = dyn_cast<RecordDecl>(D); 6033 if (RD && RD->getDefinition()) { 6034 RD = RD->getDefinition(); 6035 notify = true; 6036 } 6037 6038 if (RD) { 6039 ObjCBoxableAttr *BoxableAttr = 6040 ::new (S.Context) ObjCBoxableAttr(S.Context, AL); 6041 RD->addAttr(BoxableAttr); 6042 if (notify) { 6043 // we need to notify ASTReader/ASTWriter about 6044 // modification of existing declaration 6045 if (ASTMutationListener *L = S.getASTMutationListener()) 6046 L->AddedAttributeToRecord(BoxableAttr, RD); 6047 } 6048 } 6049 } 6050 6051 static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6052 if (hasDeclarator(D)) return; 6053 6054 S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type) 6055 << AL.getRange() << AL << ExpectedVariable; 6056 } 6057 6058 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D, 6059 const ParsedAttr &AL) { 6060 const auto *VD = cast<ValueDecl>(D); 6061 QualType QT = VD->getType(); 6062 6063 if (!QT->isDependentType() && 6064 !QT->isObjCLifetimeType()) { 6065 S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type) 6066 << QT; 6067 return; 6068 } 6069 6070 Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime(); 6071 6072 // If we have no lifetime yet, check the lifetime we're presumably 6073 // going to infer. 6074 if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType()) 6075 Lifetime = QT->getObjCARCImplicitLifetime(); 6076 6077 switch (Lifetime) { 6078 case Qualifiers::OCL_None: 6079 assert(QT->isDependentType() && 6080 "didn't infer lifetime for non-dependent type?"); 6081 break; 6082 6083 case Qualifiers::OCL_Weak: // meaningful 6084 case Qualifiers::OCL_Strong: // meaningful 6085 break; 6086 6087 case Qualifiers::OCL_ExplicitNone: 6088 case Qualifiers::OCL_Autoreleasing: 6089 S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless) 6090 << (Lifetime == Qualifiers::OCL_Autoreleasing); 6091 break; 6092 } 6093 6094 D->addAttr(::new (S.Context) ObjCPreciseLifetimeAttr(S.Context, AL)); 6095 } 6096 6097 static void handleSwiftAttrAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6098 // Make sure that there is a string literal as the annotation's single 6099 // argument. 6100 StringRef Str; 6101 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str)) 6102 return; 6103 6104 D->addAttr(::new (S.Context) SwiftAttrAttr(S.Context, AL, Str)); 6105 } 6106 6107 static void handleSwiftBridge(Sema &S, Decl *D, const ParsedAttr &AL) { 6108 // Make sure that there is a string literal as the annotation's single 6109 // argument. 6110 StringRef BT; 6111 if (!S.checkStringLiteralArgumentAttr(AL, 0, BT)) 6112 return; 6113 6114 // Warn about duplicate attributes if they have different arguments, but drop 6115 // any duplicate attributes regardless. 6116 if (const auto *Other = D->getAttr<SwiftBridgeAttr>()) { 6117 if (Other->getSwiftType() != BT) 6118 S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL; 6119 return; 6120 } 6121 6122 D->addAttr(::new (S.Context) SwiftBridgeAttr(S.Context, AL, BT)); 6123 } 6124 6125 static bool isErrorParameter(Sema &S, QualType QT) { 6126 const auto *PT = QT->getAs<PointerType>(); 6127 if (!PT) 6128 return false; 6129 6130 QualType Pointee = PT->getPointeeType(); 6131 6132 // Check for NSError**. 6133 if (const auto *OPT = Pointee->getAs<ObjCObjectPointerType>()) 6134 if (const auto *ID = OPT->getInterfaceDecl()) 6135 if (ID->getIdentifier() == S.getNSErrorIdent()) 6136 return true; 6137 6138 // Check for CFError**. 6139 if (const auto *PT = Pointee->getAs<PointerType>()) 6140 if (const auto *RT = PT->getPointeeType()->getAs<RecordType>()) 6141 if (S.isCFError(RT->getDecl())) 6142 return true; 6143 6144 return false; 6145 } 6146 6147 static void handleSwiftError(Sema &S, Decl *D, const ParsedAttr &AL) { 6148 auto hasErrorParameter = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool { 6149 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); I != E; ++I) { 6150 if (isErrorParameter(S, getFunctionOrMethodParamType(D, I))) 6151 return true; 6152 } 6153 6154 S.Diag(AL.getLoc(), diag::err_attr_swift_error_no_error_parameter) 6155 << AL << isa<ObjCMethodDecl>(D); 6156 return false; 6157 }; 6158 6159 auto hasPointerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool { 6160 // - C, ObjC, and block pointers are definitely okay. 6161 // - References are definitely not okay. 6162 // - nullptr_t is weird, but acceptable. 6163 QualType RT = getFunctionOrMethodResultType(D); 6164 if (RT->hasPointerRepresentation() && !RT->isReferenceType()) 6165 return true; 6166 6167 S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type) 6168 << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D) 6169 << /*pointer*/ 1; 6170 return false; 6171 }; 6172 6173 auto hasIntegerResult = [](Sema &S, Decl *D, const ParsedAttr &AL) -> bool { 6174 QualType RT = getFunctionOrMethodResultType(D); 6175 if (RT->isIntegralType(S.Context)) 6176 return true; 6177 6178 S.Diag(AL.getLoc(), diag::err_attr_swift_error_return_type) 6179 << AL << AL.getArgAsIdent(0)->Ident->getName() << isa<ObjCMethodDecl>(D) 6180 << /*integral*/ 0; 6181 return false; 6182 }; 6183 6184 if (D->isInvalidDecl()) 6185 return; 6186 6187 IdentifierLoc *Loc = AL.getArgAsIdent(0); 6188 SwiftErrorAttr::ConventionKind Convention; 6189 if (!SwiftErrorAttr::ConvertStrToConventionKind(Loc->Ident->getName(), 6190 Convention)) { 6191 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) 6192 << AL << Loc->Ident; 6193 return; 6194 } 6195 6196 switch (Convention) { 6197 case SwiftErrorAttr::None: 6198 // No additional validation required. 6199 break; 6200 6201 case SwiftErrorAttr::NonNullError: 6202 if (!hasErrorParameter(S, D, AL)) 6203 return; 6204 break; 6205 6206 case SwiftErrorAttr::NullResult: 6207 if (!hasErrorParameter(S, D, AL) || !hasPointerResult(S, D, AL)) 6208 return; 6209 break; 6210 6211 case SwiftErrorAttr::NonZeroResult: 6212 case SwiftErrorAttr::ZeroResult: 6213 if (!hasErrorParameter(S, D, AL) || !hasIntegerResult(S, D, AL)) 6214 return; 6215 break; 6216 } 6217 6218 D->addAttr(::new (S.Context) SwiftErrorAttr(S.Context, AL, Convention)); 6219 } 6220 6221 static void checkSwiftAsyncErrorBlock(Sema &S, Decl *D, 6222 const SwiftAsyncErrorAttr *ErrorAttr, 6223 const SwiftAsyncAttr *AsyncAttr) { 6224 if (AsyncAttr->getKind() == SwiftAsyncAttr::None) { 6225 if (ErrorAttr->getConvention() != SwiftAsyncErrorAttr::None) { 6226 S.Diag(AsyncAttr->getLocation(), 6227 diag::err_swift_async_error_without_swift_async) 6228 << AsyncAttr << isa<ObjCMethodDecl>(D); 6229 } 6230 return; 6231 } 6232 6233 const ParmVarDecl *HandlerParam = getFunctionOrMethodParam( 6234 D, AsyncAttr->getCompletionHandlerIndex().getASTIndex()); 6235 // handleSwiftAsyncAttr already verified the type is correct, so no need to 6236 // double-check it here. 6237 const auto *FuncTy = HandlerParam->getType() 6238 ->castAs<BlockPointerType>() 6239 ->getPointeeType() 6240 ->getAs<FunctionProtoType>(); 6241 ArrayRef<QualType> BlockParams; 6242 if (FuncTy) 6243 BlockParams = FuncTy->getParamTypes(); 6244 6245 switch (ErrorAttr->getConvention()) { 6246 case SwiftAsyncErrorAttr::ZeroArgument: 6247 case SwiftAsyncErrorAttr::NonZeroArgument: { 6248 uint32_t ParamIdx = ErrorAttr->getHandlerParamIdx(); 6249 if (ParamIdx == 0 || ParamIdx > BlockParams.size()) { 6250 S.Diag(ErrorAttr->getLocation(), 6251 diag::err_attribute_argument_out_of_bounds) << ErrorAttr << 2; 6252 return; 6253 } 6254 QualType ErrorParam = BlockParams[ParamIdx - 1]; 6255 if (!ErrorParam->isIntegralType(S.Context)) { 6256 StringRef ConvStr = 6257 ErrorAttr->getConvention() == SwiftAsyncErrorAttr::ZeroArgument 6258 ? "zero_argument" 6259 : "nonzero_argument"; 6260 S.Diag(ErrorAttr->getLocation(), diag::err_swift_async_error_non_integral) 6261 << ErrorAttr << ConvStr << ParamIdx << ErrorParam; 6262 return; 6263 } 6264 break; 6265 } 6266 case SwiftAsyncErrorAttr::NonNullError: { 6267 bool AnyErrorParams = false; 6268 for (QualType Param : BlockParams) { 6269 // Check for NSError *. 6270 if (const auto *ObjCPtrTy = Param->getAs<ObjCObjectPointerType>()) { 6271 if (const auto *ID = ObjCPtrTy->getInterfaceDecl()) { 6272 if (ID->getIdentifier() == S.getNSErrorIdent()) { 6273 AnyErrorParams = true; 6274 break; 6275 } 6276 } 6277 } 6278 // Check for CFError *. 6279 if (const auto *PtrTy = Param->getAs<PointerType>()) { 6280 if (const auto *RT = PtrTy->getPointeeType()->getAs<RecordType>()) { 6281 if (S.isCFError(RT->getDecl())) { 6282 AnyErrorParams = true; 6283 break; 6284 } 6285 } 6286 } 6287 } 6288 6289 if (!AnyErrorParams) { 6290 S.Diag(ErrorAttr->getLocation(), 6291 diag::err_swift_async_error_no_error_parameter) 6292 << ErrorAttr << isa<ObjCMethodDecl>(D); 6293 return; 6294 } 6295 break; 6296 } 6297 case SwiftAsyncErrorAttr::None: 6298 break; 6299 } 6300 } 6301 6302 static void handleSwiftAsyncError(Sema &S, Decl *D, const ParsedAttr &AL) { 6303 IdentifierLoc *IDLoc = AL.getArgAsIdent(0); 6304 SwiftAsyncErrorAttr::ConventionKind ConvKind; 6305 if (!SwiftAsyncErrorAttr::ConvertStrToConventionKind(IDLoc->Ident->getName(), 6306 ConvKind)) { 6307 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) 6308 << AL << IDLoc->Ident; 6309 return; 6310 } 6311 6312 uint32_t ParamIdx = 0; 6313 switch (ConvKind) { 6314 case SwiftAsyncErrorAttr::ZeroArgument: 6315 case SwiftAsyncErrorAttr::NonZeroArgument: { 6316 if (!AL.checkExactlyNumArgs(S, 2)) 6317 return; 6318 6319 Expr *IdxExpr = AL.getArgAsExpr(1); 6320 if (!checkUInt32Argument(S, AL, IdxExpr, ParamIdx)) 6321 return; 6322 break; 6323 } 6324 case SwiftAsyncErrorAttr::NonNullError: 6325 case SwiftAsyncErrorAttr::None: { 6326 if (!AL.checkExactlyNumArgs(S, 1)) 6327 return; 6328 break; 6329 } 6330 } 6331 6332 auto *ErrorAttr = 6333 ::new (S.Context) SwiftAsyncErrorAttr(S.Context, AL, ConvKind, ParamIdx); 6334 D->addAttr(ErrorAttr); 6335 6336 if (auto *AsyncAttr = D->getAttr<SwiftAsyncAttr>()) 6337 checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr); 6338 } 6339 6340 // For a function, this will validate a compound Swift name, e.g. 6341 // <code>init(foo:bar:baz:)</code> or <code>controllerForName(_:)</code>, and 6342 // the function will output the number of parameter names, and whether this is a 6343 // single-arg initializer. 6344 // 6345 // For a type, enum constant, property, or variable declaration, this will 6346 // validate either a simple identifier, or a qualified 6347 // <code>context.identifier</code> name. 6348 static bool 6349 validateSwiftFunctionName(Sema &S, const ParsedAttr &AL, SourceLocation Loc, 6350 StringRef Name, unsigned &SwiftParamCount, 6351 bool &IsSingleParamInit) { 6352 SwiftParamCount = 0; 6353 IsSingleParamInit = false; 6354 6355 // Check whether this will be mapped to a getter or setter of a property. 6356 bool IsGetter = false, IsSetter = false; 6357 if (Name.startswith("getter:")) { 6358 IsGetter = true; 6359 Name = Name.substr(7); 6360 } else if (Name.startswith("setter:")) { 6361 IsSetter = true; 6362 Name = Name.substr(7); 6363 } 6364 6365 if (Name.back() != ')') { 6366 S.Diag(Loc, diag::warn_attr_swift_name_function) << AL; 6367 return false; 6368 } 6369 6370 bool IsMember = false; 6371 StringRef ContextName, BaseName, Parameters; 6372 6373 std::tie(BaseName, Parameters) = Name.split('('); 6374 6375 // Split at the first '.', if it exists, which separates the context name 6376 // from the base name. 6377 std::tie(ContextName, BaseName) = BaseName.split('.'); 6378 if (BaseName.empty()) { 6379 BaseName = ContextName; 6380 ContextName = StringRef(); 6381 } else if (ContextName.empty() || !isValidAsciiIdentifier(ContextName)) { 6382 S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) 6383 << AL << /*context*/ 1; 6384 return false; 6385 } else { 6386 IsMember = true; 6387 } 6388 6389 if (!isValidAsciiIdentifier(BaseName) || BaseName == "_") { 6390 S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) 6391 << AL << /*basename*/ 0; 6392 return false; 6393 } 6394 6395 bool IsSubscript = BaseName == "subscript"; 6396 // A subscript accessor must be a getter or setter. 6397 if (IsSubscript && !IsGetter && !IsSetter) { 6398 S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter) 6399 << AL << /* getter or setter */ 0; 6400 return false; 6401 } 6402 6403 if (Parameters.empty()) { 6404 S.Diag(Loc, diag::warn_attr_swift_name_missing_parameters) << AL; 6405 return false; 6406 } 6407 6408 assert(Parameters.back() == ')' && "expected ')'"); 6409 Parameters = Parameters.drop_back(); // ')' 6410 6411 if (Parameters.empty()) { 6412 // Setters and subscripts must have at least one parameter. 6413 if (IsSubscript) { 6414 S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter) 6415 << AL << /* have at least one parameter */1; 6416 return false; 6417 } 6418 6419 if (IsSetter) { 6420 S.Diag(Loc, diag::warn_attr_swift_name_setter_parameters) << AL; 6421 return false; 6422 } 6423 6424 return true; 6425 } 6426 6427 if (Parameters.back() != ':') { 6428 S.Diag(Loc, diag::warn_attr_swift_name_function) << AL; 6429 return false; 6430 } 6431 6432 StringRef CurrentParam; 6433 llvm::Optional<unsigned> SelfLocation; 6434 unsigned NewValueCount = 0; 6435 llvm::Optional<unsigned> NewValueLocation; 6436 do { 6437 std::tie(CurrentParam, Parameters) = Parameters.split(':'); 6438 6439 if (!isValidAsciiIdentifier(CurrentParam)) { 6440 S.Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) 6441 << AL << /*parameter*/2; 6442 return false; 6443 } 6444 6445 if (IsMember && CurrentParam == "self") { 6446 // "self" indicates the "self" argument for a member. 6447 6448 // More than one "self"? 6449 if (SelfLocation) { 6450 S.Diag(Loc, diag::warn_attr_swift_name_multiple_selfs) << AL; 6451 return false; 6452 } 6453 6454 // The "self" location is the current parameter. 6455 SelfLocation = SwiftParamCount; 6456 } else if (CurrentParam == "newValue") { 6457 // "newValue" indicates the "newValue" argument for a setter. 6458 6459 // There should only be one 'newValue', but it's only significant for 6460 // subscript accessors, so don't error right away. 6461 ++NewValueCount; 6462 6463 NewValueLocation = SwiftParamCount; 6464 } 6465 6466 ++SwiftParamCount; 6467 } while (!Parameters.empty()); 6468 6469 // Only instance subscripts are currently supported. 6470 if (IsSubscript && !SelfLocation) { 6471 S.Diag(Loc, diag::warn_attr_swift_name_subscript_invalid_parameter) 6472 << AL << /*have a 'self:' parameter*/2; 6473 return false; 6474 } 6475 6476 IsSingleParamInit = 6477 SwiftParamCount == 1 && BaseName == "init" && CurrentParam != "_"; 6478 6479 // Check the number of parameters for a getter/setter. 6480 if (IsGetter || IsSetter) { 6481 // Setters have one parameter for the new value. 6482 unsigned NumExpectedParams = IsGetter ? 0 : 1; 6483 unsigned ParamDiag = 6484 IsGetter ? diag::warn_attr_swift_name_getter_parameters 6485 : diag::warn_attr_swift_name_setter_parameters; 6486 6487 // Instance methods have one parameter for "self". 6488 if (SelfLocation) 6489 ++NumExpectedParams; 6490 6491 // Subscripts may have additional parameters beyond the expected params for 6492 // the index. 6493 if (IsSubscript) { 6494 if (SwiftParamCount < NumExpectedParams) { 6495 S.Diag(Loc, ParamDiag) << AL; 6496 return false; 6497 } 6498 6499 // A subscript setter must explicitly label its newValue parameter to 6500 // distinguish it from index parameters. 6501 if (IsSetter) { 6502 if (!NewValueLocation) { 6503 S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_no_newValue) 6504 << AL; 6505 return false; 6506 } 6507 if (NewValueCount > 1) { 6508 S.Diag(Loc, diag::warn_attr_swift_name_subscript_setter_multiple_newValues) 6509 << AL; 6510 return false; 6511 } 6512 } else { 6513 // Subscript getters should have no 'newValue:' parameter. 6514 if (NewValueLocation) { 6515 S.Diag(Loc, diag::warn_attr_swift_name_subscript_getter_newValue) 6516 << AL; 6517 return false; 6518 } 6519 } 6520 } else { 6521 // Property accessors must have exactly the number of expected params. 6522 if (SwiftParamCount != NumExpectedParams) { 6523 S.Diag(Loc, ParamDiag) << AL; 6524 return false; 6525 } 6526 } 6527 } 6528 6529 return true; 6530 } 6531 6532 bool Sema::DiagnoseSwiftName(Decl *D, StringRef Name, SourceLocation Loc, 6533 const ParsedAttr &AL, bool IsAsync) { 6534 if (isa<ObjCMethodDecl>(D) || isa<FunctionDecl>(D)) { 6535 ArrayRef<ParmVarDecl*> Params; 6536 unsigned ParamCount; 6537 6538 if (const auto *Method = dyn_cast<ObjCMethodDecl>(D)) { 6539 ParamCount = Method->getSelector().getNumArgs(); 6540 Params = Method->parameters().slice(0, ParamCount); 6541 } else { 6542 const auto *F = cast<FunctionDecl>(D); 6543 6544 ParamCount = F->getNumParams(); 6545 Params = F->parameters(); 6546 6547 if (!F->hasWrittenPrototype()) { 6548 Diag(Loc, diag::warn_attribute_wrong_decl_type) << AL 6549 << ExpectedFunctionWithProtoType; 6550 return false; 6551 } 6552 } 6553 6554 // The async name drops the last callback parameter. 6555 if (IsAsync) { 6556 if (ParamCount == 0) { 6557 Diag(Loc, diag::warn_attr_swift_name_decl_missing_params) 6558 << AL << isa<ObjCMethodDecl>(D); 6559 return false; 6560 } 6561 ParamCount -= 1; 6562 } 6563 6564 unsigned SwiftParamCount; 6565 bool IsSingleParamInit; 6566 if (!validateSwiftFunctionName(*this, AL, Loc, Name, 6567 SwiftParamCount, IsSingleParamInit)) 6568 return false; 6569 6570 bool ParamCountValid; 6571 if (SwiftParamCount == ParamCount) { 6572 ParamCountValid = true; 6573 } else if (SwiftParamCount > ParamCount) { 6574 ParamCountValid = IsSingleParamInit && ParamCount == 0; 6575 } else { 6576 // We have fewer Swift parameters than Objective-C parameters, but that 6577 // might be because we've transformed some of them. Check for potential 6578 // "out" parameters and err on the side of not warning. 6579 unsigned MaybeOutParamCount = 6580 llvm::count_if(Params, [](const ParmVarDecl *Param) -> bool { 6581 QualType ParamTy = Param->getType(); 6582 if (ParamTy->isReferenceType() || ParamTy->isPointerType()) 6583 return !ParamTy->getPointeeType().isConstQualified(); 6584 return false; 6585 }); 6586 6587 ParamCountValid = SwiftParamCount + MaybeOutParamCount >= ParamCount; 6588 } 6589 6590 if (!ParamCountValid) { 6591 Diag(Loc, diag::warn_attr_swift_name_num_params) 6592 << (SwiftParamCount > ParamCount) << AL << ParamCount 6593 << SwiftParamCount; 6594 return false; 6595 } 6596 } else if ((isa<EnumConstantDecl>(D) || isa<ObjCProtocolDecl>(D) || 6597 isa<ObjCInterfaceDecl>(D) || isa<ObjCPropertyDecl>(D) || 6598 isa<VarDecl>(D) || isa<TypedefNameDecl>(D) || isa<TagDecl>(D) || 6599 isa<IndirectFieldDecl>(D) || isa<FieldDecl>(D)) && 6600 !IsAsync) { 6601 StringRef ContextName, BaseName; 6602 6603 std::tie(ContextName, BaseName) = Name.split('.'); 6604 if (BaseName.empty()) { 6605 BaseName = ContextName; 6606 ContextName = StringRef(); 6607 } else if (!isValidAsciiIdentifier(ContextName)) { 6608 Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL 6609 << /*context*/1; 6610 return false; 6611 } 6612 6613 if (!isValidAsciiIdentifier(BaseName)) { 6614 Diag(Loc, diag::warn_attr_swift_name_invalid_identifier) << AL 6615 << /*basename*/0; 6616 return false; 6617 } 6618 } else { 6619 Diag(Loc, diag::warn_attr_swift_name_decl_kind) << AL; 6620 return false; 6621 } 6622 return true; 6623 } 6624 6625 static void handleSwiftName(Sema &S, Decl *D, const ParsedAttr &AL) { 6626 StringRef Name; 6627 SourceLocation Loc; 6628 if (!S.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc)) 6629 return; 6630 6631 if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/false)) 6632 return; 6633 6634 D->addAttr(::new (S.Context) SwiftNameAttr(S.Context, AL, Name)); 6635 } 6636 6637 static void handleSwiftAsyncName(Sema &S, Decl *D, const ParsedAttr &AL) { 6638 StringRef Name; 6639 SourceLocation Loc; 6640 if (!S.checkStringLiteralArgumentAttr(AL, 0, Name, &Loc)) 6641 return; 6642 6643 if (!S.DiagnoseSwiftName(D, Name, Loc, AL, /*IsAsync=*/true)) 6644 return; 6645 6646 D->addAttr(::new (S.Context) SwiftAsyncNameAttr(S.Context, AL, Name)); 6647 } 6648 6649 static void handleSwiftNewType(Sema &S, Decl *D, const ParsedAttr &AL) { 6650 // Make sure that there is an identifier as the annotation's single argument. 6651 if (!AL.checkExactlyNumArgs(S, 1)) 6652 return; 6653 6654 if (!AL.isArgIdent(0)) { 6655 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 6656 << AL << AANT_ArgumentIdentifier; 6657 return; 6658 } 6659 6660 SwiftNewTypeAttr::NewtypeKind Kind; 6661 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 6662 if (!SwiftNewTypeAttr::ConvertStrToNewtypeKind(II->getName(), Kind)) { 6663 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II; 6664 return; 6665 } 6666 6667 if (!isa<TypedefNameDecl>(D)) { 6668 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str) 6669 << AL << "typedefs"; 6670 return; 6671 } 6672 6673 D->addAttr(::new (S.Context) SwiftNewTypeAttr(S.Context, AL, Kind)); 6674 } 6675 6676 static void handleSwiftAsyncAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6677 if (!AL.isArgIdent(0)) { 6678 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 6679 << AL << 1 << AANT_ArgumentIdentifier; 6680 return; 6681 } 6682 6683 SwiftAsyncAttr::Kind Kind; 6684 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 6685 if (!SwiftAsyncAttr::ConvertStrToKind(II->getName(), Kind)) { 6686 S.Diag(AL.getLoc(), diag::err_swift_async_no_access) << AL << II; 6687 return; 6688 } 6689 6690 ParamIdx Idx; 6691 if (Kind == SwiftAsyncAttr::None) { 6692 // If this is 'none', then there shouldn't be any additional arguments. 6693 if (!AL.checkExactlyNumArgs(S, 1)) 6694 return; 6695 } else { 6696 // Non-none swift_async requires a completion handler index argument. 6697 if (!AL.checkExactlyNumArgs(S, 2)) 6698 return; 6699 6700 Expr *HandlerIdx = AL.getArgAsExpr(1); 6701 if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, HandlerIdx, Idx)) 6702 return; 6703 6704 const ParmVarDecl *CompletionBlock = 6705 getFunctionOrMethodParam(D, Idx.getASTIndex()); 6706 QualType CompletionBlockType = CompletionBlock->getType(); 6707 if (!CompletionBlockType->isBlockPointerType()) { 6708 S.Diag(CompletionBlock->getLocation(), 6709 diag::err_swift_async_bad_block_type) 6710 << CompletionBlock->getType(); 6711 return; 6712 } 6713 QualType BlockTy = 6714 CompletionBlockType->castAs<BlockPointerType>()->getPointeeType(); 6715 if (!BlockTy->castAs<FunctionType>()->getReturnType()->isVoidType()) { 6716 S.Diag(CompletionBlock->getLocation(), 6717 diag::err_swift_async_bad_block_type) 6718 << CompletionBlock->getType(); 6719 return; 6720 } 6721 } 6722 6723 auto *AsyncAttr = 6724 ::new (S.Context) SwiftAsyncAttr(S.Context, AL, Kind, Idx); 6725 D->addAttr(AsyncAttr); 6726 6727 if (auto *ErrorAttr = D->getAttr<SwiftAsyncErrorAttr>()) 6728 checkSwiftAsyncErrorBlock(S, D, ErrorAttr, AsyncAttr); 6729 } 6730 6731 //===----------------------------------------------------------------------===// 6732 // Microsoft specific attribute handlers. 6733 //===----------------------------------------------------------------------===// 6734 6735 UuidAttr *Sema::mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, 6736 StringRef UuidAsWritten, MSGuidDecl *GuidDecl) { 6737 if (const auto *UA = D->getAttr<UuidAttr>()) { 6738 if (declaresSameEntity(UA->getGuidDecl(), GuidDecl)) 6739 return nullptr; 6740 if (!UA->getGuid().empty()) { 6741 Diag(UA->getLocation(), diag::err_mismatched_uuid); 6742 Diag(CI.getLoc(), diag::note_previous_uuid); 6743 D->dropAttr<UuidAttr>(); 6744 } 6745 } 6746 6747 return ::new (Context) UuidAttr(Context, CI, UuidAsWritten, GuidDecl); 6748 } 6749 6750 static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6751 if (!S.LangOpts.CPlusPlus) { 6752 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang) 6753 << AL << AttributeLangSupport::C; 6754 return; 6755 } 6756 6757 StringRef OrigStrRef; 6758 SourceLocation LiteralLoc; 6759 if (!S.checkStringLiteralArgumentAttr(AL, 0, OrigStrRef, &LiteralLoc)) 6760 return; 6761 6762 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or 6763 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former. 6764 StringRef StrRef = OrigStrRef; 6765 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}') 6766 StrRef = StrRef.drop_front().drop_back(); 6767 6768 // Validate GUID length. 6769 if (StrRef.size() != 36) { 6770 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 6771 return; 6772 } 6773 6774 for (unsigned i = 0; i < 36; ++i) { 6775 if (i == 8 || i == 13 || i == 18 || i == 23) { 6776 if (StrRef[i] != '-') { 6777 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 6778 return; 6779 } 6780 } else if (!isHexDigit(StrRef[i])) { 6781 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 6782 return; 6783 } 6784 } 6785 6786 // Convert to our parsed format and canonicalize. 6787 MSGuidDecl::Parts Parsed; 6788 StrRef.substr(0, 8).getAsInteger(16, Parsed.Part1); 6789 StrRef.substr(9, 4).getAsInteger(16, Parsed.Part2); 6790 StrRef.substr(14, 4).getAsInteger(16, Parsed.Part3); 6791 for (unsigned i = 0; i != 8; ++i) 6792 StrRef.substr(19 + 2 * i + (i >= 2 ? 1 : 0), 2) 6793 .getAsInteger(16, Parsed.Part4And5[i]); 6794 MSGuidDecl *Guid = S.Context.getMSGuidDecl(Parsed); 6795 6796 // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's 6797 // the only thing in the [] list, the [] too), and add an insertion of 6798 // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas 6799 // separating attributes nor of the [ and the ] are in the AST. 6800 // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc" 6801 // on cfe-dev. 6802 if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling. 6803 S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated); 6804 6805 UuidAttr *UA = S.mergeUuidAttr(D, AL, OrigStrRef, Guid); 6806 if (UA) 6807 D->addAttr(UA); 6808 } 6809 6810 static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6811 if (!S.LangOpts.CPlusPlus) { 6812 S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang) 6813 << AL << AttributeLangSupport::C; 6814 return; 6815 } 6816 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr( 6817 D, AL, /*BestCase=*/true, (MSInheritanceModel)AL.getSemanticSpelling()); 6818 if (IA) { 6819 D->addAttr(IA); 6820 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 6821 } 6822 } 6823 6824 static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6825 const auto *VD = cast<VarDecl>(D); 6826 if (!S.Context.getTargetInfo().isTLSSupported()) { 6827 S.Diag(AL.getLoc(), diag::err_thread_unsupported); 6828 return; 6829 } 6830 if (VD->getTSCSpec() != TSCS_unspecified) { 6831 S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable); 6832 return; 6833 } 6834 if (VD->hasLocalStorage()) { 6835 S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)"; 6836 return; 6837 } 6838 D->addAttr(::new (S.Context) ThreadAttr(S.Context, AL)); 6839 } 6840 6841 static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6842 SmallVector<StringRef, 4> Tags; 6843 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) { 6844 StringRef Tag; 6845 if (!S.checkStringLiteralArgumentAttr(AL, I, Tag)) 6846 return; 6847 Tags.push_back(Tag); 6848 } 6849 6850 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) { 6851 if (!NS->isInline()) { 6852 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 0; 6853 return; 6854 } 6855 if (NS->isAnonymousNamespace()) { 6856 S.Diag(AL.getLoc(), diag::warn_attr_abi_tag_namespace) << 1; 6857 return; 6858 } 6859 if (AL.getNumArgs() == 0) 6860 Tags.push_back(NS->getName()); 6861 } else if (!AL.checkAtLeastNumArgs(S, 1)) 6862 return; 6863 6864 // Store tags sorted and without duplicates. 6865 llvm::sort(Tags); 6866 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end()); 6867 6868 D->addAttr(::new (S.Context) 6869 AbiTagAttr(S.Context, AL, Tags.data(), Tags.size())); 6870 } 6871 6872 static void handleARMInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6873 // Check the attribute arguments. 6874 if (AL.getNumArgs() > 1) { 6875 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1; 6876 return; 6877 } 6878 6879 StringRef Str; 6880 SourceLocation ArgLoc; 6881 6882 if (AL.getNumArgs() == 0) 6883 Str = ""; 6884 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) 6885 return; 6886 6887 ARMInterruptAttr::InterruptType Kind; 6888 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { 6889 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str 6890 << ArgLoc; 6891 return; 6892 } 6893 6894 D->addAttr(::new (S.Context) ARMInterruptAttr(S.Context, AL, Kind)); 6895 } 6896 6897 static void handleMSP430InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6898 // MSP430 'interrupt' attribute is applied to 6899 // a function with no parameters and void return type. 6900 if (!isFunctionOrMethod(D)) { 6901 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 6902 << "'interrupt'" << ExpectedFunctionOrMethod; 6903 return; 6904 } 6905 6906 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) { 6907 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid) 6908 << /*MSP430*/ 1 << 0; 6909 return; 6910 } 6911 6912 if (!getFunctionOrMethodResultType(D)->isVoidType()) { 6913 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid) 6914 << /*MSP430*/ 1 << 1; 6915 return; 6916 } 6917 6918 // The attribute takes one integer argument. 6919 if (!AL.checkExactlyNumArgs(S, 1)) 6920 return; 6921 6922 if (!AL.isArgExpr(0)) { 6923 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 6924 << AL << AANT_ArgumentIntegerConstant; 6925 return; 6926 } 6927 6928 Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0)); 6929 Optional<llvm::APSInt> NumParams = llvm::APSInt(32); 6930 if (!(NumParams = NumParamsExpr->getIntegerConstantExpr(S.Context))) { 6931 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 6932 << AL << AANT_ArgumentIntegerConstant 6933 << NumParamsExpr->getSourceRange(); 6934 return; 6935 } 6936 // The argument should be in range 0..63. 6937 unsigned Num = NumParams->getLimitedValue(255); 6938 if (Num > 63) { 6939 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 6940 << AL << (int)NumParams->getSExtValue() 6941 << NumParamsExpr->getSourceRange(); 6942 return; 6943 } 6944 6945 D->addAttr(::new (S.Context) MSP430InterruptAttr(S.Context, AL, Num)); 6946 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 6947 } 6948 6949 static void handleMipsInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 6950 // Only one optional argument permitted. 6951 if (AL.getNumArgs() > 1) { 6952 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1; 6953 return; 6954 } 6955 6956 StringRef Str; 6957 SourceLocation ArgLoc; 6958 6959 if (AL.getNumArgs() == 0) 6960 Str = ""; 6961 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) 6962 return; 6963 6964 // Semantic checks for a function with the 'interrupt' attribute for MIPS: 6965 // a) Must be a function. 6966 // b) Must have no parameters. 6967 // c) Must have the 'void' return type. 6968 // d) Cannot have the 'mips16' attribute, as that instruction set 6969 // lacks the 'eret' instruction. 6970 // e) The attribute itself must either have no argument or one of the 6971 // valid interrupt types, see [MipsInterruptDocs]. 6972 6973 if (!isFunctionOrMethod(D)) { 6974 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 6975 << "'interrupt'" << ExpectedFunctionOrMethod; 6976 return; 6977 } 6978 6979 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) { 6980 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid) 6981 << /*MIPS*/ 0 << 0; 6982 return; 6983 } 6984 6985 if (!getFunctionOrMethodResultType(D)->isVoidType()) { 6986 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid) 6987 << /*MIPS*/ 0 << 1; 6988 return; 6989 } 6990 6991 // We still have to do this manually because the Interrupt attributes are 6992 // a bit special due to sharing their spellings across targets. 6993 if (checkAttrMutualExclusion<Mips16Attr>(S, D, AL)) 6994 return; 6995 6996 MipsInterruptAttr::InterruptType Kind; 6997 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { 6998 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) 6999 << AL << "'" + std::string(Str) + "'"; 7000 return; 7001 } 7002 7003 D->addAttr(::new (S.Context) MipsInterruptAttr(S.Context, AL, Kind)); 7004 } 7005 7006 static void handleM68kInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7007 if (!AL.checkExactlyNumArgs(S, 1)) 7008 return; 7009 7010 if (!AL.isArgExpr(0)) { 7011 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 7012 << AL << AANT_ArgumentIntegerConstant; 7013 return; 7014 } 7015 7016 // FIXME: Check for decl - it should be void ()(void). 7017 7018 Expr *NumParamsExpr = static_cast<Expr *>(AL.getArgAsExpr(0)); 7019 auto MaybeNumParams = NumParamsExpr->getIntegerConstantExpr(S.Context); 7020 if (!MaybeNumParams) { 7021 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 7022 << AL << AANT_ArgumentIntegerConstant 7023 << NumParamsExpr->getSourceRange(); 7024 return; 7025 } 7026 7027 unsigned Num = MaybeNumParams->getLimitedValue(255); 7028 if ((Num & 1) || Num > 30) { 7029 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 7030 << AL << (int)MaybeNumParams->getSExtValue() 7031 << NumParamsExpr->getSourceRange(); 7032 return; 7033 } 7034 7035 D->addAttr(::new (S.Context) M68kInterruptAttr(S.Context, AL, Num)); 7036 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 7037 } 7038 7039 static void handleAnyX86InterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7040 // Semantic checks for a function with the 'interrupt' attribute. 7041 // a) Must be a function. 7042 // b) Must have the 'void' return type. 7043 // c) Must take 1 or 2 arguments. 7044 // d) The 1st argument must be a pointer. 7045 // e) The 2nd argument (if any) must be an unsigned integer. 7046 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) || 7047 CXXMethodDecl::isStaticOverloadedOperator( 7048 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) { 7049 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 7050 << AL << ExpectedFunctionWithProtoType; 7051 return; 7052 } 7053 // Interrupt handler must have void return type. 7054 if (!getFunctionOrMethodResultType(D)->isVoidType()) { 7055 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(), 7056 diag::err_anyx86_interrupt_attribute) 7057 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 7058 ? 0 7059 : 1) 7060 << 0; 7061 return; 7062 } 7063 // Interrupt handler must have 1 or 2 parameters. 7064 unsigned NumParams = getFunctionOrMethodNumParams(D); 7065 if (NumParams < 1 || NumParams > 2) { 7066 S.Diag(D->getBeginLoc(), diag::err_anyx86_interrupt_attribute) 7067 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 7068 ? 0 7069 : 1) 7070 << 1; 7071 return; 7072 } 7073 // The first argument must be a pointer. 7074 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) { 7075 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(), 7076 diag::err_anyx86_interrupt_attribute) 7077 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 7078 ? 0 7079 : 1) 7080 << 2; 7081 return; 7082 } 7083 // The second argument, if present, must be an unsigned integer. 7084 unsigned TypeSize = 7085 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64 7086 ? 64 7087 : 32; 7088 if (NumParams == 2 && 7089 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() || 7090 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) { 7091 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(), 7092 diag::err_anyx86_interrupt_attribute) 7093 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 7094 ? 0 7095 : 1) 7096 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false); 7097 return; 7098 } 7099 D->addAttr(::new (S.Context) AnyX86InterruptAttr(S.Context, AL)); 7100 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 7101 } 7102 7103 static void handleAVRInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7104 if (!isFunctionOrMethod(D)) { 7105 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 7106 << "'interrupt'" << ExpectedFunction; 7107 return; 7108 } 7109 7110 if (!AL.checkExactlyNumArgs(S, 0)) 7111 return; 7112 7113 handleSimpleAttribute<AVRInterruptAttr>(S, D, AL); 7114 } 7115 7116 static void handleAVRSignalAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7117 if (!isFunctionOrMethod(D)) { 7118 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 7119 << "'signal'" << ExpectedFunction; 7120 return; 7121 } 7122 7123 if (!AL.checkExactlyNumArgs(S, 0)) 7124 return; 7125 7126 handleSimpleAttribute<AVRSignalAttr>(S, D, AL); 7127 } 7128 7129 static void handleBPFPreserveAIRecord(Sema &S, RecordDecl *RD) { 7130 // Add preserve_access_index attribute to all fields and inner records. 7131 for (auto D : RD->decls()) { 7132 if (D->hasAttr<BPFPreserveAccessIndexAttr>()) 7133 continue; 7134 7135 D->addAttr(BPFPreserveAccessIndexAttr::CreateImplicit(S.Context)); 7136 if (auto *Rec = dyn_cast<RecordDecl>(D)) 7137 handleBPFPreserveAIRecord(S, Rec); 7138 } 7139 } 7140 7141 static void handleBPFPreserveAccessIndexAttr(Sema &S, Decl *D, 7142 const ParsedAttr &AL) { 7143 auto *Rec = cast<RecordDecl>(D); 7144 handleBPFPreserveAIRecord(S, Rec); 7145 Rec->addAttr(::new (S.Context) BPFPreserveAccessIndexAttr(S.Context, AL)); 7146 } 7147 7148 static bool hasBTFDeclTagAttr(Decl *D, StringRef Tag) { 7149 for (const auto *I : D->specific_attrs<BTFDeclTagAttr>()) { 7150 if (I->getBTFDeclTag() == Tag) 7151 return true; 7152 } 7153 return false; 7154 } 7155 7156 static void handleBTFDeclTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7157 StringRef Str; 7158 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str)) 7159 return; 7160 if (hasBTFDeclTagAttr(D, Str)) 7161 return; 7162 7163 D->addAttr(::new (S.Context) BTFDeclTagAttr(S.Context, AL, Str)); 7164 } 7165 7166 BTFDeclTagAttr *Sema::mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL) { 7167 if (hasBTFDeclTagAttr(D, AL.getBTFDeclTag())) 7168 return nullptr; 7169 return ::new (Context) BTFDeclTagAttr(Context, AL, AL.getBTFDeclTag()); 7170 } 7171 7172 static void handleWebAssemblyExportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7173 if (!isFunctionOrMethod(D)) { 7174 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 7175 << "'export_name'" << ExpectedFunction; 7176 return; 7177 } 7178 7179 auto *FD = cast<FunctionDecl>(D); 7180 if (FD->isThisDeclarationADefinition()) { 7181 S.Diag(D->getLocation(), diag::err_alias_is_definition) << FD << 0; 7182 return; 7183 } 7184 7185 StringRef Str; 7186 SourceLocation ArgLoc; 7187 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) 7188 return; 7189 7190 D->addAttr(::new (S.Context) WebAssemblyExportNameAttr(S.Context, AL, Str)); 7191 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 7192 } 7193 7194 WebAssemblyImportModuleAttr * 7195 Sema::mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL) { 7196 auto *FD = cast<FunctionDecl>(D); 7197 7198 if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportModuleAttr>()) { 7199 if (ExistingAttr->getImportModule() == AL.getImportModule()) 7200 return nullptr; 7201 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 0 7202 << ExistingAttr->getImportModule() << AL.getImportModule(); 7203 Diag(AL.getLoc(), diag::note_previous_attribute); 7204 return nullptr; 7205 } 7206 if (FD->hasBody()) { 7207 Diag(AL.getLoc(), diag::warn_import_on_definition) << 0; 7208 return nullptr; 7209 } 7210 return ::new (Context) WebAssemblyImportModuleAttr(Context, AL, 7211 AL.getImportModule()); 7212 } 7213 7214 WebAssemblyImportNameAttr * 7215 Sema::mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL) { 7216 auto *FD = cast<FunctionDecl>(D); 7217 7218 if (const auto *ExistingAttr = FD->getAttr<WebAssemblyImportNameAttr>()) { 7219 if (ExistingAttr->getImportName() == AL.getImportName()) 7220 return nullptr; 7221 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_import) << 1 7222 << ExistingAttr->getImportName() << AL.getImportName(); 7223 Diag(AL.getLoc(), diag::note_previous_attribute); 7224 return nullptr; 7225 } 7226 if (FD->hasBody()) { 7227 Diag(AL.getLoc(), diag::warn_import_on_definition) << 1; 7228 return nullptr; 7229 } 7230 return ::new (Context) WebAssemblyImportNameAttr(Context, AL, 7231 AL.getImportName()); 7232 } 7233 7234 static void 7235 handleWebAssemblyImportModuleAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7236 auto *FD = cast<FunctionDecl>(D); 7237 7238 StringRef Str; 7239 SourceLocation ArgLoc; 7240 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) 7241 return; 7242 if (FD->hasBody()) { 7243 S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 0; 7244 return; 7245 } 7246 7247 FD->addAttr(::new (S.Context) 7248 WebAssemblyImportModuleAttr(S.Context, AL, Str)); 7249 } 7250 7251 static void 7252 handleWebAssemblyImportNameAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7253 auto *FD = cast<FunctionDecl>(D); 7254 7255 StringRef Str; 7256 SourceLocation ArgLoc; 7257 if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) 7258 return; 7259 if (FD->hasBody()) { 7260 S.Diag(AL.getLoc(), diag::warn_import_on_definition) << 1; 7261 return; 7262 } 7263 7264 FD->addAttr(::new (S.Context) WebAssemblyImportNameAttr(S.Context, AL, Str)); 7265 } 7266 7267 static void handleRISCVInterruptAttr(Sema &S, Decl *D, 7268 const ParsedAttr &AL) { 7269 // Warn about repeated attributes. 7270 if (const auto *A = D->getAttr<RISCVInterruptAttr>()) { 7271 S.Diag(AL.getRange().getBegin(), 7272 diag::warn_riscv_repeated_interrupt_attribute); 7273 S.Diag(A->getLocation(), diag::note_riscv_repeated_interrupt_attribute); 7274 return; 7275 } 7276 7277 // Check the attribute argument. Argument is optional. 7278 if (!AL.checkAtMostNumArgs(S, 1)) 7279 return; 7280 7281 StringRef Str; 7282 SourceLocation ArgLoc; 7283 7284 // 'machine'is the default interrupt mode. 7285 if (AL.getNumArgs() == 0) 7286 Str = "machine"; 7287 else if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &ArgLoc)) 7288 return; 7289 7290 // Semantic checks for a function with the 'interrupt' attribute: 7291 // - Must be a function. 7292 // - Must have no parameters. 7293 // - Must have the 'void' return type. 7294 // - The attribute itself must either have no argument or one of the 7295 // valid interrupt types, see [RISCVInterruptDocs]. 7296 7297 if (D->getFunctionType() == nullptr) { 7298 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 7299 << "'interrupt'" << ExpectedFunction; 7300 return; 7301 } 7302 7303 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) { 7304 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid) 7305 << /*RISC-V*/ 2 << 0; 7306 return; 7307 } 7308 7309 if (!getFunctionOrMethodResultType(D)->isVoidType()) { 7310 S.Diag(D->getLocation(), diag::warn_interrupt_attribute_invalid) 7311 << /*RISC-V*/ 2 << 1; 7312 return; 7313 } 7314 7315 RISCVInterruptAttr::InterruptType Kind; 7316 if (!RISCVInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { 7317 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << Str 7318 << ArgLoc; 7319 return; 7320 } 7321 7322 D->addAttr(::new (S.Context) RISCVInterruptAttr(S.Context, AL, Kind)); 7323 } 7324 7325 static void handleInterruptAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7326 // Dispatch the interrupt attribute based on the current target. 7327 switch (S.Context.getTargetInfo().getTriple().getArch()) { 7328 case llvm::Triple::msp430: 7329 handleMSP430InterruptAttr(S, D, AL); 7330 break; 7331 case llvm::Triple::mipsel: 7332 case llvm::Triple::mips: 7333 handleMipsInterruptAttr(S, D, AL); 7334 break; 7335 case llvm::Triple::m68k: 7336 handleM68kInterruptAttr(S, D, AL); 7337 break; 7338 case llvm::Triple::x86: 7339 case llvm::Triple::x86_64: 7340 handleAnyX86InterruptAttr(S, D, AL); 7341 break; 7342 case llvm::Triple::avr: 7343 handleAVRInterruptAttr(S, D, AL); 7344 break; 7345 case llvm::Triple::riscv32: 7346 case llvm::Triple::riscv64: 7347 handleRISCVInterruptAttr(S, D, AL); 7348 break; 7349 default: 7350 handleARMInterruptAttr(S, D, AL); 7351 break; 7352 } 7353 } 7354 7355 static bool 7356 checkAMDGPUFlatWorkGroupSizeArguments(Sema &S, Expr *MinExpr, Expr *MaxExpr, 7357 const AMDGPUFlatWorkGroupSizeAttr &Attr) { 7358 // Accept template arguments for now as they depend on something else. 7359 // We'll get to check them when they eventually get instantiated. 7360 if (MinExpr->isValueDependent() || MaxExpr->isValueDependent()) 7361 return false; 7362 7363 uint32_t Min = 0; 7364 if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0)) 7365 return true; 7366 7367 uint32_t Max = 0; 7368 if (!checkUInt32Argument(S, Attr, MaxExpr, Max, 1)) 7369 return true; 7370 7371 if (Min == 0 && Max != 0) { 7372 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid) 7373 << &Attr << 0; 7374 return true; 7375 } 7376 if (Min > Max) { 7377 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid) 7378 << &Attr << 1; 7379 return true; 7380 } 7381 7382 return false; 7383 } 7384 7385 void Sema::addAMDGPUFlatWorkGroupSizeAttr(Decl *D, 7386 const AttributeCommonInfo &CI, 7387 Expr *MinExpr, Expr *MaxExpr) { 7388 AMDGPUFlatWorkGroupSizeAttr TmpAttr(Context, CI, MinExpr, MaxExpr); 7389 7390 if (checkAMDGPUFlatWorkGroupSizeArguments(*this, MinExpr, MaxExpr, TmpAttr)) 7391 return; 7392 7393 D->addAttr(::new (Context) 7394 AMDGPUFlatWorkGroupSizeAttr(Context, CI, MinExpr, MaxExpr)); 7395 } 7396 7397 static void handleAMDGPUFlatWorkGroupSizeAttr(Sema &S, Decl *D, 7398 const ParsedAttr &AL) { 7399 Expr *MinExpr = AL.getArgAsExpr(0); 7400 Expr *MaxExpr = AL.getArgAsExpr(1); 7401 7402 S.addAMDGPUFlatWorkGroupSizeAttr(D, AL, MinExpr, MaxExpr); 7403 } 7404 7405 static bool checkAMDGPUWavesPerEUArguments(Sema &S, Expr *MinExpr, 7406 Expr *MaxExpr, 7407 const AMDGPUWavesPerEUAttr &Attr) { 7408 if (S.DiagnoseUnexpandedParameterPack(MinExpr) || 7409 (MaxExpr && S.DiagnoseUnexpandedParameterPack(MaxExpr))) 7410 return true; 7411 7412 // Accept template arguments for now as they depend on something else. 7413 // We'll get to check them when they eventually get instantiated. 7414 if (MinExpr->isValueDependent() || (MaxExpr && MaxExpr->isValueDependent())) 7415 return false; 7416 7417 uint32_t Min = 0; 7418 if (!checkUInt32Argument(S, Attr, MinExpr, Min, 0)) 7419 return true; 7420 7421 uint32_t Max = 0; 7422 if (MaxExpr && !checkUInt32Argument(S, Attr, MaxExpr, Max, 1)) 7423 return true; 7424 7425 if (Min == 0 && Max != 0) { 7426 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid) 7427 << &Attr << 0; 7428 return true; 7429 } 7430 if (Max != 0 && Min > Max) { 7431 S.Diag(Attr.getLocation(), diag::err_attribute_argument_invalid) 7432 << &Attr << 1; 7433 return true; 7434 } 7435 7436 return false; 7437 } 7438 7439 void Sema::addAMDGPUWavesPerEUAttr(Decl *D, const AttributeCommonInfo &CI, 7440 Expr *MinExpr, Expr *MaxExpr) { 7441 AMDGPUWavesPerEUAttr TmpAttr(Context, CI, MinExpr, MaxExpr); 7442 7443 if (checkAMDGPUWavesPerEUArguments(*this, MinExpr, MaxExpr, TmpAttr)) 7444 return; 7445 7446 D->addAttr(::new (Context) 7447 AMDGPUWavesPerEUAttr(Context, CI, MinExpr, MaxExpr)); 7448 } 7449 7450 static void handleAMDGPUWavesPerEUAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7451 if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2)) 7452 return; 7453 7454 Expr *MinExpr = AL.getArgAsExpr(0); 7455 Expr *MaxExpr = (AL.getNumArgs() > 1) ? AL.getArgAsExpr(1) : nullptr; 7456 7457 S.addAMDGPUWavesPerEUAttr(D, AL, MinExpr, MaxExpr); 7458 } 7459 7460 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7461 uint32_t NumSGPR = 0; 7462 Expr *NumSGPRExpr = AL.getArgAsExpr(0); 7463 if (!checkUInt32Argument(S, AL, NumSGPRExpr, NumSGPR)) 7464 return; 7465 7466 D->addAttr(::new (S.Context) AMDGPUNumSGPRAttr(S.Context, AL, NumSGPR)); 7467 } 7468 7469 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7470 uint32_t NumVGPR = 0; 7471 Expr *NumVGPRExpr = AL.getArgAsExpr(0); 7472 if (!checkUInt32Argument(S, AL, NumVGPRExpr, NumVGPR)) 7473 return; 7474 7475 D->addAttr(::new (S.Context) AMDGPUNumVGPRAttr(S.Context, AL, NumVGPR)); 7476 } 7477 7478 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D, 7479 const ParsedAttr &AL) { 7480 // If we try to apply it to a function pointer, don't warn, but don't 7481 // do anything, either. It doesn't matter anyway, because there's nothing 7482 // special about calling a force_align_arg_pointer function. 7483 const auto *VD = dyn_cast<ValueDecl>(D); 7484 if (VD && VD->getType()->isFunctionPointerType()) 7485 return; 7486 // Also don't warn on function pointer typedefs. 7487 const auto *TD = dyn_cast<TypedefNameDecl>(D); 7488 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() || 7489 TD->getUnderlyingType()->isFunctionType())) 7490 return; 7491 // Attribute can only be applied to function types. 7492 if (!isa<FunctionDecl>(D)) { 7493 S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) 7494 << AL << ExpectedFunction; 7495 return; 7496 } 7497 7498 D->addAttr(::new (S.Context) X86ForceAlignArgPointerAttr(S.Context, AL)); 7499 } 7500 7501 static void handleLayoutVersion(Sema &S, Decl *D, const ParsedAttr &AL) { 7502 uint32_t Version; 7503 Expr *VersionExpr = static_cast<Expr *>(AL.getArgAsExpr(0)); 7504 if (!checkUInt32Argument(S, AL, AL.getArgAsExpr(0), Version)) 7505 return; 7506 7507 // TODO: Investigate what happens with the next major version of MSVC. 7508 if (Version != LangOptions::MSVC2015 / 100) { 7509 S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds) 7510 << AL << Version << VersionExpr->getSourceRange(); 7511 return; 7512 } 7513 7514 // The attribute expects a "major" version number like 19, but new versions of 7515 // MSVC have moved to updating the "minor", or less significant numbers, so we 7516 // have to multiply by 100 now. 7517 Version *= 100; 7518 7519 D->addAttr(::new (S.Context) LayoutVersionAttr(S.Context, AL, Version)); 7520 } 7521 7522 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, 7523 const AttributeCommonInfo &CI) { 7524 if (D->hasAttr<DLLExportAttr>()) { 7525 Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'dllimport'"; 7526 return nullptr; 7527 } 7528 7529 if (D->hasAttr<DLLImportAttr>()) 7530 return nullptr; 7531 7532 return ::new (Context) DLLImportAttr(Context, CI); 7533 } 7534 7535 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, 7536 const AttributeCommonInfo &CI) { 7537 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) { 7538 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import; 7539 D->dropAttr<DLLImportAttr>(); 7540 } 7541 7542 if (D->hasAttr<DLLExportAttr>()) 7543 return nullptr; 7544 7545 return ::new (Context) DLLExportAttr(Context, CI); 7546 } 7547 7548 static void handleDLLAttr(Sema &S, Decl *D, const ParsedAttr &A) { 7549 if (isa<ClassTemplatePartialSpecializationDecl>(D) && 7550 (S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) { 7551 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) << A; 7552 return; 7553 } 7554 7555 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 7556 if (FD->isInlined() && A.getKind() == ParsedAttr::AT_DLLImport && 7557 !(S.Context.getTargetInfo().shouldDLLImportComdatSymbols())) { 7558 // MinGW doesn't allow dllimport on inline functions. 7559 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline) 7560 << A; 7561 return; 7562 } 7563 } 7564 7565 if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) { 7566 if ((S.Context.getTargetInfo().shouldDLLImportComdatSymbols()) && 7567 MD->getParent()->isLambda()) { 7568 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A; 7569 return; 7570 } 7571 } 7572 7573 Attr *NewAttr = A.getKind() == ParsedAttr::AT_DLLExport 7574 ? (Attr *)S.mergeDLLExportAttr(D, A) 7575 : (Attr *)S.mergeDLLImportAttr(D, A); 7576 if (NewAttr) 7577 D->addAttr(NewAttr); 7578 } 7579 7580 MSInheritanceAttr * 7581 Sema::mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, 7582 bool BestCase, 7583 MSInheritanceModel Model) { 7584 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) { 7585 if (IA->getInheritanceModel() == Model) 7586 return nullptr; 7587 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance) 7588 << 1 /*previous declaration*/; 7589 Diag(CI.getLoc(), diag::note_previous_ms_inheritance); 7590 D->dropAttr<MSInheritanceAttr>(); 7591 } 7592 7593 auto *RD = cast<CXXRecordDecl>(D); 7594 if (RD->hasDefinition()) { 7595 if (checkMSInheritanceAttrOnDefinition(RD, CI.getRange(), BestCase, 7596 Model)) { 7597 return nullptr; 7598 } 7599 } else { 7600 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) { 7601 Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance) 7602 << 1 /*partial specialization*/; 7603 return nullptr; 7604 } 7605 if (RD->getDescribedClassTemplate()) { 7606 Diag(CI.getLoc(), diag::warn_ignored_ms_inheritance) 7607 << 0 /*primary template*/; 7608 return nullptr; 7609 } 7610 } 7611 7612 return ::new (Context) MSInheritanceAttr(Context, CI, BestCase); 7613 } 7614 7615 static void handleCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7616 // The capability attributes take a single string parameter for the name of 7617 // the capability they represent. The lockable attribute does not take any 7618 // parameters. However, semantically, both attributes represent the same 7619 // concept, and so they use the same semantic attribute. Eventually, the 7620 // lockable attribute will be removed. 7621 // 7622 // For backward compatibility, any capability which has no specified string 7623 // literal will be considered a "mutex." 7624 StringRef N("mutex"); 7625 SourceLocation LiteralLoc; 7626 if (AL.getKind() == ParsedAttr::AT_Capability && 7627 !S.checkStringLiteralArgumentAttr(AL, 0, N, &LiteralLoc)) 7628 return; 7629 7630 D->addAttr(::new (S.Context) CapabilityAttr(S.Context, AL, N)); 7631 } 7632 7633 static void handleAssertCapabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7634 SmallVector<Expr*, 1> Args; 7635 if (!checkLockFunAttrCommon(S, D, AL, Args)) 7636 return; 7637 7638 D->addAttr(::new (S.Context) 7639 AssertCapabilityAttr(S.Context, AL, Args.data(), Args.size())); 7640 } 7641 7642 static void handleAcquireCapabilityAttr(Sema &S, Decl *D, 7643 const ParsedAttr &AL) { 7644 SmallVector<Expr*, 1> Args; 7645 if (!checkLockFunAttrCommon(S, D, AL, Args)) 7646 return; 7647 7648 D->addAttr(::new (S.Context) AcquireCapabilityAttr(S.Context, AL, Args.data(), 7649 Args.size())); 7650 } 7651 7652 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D, 7653 const ParsedAttr &AL) { 7654 SmallVector<Expr*, 2> Args; 7655 if (!checkTryLockFunAttrCommon(S, D, AL, Args)) 7656 return; 7657 7658 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr( 7659 S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size())); 7660 } 7661 7662 static void handleReleaseCapabilityAttr(Sema &S, Decl *D, 7663 const ParsedAttr &AL) { 7664 // Check that all arguments are lockable objects. 7665 SmallVector<Expr *, 1> Args; 7666 checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, true); 7667 7668 D->addAttr(::new (S.Context) ReleaseCapabilityAttr(S.Context, AL, Args.data(), 7669 Args.size())); 7670 } 7671 7672 static void handleRequiresCapabilityAttr(Sema &S, Decl *D, 7673 const ParsedAttr &AL) { 7674 if (!AL.checkAtLeastNumArgs(S, 1)) 7675 return; 7676 7677 // check that all arguments are lockable objects 7678 SmallVector<Expr*, 1> Args; 7679 checkAttrArgsAreCapabilityObjs(S, D, AL, Args); 7680 if (Args.empty()) 7681 return; 7682 7683 RequiresCapabilityAttr *RCA = ::new (S.Context) 7684 RequiresCapabilityAttr(S.Context, AL, Args.data(), Args.size()); 7685 7686 D->addAttr(RCA); 7687 } 7688 7689 static void handleDeprecatedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7690 if (const auto *NSD = dyn_cast<NamespaceDecl>(D)) { 7691 if (NSD->isAnonymousNamespace()) { 7692 S.Diag(AL.getLoc(), diag::warn_deprecated_anonymous_namespace); 7693 // Do not want to attach the attribute to the namespace because that will 7694 // cause confusing diagnostic reports for uses of declarations within the 7695 // namespace. 7696 return; 7697 } 7698 } else if (isa<UsingDecl, UnresolvedUsingTypenameDecl, 7699 UnresolvedUsingValueDecl>(D)) { 7700 S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using) 7701 << AL; 7702 return; 7703 } 7704 7705 // Handle the cases where the attribute has a text message. 7706 StringRef Str, Replacement; 7707 if (AL.isArgExpr(0) && AL.getArgAsExpr(0) && 7708 !S.checkStringLiteralArgumentAttr(AL, 0, Str)) 7709 return; 7710 7711 // Support a single optional message only for Declspec and [[]] spellings. 7712 if (AL.isDeclspecAttribute() || AL.isStandardAttributeSyntax()) 7713 AL.checkAtMostNumArgs(S, 1); 7714 else if (AL.isArgExpr(1) && AL.getArgAsExpr(1) && 7715 !S.checkStringLiteralArgumentAttr(AL, 1, Replacement)) 7716 return; 7717 7718 if (!S.getLangOpts().CPlusPlus14 && AL.isCXX11Attribute() && !AL.isGNUScope()) 7719 S.Diag(AL.getLoc(), diag::ext_cxx14_attr) << AL; 7720 7721 D->addAttr(::new (S.Context) DeprecatedAttr(S.Context, AL, Str, Replacement)); 7722 } 7723 7724 static bool isGlobalVar(const Decl *D) { 7725 if (const auto *S = dyn_cast<VarDecl>(D)) 7726 return S->hasGlobalStorage(); 7727 return false; 7728 } 7729 7730 static void handleNoSanitizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7731 if (!AL.checkAtLeastNumArgs(S, 1)) 7732 return; 7733 7734 std::vector<StringRef> Sanitizers; 7735 7736 for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) { 7737 StringRef SanitizerName; 7738 SourceLocation LiteralLoc; 7739 7740 if (!S.checkStringLiteralArgumentAttr(AL, I, SanitizerName, &LiteralLoc)) 7741 return; 7742 7743 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 7744 SanitizerMask() && 7745 SanitizerName != "coverage") 7746 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName; 7747 else if (isGlobalVar(D) && SanitizerName != "address") 7748 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 7749 << AL << ExpectedFunctionOrMethod; 7750 Sanitizers.push_back(SanitizerName); 7751 } 7752 7753 D->addAttr(::new (S.Context) NoSanitizeAttr(S.Context, AL, Sanitizers.data(), 7754 Sanitizers.size())); 7755 } 7756 7757 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D, 7758 const ParsedAttr &AL) { 7759 StringRef AttrName = AL.getAttrName()->getName(); 7760 normalizeName(AttrName); 7761 StringRef SanitizerName = llvm::StringSwitch<StringRef>(AttrName) 7762 .Case("no_address_safety_analysis", "address") 7763 .Case("no_sanitize_address", "address") 7764 .Case("no_sanitize_thread", "thread") 7765 .Case("no_sanitize_memory", "memory"); 7766 if (isGlobalVar(D) && SanitizerName != "address") 7767 S.Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 7768 << AL << ExpectedFunction; 7769 7770 // FIXME: Rather than create a NoSanitizeSpecificAttr, this creates a 7771 // NoSanitizeAttr object; but we need to calculate the correct spelling list 7772 // index rather than incorrectly assume the index for NoSanitizeSpecificAttr 7773 // has the same spellings as the index for NoSanitizeAttr. We don't have a 7774 // general way to "translate" between the two, so this hack attempts to work 7775 // around the issue with hard-coded indices. This is critical for calling 7776 // getSpelling() or prettyPrint() on the resulting semantic attribute object 7777 // without failing assertions. 7778 unsigned TranslatedSpellingIndex = 0; 7779 if (AL.isStandardAttributeSyntax()) 7780 TranslatedSpellingIndex = 1; 7781 7782 AttributeCommonInfo Info = AL; 7783 Info.setAttributeSpellingListIndex(TranslatedSpellingIndex); 7784 D->addAttr(::new (S.Context) 7785 NoSanitizeAttr(S.Context, Info, &SanitizerName, 1)); 7786 } 7787 7788 static void handleInternalLinkageAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7789 if (InternalLinkageAttr *Internal = S.mergeInternalLinkageAttr(D, AL)) 7790 D->addAttr(Internal); 7791 } 7792 7793 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7794 if (S.LangOpts.getOpenCLCompatibleVersion() < 200) 7795 S.Diag(AL.getLoc(), diag::err_attribute_requires_opencl_version) 7796 << AL << "2.0" << 1; 7797 else 7798 S.Diag(AL.getLoc(), diag::warn_opencl_attr_deprecated_ignored) 7799 << AL << S.LangOpts.getOpenCLVersionString(); 7800 } 7801 7802 static void handleOpenCLAccessAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7803 if (D->isInvalidDecl()) 7804 return; 7805 7806 // Check if there is only one access qualifier. 7807 if (D->hasAttr<OpenCLAccessAttr>()) { 7808 if (D->getAttr<OpenCLAccessAttr>()->getSemanticSpelling() == 7809 AL.getSemanticSpelling()) { 7810 S.Diag(AL.getLoc(), diag::warn_duplicate_declspec) 7811 << AL.getAttrName()->getName() << AL.getRange(); 7812 } else { 7813 S.Diag(AL.getLoc(), diag::err_opencl_multiple_access_qualifiers) 7814 << D->getSourceRange(); 7815 D->setInvalidDecl(true); 7816 return; 7817 } 7818 } 7819 7820 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that 7821 // an image object can be read and written. OpenCL v2.0 s6.13.6 - A kernel 7822 // cannot read from and write to the same pipe object. Using the read_write 7823 // (or __read_write) qualifier with the pipe qualifier is a compilation error. 7824 // OpenCL v3.0 s6.8 - For OpenCL C 2.0, or with the 7825 // __opencl_c_read_write_images feature, image objects specified as arguments 7826 // to a kernel can additionally be declared to be read-write. 7827 // C++ for OpenCL 1.0 inherits rule from OpenCL C v2.0. 7828 // C++ for OpenCL 2021 inherits rule from OpenCL C v3.0. 7829 if (const auto *PDecl = dyn_cast<ParmVarDecl>(D)) { 7830 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr(); 7831 if (AL.getAttrName()->getName().contains("read_write")) { 7832 bool ReadWriteImagesUnsupported = 7833 (S.getLangOpts().getOpenCLCompatibleVersion() < 200) || 7834 (S.getLangOpts().getOpenCLCompatibleVersion() == 300 && 7835 !S.getOpenCLOptions().isSupported("__opencl_c_read_write_images", 7836 S.getLangOpts())); 7837 if (ReadWriteImagesUnsupported || DeclTy->isPipeType()) { 7838 S.Diag(AL.getLoc(), diag::err_opencl_invalid_read_write) 7839 << AL << PDecl->getType() << DeclTy->isImageType(); 7840 D->setInvalidDecl(true); 7841 return; 7842 } 7843 } 7844 } 7845 7846 D->addAttr(::new (S.Context) OpenCLAccessAttr(S.Context, AL)); 7847 } 7848 7849 static void handleZeroCallUsedRegsAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7850 // Check that the argument is a string literal. 7851 StringRef KindStr; 7852 SourceLocation LiteralLoc; 7853 if (!S.checkStringLiteralArgumentAttr(AL, 0, KindStr, &LiteralLoc)) 7854 return; 7855 7856 ZeroCallUsedRegsAttr::ZeroCallUsedRegsKind Kind; 7857 if (!ZeroCallUsedRegsAttr::ConvertStrToZeroCallUsedRegsKind(KindStr, Kind)) { 7858 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) 7859 << AL << KindStr; 7860 return; 7861 } 7862 7863 D->dropAttr<ZeroCallUsedRegsAttr>(); 7864 D->addAttr(ZeroCallUsedRegsAttr::Create(S.Context, Kind, AL)); 7865 } 7866 7867 static void handleSYCLKernelAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7868 // The 'sycl_kernel' attribute applies only to function templates. 7869 const auto *FD = cast<FunctionDecl>(D); 7870 const FunctionTemplateDecl *FT = FD->getDescribedFunctionTemplate(); 7871 assert(FT && "Function template is expected"); 7872 7873 // Function template must have at least two template parameters. 7874 const TemplateParameterList *TL = FT->getTemplateParameters(); 7875 if (TL->size() < 2) { 7876 S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_template_params); 7877 return; 7878 } 7879 7880 // Template parameters must be typenames. 7881 for (unsigned I = 0; I < 2; ++I) { 7882 const NamedDecl *TParam = TL->getParam(I); 7883 if (isa<NonTypeTemplateParmDecl>(TParam)) { 7884 S.Diag(FT->getLocation(), 7885 diag::warn_sycl_kernel_invalid_template_param_type); 7886 return; 7887 } 7888 } 7889 7890 // Function must have at least one argument. 7891 if (getFunctionOrMethodNumParams(D) != 1) { 7892 S.Diag(FT->getLocation(), diag::warn_sycl_kernel_num_of_function_params); 7893 return; 7894 } 7895 7896 // Function must return void. 7897 QualType RetTy = getFunctionOrMethodResultType(D); 7898 if (!RetTy->isVoidType()) { 7899 S.Diag(FT->getLocation(), diag::warn_sycl_kernel_return_type); 7900 return; 7901 } 7902 7903 handleSimpleAttribute<SYCLKernelAttr>(S, D, AL); 7904 } 7905 7906 static void handleDestroyAttr(Sema &S, Decl *D, const ParsedAttr &A) { 7907 if (!cast<VarDecl>(D)->hasGlobalStorage()) { 7908 S.Diag(D->getLocation(), diag::err_destroy_attr_on_non_static_var) 7909 << (A.getKind() == ParsedAttr::AT_AlwaysDestroy); 7910 return; 7911 } 7912 7913 if (A.getKind() == ParsedAttr::AT_AlwaysDestroy) 7914 handleSimpleAttribute<AlwaysDestroyAttr>(S, D, A); 7915 else 7916 handleSimpleAttribute<NoDestroyAttr>(S, D, A); 7917 } 7918 7919 static void handleUninitializedAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 7920 assert(cast<VarDecl>(D)->getStorageDuration() == SD_Automatic && 7921 "uninitialized is only valid on automatic duration variables"); 7922 D->addAttr(::new (S.Context) UninitializedAttr(S.Context, AL)); 7923 } 7924 7925 static bool tryMakeVariablePseudoStrong(Sema &S, VarDecl *VD, 7926 bool DiagnoseFailure) { 7927 QualType Ty = VD->getType(); 7928 if (!Ty->isObjCRetainableType()) { 7929 if (DiagnoseFailure) { 7930 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained) 7931 << 0; 7932 } 7933 return false; 7934 } 7935 7936 Qualifiers::ObjCLifetime LifetimeQual = Ty.getQualifiers().getObjCLifetime(); 7937 7938 // Sema::inferObjCARCLifetime must run after processing decl attributes 7939 // (because __block lowers to an attribute), so if the lifetime hasn't been 7940 // explicitly specified, infer it locally now. 7941 if (LifetimeQual == Qualifiers::OCL_None) 7942 LifetimeQual = Ty->getObjCARCImplicitLifetime(); 7943 7944 // The attributes only really makes sense for __strong variables; ignore any 7945 // attempts to annotate a parameter with any other lifetime qualifier. 7946 if (LifetimeQual != Qualifiers::OCL_Strong) { 7947 if (DiagnoseFailure) { 7948 S.Diag(VD->getBeginLoc(), diag::warn_ignored_objc_externally_retained) 7949 << 1; 7950 } 7951 return false; 7952 } 7953 7954 // Tampering with the type of a VarDecl here is a bit of a hack, but we need 7955 // to ensure that the variable is 'const' so that we can error on 7956 // modification, which can otherwise over-release. 7957 VD->setType(Ty.withConst()); 7958 VD->setARCPseudoStrong(true); 7959 return true; 7960 } 7961 7962 static void handleObjCExternallyRetainedAttr(Sema &S, Decl *D, 7963 const ParsedAttr &AL) { 7964 if (auto *VD = dyn_cast<VarDecl>(D)) { 7965 assert(!isa<ParmVarDecl>(VD) && "should be diagnosed automatically"); 7966 if (!VD->hasLocalStorage()) { 7967 S.Diag(D->getBeginLoc(), diag::warn_ignored_objc_externally_retained) 7968 << 0; 7969 return; 7970 } 7971 7972 if (!tryMakeVariablePseudoStrong(S, VD, /*DiagnoseFailure=*/true)) 7973 return; 7974 7975 handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL); 7976 return; 7977 } 7978 7979 // If D is a function-like declaration (method, block, or function), then we 7980 // make every parameter psuedo-strong. 7981 unsigned NumParams = 7982 hasFunctionProto(D) ? getFunctionOrMethodNumParams(D) : 0; 7983 for (unsigned I = 0; I != NumParams; ++I) { 7984 auto *PVD = const_cast<ParmVarDecl *>(getFunctionOrMethodParam(D, I)); 7985 QualType Ty = PVD->getType(); 7986 7987 // If a user wrote a parameter with __strong explicitly, then assume they 7988 // want "real" strong semantics for that parameter. This works because if 7989 // the parameter was written with __strong, then the strong qualifier will 7990 // be non-local. 7991 if (Ty.getLocalUnqualifiedType().getQualifiers().getObjCLifetime() == 7992 Qualifiers::OCL_Strong) 7993 continue; 7994 7995 tryMakeVariablePseudoStrong(S, PVD, /*DiagnoseFailure=*/false); 7996 } 7997 handleSimpleAttribute<ObjCExternallyRetainedAttr>(S, D, AL); 7998 } 7999 8000 static void handleMIGServerRoutineAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 8001 // Check that the return type is a `typedef int kern_return_t` or a typedef 8002 // around it, because otherwise MIG convention checks make no sense. 8003 // BlockDecl doesn't store a return type, so it's annoying to check, 8004 // so let's skip it for now. 8005 if (!isa<BlockDecl>(D)) { 8006 QualType T = getFunctionOrMethodResultType(D); 8007 bool IsKernReturnT = false; 8008 while (const auto *TT = T->getAs<TypedefType>()) { 8009 IsKernReturnT = (TT->getDecl()->getName() == "kern_return_t"); 8010 T = TT->desugar(); 8011 } 8012 if (!IsKernReturnT || T.getCanonicalType() != S.getASTContext().IntTy) { 8013 S.Diag(D->getBeginLoc(), 8014 diag::warn_mig_server_routine_does_not_return_kern_return_t); 8015 return; 8016 } 8017 } 8018 8019 handleSimpleAttribute<MIGServerRoutineAttr>(S, D, AL); 8020 } 8021 8022 static void handleMSAllocatorAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 8023 // Warn if the return type is not a pointer or reference type. 8024 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 8025 QualType RetTy = FD->getReturnType(); 8026 if (!RetTy->isPointerType() && !RetTy->isReferenceType()) { 8027 S.Diag(AL.getLoc(), diag::warn_declspec_allocator_nonpointer) 8028 << AL.getRange() << RetTy; 8029 return; 8030 } 8031 } 8032 8033 handleSimpleAttribute<MSAllocatorAttr>(S, D, AL); 8034 } 8035 8036 static void handleAcquireHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 8037 if (AL.isUsedAsTypeAttr()) 8038 return; 8039 // Warn if the parameter is definitely not an output parameter. 8040 if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) { 8041 if (PVD->getType()->isIntegerType()) { 8042 S.Diag(AL.getLoc(), diag::err_attribute_output_parameter) 8043 << AL.getRange(); 8044 return; 8045 } 8046 } 8047 StringRef Argument; 8048 if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument)) 8049 return; 8050 D->addAttr(AcquireHandleAttr::Create(S.Context, Argument, AL)); 8051 } 8052 8053 template<typename Attr> 8054 static void handleHandleAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 8055 StringRef Argument; 8056 if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument)) 8057 return; 8058 D->addAttr(Attr::Create(S.Context, Argument, AL)); 8059 } 8060 8061 static void handleCFGuardAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 8062 // The guard attribute takes a single identifier argument. 8063 8064 if (!AL.isArgIdent(0)) { 8065 S.Diag(AL.getLoc(), diag::err_attribute_argument_type) 8066 << AL << AANT_ArgumentIdentifier; 8067 return; 8068 } 8069 8070 CFGuardAttr::GuardArg Arg; 8071 IdentifierInfo *II = AL.getArgAsIdent(0)->Ident; 8072 if (!CFGuardAttr::ConvertStrToGuardArg(II->getName(), Arg)) { 8073 S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II; 8074 return; 8075 } 8076 8077 D->addAttr(::new (S.Context) CFGuardAttr(S.Context, AL, Arg)); 8078 } 8079 8080 8081 template <typename AttrTy> 8082 static const AttrTy *findEnforceTCBAttrByName(Decl *D, StringRef Name) { 8083 auto Attrs = D->specific_attrs<AttrTy>(); 8084 auto I = llvm::find_if(Attrs, 8085 [Name](const AttrTy *A) { 8086 return A->getTCBName() == Name; 8087 }); 8088 return I == Attrs.end() ? nullptr : *I; 8089 } 8090 8091 template <typename AttrTy, typename ConflictingAttrTy> 8092 static void handleEnforceTCBAttr(Sema &S, Decl *D, const ParsedAttr &AL) { 8093 StringRef Argument; 8094 if (!S.checkStringLiteralArgumentAttr(AL, 0, Argument)) 8095 return; 8096 8097 // A function cannot be have both regular and leaf membership in the same TCB. 8098 if (const ConflictingAttrTy *ConflictingAttr = 8099 findEnforceTCBAttrByName<ConflictingAttrTy>(D, Argument)) { 8100 // We could attach a note to the other attribute but in this case 8101 // there's no need given how the two are very close to each other. 8102 S.Diag(AL.getLoc(), diag::err_tcb_conflicting_attributes) 8103 << AL.getAttrName()->getName() << ConflictingAttr->getAttrName()->getName() 8104 << Argument; 8105 8106 // Error recovery: drop the non-leaf attribute so that to suppress 8107 // all future warnings caused by erroneous attributes. The leaf attribute 8108 // needs to be kept because it can only suppresses warnings, not cause them. 8109 D->dropAttr<EnforceTCBAttr>(); 8110 return; 8111 } 8112 8113 D->addAttr(AttrTy::Create(S.Context, Argument, AL)); 8114 } 8115 8116 template <typename AttrTy, typename ConflictingAttrTy> 8117 static AttrTy *mergeEnforceTCBAttrImpl(Sema &S, Decl *D, const AttrTy &AL) { 8118 // Check if the new redeclaration has different leaf-ness in the same TCB. 8119 StringRef TCBName = AL.getTCBName(); 8120 if (const ConflictingAttrTy *ConflictingAttr = 8121 findEnforceTCBAttrByName<ConflictingAttrTy>(D, TCBName)) { 8122 S.Diag(ConflictingAttr->getLoc(), diag::err_tcb_conflicting_attributes) 8123 << ConflictingAttr->getAttrName()->getName() 8124 << AL.getAttrName()->getName() << TCBName; 8125 8126 // Add a note so that the user could easily find the conflicting attribute. 8127 S.Diag(AL.getLoc(), diag::note_conflicting_attribute); 8128 8129 // More error recovery. 8130 D->dropAttr<EnforceTCBAttr>(); 8131 return nullptr; 8132 } 8133 8134 ASTContext &Context = S.getASTContext(); 8135 return ::new(Context) AttrTy(Context, AL, AL.getTCBName()); 8136 } 8137 8138 EnforceTCBAttr *Sema::mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL) { 8139 return mergeEnforceTCBAttrImpl<EnforceTCBAttr, EnforceTCBLeafAttr>( 8140 *this, D, AL); 8141 } 8142 8143 EnforceTCBLeafAttr *Sema::mergeEnforceTCBLeafAttr( 8144 Decl *D, const EnforceTCBLeafAttr &AL) { 8145 return mergeEnforceTCBAttrImpl<EnforceTCBLeafAttr, EnforceTCBAttr>( 8146 *this, D, AL); 8147 } 8148 8149 //===----------------------------------------------------------------------===// 8150 // Top Level Sema Entry Points 8151 //===----------------------------------------------------------------------===// 8152 8153 // Returns true if the attribute must delay setting its arguments until after 8154 // template instantiation, and false otherwise. 8155 static bool MustDelayAttributeArguments(const ParsedAttr &AL) { 8156 // Only attributes that accept expression parameter packs can delay arguments. 8157 if (!AL.acceptsExprPack()) 8158 return false; 8159 8160 bool AttrHasVariadicArg = AL.hasVariadicArg(); 8161 unsigned AttrNumArgs = AL.getNumArgMembers(); 8162 for (size_t I = 0; I < std::min(AL.getNumArgs(), AttrNumArgs); ++I) { 8163 bool IsLastAttrArg = I == (AttrNumArgs - 1); 8164 // If the argument is the last argument and it is variadic it can contain 8165 // any expression. 8166 if (IsLastAttrArg && AttrHasVariadicArg) 8167 return false; 8168 Expr *E = AL.getArgAsExpr(I); 8169 bool ArgMemberCanHoldExpr = AL.isParamExpr(I); 8170 // If the expression is a pack expansion then arguments must be delayed 8171 // unless the argument is an expression and it is the last argument of the 8172 // attribute. 8173 if (isa<PackExpansionExpr>(E)) 8174 return !(IsLastAttrArg && ArgMemberCanHoldExpr); 8175 // Last case is if the expression is value dependent then it must delay 8176 // arguments unless the corresponding argument is able to hold the 8177 // expression. 8178 if (E->isValueDependent() && !ArgMemberCanHoldExpr) 8179 return true; 8180 } 8181 return false; 8182 } 8183 8184 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if 8185 /// the attribute applies to decls. If the attribute is a type attribute, just 8186 /// silently ignore it if a GNU attribute. 8187 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, 8188 const ParsedAttr &AL, 8189 bool IncludeCXX11Attributes) { 8190 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute) 8191 return; 8192 8193 // Ignore C++11 attributes on declarator chunks: they appertain to the type 8194 // instead. 8195 if (AL.isCXX11Attribute() && !IncludeCXX11Attributes) 8196 return; 8197 8198 // Unknown attributes are automatically warned on. Target-specific attributes 8199 // which do not apply to the current target architecture are treated as 8200 // though they were unknown attributes. 8201 if (AL.getKind() == ParsedAttr::UnknownAttribute || 8202 !AL.existsInTarget(S.Context.getTargetInfo())) { 8203 S.Diag(AL.getLoc(), 8204 AL.isDeclspecAttribute() 8205 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored 8206 : (unsigned)diag::warn_unknown_attribute_ignored) 8207 << AL << AL.getRange(); 8208 return; 8209 } 8210 8211 // Check if argument population must delayed to after template instantiation. 8212 bool MustDelayArgs = MustDelayAttributeArguments(AL); 8213 8214 // Argument number check must be skipped if arguments are delayed. 8215 if (S.checkCommonAttributeFeatures(D, AL, MustDelayArgs)) 8216 return; 8217 8218 if (MustDelayArgs) { 8219 AL.handleAttrWithDelayedArgs(S, D); 8220 return; 8221 } 8222 8223 switch (AL.getKind()) { 8224 default: 8225 if (AL.getInfo().handleDeclAttribute(S, D, AL) != ParsedAttrInfo::NotHandled) 8226 break; 8227 if (!AL.isStmtAttr()) { 8228 // Type attributes are handled elsewhere; silently move on. 8229 assert(AL.isTypeAttr() && "Non-type attribute not handled"); 8230 break; 8231 } 8232 // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a 8233 // statement attribute is not written on a declaration, but this code is 8234 // needed for attributes in Attr.td that do not list any subjects. 8235 S.Diag(AL.getLoc(), diag::err_stmt_attribute_invalid_on_decl) 8236 << AL << D->getLocation(); 8237 break; 8238 case ParsedAttr::AT_Interrupt: 8239 handleInterruptAttr(S, D, AL); 8240 break; 8241 case ParsedAttr::AT_X86ForceAlignArgPointer: 8242 handleX86ForceAlignArgPointerAttr(S, D, AL); 8243 break; 8244 case ParsedAttr::AT_DLLExport: 8245 case ParsedAttr::AT_DLLImport: 8246 handleDLLAttr(S, D, AL); 8247 break; 8248 case ParsedAttr::AT_AMDGPUFlatWorkGroupSize: 8249 handleAMDGPUFlatWorkGroupSizeAttr(S, D, AL); 8250 break; 8251 case ParsedAttr::AT_AMDGPUWavesPerEU: 8252 handleAMDGPUWavesPerEUAttr(S, D, AL); 8253 break; 8254 case ParsedAttr::AT_AMDGPUNumSGPR: 8255 handleAMDGPUNumSGPRAttr(S, D, AL); 8256 break; 8257 case ParsedAttr::AT_AMDGPUNumVGPR: 8258 handleAMDGPUNumVGPRAttr(S, D, AL); 8259 break; 8260 case ParsedAttr::AT_AVRSignal: 8261 handleAVRSignalAttr(S, D, AL); 8262 break; 8263 case ParsedAttr::AT_BPFPreserveAccessIndex: 8264 handleBPFPreserveAccessIndexAttr(S, D, AL); 8265 break; 8266 case ParsedAttr::AT_BTFDeclTag: 8267 handleBTFDeclTagAttr(S, D, AL); 8268 break; 8269 case ParsedAttr::AT_WebAssemblyExportName: 8270 handleWebAssemblyExportNameAttr(S, D, AL); 8271 break; 8272 case ParsedAttr::AT_WebAssemblyImportModule: 8273 handleWebAssemblyImportModuleAttr(S, D, AL); 8274 break; 8275 case ParsedAttr::AT_WebAssemblyImportName: 8276 handleWebAssemblyImportNameAttr(S, D, AL); 8277 break; 8278 case ParsedAttr::AT_IBOutlet: 8279 handleIBOutlet(S, D, AL); 8280 break; 8281 case ParsedAttr::AT_IBOutletCollection: 8282 handleIBOutletCollection(S, D, AL); 8283 break; 8284 case ParsedAttr::AT_IFunc: 8285 handleIFuncAttr(S, D, AL); 8286 break; 8287 case ParsedAttr::AT_Alias: 8288 handleAliasAttr(S, D, AL); 8289 break; 8290 case ParsedAttr::AT_Aligned: 8291 handleAlignedAttr(S, D, AL); 8292 break; 8293 case ParsedAttr::AT_AlignValue: 8294 handleAlignValueAttr(S, D, AL); 8295 break; 8296 case ParsedAttr::AT_AllocSize: 8297 handleAllocSizeAttr(S, D, AL); 8298 break; 8299 case ParsedAttr::AT_AlwaysInline: 8300 handleAlwaysInlineAttr(S, D, AL); 8301 break; 8302 case ParsedAttr::AT_AnalyzerNoReturn: 8303 handleAnalyzerNoReturnAttr(S, D, AL); 8304 break; 8305 case ParsedAttr::AT_TLSModel: 8306 handleTLSModelAttr(S, D, AL); 8307 break; 8308 case ParsedAttr::AT_Annotate: 8309 handleAnnotateAttr(S, D, AL); 8310 break; 8311 case ParsedAttr::AT_Availability: 8312 handleAvailabilityAttr(S, D, AL); 8313 break; 8314 case ParsedAttr::AT_CarriesDependency: 8315 handleDependencyAttr(S, scope, D, AL); 8316 break; 8317 case ParsedAttr::AT_CPUDispatch: 8318 case ParsedAttr::AT_CPUSpecific: 8319 handleCPUSpecificAttr(S, D, AL); 8320 break; 8321 case ParsedAttr::AT_Common: 8322 handleCommonAttr(S, D, AL); 8323 break; 8324 case ParsedAttr::AT_CUDAConstant: 8325 handleConstantAttr(S, D, AL); 8326 break; 8327 case ParsedAttr::AT_PassObjectSize: 8328 handlePassObjectSizeAttr(S, D, AL); 8329 break; 8330 case ParsedAttr::AT_Constructor: 8331 handleConstructorAttr(S, D, AL); 8332 break; 8333 case ParsedAttr::AT_Deprecated: 8334 handleDeprecatedAttr(S, D, AL); 8335 break; 8336 case ParsedAttr::AT_Destructor: 8337 handleDestructorAttr(S, D, AL); 8338 break; 8339 case ParsedAttr::AT_EnableIf: 8340 handleEnableIfAttr(S, D, AL); 8341 break; 8342 case ParsedAttr::AT_Error: 8343 handleErrorAttr(S, D, AL); 8344 break; 8345 case ParsedAttr::AT_DiagnoseIf: 8346 handleDiagnoseIfAttr(S, D, AL); 8347 break; 8348 case ParsedAttr::AT_DiagnoseAsBuiltin: 8349 handleDiagnoseAsBuiltinAttr(S, D, AL); 8350 break; 8351 case ParsedAttr::AT_NoBuiltin: 8352 handleNoBuiltinAttr(S, D, AL); 8353 break; 8354 case ParsedAttr::AT_ExtVectorType: 8355 handleExtVectorTypeAttr(S, D, AL); 8356 break; 8357 case ParsedAttr::AT_ExternalSourceSymbol: 8358 handleExternalSourceSymbolAttr(S, D, AL); 8359 break; 8360 case ParsedAttr::AT_MinSize: 8361 handleMinSizeAttr(S, D, AL); 8362 break; 8363 case ParsedAttr::AT_OptimizeNone: 8364 handleOptimizeNoneAttr(S, D, AL); 8365 break; 8366 case ParsedAttr::AT_EnumExtensibility: 8367 handleEnumExtensibilityAttr(S, D, AL); 8368 break; 8369 case ParsedAttr::AT_SYCLKernel: 8370 handleSYCLKernelAttr(S, D, AL); 8371 break; 8372 case ParsedAttr::AT_SYCLSpecialClass: 8373 handleSimpleAttribute<SYCLSpecialClassAttr>(S, D, AL); 8374 break; 8375 case ParsedAttr::AT_Format: 8376 handleFormatAttr(S, D, AL); 8377 break; 8378 case ParsedAttr::AT_FormatArg: 8379 handleFormatArgAttr(S, D, AL); 8380 break; 8381 case ParsedAttr::AT_Callback: 8382 handleCallbackAttr(S, D, AL); 8383 break; 8384 case ParsedAttr::AT_CalledOnce: 8385 handleCalledOnceAttr(S, D, AL); 8386 break; 8387 case ParsedAttr::AT_CUDAGlobal: 8388 handleGlobalAttr(S, D, AL); 8389 break; 8390 case ParsedAttr::AT_CUDADevice: 8391 handleDeviceAttr(S, D, AL); 8392 break; 8393 case ParsedAttr::AT_HIPManaged: 8394 handleManagedAttr(S, D, AL); 8395 break; 8396 case ParsedAttr::AT_GNUInline: 8397 handleGNUInlineAttr(S, D, AL); 8398 break; 8399 case ParsedAttr::AT_CUDALaunchBounds: 8400 handleLaunchBoundsAttr(S, D, AL); 8401 break; 8402 case ParsedAttr::AT_Restrict: 8403 handleRestrictAttr(S, D, AL); 8404 break; 8405 case ParsedAttr::AT_Mode: 8406 handleModeAttr(S, D, AL); 8407 break; 8408 case ParsedAttr::AT_NonNull: 8409 if (auto *PVD = dyn_cast<ParmVarDecl>(D)) 8410 handleNonNullAttrParameter(S, PVD, AL); 8411 else 8412 handleNonNullAttr(S, D, AL); 8413 break; 8414 case ParsedAttr::AT_ReturnsNonNull: 8415 handleReturnsNonNullAttr(S, D, AL); 8416 break; 8417 case ParsedAttr::AT_NoEscape: 8418 handleNoEscapeAttr(S, D, AL); 8419 break; 8420 case ParsedAttr::AT_AssumeAligned: 8421 handleAssumeAlignedAttr(S, D, AL); 8422 break; 8423 case ParsedAttr::AT_AllocAlign: 8424 handleAllocAlignAttr(S, D, AL); 8425 break; 8426 case ParsedAttr::AT_Ownership: 8427 handleOwnershipAttr(S, D, AL); 8428 break; 8429 case ParsedAttr::AT_Naked: 8430 handleNakedAttr(S, D, AL); 8431 break; 8432 case ParsedAttr::AT_NoReturn: 8433 handleNoReturnAttr(S, D, AL); 8434 break; 8435 case ParsedAttr::AT_AnyX86NoCfCheck: 8436 handleNoCfCheckAttr(S, D, AL); 8437 break; 8438 case ParsedAttr::AT_NoThrow: 8439 if (!AL.isUsedAsTypeAttr()) 8440 handleSimpleAttribute<NoThrowAttr>(S, D, AL); 8441 break; 8442 case ParsedAttr::AT_CUDAShared: 8443 handleSharedAttr(S, D, AL); 8444 break; 8445 case ParsedAttr::AT_VecReturn: 8446 handleVecReturnAttr(S, D, AL); 8447 break; 8448 case ParsedAttr::AT_ObjCOwnership: 8449 handleObjCOwnershipAttr(S, D, AL); 8450 break; 8451 case ParsedAttr::AT_ObjCPreciseLifetime: 8452 handleObjCPreciseLifetimeAttr(S, D, AL); 8453 break; 8454 case ParsedAttr::AT_ObjCReturnsInnerPointer: 8455 handleObjCReturnsInnerPointerAttr(S, D, AL); 8456 break; 8457 case ParsedAttr::AT_ObjCRequiresSuper: 8458 handleObjCRequiresSuperAttr(S, D, AL); 8459 break; 8460 case ParsedAttr::AT_ObjCBridge: 8461 handleObjCBridgeAttr(S, D, AL); 8462 break; 8463 case ParsedAttr::AT_ObjCBridgeMutable: 8464 handleObjCBridgeMutableAttr(S, D, AL); 8465 break; 8466 case ParsedAttr::AT_ObjCBridgeRelated: 8467 handleObjCBridgeRelatedAttr(S, D, AL); 8468 break; 8469 case ParsedAttr::AT_ObjCDesignatedInitializer: 8470 handleObjCDesignatedInitializer(S, D, AL); 8471 break; 8472 case ParsedAttr::AT_ObjCRuntimeName: 8473 handleObjCRuntimeName(S, D, AL); 8474 break; 8475 case ParsedAttr::AT_ObjCBoxable: 8476 handleObjCBoxable(S, D, AL); 8477 break; 8478 case ParsedAttr::AT_NSErrorDomain: 8479 handleNSErrorDomain(S, D, AL); 8480 break; 8481 case ParsedAttr::AT_CFConsumed: 8482 case ParsedAttr::AT_NSConsumed: 8483 case ParsedAttr::AT_OSConsumed: 8484 S.AddXConsumedAttr(D, AL, parsedAttrToRetainOwnershipKind(AL), 8485 /*IsTemplateInstantiation=*/false); 8486 break; 8487 case ParsedAttr::AT_OSReturnsRetainedOnZero: 8488 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnZeroAttr>( 8489 S, D, AL, isValidOSObjectOutParameter(D), 8490 diag::warn_ns_attribute_wrong_parameter_type, 8491 /*Extra Args=*/AL, /*pointer-to-OSObject-pointer*/ 3, AL.getRange()); 8492 break; 8493 case ParsedAttr::AT_OSReturnsRetainedOnNonZero: 8494 handleSimpleAttributeOrDiagnose<OSReturnsRetainedOnNonZeroAttr>( 8495 S, D, AL, isValidOSObjectOutParameter(D), 8496 diag::warn_ns_attribute_wrong_parameter_type, 8497 /*Extra Args=*/AL, /*pointer-to-OSObject-poointer*/ 3, AL.getRange()); 8498 break; 8499 case ParsedAttr::AT_NSReturnsAutoreleased: 8500 case ParsedAttr::AT_NSReturnsNotRetained: 8501 case ParsedAttr::AT_NSReturnsRetained: 8502 case ParsedAttr::AT_CFReturnsNotRetained: 8503 case ParsedAttr::AT_CFReturnsRetained: 8504 case ParsedAttr::AT_OSReturnsNotRetained: 8505 case ParsedAttr::AT_OSReturnsRetained: 8506 handleXReturnsXRetainedAttr(S, D, AL); 8507 break; 8508 case ParsedAttr::AT_WorkGroupSizeHint: 8509 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, AL); 8510 break; 8511 case ParsedAttr::AT_ReqdWorkGroupSize: 8512 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, AL); 8513 break; 8514 case ParsedAttr::AT_OpenCLIntelReqdSubGroupSize: 8515 handleSubGroupSize(S, D, AL); 8516 break; 8517 case ParsedAttr::AT_VecTypeHint: 8518 handleVecTypeHint(S, D, AL); 8519 break; 8520 case ParsedAttr::AT_InitPriority: 8521 handleInitPriorityAttr(S, D, AL); 8522 break; 8523 case ParsedAttr::AT_Packed: 8524 handlePackedAttr(S, D, AL); 8525 break; 8526 case ParsedAttr::AT_PreferredName: 8527 handlePreferredName(S, D, AL); 8528 break; 8529 case ParsedAttr::AT_Section: 8530 handleSectionAttr(S, D, AL); 8531 break; 8532 case ParsedAttr::AT_CodeSeg: 8533 handleCodeSegAttr(S, D, AL); 8534 break; 8535 case ParsedAttr::AT_Target: 8536 handleTargetAttr(S, D, AL); 8537 break; 8538 case ParsedAttr::AT_TargetClones: 8539 handleTargetClonesAttr(S, D, AL); 8540 break; 8541 case ParsedAttr::AT_MinVectorWidth: 8542 handleMinVectorWidthAttr(S, D, AL); 8543 break; 8544 case ParsedAttr::AT_Unavailable: 8545 handleAttrWithMessage<UnavailableAttr>(S, D, AL); 8546 break; 8547 case ParsedAttr::AT_Assumption: 8548 handleAssumumptionAttr(S, D, AL); 8549 break; 8550 case ParsedAttr::AT_ObjCDirect: 8551 handleObjCDirectAttr(S, D, AL); 8552 break; 8553 case ParsedAttr::AT_ObjCDirectMembers: 8554 handleObjCDirectMembersAttr(S, D, AL); 8555 handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL); 8556 break; 8557 case ParsedAttr::AT_ObjCExplicitProtocolImpl: 8558 handleObjCSuppresProtocolAttr(S, D, AL); 8559 break; 8560 case ParsedAttr::AT_Unused: 8561 handleUnusedAttr(S, D, AL); 8562 break; 8563 case ParsedAttr::AT_Visibility: 8564 handleVisibilityAttr(S, D, AL, false); 8565 break; 8566 case ParsedAttr::AT_TypeVisibility: 8567 handleVisibilityAttr(S, D, AL, true); 8568 break; 8569 case ParsedAttr::AT_WarnUnusedResult: 8570 handleWarnUnusedResult(S, D, AL); 8571 break; 8572 case ParsedAttr::AT_WeakRef: 8573 handleWeakRefAttr(S, D, AL); 8574 break; 8575 case ParsedAttr::AT_WeakImport: 8576 handleWeakImportAttr(S, D, AL); 8577 break; 8578 case ParsedAttr::AT_TransparentUnion: 8579 handleTransparentUnionAttr(S, D, AL); 8580 break; 8581 case ParsedAttr::AT_ObjCMethodFamily: 8582 handleObjCMethodFamilyAttr(S, D, AL); 8583 break; 8584 case ParsedAttr::AT_ObjCNSObject: 8585 handleObjCNSObject(S, D, AL); 8586 break; 8587 case ParsedAttr::AT_ObjCIndependentClass: 8588 handleObjCIndependentClass(S, D, AL); 8589 break; 8590 case ParsedAttr::AT_Blocks: 8591 handleBlocksAttr(S, D, AL); 8592 break; 8593 case ParsedAttr::AT_Sentinel: 8594 handleSentinelAttr(S, D, AL); 8595 break; 8596 case ParsedAttr::AT_Cleanup: 8597 handleCleanupAttr(S, D, AL); 8598 break; 8599 case ParsedAttr::AT_NoDebug: 8600 handleNoDebugAttr(S, D, AL); 8601 break; 8602 case ParsedAttr::AT_CmseNSEntry: 8603 handleCmseNSEntryAttr(S, D, AL); 8604 break; 8605 case ParsedAttr::AT_StdCall: 8606 case ParsedAttr::AT_CDecl: 8607 case ParsedAttr::AT_FastCall: 8608 case ParsedAttr::AT_ThisCall: 8609 case ParsedAttr::AT_Pascal: 8610 case ParsedAttr::AT_RegCall: 8611 case ParsedAttr::AT_SwiftCall: 8612 case ParsedAttr::AT_SwiftAsyncCall: 8613 case ParsedAttr::AT_VectorCall: 8614 case ParsedAttr::AT_MSABI: 8615 case ParsedAttr::AT_SysVABI: 8616 case ParsedAttr::AT_Pcs: 8617 case ParsedAttr::AT_IntelOclBicc: 8618 case ParsedAttr::AT_PreserveMost: 8619 case ParsedAttr::AT_PreserveAll: 8620 case ParsedAttr::AT_AArch64VectorPcs: 8621 handleCallConvAttr(S, D, AL); 8622 break; 8623 case ParsedAttr::AT_Suppress: 8624 handleSuppressAttr(S, D, AL); 8625 break; 8626 case ParsedAttr::AT_Owner: 8627 case ParsedAttr::AT_Pointer: 8628 handleLifetimeCategoryAttr(S, D, AL); 8629 break; 8630 case ParsedAttr::AT_OpenCLAccess: 8631 handleOpenCLAccessAttr(S, D, AL); 8632 break; 8633 case ParsedAttr::AT_OpenCLNoSVM: 8634 handleOpenCLNoSVMAttr(S, D, AL); 8635 break; 8636 case ParsedAttr::AT_SwiftContext: 8637 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftContext); 8638 break; 8639 case ParsedAttr::AT_SwiftAsyncContext: 8640 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftAsyncContext); 8641 break; 8642 case ParsedAttr::AT_SwiftErrorResult: 8643 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftErrorResult); 8644 break; 8645 case ParsedAttr::AT_SwiftIndirectResult: 8646 S.AddParameterABIAttr(D, AL, ParameterABI::SwiftIndirectResult); 8647 break; 8648 case ParsedAttr::AT_InternalLinkage: 8649 handleInternalLinkageAttr(S, D, AL); 8650 break; 8651 case ParsedAttr::AT_ZeroCallUsedRegs: 8652 handleZeroCallUsedRegsAttr(S, D, AL); 8653 break; 8654 8655 // Microsoft attributes: 8656 case ParsedAttr::AT_LayoutVersion: 8657 handleLayoutVersion(S, D, AL); 8658 break; 8659 case ParsedAttr::AT_Uuid: 8660 handleUuidAttr(S, D, AL); 8661 break; 8662 case ParsedAttr::AT_MSInheritance: 8663 handleMSInheritanceAttr(S, D, AL); 8664 break; 8665 case ParsedAttr::AT_Thread: 8666 handleDeclspecThreadAttr(S, D, AL); 8667 break; 8668 8669 case ParsedAttr::AT_AbiTag: 8670 handleAbiTagAttr(S, D, AL); 8671 break; 8672 case ParsedAttr::AT_CFGuard: 8673 handleCFGuardAttr(S, D, AL); 8674 break; 8675 8676 // Thread safety attributes: 8677 case ParsedAttr::AT_AssertExclusiveLock: 8678 handleAssertExclusiveLockAttr(S, D, AL); 8679 break; 8680 case ParsedAttr::AT_AssertSharedLock: 8681 handleAssertSharedLockAttr(S, D, AL); 8682 break; 8683 case ParsedAttr::AT_PtGuardedVar: 8684 handlePtGuardedVarAttr(S, D, AL); 8685 break; 8686 case ParsedAttr::AT_NoSanitize: 8687 handleNoSanitizeAttr(S, D, AL); 8688 break; 8689 case ParsedAttr::AT_NoSanitizeSpecific: 8690 handleNoSanitizeSpecificAttr(S, D, AL); 8691 break; 8692 case ParsedAttr::AT_GuardedBy: 8693 handleGuardedByAttr(S, D, AL); 8694 break; 8695 case ParsedAttr::AT_PtGuardedBy: 8696 handlePtGuardedByAttr(S, D, AL); 8697 break; 8698 case ParsedAttr::AT_ExclusiveTrylockFunction: 8699 handleExclusiveTrylockFunctionAttr(S, D, AL); 8700 break; 8701 case ParsedAttr::AT_LockReturned: 8702 handleLockReturnedAttr(S, D, AL); 8703 break; 8704 case ParsedAttr::AT_LocksExcluded: 8705 handleLocksExcludedAttr(S, D, AL); 8706 break; 8707 case ParsedAttr::AT_SharedTrylockFunction: 8708 handleSharedTrylockFunctionAttr(S, D, AL); 8709 break; 8710 case ParsedAttr::AT_AcquiredBefore: 8711 handleAcquiredBeforeAttr(S, D, AL); 8712 break; 8713 case ParsedAttr::AT_AcquiredAfter: 8714 handleAcquiredAfterAttr(S, D, AL); 8715 break; 8716 8717 // Capability analysis attributes. 8718 case ParsedAttr::AT_Capability: 8719 case ParsedAttr::AT_Lockable: 8720 handleCapabilityAttr(S, D, AL); 8721 break; 8722 case ParsedAttr::AT_RequiresCapability: 8723 handleRequiresCapabilityAttr(S, D, AL); 8724 break; 8725 8726 case ParsedAttr::AT_AssertCapability: 8727 handleAssertCapabilityAttr(S, D, AL); 8728 break; 8729 case ParsedAttr::AT_AcquireCapability: 8730 handleAcquireCapabilityAttr(S, D, AL); 8731 break; 8732 case ParsedAttr::AT_ReleaseCapability: 8733 handleReleaseCapabilityAttr(S, D, AL); 8734 break; 8735 case ParsedAttr::AT_TryAcquireCapability: 8736 handleTryAcquireCapabilityAttr(S, D, AL); 8737 break; 8738 8739 // Consumed analysis attributes. 8740 case ParsedAttr::AT_Consumable: 8741 handleConsumableAttr(S, D, AL); 8742 break; 8743 case ParsedAttr::AT_CallableWhen: 8744 handleCallableWhenAttr(S, D, AL); 8745 break; 8746 case ParsedAttr::AT_ParamTypestate: 8747 handleParamTypestateAttr(S, D, AL); 8748 break; 8749 case ParsedAttr::AT_ReturnTypestate: 8750 handleReturnTypestateAttr(S, D, AL); 8751 break; 8752 case ParsedAttr::AT_SetTypestate: 8753 handleSetTypestateAttr(S, D, AL); 8754 break; 8755 case ParsedAttr::AT_TestTypestate: 8756 handleTestTypestateAttr(S, D, AL); 8757 break; 8758 8759 // Type safety attributes. 8760 case ParsedAttr::AT_ArgumentWithTypeTag: 8761 handleArgumentWithTypeTagAttr(S, D, AL); 8762 break; 8763 case ParsedAttr::AT_TypeTagForDatatype: 8764 handleTypeTagForDatatypeAttr(S, D, AL); 8765 break; 8766 8767 // Swift attributes. 8768 case ParsedAttr::AT_SwiftAsyncName: 8769 handleSwiftAsyncName(S, D, AL); 8770 break; 8771 case ParsedAttr::AT_SwiftAttr: 8772 handleSwiftAttrAttr(S, D, AL); 8773 break; 8774 case ParsedAttr::AT_SwiftBridge: 8775 handleSwiftBridge(S, D, AL); 8776 break; 8777 case ParsedAttr::AT_SwiftError: 8778 handleSwiftError(S, D, AL); 8779 break; 8780 case ParsedAttr::AT_SwiftName: 8781 handleSwiftName(S, D, AL); 8782 break; 8783 case ParsedAttr::AT_SwiftNewType: 8784 handleSwiftNewType(S, D, AL); 8785 break; 8786 case ParsedAttr::AT_SwiftAsync: 8787 handleSwiftAsyncAttr(S, D, AL); 8788 break; 8789 case ParsedAttr::AT_SwiftAsyncError: 8790 handleSwiftAsyncError(S, D, AL); 8791 break; 8792 8793 // XRay attributes. 8794 case ParsedAttr::AT_XRayLogArgs: 8795 handleXRayLogArgsAttr(S, D, AL); 8796 break; 8797 8798 case ParsedAttr::AT_PatchableFunctionEntry: 8799 handlePatchableFunctionEntryAttr(S, D, AL); 8800 break; 8801 8802 case ParsedAttr::AT_AlwaysDestroy: 8803 case ParsedAttr::AT_NoDestroy: 8804 handleDestroyAttr(S, D, AL); 8805 break; 8806 8807 case ParsedAttr::AT_Uninitialized: 8808 handleUninitializedAttr(S, D, AL); 8809 break; 8810 8811 case ParsedAttr::AT_ObjCExternallyRetained: 8812 handleObjCExternallyRetainedAttr(S, D, AL); 8813 break; 8814 8815 case ParsedAttr::AT_MIGServerRoutine: 8816 handleMIGServerRoutineAttr(S, D, AL); 8817 break; 8818 8819 case ParsedAttr::AT_MSAllocator: 8820 handleMSAllocatorAttr(S, D, AL); 8821 break; 8822 8823 case ParsedAttr::AT_ArmBuiltinAlias: 8824 handleArmBuiltinAliasAttr(S, D, AL); 8825 break; 8826 8827 case ParsedAttr::AT_AcquireHandle: 8828 handleAcquireHandleAttr(S, D, AL); 8829 break; 8830 8831 case ParsedAttr::AT_ReleaseHandle: 8832 handleHandleAttr<ReleaseHandleAttr>(S, D, AL); 8833 break; 8834 8835 case ParsedAttr::AT_UseHandle: 8836 handleHandleAttr<UseHandleAttr>(S, D, AL); 8837 break; 8838 8839 case ParsedAttr::AT_EnforceTCB: 8840 handleEnforceTCBAttr<EnforceTCBAttr, EnforceTCBLeafAttr>(S, D, AL); 8841 break; 8842 8843 case ParsedAttr::AT_EnforceTCBLeaf: 8844 handleEnforceTCBAttr<EnforceTCBLeafAttr, EnforceTCBAttr>(S, D, AL); 8845 break; 8846 8847 case ParsedAttr::AT_BuiltinAlias: 8848 handleBuiltinAliasAttr(S, D, AL); 8849 break; 8850 8851 case ParsedAttr::AT_UsingIfExists: 8852 handleSimpleAttribute<UsingIfExistsAttr>(S, D, AL); 8853 break; 8854 } 8855 } 8856 8857 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified 8858 /// attribute list to the specified decl, ignoring any type attributes. 8859 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D, 8860 const ParsedAttributesView &AttrList, 8861 bool IncludeCXX11Attributes) { 8862 if (AttrList.empty()) 8863 return; 8864 8865 for (const ParsedAttr &AL : AttrList) 8866 ProcessDeclAttribute(*this, S, D, AL, IncludeCXX11Attributes); 8867 8868 // FIXME: We should be able to handle these cases in TableGen. 8869 // GCC accepts 8870 // static int a9 __attribute__((weakref)); 8871 // but that looks really pointless. We reject it. 8872 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) { 8873 Diag(AttrList.begin()->getLoc(), diag::err_attribute_weakref_without_alias) 8874 << cast<NamedDecl>(D); 8875 D->dropAttr<WeakRefAttr>(); 8876 return; 8877 } 8878 8879 // FIXME: We should be able to handle this in TableGen as well. It would be 8880 // good to have a way to specify "these attributes must appear as a group", 8881 // for these. Additionally, it would be good to have a way to specify "these 8882 // attribute must never appear as a group" for attributes like cold and hot. 8883 if (!D->hasAttr<OpenCLKernelAttr>()) { 8884 // These attributes cannot be applied to a non-kernel function. 8885 if (const auto *A = D->getAttr<ReqdWorkGroupSizeAttr>()) { 8886 // FIXME: This emits a different error message than 8887 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction. 8888 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 8889 D->setInvalidDecl(); 8890 } else if (const auto *A = D->getAttr<WorkGroupSizeHintAttr>()) { 8891 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 8892 D->setInvalidDecl(); 8893 } else if (const auto *A = D->getAttr<VecTypeHintAttr>()) { 8894 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 8895 D->setInvalidDecl(); 8896 } else if (const auto *A = D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>()) { 8897 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 8898 D->setInvalidDecl(); 8899 } else if (!D->hasAttr<CUDAGlobalAttr>()) { 8900 if (const auto *A = D->getAttr<AMDGPUFlatWorkGroupSizeAttr>()) { 8901 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 8902 << A << ExpectedKernelFunction; 8903 D->setInvalidDecl(); 8904 } else if (const auto *A = D->getAttr<AMDGPUWavesPerEUAttr>()) { 8905 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 8906 << A << ExpectedKernelFunction; 8907 D->setInvalidDecl(); 8908 } else if (const auto *A = D->getAttr<AMDGPUNumSGPRAttr>()) { 8909 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 8910 << A << ExpectedKernelFunction; 8911 D->setInvalidDecl(); 8912 } else if (const auto *A = D->getAttr<AMDGPUNumVGPRAttr>()) { 8913 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 8914 << A << ExpectedKernelFunction; 8915 D->setInvalidDecl(); 8916 } 8917 } 8918 } 8919 8920 // Do this check after processing D's attributes because the attribute 8921 // objc_method_family can change whether the given method is in the init 8922 // family, and it can be applied after objc_designated_initializer. This is a 8923 // bit of a hack, but we need it to be compatible with versions of clang that 8924 // processed the attribute list in the wrong order. 8925 if (D->hasAttr<ObjCDesignatedInitializerAttr>() && 8926 cast<ObjCMethodDecl>(D)->getMethodFamily() != OMF_init) { 8927 Diag(D->getLocation(), diag::err_designated_init_attr_non_init); 8928 D->dropAttr<ObjCDesignatedInitializerAttr>(); 8929 } 8930 } 8931 8932 // Helper for delayed processing TransparentUnion or BPFPreserveAccessIndexAttr 8933 // attribute. 8934 void Sema::ProcessDeclAttributeDelayed(Decl *D, 8935 const ParsedAttributesView &AttrList) { 8936 for (const ParsedAttr &AL : AttrList) 8937 if (AL.getKind() == ParsedAttr::AT_TransparentUnion) { 8938 handleTransparentUnionAttr(*this, D, AL); 8939 break; 8940 } 8941 8942 // For BPFPreserveAccessIndexAttr, we want to populate the attributes 8943 // to fields and inner records as well. 8944 if (D && D->hasAttr<BPFPreserveAccessIndexAttr>()) 8945 handleBPFPreserveAIRecord(*this, cast<RecordDecl>(D)); 8946 } 8947 8948 // Annotation attributes are the only attributes allowed after an access 8949 // specifier. 8950 bool Sema::ProcessAccessDeclAttributeList( 8951 AccessSpecDecl *ASDecl, const ParsedAttributesView &AttrList) { 8952 for (const ParsedAttr &AL : AttrList) { 8953 if (AL.getKind() == ParsedAttr::AT_Annotate) { 8954 ProcessDeclAttribute(*this, nullptr, ASDecl, AL, AL.isCXX11Attribute()); 8955 } else { 8956 Diag(AL.getLoc(), diag::err_only_annotate_after_access_spec); 8957 return true; 8958 } 8959 } 8960 return false; 8961 } 8962 8963 /// checkUnusedDeclAttributes - Check a list of attributes to see if it 8964 /// contains any decl attributes that we should warn about. 8965 static void checkUnusedDeclAttributes(Sema &S, const ParsedAttributesView &A) { 8966 for (const ParsedAttr &AL : A) { 8967 // Only warn if the attribute is an unignored, non-type attribute. 8968 if (AL.isUsedAsTypeAttr() || AL.isInvalid()) 8969 continue; 8970 if (AL.getKind() == ParsedAttr::IgnoredAttribute) 8971 continue; 8972 8973 if (AL.getKind() == ParsedAttr::UnknownAttribute) { 8974 S.Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored) 8975 << AL << AL.getRange(); 8976 } else { 8977 S.Diag(AL.getLoc(), diag::warn_attribute_not_on_decl) << AL 8978 << AL.getRange(); 8979 } 8980 } 8981 } 8982 8983 /// checkUnusedDeclAttributes - Given a declarator which is not being 8984 /// used to build a declaration, complain about any decl attributes 8985 /// which might be lying around on it. 8986 void Sema::checkUnusedDeclAttributes(Declarator &D) { 8987 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes()); 8988 ::checkUnusedDeclAttributes(*this, D.getAttributes()); 8989 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) 8990 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs()); 8991 } 8992 8993 /// DeclClonePragmaWeak - clone existing decl (maybe definition), 8994 /// \#pragma weak needs a non-definition decl and source may not have one. 8995 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 8996 SourceLocation Loc) { 8997 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND)); 8998 NamedDecl *NewD = nullptr; 8999 if (auto *FD = dyn_cast<FunctionDecl>(ND)) { 9000 FunctionDecl *NewFD; 9001 // FIXME: Missing call to CheckFunctionDeclaration(). 9002 // FIXME: Mangling? 9003 // FIXME: Is the qualifier info correct? 9004 // FIXME: Is the DeclContext correct? 9005 NewFD = FunctionDecl::Create( 9006 FD->getASTContext(), FD->getDeclContext(), Loc, Loc, 9007 DeclarationName(II), FD->getType(), FD->getTypeSourceInfo(), SC_None, 9008 getCurFPFeatures().isFPConstrained(), false /*isInlineSpecified*/, 9009 FD->hasPrototype(), ConstexprSpecKind::Unspecified, 9010 FD->getTrailingRequiresClause()); 9011 NewD = NewFD; 9012 9013 if (FD->getQualifier()) 9014 NewFD->setQualifierInfo(FD->getQualifierLoc()); 9015 9016 // Fake up parameter variables; they are declared as if this were 9017 // a typedef. 9018 QualType FDTy = FD->getType(); 9019 if (const auto *FT = FDTy->getAs<FunctionProtoType>()) { 9020 SmallVector<ParmVarDecl*, 16> Params; 9021 for (const auto &AI : FT->param_types()) { 9022 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI); 9023 Param->setScopeInfo(0, Params.size()); 9024 Params.push_back(Param); 9025 } 9026 NewFD->setParams(Params); 9027 } 9028 } else if (auto *VD = dyn_cast<VarDecl>(ND)) { 9029 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(), 9030 VD->getInnerLocStart(), VD->getLocation(), II, 9031 VD->getType(), VD->getTypeSourceInfo(), 9032 VD->getStorageClass()); 9033 if (VD->getQualifier()) 9034 cast<VarDecl>(NewD)->setQualifierInfo(VD->getQualifierLoc()); 9035 } 9036 return NewD; 9037 } 9038 9039 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak 9040 /// applied to it, possibly with an alias. 9041 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) { 9042 if (W.getUsed()) return; // only do this once 9043 W.setUsed(true); 9044 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...)) 9045 IdentifierInfo *NDId = ND->getIdentifier(); 9046 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation()); 9047 NewD->addAttr( 9048 AliasAttr::CreateImplicit(Context, NDId->getName(), W.getLocation())); 9049 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation(), 9050 AttributeCommonInfo::AS_Pragma)); 9051 WeakTopLevelDecl.push_back(NewD); 9052 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin 9053 // to insert Decl at TU scope, sorry. 9054 DeclContext *SavedContext = CurContext; 9055 CurContext = Context.getTranslationUnitDecl(); 9056 NewD->setDeclContext(CurContext); 9057 NewD->setLexicalDeclContext(CurContext); 9058 PushOnScopeChains(NewD, S); 9059 CurContext = SavedContext; 9060 } else { // just add weak to existing 9061 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation(), 9062 AttributeCommonInfo::AS_Pragma)); 9063 } 9064 } 9065 9066 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) { 9067 // It's valid to "forward-declare" #pragma weak, in which case we 9068 // have to do this. 9069 LoadExternalWeakUndeclaredIdentifiers(); 9070 if (!WeakUndeclaredIdentifiers.empty()) { 9071 NamedDecl *ND = nullptr; 9072 if (auto *VD = dyn_cast<VarDecl>(D)) 9073 if (VD->isExternC()) 9074 ND = VD; 9075 if (auto *FD = dyn_cast<FunctionDecl>(D)) 9076 if (FD->isExternC()) 9077 ND = FD; 9078 if (ND) { 9079 if (IdentifierInfo *Id = ND->getIdentifier()) { 9080 auto I = WeakUndeclaredIdentifiers.find(Id); 9081 if (I != WeakUndeclaredIdentifiers.end()) { 9082 WeakInfo W = I->second; 9083 DeclApplyPragmaWeak(S, ND, W); 9084 WeakUndeclaredIdentifiers[Id] = W; 9085 } 9086 } 9087 } 9088 } 9089 } 9090 9091 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in 9092 /// it, apply them to D. This is a bit tricky because PD can have attributes 9093 /// specified in many different places, and we need to find and apply them all. 9094 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) { 9095 // Apply decl attributes from the DeclSpec if present. 9096 if (!PD.getDeclSpec().getAttributes().empty()) 9097 ProcessDeclAttributeList(S, D, PD.getDeclSpec().getAttributes()); 9098 9099 // Walk the declarator structure, applying decl attributes that were in a type 9100 // position to the decl itself. This handles cases like: 9101 // int *__attr__(x)** D; 9102 // when X is a decl attribute. 9103 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i) 9104 ProcessDeclAttributeList(S, D, PD.getTypeObject(i).getAttrs(), 9105 /*IncludeCXX11Attributes=*/false); 9106 9107 // Finally, apply any attributes on the decl itself. 9108 ProcessDeclAttributeList(S, D, PD.getAttributes()); 9109 9110 // Apply additional attributes specified by '#pragma clang attribute'. 9111 AddPragmaAttributes(S, D); 9112 } 9113 9114 /// Is the given declaration allowed to use a forbidden type? 9115 /// If so, it'll still be annotated with an attribute that makes it 9116 /// illegal to actually use. 9117 static bool isForbiddenTypeAllowed(Sema &S, Decl *D, 9118 const DelayedDiagnostic &diag, 9119 UnavailableAttr::ImplicitReason &reason) { 9120 // Private ivars are always okay. Unfortunately, people don't 9121 // always properly make their ivars private, even in system headers. 9122 // Plus we need to make fields okay, too. 9123 if (!isa<FieldDecl>(D) && !isa<ObjCPropertyDecl>(D) && 9124 !isa<FunctionDecl>(D)) 9125 return false; 9126 9127 // Silently accept unsupported uses of __weak in both user and system 9128 // declarations when it's been disabled, for ease of integration with 9129 // -fno-objc-arc files. We do have to take some care against attempts 9130 // to define such things; for now, we've only done that for ivars 9131 // and properties. 9132 if ((isa<ObjCIvarDecl>(D) || isa<ObjCPropertyDecl>(D))) { 9133 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled || 9134 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) { 9135 reason = UnavailableAttr::IR_ForbiddenWeak; 9136 return true; 9137 } 9138 } 9139 9140 // Allow all sorts of things in system headers. 9141 if (S.Context.getSourceManager().isInSystemHeader(D->getLocation())) { 9142 // Currently, all the failures dealt with this way are due to ARC 9143 // restrictions. 9144 reason = UnavailableAttr::IR_ARCForbiddenType; 9145 return true; 9146 } 9147 9148 return false; 9149 } 9150 9151 /// Handle a delayed forbidden-type diagnostic. 9152 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &DD, 9153 Decl *D) { 9154 auto Reason = UnavailableAttr::IR_None; 9155 if (D && isForbiddenTypeAllowed(S, D, DD, Reason)) { 9156 assert(Reason && "didn't set reason?"); 9157 D->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", Reason, DD.Loc)); 9158 return; 9159 } 9160 if (S.getLangOpts().ObjCAutoRefCount) 9161 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 9162 // FIXME: we may want to suppress diagnostics for all 9163 // kind of forbidden type messages on unavailable functions. 9164 if (FD->hasAttr<UnavailableAttr>() && 9165 DD.getForbiddenTypeDiagnostic() == 9166 diag::err_arc_array_param_no_ownership) { 9167 DD.Triggered = true; 9168 return; 9169 } 9170 } 9171 9172 S.Diag(DD.Loc, DD.getForbiddenTypeDiagnostic()) 9173 << DD.getForbiddenTypeOperand() << DD.getForbiddenTypeArgument(); 9174 DD.Triggered = true; 9175 } 9176 9177 9178 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) { 9179 assert(DelayedDiagnostics.getCurrentPool()); 9180 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool(); 9181 DelayedDiagnostics.popWithoutEmitting(state); 9182 9183 // When delaying diagnostics to run in the context of a parsed 9184 // declaration, we only want to actually emit anything if parsing 9185 // succeeds. 9186 if (!decl) return; 9187 9188 // We emit all the active diagnostics in this pool or any of its 9189 // parents. In general, we'll get one pool for the decl spec 9190 // and a child pool for each declarator; in a decl group like: 9191 // deprecated_typedef foo, *bar, baz(); 9192 // only the declarator pops will be passed decls. This is correct; 9193 // we really do need to consider delayed diagnostics from the decl spec 9194 // for each of the different declarations. 9195 const DelayedDiagnosticPool *pool = &poppedPool; 9196 do { 9197 bool AnyAccessFailures = false; 9198 for (DelayedDiagnosticPool::pool_iterator 9199 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) { 9200 // This const_cast is a bit lame. Really, Triggered should be mutable. 9201 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i); 9202 if (diag.Triggered) 9203 continue; 9204 9205 switch (diag.Kind) { 9206 case DelayedDiagnostic::Availability: 9207 // Don't bother giving deprecation/unavailable diagnostics if 9208 // the decl is invalid. 9209 if (!decl->isInvalidDecl()) 9210 handleDelayedAvailabilityCheck(diag, decl); 9211 break; 9212 9213 case DelayedDiagnostic::Access: 9214 // Only produce one access control diagnostic for a structured binding 9215 // declaration: we don't need to tell the user that all the fields are 9216 // inaccessible one at a time. 9217 if (AnyAccessFailures && isa<DecompositionDecl>(decl)) 9218 continue; 9219 HandleDelayedAccessCheck(diag, decl); 9220 if (diag.Triggered) 9221 AnyAccessFailures = true; 9222 break; 9223 9224 case DelayedDiagnostic::ForbiddenType: 9225 handleDelayedForbiddenType(*this, diag, decl); 9226 break; 9227 } 9228 } 9229 } while ((pool = pool->getParent())); 9230 } 9231 9232 /// Given a set of delayed diagnostics, re-emit them as if they had 9233 /// been delayed in the current context instead of in the given pool. 9234 /// Essentially, this just moves them to the current pool. 9235 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) { 9236 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool(); 9237 assert(curPool && "re-emitting in undelayed context not supported"); 9238 curPool->steal(pool); 9239 } 9240