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