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