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