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