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