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