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