1 //===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements decl-related attribute processing. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Sema/SemaInternal.h" 15 #include "clang/AST/ASTConsumer.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/CXXInheritance.h" 18 #include "clang/AST/DeclCXX.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/Mangle.h" 24 #include "clang/AST/ASTMutationListener.h" 25 #include "clang/Basic/CharInfo.h" 26 #include "clang/Basic/SourceManager.h" 27 #include "clang/Basic/TargetInfo.h" 28 #include "clang/Lex/Preprocessor.h" 29 #include "clang/Sema/DeclSpec.h" 30 #include "clang/Sema/DelayedDiagnostic.h" 31 #include "clang/Sema/Initialization.h" 32 #include "clang/Sema/Lookup.h" 33 #include "clang/Sema/Scope.h" 34 #include "llvm/ADT/StringExtras.h" 35 #include "llvm/Support/MathExtras.h" 36 37 using namespace clang; 38 using namespace sema; 39 40 namespace AttributeLangSupport { 41 enum LANG { 42 C, 43 Cpp, 44 ObjC 45 }; 46 } // end namespace AttributeLangSupport 47 48 //===----------------------------------------------------------------------===// 49 // Helper functions 50 //===----------------------------------------------------------------------===// 51 52 /// isFunctionOrMethod - Return true if the given decl has function 53 /// type (function or function-typed variable) or an Objective-C 54 /// method. 55 static bool isFunctionOrMethod(const Decl *D) { 56 return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D); 57 } 58 59 /// \brief Return true if the given decl has function type (function or 60 /// function-typed variable) or an Objective-C method or a block. 61 static bool isFunctionOrMethodOrBlock(const Decl *D) { 62 return isFunctionOrMethod(D) || isa<BlockDecl>(D); 63 } 64 65 /// Return true if the given decl has a declarator that should have 66 /// been processed by Sema::GetTypeForDeclarator. 67 static bool hasDeclarator(const Decl *D) { 68 // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl. 69 return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) || 70 isa<ObjCPropertyDecl>(D); 71 } 72 73 /// hasFunctionProto - Return true if the given decl has a argument 74 /// information. This decl should have already passed 75 /// isFunctionOrMethod or isFunctionOrMethodOrBlock. 76 static bool hasFunctionProto(const Decl *D) { 77 if (const FunctionType *FnTy = D->getFunctionType()) 78 return isa<FunctionProtoType>(FnTy); 79 return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D); 80 } 81 82 /// getFunctionOrMethodNumParams - Return number of function or method 83 /// parameters. It is an error to call this on a K&R function (use 84 /// hasFunctionProto first). 85 static unsigned getFunctionOrMethodNumParams(const Decl *D) { 86 if (const FunctionType *FnTy = D->getFunctionType()) 87 return cast<FunctionProtoType>(FnTy)->getNumParams(); 88 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) 89 return BD->getNumParams(); 90 return cast<ObjCMethodDecl>(D)->param_size(); 91 } 92 93 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) { 94 if (const FunctionType *FnTy = D->getFunctionType()) 95 return cast<FunctionProtoType>(FnTy)->getParamType(Idx); 96 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) 97 return BD->getParamDecl(Idx)->getType(); 98 99 return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType(); 100 } 101 102 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) { 103 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 104 return FD->getParamDecl(Idx)->getSourceRange(); 105 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 106 return MD->parameters()[Idx]->getSourceRange(); 107 if (const auto *BD = dyn_cast<BlockDecl>(D)) 108 return BD->getParamDecl(Idx)->getSourceRange(); 109 return SourceRange(); 110 } 111 112 static QualType getFunctionOrMethodResultType(const Decl *D) { 113 if (const FunctionType *FnTy = D->getFunctionType()) 114 return cast<FunctionType>(FnTy)->getReturnType(); 115 return cast<ObjCMethodDecl>(D)->getReturnType(); 116 } 117 118 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) { 119 if (const auto *FD = dyn_cast<FunctionDecl>(D)) 120 return FD->getReturnTypeSourceRange(); 121 if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) 122 return MD->getReturnTypeSourceRange(); 123 return SourceRange(); 124 } 125 126 static bool isFunctionOrMethodVariadic(const Decl *D) { 127 if (const FunctionType *FnTy = D->getFunctionType()) { 128 const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy); 129 return proto->isVariadic(); 130 } 131 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) 132 return BD->isVariadic(); 133 134 return cast<ObjCMethodDecl>(D)->isVariadic(); 135 } 136 137 static bool isInstanceMethod(const Decl *D) { 138 if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D)) 139 return MethodDecl->isInstance(); 140 return false; 141 } 142 143 static inline bool isNSStringType(QualType T, ASTContext &Ctx) { 144 const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>(); 145 if (!PT) 146 return false; 147 148 ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface(); 149 if (!Cls) 150 return false; 151 152 IdentifierInfo* ClsName = Cls->getIdentifier(); 153 154 // FIXME: Should we walk the chain of classes? 155 return ClsName == &Ctx.Idents.get("NSString") || 156 ClsName == &Ctx.Idents.get("NSMutableString"); 157 } 158 159 static inline bool isCFStringType(QualType T, ASTContext &Ctx) { 160 const PointerType *PT = T->getAs<PointerType>(); 161 if (!PT) 162 return false; 163 164 const RecordType *RT = PT->getPointeeType()->getAs<RecordType>(); 165 if (!RT) 166 return false; 167 168 const RecordDecl *RD = RT->getDecl(); 169 if (RD->getTagKind() != TTK_Struct) 170 return false; 171 172 return RD->getIdentifier() == &Ctx.Idents.get("__CFString"); 173 } 174 175 static unsigned getNumAttributeArgs(const AttributeList &Attr) { 176 // FIXME: Include the type in the argument list. 177 return Attr.getNumArgs() + Attr.hasParsedType(); 178 } 179 180 template <typename Compare> 181 static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr, 182 unsigned Num, unsigned Diag, 183 Compare Comp) { 184 if (Comp(getNumAttributeArgs(Attr), Num)) { 185 S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num; 186 return false; 187 } 188 189 return true; 190 } 191 192 /// \brief Check if the attribute has exactly as many args as Num. May 193 /// output an error. 194 static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr, 195 unsigned Num) { 196 return checkAttributeNumArgsImpl(S, Attr, Num, 197 diag::err_attribute_wrong_number_arguments, 198 std::not_equal_to<unsigned>()); 199 } 200 201 /// \brief Check if the attribute has at least as many args as Num. May 202 /// output an error. 203 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr, 204 unsigned Num) { 205 return checkAttributeNumArgsImpl(S, Attr, Num, 206 diag::err_attribute_too_few_arguments, 207 std::less<unsigned>()); 208 } 209 210 /// \brief Check if the attribute has at most as many args as Num. May 211 /// output an error. 212 static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr, 213 unsigned Num) { 214 return checkAttributeNumArgsImpl(S, Attr, Num, 215 diag::err_attribute_too_many_arguments, 216 std::greater<unsigned>()); 217 } 218 219 /// \brief If Expr is a valid integer constant, get the value of the integer 220 /// expression and return success or failure. May output an error. 221 static bool checkUInt32Argument(Sema &S, const AttributeList &Attr, 222 const Expr *Expr, uint32_t &Val, 223 unsigned Idx = UINT_MAX) { 224 llvm::APSInt I(32); 225 if (Expr->isTypeDependent() || Expr->isValueDependent() || 226 !Expr->isIntegerConstantExpr(I, S.Context)) { 227 if (Idx != UINT_MAX) 228 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 229 << Attr.getName() << Idx << AANT_ArgumentIntegerConstant 230 << Expr->getSourceRange(); 231 else 232 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 233 << Attr.getName() << AANT_ArgumentIntegerConstant 234 << Expr->getSourceRange(); 235 return false; 236 } 237 238 if (!I.isIntN(32)) { 239 S.Diag(Expr->getExprLoc(), diag::err_ice_too_large) 240 << I.toString(10, false) << 32 << /* Unsigned */ 1; 241 return false; 242 } 243 244 Val = (uint32_t)I.getZExtValue(); 245 return true; 246 } 247 248 /// \brief Diagnose mutually exclusive attributes when present on a given 249 /// declaration. Returns true if diagnosed. 250 template <typename AttrTy> 251 static bool checkAttrMutualExclusion(Sema &S, Decl *D, SourceRange Range, 252 IdentifierInfo *Ident) { 253 if (AttrTy *A = D->getAttr<AttrTy>()) { 254 S.Diag(Range.getBegin(), diag::err_attributes_are_not_compatible) << Ident 255 << A; 256 S.Diag(A->getLocation(), diag::note_conflicting_attribute); 257 return true; 258 } 259 return false; 260 } 261 262 /// \brief Check if IdxExpr is a valid parameter index for a function or 263 /// instance method D. May output an error. 264 /// 265 /// \returns true if IdxExpr is a valid index. 266 static bool checkFunctionOrMethodParameterIndex(Sema &S, const Decl *D, 267 const AttributeList &Attr, 268 unsigned AttrArgNum, 269 const Expr *IdxExpr, 270 uint64_t &Idx) { 271 assert(isFunctionOrMethodOrBlock(D)); 272 273 // In C++ the implicit 'this' function parameter also counts. 274 // Parameters are counted from one. 275 bool HP = hasFunctionProto(D); 276 bool HasImplicitThisParam = isInstanceMethod(D); 277 bool IV = HP && isFunctionOrMethodVariadic(D); 278 unsigned NumParams = 279 (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam; 280 281 llvm::APSInt IdxInt; 282 if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() || 283 !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) { 284 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 285 << Attr.getName() << AttrArgNum << AANT_ArgumentIntegerConstant 286 << IdxExpr->getSourceRange(); 287 return false; 288 } 289 290 Idx = IdxInt.getLimitedValue(); 291 if (Idx < 1 || (!IV && Idx > NumParams)) { 292 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 293 << Attr.getName() << AttrArgNum << IdxExpr->getSourceRange(); 294 return false; 295 } 296 Idx--; // Convert to zero-based. 297 if (HasImplicitThisParam) { 298 if (Idx == 0) { 299 S.Diag(Attr.getLoc(), 300 diag::err_attribute_invalid_implicit_this_argument) 301 << Attr.getName() << IdxExpr->getSourceRange(); 302 return false; 303 } 304 --Idx; 305 } 306 307 return true; 308 } 309 310 /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal. 311 /// If not emit an error and return false. If the argument is an identifier it 312 /// will emit an error with a fixit hint and treat it as if it was a string 313 /// literal. 314 bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr, 315 unsigned ArgNum, StringRef &Str, 316 SourceLocation *ArgLocation) { 317 // Look for identifiers. If we have one emit a hint to fix it to a literal. 318 if (Attr.isArgIdent(ArgNum)) { 319 IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum); 320 Diag(Loc->Loc, diag::err_attribute_argument_type) 321 << Attr.getName() << AANT_ArgumentString 322 << FixItHint::CreateInsertion(Loc->Loc, "\"") 323 << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\""); 324 Str = Loc->Ident->getName(); 325 if (ArgLocation) 326 *ArgLocation = Loc->Loc; 327 return true; 328 } 329 330 // Now check for an actual string literal. 331 Expr *ArgExpr = Attr.getArgAsExpr(ArgNum); 332 StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts()); 333 if (ArgLocation) 334 *ArgLocation = ArgExpr->getLocStart(); 335 336 if (!Literal || !Literal->isAscii()) { 337 Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type) 338 << Attr.getName() << AANT_ArgumentString; 339 return false; 340 } 341 342 Str = Literal->getString(); 343 return true; 344 } 345 346 /// \brief Applies the given attribute to the Decl without performing any 347 /// additional semantic checking. 348 template <typename AttrType> 349 static void handleSimpleAttribute(Sema &S, Decl *D, 350 const AttributeList &Attr) { 351 D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context, 352 Attr.getAttributeSpellingListIndex())); 353 } 354 355 template <typename AttrType> 356 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D, 357 const AttributeList &Attr) { 358 handleSimpleAttribute<AttrType>(S, D, Attr); 359 } 360 361 /// \brief Applies the given attribute to the Decl so long as the Decl doesn't 362 /// already have one of the given incompatible attributes. 363 template <typename AttrType, typename IncompatibleAttrType, 364 typename... IncompatibleAttrTypes> 365 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D, 366 const AttributeList &Attr) { 367 if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, Attr.getRange(), 368 Attr.getName())) 369 return; 370 handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D, 371 Attr); 372 } 373 374 /// \brief Check if the passed-in expression is of type int or bool. 375 static bool isIntOrBool(Expr *Exp) { 376 QualType QT = Exp->getType(); 377 return QT->isBooleanType() || QT->isIntegerType(); 378 } 379 380 381 // Check to see if the type is a smart pointer of some kind. We assume 382 // it's a smart pointer if it defines both operator-> and operator*. 383 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) { 384 DeclContextLookupResult Res1 = RT->getDecl()->lookup( 385 S.Context.DeclarationNames.getCXXOperatorName(OO_Star)); 386 if (Res1.empty()) 387 return false; 388 389 DeclContextLookupResult Res2 = RT->getDecl()->lookup( 390 S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow)); 391 if (Res2.empty()) 392 return false; 393 394 return true; 395 } 396 397 /// \brief Check if passed in Decl is a pointer type. 398 /// Note that this function may produce an error message. 399 /// \return true if the Decl is a pointer type; false otherwise 400 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D, 401 const AttributeList &Attr) { 402 const ValueDecl *vd = cast<ValueDecl>(D); 403 QualType QT = vd->getType(); 404 if (QT->isAnyPointerType()) 405 return true; 406 407 if (const RecordType *RT = QT->getAs<RecordType>()) { 408 // If it's an incomplete type, it could be a smart pointer; skip it. 409 // (We don't want to force template instantiation if we can avoid it, 410 // since that would alter the order in which templates are instantiated.) 411 if (RT->isIncompleteType()) 412 return true; 413 414 if (threadSafetyCheckIsSmartPointer(S, RT)) 415 return true; 416 } 417 418 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer) 419 << Attr.getName() << QT; 420 return false; 421 } 422 423 /// \brief Checks that the passed in QualType either is of RecordType or points 424 /// to RecordType. Returns the relevant RecordType, null if it does not exit. 425 static const RecordType *getRecordType(QualType QT) { 426 if (const RecordType *RT = QT->getAs<RecordType>()) 427 return RT; 428 429 // Now check if we point to record type. 430 if (const PointerType *PT = QT->getAs<PointerType>()) 431 return PT->getPointeeType()->getAs<RecordType>(); 432 433 return nullptr; 434 } 435 436 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) { 437 const RecordType *RT = getRecordType(Ty); 438 439 if (!RT) 440 return false; 441 442 // Don't check for the capability if the class hasn't been defined yet. 443 if (RT->isIncompleteType()) 444 return true; 445 446 // Allow smart pointers to be used as capability objects. 447 // FIXME -- Check the type that the smart pointer points to. 448 if (threadSafetyCheckIsSmartPointer(S, RT)) 449 return true; 450 451 // Check if the record itself has a capability. 452 RecordDecl *RD = RT->getDecl(); 453 if (RD->hasAttr<CapabilityAttr>()) 454 return true; 455 456 // Else check if any base classes have a capability. 457 if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) { 458 CXXBasePaths BPaths(false, false); 459 if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) { 460 const auto *Type = BS->getType()->getAs<RecordType>(); 461 return Type->getDecl()->hasAttr<CapabilityAttr>(); 462 }, BPaths)) 463 return true; 464 } 465 return false; 466 } 467 468 static bool checkTypedefTypeForCapability(QualType Ty) { 469 const auto *TD = Ty->getAs<TypedefType>(); 470 if (!TD) 471 return false; 472 473 TypedefNameDecl *TN = TD->getDecl(); 474 if (!TN) 475 return false; 476 477 return TN->hasAttr<CapabilityAttr>(); 478 } 479 480 static bool typeHasCapability(Sema &S, QualType Ty) { 481 if (checkTypedefTypeForCapability(Ty)) 482 return true; 483 484 if (checkRecordTypeForCapability(S, Ty)) 485 return true; 486 487 return false; 488 } 489 490 static bool isCapabilityExpr(Sema &S, const Expr *Ex) { 491 // Capability expressions are simple expressions involving the boolean logic 492 // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once 493 // a DeclRefExpr is found, its type should be checked to determine whether it 494 // is a capability or not. 495 496 if (const auto *E = dyn_cast<DeclRefExpr>(Ex)) 497 return typeHasCapability(S, E->getType()); 498 else if (const auto *E = dyn_cast<CastExpr>(Ex)) 499 return isCapabilityExpr(S, E->getSubExpr()); 500 else if (const auto *E = dyn_cast<ParenExpr>(Ex)) 501 return isCapabilityExpr(S, E->getSubExpr()); 502 else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) { 503 if (E->getOpcode() == UO_LNot) 504 return isCapabilityExpr(S, E->getSubExpr()); 505 return false; 506 } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) { 507 if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr) 508 return isCapabilityExpr(S, E->getLHS()) && 509 isCapabilityExpr(S, E->getRHS()); 510 return false; 511 } 512 513 return false; 514 } 515 516 /// \brief Checks that all attribute arguments, starting from Sidx, resolve to 517 /// a capability object. 518 /// \param Sidx The attribute argument index to start checking with. 519 /// \param ParamIdxOk Whether an argument can be indexing into a function 520 /// parameter list. 521 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D, 522 const AttributeList &Attr, 523 SmallVectorImpl<Expr *> &Args, 524 int Sidx = 0, 525 bool ParamIdxOk = false) { 526 for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) { 527 Expr *ArgExp = Attr.getArgAsExpr(Idx); 528 529 if (ArgExp->isTypeDependent()) { 530 // FIXME -- need to check this again on template instantiation 531 Args.push_back(ArgExp); 532 continue; 533 } 534 535 if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) { 536 if (StrLit->getLength() == 0 || 537 (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) { 538 // Pass empty strings to the analyzer without warnings. 539 // Treat "*" as the universal lock. 540 Args.push_back(ArgExp); 541 continue; 542 } 543 544 // We allow constant strings to be used as a placeholder for expressions 545 // that are not valid C++ syntax, but warn that they are ignored. 546 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) << 547 Attr.getName(); 548 Args.push_back(ArgExp); 549 continue; 550 } 551 552 QualType ArgTy = ArgExp->getType(); 553 554 // A pointer to member expression of the form &MyClass::mu is treated 555 // specially -- we need to look at the type of the member. 556 if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp)) 557 if (UOp->getOpcode() == UO_AddrOf) 558 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr())) 559 if (DRE->getDecl()->isCXXInstanceMember()) 560 ArgTy = DRE->getDecl()->getType(); 561 562 // First see if we can just cast to record type, or pointer to record type. 563 const RecordType *RT = getRecordType(ArgTy); 564 565 // Now check if we index into a record type function param. 566 if(!RT && ParamIdxOk) { 567 FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 568 IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp); 569 if(FD && IL) { 570 unsigned int NumParams = FD->getNumParams(); 571 llvm::APInt ArgValue = IL->getValue(); 572 uint64_t ParamIdxFromOne = ArgValue.getZExtValue(); 573 uint64_t ParamIdxFromZero = ParamIdxFromOne - 1; 574 if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) { 575 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range) 576 << Attr.getName() << Idx + 1 << NumParams; 577 continue; 578 } 579 ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType(); 580 } 581 } 582 583 // If the type does not have a capability, see if the components of the 584 // expression have capabilities. This allows for writing C code where the 585 // capability may be on the type, and the expression is a capability 586 // boolean logic expression. Eg) requires_capability(A || B && !C) 587 if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp)) 588 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable) 589 << Attr.getName() << ArgTy; 590 591 Args.push_back(ArgExp); 592 } 593 } 594 595 //===----------------------------------------------------------------------===// 596 // Attribute Implementations 597 //===----------------------------------------------------------------------===// 598 599 static void handlePtGuardedVarAttr(Sema &S, Decl *D, 600 const AttributeList &Attr) { 601 if (!threadSafetyCheckIsPointer(S, D, Attr)) 602 return; 603 604 D->addAttr(::new (S.Context) 605 PtGuardedVarAttr(Attr.getRange(), S.Context, 606 Attr.getAttributeSpellingListIndex())); 607 } 608 609 static bool checkGuardedByAttrCommon(Sema &S, Decl *D, 610 const AttributeList &Attr, 611 Expr* &Arg) { 612 SmallVector<Expr*, 1> Args; 613 // check that all arguments are lockable objects 614 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 615 unsigned Size = Args.size(); 616 if (Size != 1) 617 return false; 618 619 Arg = Args[0]; 620 621 return true; 622 } 623 624 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) { 625 Expr *Arg = nullptr; 626 if (!checkGuardedByAttrCommon(S, D, Attr, Arg)) 627 return; 628 629 D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg, 630 Attr.getAttributeSpellingListIndex())); 631 } 632 633 static void handlePtGuardedByAttr(Sema &S, Decl *D, 634 const AttributeList &Attr) { 635 Expr *Arg = nullptr; 636 if (!checkGuardedByAttrCommon(S, D, Attr, Arg)) 637 return; 638 639 if (!threadSafetyCheckIsPointer(S, D, Attr)) 640 return; 641 642 D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(), 643 S.Context, Arg, 644 Attr.getAttributeSpellingListIndex())); 645 } 646 647 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, 648 const AttributeList &Attr, 649 SmallVectorImpl<Expr *> &Args) { 650 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 651 return false; 652 653 // Check that this attribute only applies to lockable types. 654 QualType QT = cast<ValueDecl>(D)->getType(); 655 if (!QT->isDependentType() && !typeHasCapability(S, QT)) { 656 S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable) 657 << Attr.getName(); 658 return false; 659 } 660 661 // Check that all arguments are lockable objects. 662 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 663 if (Args.empty()) 664 return false; 665 666 return true; 667 } 668 669 static void handleAcquiredAfterAttr(Sema &S, Decl *D, 670 const AttributeList &Attr) { 671 SmallVector<Expr*, 1> Args; 672 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args)) 673 return; 674 675 Expr **StartArg = &Args[0]; 676 D->addAttr(::new (S.Context) 677 AcquiredAfterAttr(Attr.getRange(), S.Context, 678 StartArg, Args.size(), 679 Attr.getAttributeSpellingListIndex())); 680 } 681 682 static void handleAcquiredBeforeAttr(Sema &S, Decl *D, 683 const AttributeList &Attr) { 684 SmallVector<Expr*, 1> Args; 685 if (!checkAcquireOrderAttrCommon(S, D, Attr, Args)) 686 return; 687 688 Expr **StartArg = &Args[0]; 689 D->addAttr(::new (S.Context) 690 AcquiredBeforeAttr(Attr.getRange(), S.Context, 691 StartArg, Args.size(), 692 Attr.getAttributeSpellingListIndex())); 693 } 694 695 static bool checkLockFunAttrCommon(Sema &S, Decl *D, 696 const AttributeList &Attr, 697 SmallVectorImpl<Expr *> &Args) { 698 // zero or more arguments ok 699 // check that all arguments are lockable objects 700 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true); 701 702 return true; 703 } 704 705 static void handleAssertSharedLockAttr(Sema &S, Decl *D, 706 const AttributeList &Attr) { 707 SmallVector<Expr*, 1> Args; 708 if (!checkLockFunAttrCommon(S, D, Attr, Args)) 709 return; 710 711 unsigned Size = Args.size(); 712 Expr **StartArg = Size == 0 ? nullptr : &Args[0]; 713 D->addAttr(::new (S.Context) 714 AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size, 715 Attr.getAttributeSpellingListIndex())); 716 } 717 718 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D, 719 const AttributeList &Attr) { 720 SmallVector<Expr*, 1> Args; 721 if (!checkLockFunAttrCommon(S, D, Attr, Args)) 722 return; 723 724 unsigned Size = Args.size(); 725 Expr **StartArg = Size == 0 ? nullptr : &Args[0]; 726 D->addAttr(::new (S.Context) 727 AssertExclusiveLockAttr(Attr.getRange(), S.Context, 728 StartArg, Size, 729 Attr.getAttributeSpellingListIndex())); 730 } 731 732 733 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, 734 const AttributeList &Attr, 735 SmallVectorImpl<Expr *> &Args) { 736 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 737 return false; 738 739 if (!isIntOrBool(Attr.getArgAsExpr(0))) { 740 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 741 << Attr.getName() << 1 << AANT_ArgumentIntOrBool; 742 return false; 743 } 744 745 // check that all arguments are lockable objects 746 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1); 747 748 return true; 749 } 750 751 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D, 752 const AttributeList &Attr) { 753 SmallVector<Expr*, 2> Args; 754 if (!checkTryLockFunAttrCommon(S, D, Attr, Args)) 755 return; 756 757 D->addAttr(::new (S.Context) 758 SharedTrylockFunctionAttr(Attr.getRange(), S.Context, 759 Attr.getArgAsExpr(0), 760 Args.data(), Args.size(), 761 Attr.getAttributeSpellingListIndex())); 762 } 763 764 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D, 765 const AttributeList &Attr) { 766 SmallVector<Expr*, 2> Args; 767 if (!checkTryLockFunAttrCommon(S, D, Attr, Args)) 768 return; 769 770 D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr( 771 Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(), 772 Args.size(), Attr.getAttributeSpellingListIndex())); 773 } 774 775 static void handleLockReturnedAttr(Sema &S, Decl *D, 776 const AttributeList &Attr) { 777 // check that the argument is lockable object 778 SmallVector<Expr*, 1> Args; 779 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 780 unsigned Size = Args.size(); 781 if (Size == 0) 782 return; 783 784 D->addAttr(::new (S.Context) 785 LockReturnedAttr(Attr.getRange(), S.Context, Args[0], 786 Attr.getAttributeSpellingListIndex())); 787 } 788 789 static void handleLocksExcludedAttr(Sema &S, Decl *D, 790 const AttributeList &Attr) { 791 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 792 return; 793 794 // check that all arguments are lockable objects 795 SmallVector<Expr*, 1> Args; 796 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 797 unsigned Size = Args.size(); 798 if (Size == 0) 799 return; 800 Expr **StartArg = &Args[0]; 801 802 D->addAttr(::new (S.Context) 803 LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size, 804 Attr.getAttributeSpellingListIndex())); 805 } 806 807 static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) { 808 S.Diag(Attr.getLoc(), diag::ext_clang_enable_if); 809 810 Expr *Cond = Attr.getArgAsExpr(0); 811 if (!Cond->isTypeDependent()) { 812 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond); 813 if (Converted.isInvalid()) 814 return; 815 Cond = Converted.get(); 816 } 817 818 StringRef Msg; 819 if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg)) 820 return; 821 822 SmallVector<PartialDiagnosticAt, 8> Diags; 823 if (!Cond->isValueDependent() && 824 !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D), 825 Diags)) { 826 S.Diag(Attr.getLoc(), diag::err_enable_if_never_constant_expr); 827 for (int I = 0, N = Diags.size(); I != N; ++I) 828 S.Diag(Diags[I].first, Diags[I].second); 829 return; 830 } 831 832 D->addAttr(::new (S.Context) 833 EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg, 834 Attr.getAttributeSpellingListIndex())); 835 } 836 837 static void handlePassObjectSizeAttr(Sema &S, Decl *D, 838 const AttributeList &Attr) { 839 if (D->hasAttr<PassObjectSizeAttr>()) { 840 S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter) 841 << Attr.getName(); 842 return; 843 } 844 845 Expr *E = Attr.getArgAsExpr(0); 846 uint32_t Type; 847 if (!checkUInt32Argument(S, Attr, E, Type, /*Idx=*/1)) 848 return; 849 850 // pass_object_size's argument is passed in as the second argument of 851 // __builtin_object_size. So, it has the same constraints as that second 852 // argument; namely, it must be in the range [0, 3]. 853 if (Type > 3) { 854 S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range) 855 << Attr.getName() << 0 << 3 << E->getSourceRange(); 856 return; 857 } 858 859 // pass_object_size is only supported on constant pointer parameters; as a 860 // kindness to users, we allow the parameter to be non-const for declarations. 861 // At this point, we have no clue if `D` belongs to a function declaration or 862 // definition, so we defer the constness check until later. 863 if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) { 864 S.Diag(D->getLocStart(), diag::err_attribute_pointers_only) 865 << Attr.getName() << 1; 866 return; 867 } 868 869 D->addAttr(::new (S.Context) 870 PassObjectSizeAttr(Attr.getRange(), S.Context, (int)Type, 871 Attr.getAttributeSpellingListIndex())); 872 } 873 874 static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) { 875 ConsumableAttr::ConsumedState DefaultState; 876 877 if (Attr.isArgIdent(0)) { 878 IdentifierLoc *IL = Attr.getArgAsIdent(0); 879 if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(), 880 DefaultState)) { 881 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) 882 << Attr.getName() << IL->Ident; 883 return; 884 } 885 } else { 886 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 887 << Attr.getName() << AANT_ArgumentIdentifier; 888 return; 889 } 890 891 D->addAttr(::new (S.Context) 892 ConsumableAttr(Attr.getRange(), S.Context, DefaultState, 893 Attr.getAttributeSpellingListIndex())); 894 } 895 896 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD, 897 const AttributeList &Attr) { 898 ASTContext &CurrContext = S.getASTContext(); 899 QualType ThisType = MD->getThisType(CurrContext)->getPointeeType(); 900 901 if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) { 902 if (!RD->hasAttr<ConsumableAttr>()) { 903 S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) << 904 RD->getNameAsString(); 905 906 return false; 907 } 908 } 909 910 return true; 911 } 912 913 static void handleCallableWhenAttr(Sema &S, Decl *D, 914 const AttributeList &Attr) { 915 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 916 return; 917 918 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr)) 919 return; 920 921 SmallVector<CallableWhenAttr::ConsumedState, 3> States; 922 for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) { 923 CallableWhenAttr::ConsumedState CallableState; 924 925 StringRef StateString; 926 SourceLocation Loc; 927 if (Attr.isArgIdent(ArgIndex)) { 928 IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex); 929 StateString = Ident->Ident->getName(); 930 Loc = Ident->Loc; 931 } else { 932 if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc)) 933 return; 934 } 935 936 if (!CallableWhenAttr::ConvertStrToConsumedState(StateString, 937 CallableState)) { 938 S.Diag(Loc, diag::warn_attribute_type_not_supported) 939 << Attr.getName() << StateString; 940 return; 941 } 942 943 States.push_back(CallableState); 944 } 945 946 D->addAttr(::new (S.Context) 947 CallableWhenAttr(Attr.getRange(), S.Context, States.data(), 948 States.size(), Attr.getAttributeSpellingListIndex())); 949 } 950 951 static void handleParamTypestateAttr(Sema &S, Decl *D, 952 const AttributeList &Attr) { 953 ParamTypestateAttr::ConsumedState ParamState; 954 955 if (Attr.isArgIdent(0)) { 956 IdentifierLoc *Ident = Attr.getArgAsIdent(0); 957 StringRef StateString = Ident->Ident->getName(); 958 959 if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString, 960 ParamState)) { 961 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) 962 << Attr.getName() << StateString; 963 return; 964 } 965 } else { 966 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << 967 Attr.getName() << AANT_ArgumentIdentifier; 968 return; 969 } 970 971 // FIXME: This check is currently being done in the analysis. It can be 972 // enabled here only after the parser propagates attributes at 973 // template specialization definition, not declaration. 974 //QualType ReturnType = cast<ParmVarDecl>(D)->getType(); 975 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); 976 // 977 //if (!RD || !RD->hasAttr<ConsumableAttr>()) { 978 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) << 979 // ReturnType.getAsString(); 980 // return; 981 //} 982 983 D->addAttr(::new (S.Context) 984 ParamTypestateAttr(Attr.getRange(), S.Context, ParamState, 985 Attr.getAttributeSpellingListIndex())); 986 } 987 988 static void handleReturnTypestateAttr(Sema &S, Decl *D, 989 const AttributeList &Attr) { 990 ReturnTypestateAttr::ConsumedState ReturnState; 991 992 if (Attr.isArgIdent(0)) { 993 IdentifierLoc *IL = Attr.getArgAsIdent(0); 994 if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(), 995 ReturnState)) { 996 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) 997 << Attr.getName() << IL->Ident; 998 return; 999 } 1000 } else { 1001 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << 1002 Attr.getName() << AANT_ArgumentIdentifier; 1003 return; 1004 } 1005 1006 // FIXME: This check is currently being done in the analysis. It can be 1007 // enabled here only after the parser propagates attributes at 1008 // template specialization definition, not declaration. 1009 //QualType ReturnType; 1010 // 1011 //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) { 1012 // ReturnType = Param->getType(); 1013 // 1014 //} else if (const CXXConstructorDecl *Constructor = 1015 // dyn_cast<CXXConstructorDecl>(D)) { 1016 // ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType(); 1017 // 1018 //} else { 1019 // 1020 // ReturnType = cast<FunctionDecl>(D)->getCallResultType(); 1021 //} 1022 // 1023 //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl(); 1024 // 1025 //if (!RD || !RD->hasAttr<ConsumableAttr>()) { 1026 // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) << 1027 // ReturnType.getAsString(); 1028 // return; 1029 //} 1030 1031 D->addAttr(::new (S.Context) 1032 ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState, 1033 Attr.getAttributeSpellingListIndex())); 1034 } 1035 1036 static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1037 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr)) 1038 return; 1039 1040 SetTypestateAttr::ConsumedState NewState; 1041 if (Attr.isArgIdent(0)) { 1042 IdentifierLoc *Ident = Attr.getArgAsIdent(0); 1043 StringRef Param = Ident->Ident->getName(); 1044 if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) { 1045 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) 1046 << Attr.getName() << Param; 1047 return; 1048 } 1049 } else { 1050 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << 1051 Attr.getName() << AANT_ArgumentIdentifier; 1052 return; 1053 } 1054 1055 D->addAttr(::new (S.Context) 1056 SetTypestateAttr(Attr.getRange(), S.Context, NewState, 1057 Attr.getAttributeSpellingListIndex())); 1058 } 1059 1060 static void handleTestTypestateAttr(Sema &S, Decl *D, 1061 const AttributeList &Attr) { 1062 if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr)) 1063 return; 1064 1065 TestTypestateAttr::ConsumedState TestState; 1066 if (Attr.isArgIdent(0)) { 1067 IdentifierLoc *Ident = Attr.getArgAsIdent(0); 1068 StringRef Param = Ident->Ident->getName(); 1069 if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) { 1070 S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) 1071 << Attr.getName() << Param; 1072 return; 1073 } 1074 } else { 1075 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << 1076 Attr.getName() << AANT_ArgumentIdentifier; 1077 return; 1078 } 1079 1080 D->addAttr(::new (S.Context) 1081 TestTypestateAttr(Attr.getRange(), S.Context, TestState, 1082 Attr.getAttributeSpellingListIndex())); 1083 } 1084 1085 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D, 1086 const AttributeList &Attr) { 1087 // Remember this typedef decl, we will need it later for diagnostics. 1088 S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D)); 1089 } 1090 1091 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1092 if (TagDecl *TD = dyn_cast<TagDecl>(D)) 1093 TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context, 1094 Attr.getAttributeSpellingListIndex())); 1095 else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 1096 // Report warning about changed offset in the newer compiler versions. 1097 if (!FD->getType()->isDependentType() && 1098 !FD->getType()->isIncompleteType() && FD->isBitField() && 1099 S.Context.getTypeAlign(FD->getType()) <= 8) 1100 S.Diag(Attr.getLoc(), diag::warn_attribute_packed_for_bitfield); 1101 1102 FD->addAttr(::new (S.Context) PackedAttr( 1103 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 1104 } else 1105 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 1106 } 1107 1108 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) { 1109 // The IBOutlet/IBOutletCollection attributes only apply to instance 1110 // variables or properties of Objective-C classes. The outlet must also 1111 // have an object reference type. 1112 if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) { 1113 if (!VD->getType()->getAs<ObjCObjectPointerType>()) { 1114 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type) 1115 << Attr.getName() << VD->getType() << 0; 1116 return false; 1117 } 1118 } 1119 else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) { 1120 if (!PD->getType()->getAs<ObjCObjectPointerType>()) { 1121 S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type) 1122 << Attr.getName() << PD->getType() << 1; 1123 return false; 1124 } 1125 } 1126 else { 1127 S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName(); 1128 return false; 1129 } 1130 1131 return true; 1132 } 1133 1134 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) { 1135 if (!checkIBOutletCommon(S, D, Attr)) 1136 return; 1137 1138 D->addAttr(::new (S.Context) 1139 IBOutletAttr(Attr.getRange(), S.Context, 1140 Attr.getAttributeSpellingListIndex())); 1141 } 1142 1143 static void handleIBOutletCollection(Sema &S, Decl *D, 1144 const AttributeList &Attr) { 1145 1146 // The iboutletcollection attribute can have zero or one arguments. 1147 if (Attr.getNumArgs() > 1) { 1148 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 1149 << Attr.getName() << 1; 1150 return; 1151 } 1152 1153 if (!checkIBOutletCommon(S, D, Attr)) 1154 return; 1155 1156 ParsedType PT; 1157 1158 if (Attr.hasParsedType()) 1159 PT = Attr.getTypeArg(); 1160 else { 1161 PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(), 1162 S.getScopeForContext(D->getDeclContext()->getParent())); 1163 if (!PT) { 1164 S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject"; 1165 return; 1166 } 1167 } 1168 1169 TypeSourceInfo *QTLoc = nullptr; 1170 QualType QT = S.GetTypeFromParser(PT, &QTLoc); 1171 if (!QTLoc) 1172 QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc()); 1173 1174 // Diagnose use of non-object type in iboutletcollection attribute. 1175 // FIXME. Gnu attribute extension ignores use of builtin types in 1176 // attributes. So, __attribute__((iboutletcollection(char))) will be 1177 // treated as __attribute__((iboutletcollection())). 1178 if (!QT->isObjCIdType() && !QT->isObjCObjectType()) { 1179 S.Diag(Attr.getLoc(), 1180 QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype 1181 : diag::err_iboutletcollection_type) << QT; 1182 return; 1183 } 1184 1185 D->addAttr(::new (S.Context) 1186 IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc, 1187 Attr.getAttributeSpellingListIndex())); 1188 } 1189 1190 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) { 1191 if (RefOkay) { 1192 if (T->isReferenceType()) 1193 return true; 1194 } else { 1195 T = T.getNonReferenceType(); 1196 } 1197 1198 // The nonnull attribute, and other similar attributes, can be applied to a 1199 // transparent union that contains a pointer type. 1200 if (const RecordType *UT = T->getAsUnionType()) { 1201 if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) { 1202 RecordDecl *UD = UT->getDecl(); 1203 for (const auto *I : UD->fields()) { 1204 QualType QT = I->getType(); 1205 if (QT->isAnyPointerType() || QT->isBlockPointerType()) 1206 return true; 1207 } 1208 } 1209 } 1210 1211 return T->isAnyPointerType() || T->isBlockPointerType(); 1212 } 1213 1214 static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr, 1215 SourceRange AttrParmRange, 1216 SourceRange TypeRange, 1217 bool isReturnValue = false) { 1218 if (!S.isValidPointerAttrType(T)) { 1219 if (isReturnValue) 1220 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only) 1221 << Attr.getName() << AttrParmRange << TypeRange; 1222 else 1223 S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only) 1224 << Attr.getName() << AttrParmRange << TypeRange << 0; 1225 return false; 1226 } 1227 return true; 1228 } 1229 1230 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1231 SmallVector<unsigned, 8> NonNullArgs; 1232 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) { 1233 Expr *Ex = Attr.getArgAsExpr(I); 1234 uint64_t Idx; 1235 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx)) 1236 return; 1237 1238 // Is the function argument a pointer type? 1239 if (Idx < getFunctionOrMethodNumParams(D) && 1240 !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr, 1241 Ex->getSourceRange(), 1242 getFunctionOrMethodParamRange(D, Idx))) 1243 continue; 1244 1245 NonNullArgs.push_back(Idx); 1246 } 1247 1248 // If no arguments were specified to __attribute__((nonnull)) then all pointer 1249 // arguments have a nonnull attribute; warn if there aren't any. Skip this 1250 // check if the attribute came from a macro expansion or a template 1251 // instantiation. 1252 if (NonNullArgs.empty() && Attr.getLoc().isFileID() && 1253 S.ActiveTemplateInstantiations.empty()) { 1254 bool AnyPointers = isFunctionOrMethodVariadic(D); 1255 for (unsigned I = 0, E = getFunctionOrMethodNumParams(D); 1256 I != E && !AnyPointers; ++I) { 1257 QualType T = getFunctionOrMethodParamType(D, I); 1258 if (T->isDependentType() || S.isValidPointerAttrType(T)) 1259 AnyPointers = true; 1260 } 1261 1262 if (!AnyPointers) 1263 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers); 1264 } 1265 1266 unsigned *Start = NonNullArgs.data(); 1267 unsigned Size = NonNullArgs.size(); 1268 llvm::array_pod_sort(Start, Start + Size); 1269 D->addAttr(::new (S.Context) 1270 NonNullAttr(Attr.getRange(), S.Context, Start, Size, 1271 Attr.getAttributeSpellingListIndex())); 1272 } 1273 1274 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D, 1275 const AttributeList &Attr) { 1276 if (Attr.getNumArgs() > 0) { 1277 if (D->getFunctionType()) { 1278 handleNonNullAttr(S, D, Attr); 1279 } else { 1280 S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args) 1281 << D->getSourceRange(); 1282 } 1283 return; 1284 } 1285 1286 // Is the argument a pointer type? 1287 if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(), 1288 D->getSourceRange())) 1289 return; 1290 1291 D->addAttr(::new (S.Context) 1292 NonNullAttr(Attr.getRange(), S.Context, nullptr, 0, 1293 Attr.getAttributeSpellingListIndex())); 1294 } 1295 1296 static void handleReturnsNonNullAttr(Sema &S, Decl *D, 1297 const AttributeList &Attr) { 1298 QualType ResultType = getFunctionOrMethodResultType(D); 1299 SourceRange SR = getFunctionOrMethodResultSourceRange(D); 1300 if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR, 1301 /* isReturnValue */ true)) 1302 return; 1303 1304 D->addAttr(::new (S.Context) 1305 ReturnsNonNullAttr(Attr.getRange(), S.Context, 1306 Attr.getAttributeSpellingListIndex())); 1307 } 1308 1309 static void handleAssumeAlignedAttr(Sema &S, Decl *D, 1310 const AttributeList &Attr) { 1311 Expr *E = Attr.getArgAsExpr(0), 1312 *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr; 1313 S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE, 1314 Attr.getAttributeSpellingListIndex()); 1315 } 1316 1317 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, 1318 Expr *OE, unsigned SpellingListIndex) { 1319 QualType ResultType = getFunctionOrMethodResultType(D); 1320 SourceRange SR = getFunctionOrMethodResultSourceRange(D); 1321 1322 AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex); 1323 SourceLocation AttrLoc = AttrRange.getBegin(); 1324 1325 if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) { 1326 Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only) 1327 << &TmpAttr << AttrRange << SR; 1328 return; 1329 } 1330 1331 if (!E->isValueDependent()) { 1332 llvm::APSInt I(64); 1333 if (!E->isIntegerConstantExpr(I, Context)) { 1334 if (OE) 1335 Diag(AttrLoc, diag::err_attribute_argument_n_type) 1336 << &TmpAttr << 1 << AANT_ArgumentIntegerConstant 1337 << E->getSourceRange(); 1338 else 1339 Diag(AttrLoc, diag::err_attribute_argument_type) 1340 << &TmpAttr << AANT_ArgumentIntegerConstant 1341 << E->getSourceRange(); 1342 return; 1343 } 1344 1345 if (!I.isPowerOf2()) { 1346 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 1347 << E->getSourceRange(); 1348 return; 1349 } 1350 } 1351 1352 if (OE) { 1353 if (!OE->isValueDependent()) { 1354 llvm::APSInt I(64); 1355 if (!OE->isIntegerConstantExpr(I, Context)) { 1356 Diag(AttrLoc, diag::err_attribute_argument_n_type) 1357 << &TmpAttr << 2 << AANT_ArgumentIntegerConstant 1358 << OE->getSourceRange(); 1359 return; 1360 } 1361 } 1362 } 1363 1364 D->addAttr(::new (Context) 1365 AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex)); 1366 } 1367 1368 /// Normalize the attribute, __foo__ becomes foo. 1369 /// Returns true if normalization was applied. 1370 static bool normalizeName(StringRef &AttrName) { 1371 if (AttrName.size() > 4 && AttrName.startswith("__") && 1372 AttrName.endswith("__")) { 1373 AttrName = AttrName.drop_front(2).drop_back(2); 1374 return true; 1375 } 1376 return false; 1377 } 1378 1379 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) { 1380 // This attribute must be applied to a function declaration. The first 1381 // argument to the attribute must be an identifier, the name of the resource, 1382 // for example: malloc. The following arguments must be argument indexes, the 1383 // arguments must be of integer type for Returns, otherwise of pointer type. 1384 // The difference between Holds and Takes is that a pointer may still be used 1385 // after being held. free() should be __attribute((ownership_takes)), whereas 1386 // a list append function may well be __attribute((ownership_holds)). 1387 1388 if (!AL.isArgIdent(0)) { 1389 S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type) 1390 << AL.getName() << 1 << AANT_ArgumentIdentifier; 1391 return; 1392 } 1393 1394 // Figure out our Kind. 1395 OwnershipAttr::OwnershipKind K = 1396 OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0, 1397 AL.getAttributeSpellingListIndex()).getOwnKind(); 1398 1399 // Check arguments. 1400 switch (K) { 1401 case OwnershipAttr::Takes: 1402 case OwnershipAttr::Holds: 1403 if (AL.getNumArgs() < 2) { 1404 S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) 1405 << AL.getName() << 2; 1406 return; 1407 } 1408 break; 1409 case OwnershipAttr::Returns: 1410 if (AL.getNumArgs() > 2) { 1411 S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) 1412 << AL.getName() << 1; 1413 return; 1414 } 1415 break; 1416 } 1417 1418 IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident; 1419 1420 StringRef ModuleName = Module->getName(); 1421 if (normalizeName(ModuleName)) { 1422 Module = &S.PP.getIdentifierTable().get(ModuleName); 1423 } 1424 1425 SmallVector<unsigned, 8> OwnershipArgs; 1426 for (unsigned i = 1; i < AL.getNumArgs(); ++i) { 1427 Expr *Ex = AL.getArgAsExpr(i); 1428 uint64_t Idx; 1429 if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx)) 1430 return; 1431 1432 // Is the function argument a pointer type? 1433 QualType T = getFunctionOrMethodParamType(D, Idx); 1434 int Err = -1; // No error 1435 switch (K) { 1436 case OwnershipAttr::Takes: 1437 case OwnershipAttr::Holds: 1438 if (!T->isAnyPointerType() && !T->isBlockPointerType()) 1439 Err = 0; 1440 break; 1441 case OwnershipAttr::Returns: 1442 if (!T->isIntegerType()) 1443 Err = 1; 1444 break; 1445 } 1446 if (-1 != Err) { 1447 S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err 1448 << Ex->getSourceRange(); 1449 return; 1450 } 1451 1452 // Check we don't have a conflict with another ownership attribute. 1453 for (const auto *I : D->specific_attrs<OwnershipAttr>()) { 1454 // Cannot have two ownership attributes of different kinds for the same 1455 // index. 1456 if (I->getOwnKind() != K && I->args_end() != 1457 std::find(I->args_begin(), I->args_end(), Idx)) { 1458 S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) 1459 << AL.getName() << I; 1460 return; 1461 } else if (K == OwnershipAttr::Returns && 1462 I->getOwnKind() == OwnershipAttr::Returns) { 1463 // A returns attribute conflicts with any other returns attribute using 1464 // a different index. Note, diagnostic reporting is 1-based, but stored 1465 // argument indexes are 0-based. 1466 if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) { 1467 S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch) 1468 << *(I->args_begin()) + 1; 1469 if (I->args_size()) 1470 S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch) 1471 << (unsigned)Idx + 1 << Ex->getSourceRange(); 1472 return; 1473 } 1474 } 1475 } 1476 OwnershipArgs.push_back(Idx); 1477 } 1478 1479 unsigned* start = OwnershipArgs.data(); 1480 unsigned size = OwnershipArgs.size(); 1481 llvm::array_pod_sort(start, start + size); 1482 1483 D->addAttr(::new (S.Context) 1484 OwnershipAttr(AL.getLoc(), S.Context, Module, start, size, 1485 AL.getAttributeSpellingListIndex())); 1486 } 1487 1488 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1489 // Check the attribute arguments. 1490 if (Attr.getNumArgs() > 1) { 1491 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 1492 << Attr.getName() << 1; 1493 return; 1494 } 1495 1496 NamedDecl *nd = cast<NamedDecl>(D); 1497 1498 // gcc rejects 1499 // class c { 1500 // static int a __attribute__((weakref ("v2"))); 1501 // static int b() __attribute__((weakref ("f3"))); 1502 // }; 1503 // and ignores the attributes of 1504 // void f(void) { 1505 // static int a __attribute__((weakref ("v2"))); 1506 // } 1507 // we reject them 1508 const DeclContext *Ctx = D->getDeclContext()->getRedeclContext(); 1509 if (!Ctx->isFileContext()) { 1510 S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context) 1511 << nd; 1512 return; 1513 } 1514 1515 // The GCC manual says 1516 // 1517 // At present, a declaration to which `weakref' is attached can only 1518 // be `static'. 1519 // 1520 // It also says 1521 // 1522 // Without a TARGET, 1523 // given as an argument to `weakref' or to `alias', `weakref' is 1524 // equivalent to `weak'. 1525 // 1526 // gcc 4.4.1 will accept 1527 // int a7 __attribute__((weakref)); 1528 // as 1529 // int a7 __attribute__((weak)); 1530 // This looks like a bug in gcc. We reject that for now. We should revisit 1531 // it if this behaviour is actually used. 1532 1533 // GCC rejects 1534 // static ((alias ("y"), weakref)). 1535 // Should we? How to check that weakref is before or after alias? 1536 1537 // FIXME: it would be good for us to keep the WeakRefAttr as-written instead 1538 // of transforming it into an AliasAttr. The WeakRefAttr never uses the 1539 // StringRef parameter it was given anyway. 1540 StringRef Str; 1541 if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 1542 // GCC will accept anything as the argument of weakref. Should we 1543 // check for an existing decl? 1544 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str, 1545 Attr.getAttributeSpellingListIndex())); 1546 1547 D->addAttr(::new (S.Context) 1548 WeakRefAttr(Attr.getRange(), S.Context, 1549 Attr.getAttributeSpellingListIndex())); 1550 } 1551 1552 static void handleIFuncAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1553 StringRef Str; 1554 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 1555 return; 1556 1557 // Aliases should be on declarations, not definitions. 1558 const auto *FD = cast<FunctionDecl>(D); 1559 if (FD->isThisDeclarationADefinition()) { 1560 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 1; 1561 return; 1562 } 1563 // FIXME: it should be handled as a target specific attribute. 1564 if (S.Context.getTargetInfo().getTriple().getObjectFormat() != 1565 llvm::Triple::ELF) { 1566 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 1567 return; 1568 } 1569 1570 D->addAttr(::new (S.Context) IFuncAttr(Attr.getRange(), S.Context, Str, 1571 Attr.getAttributeSpellingListIndex())); 1572 } 1573 1574 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1575 StringRef Str; 1576 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 1577 return; 1578 1579 if (S.Context.getTargetInfo().getTriple().isOSDarwin()) { 1580 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin); 1581 return; 1582 } 1583 if (S.Context.getTargetInfo().getTriple().isNVPTX()) { 1584 S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_nvptx); 1585 } 1586 1587 // Aliases should be on declarations, not definitions. 1588 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 1589 if (FD->isThisDeclarationADefinition()) { 1590 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD << 0; 1591 return; 1592 } 1593 } else { 1594 const auto *VD = cast<VarDecl>(D); 1595 if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) { 1596 S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD << 0; 1597 return; 1598 } 1599 } 1600 1601 // FIXME: check if target symbol exists in current file 1602 1603 D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str, 1604 Attr.getAttributeSpellingListIndex())); 1605 } 1606 1607 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1608 if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName())) 1609 return; 1610 1611 D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context, 1612 Attr.getAttributeSpellingListIndex())); 1613 } 1614 1615 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1616 if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName())) 1617 return; 1618 1619 D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context, 1620 Attr.getAttributeSpellingListIndex())); 1621 } 1622 1623 static void handleTLSModelAttr(Sema &S, Decl *D, 1624 const AttributeList &Attr) { 1625 StringRef Model; 1626 SourceLocation LiteralLoc; 1627 // Check that it is a string. 1628 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc)) 1629 return; 1630 1631 // Check that the value. 1632 if (Model != "global-dynamic" && Model != "local-dynamic" 1633 && Model != "initial-exec" && Model != "local-exec") { 1634 S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg); 1635 return; 1636 } 1637 1638 D->addAttr(::new (S.Context) 1639 TLSModelAttr(Attr.getRange(), S.Context, Model, 1640 Attr.getAttributeSpellingListIndex())); 1641 } 1642 1643 static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1644 QualType ResultType = getFunctionOrMethodResultType(D); 1645 if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) { 1646 D->addAttr(::new (S.Context) RestrictAttr( 1647 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 1648 return; 1649 } 1650 1651 S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only) 1652 << Attr.getName() << getFunctionOrMethodResultSourceRange(D); 1653 } 1654 1655 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1656 if (S.LangOpts.CPlusPlus) { 1657 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang) 1658 << Attr.getName() << AttributeLangSupport::Cpp; 1659 return; 1660 } 1661 1662 if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(), 1663 Attr.getAttributeSpellingListIndex())) 1664 D->addAttr(CA); 1665 } 1666 1667 static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1668 if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(), 1669 Attr.getName())) 1670 return; 1671 1672 D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context, 1673 Attr.getAttributeSpellingListIndex())); 1674 } 1675 1676 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) { 1677 if (hasDeclarator(D)) return; 1678 1679 if (S.CheckNoReturnAttr(attr)) return; 1680 1681 if (!isa<ObjCMethodDecl>(D)) { 1682 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type) 1683 << attr.getName() << ExpectedFunctionOrMethod; 1684 return; 1685 } 1686 1687 D->addAttr(::new (S.Context) 1688 NoReturnAttr(attr.getRange(), S.Context, 1689 attr.getAttributeSpellingListIndex())); 1690 } 1691 1692 bool Sema::CheckNoReturnAttr(const AttributeList &attr) { 1693 if (!checkAttributeNumArgs(*this, attr, 0)) { 1694 attr.setInvalid(); 1695 return true; 1696 } 1697 1698 return false; 1699 } 1700 1701 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, 1702 const AttributeList &Attr) { 1703 1704 // The checking path for 'noreturn' and 'analyzer_noreturn' are different 1705 // because 'analyzer_noreturn' does not impact the type. 1706 if (!isFunctionOrMethodOrBlock(D)) { 1707 ValueDecl *VD = dyn_cast<ValueDecl>(D); 1708 if (!VD || (!VD->getType()->isBlockPointerType() && 1709 !VD->getType()->isFunctionPointerType())) { 1710 S.Diag(Attr.getLoc(), 1711 Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type 1712 : diag::warn_attribute_wrong_decl_type) 1713 << Attr.getName() << ExpectedFunctionMethodOrBlock; 1714 return; 1715 } 1716 } 1717 1718 D->addAttr(::new (S.Context) 1719 AnalyzerNoReturnAttr(Attr.getRange(), S.Context, 1720 Attr.getAttributeSpellingListIndex())); 1721 } 1722 1723 // PS3 PPU-specific. 1724 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1725 /* 1726 Returning a Vector Class in Registers 1727 1728 According to the PPU ABI specifications, a class with a single member of 1729 vector type is returned in memory when used as the return value of a function. 1730 This results in inefficient code when implementing vector classes. To return 1731 the value in a single vector register, add the vecreturn attribute to the 1732 class definition. This attribute is also applicable to struct types. 1733 1734 Example: 1735 1736 struct Vector 1737 { 1738 __vector float xyzw; 1739 } __attribute__((vecreturn)); 1740 1741 Vector Add(Vector lhs, Vector rhs) 1742 { 1743 Vector result; 1744 result.xyzw = vec_add(lhs.xyzw, rhs.xyzw); 1745 return result; // This will be returned in a register 1746 } 1747 */ 1748 if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) { 1749 S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A; 1750 return; 1751 } 1752 1753 RecordDecl *record = cast<RecordDecl>(D); 1754 int count = 0; 1755 1756 if (!isa<CXXRecordDecl>(record)) { 1757 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member); 1758 return; 1759 } 1760 1761 if (!cast<CXXRecordDecl>(record)->isPOD()) { 1762 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record); 1763 return; 1764 } 1765 1766 for (const auto *I : record->fields()) { 1767 if ((count == 1) || !I->getType()->isVectorType()) { 1768 S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member); 1769 return; 1770 } 1771 count++; 1772 } 1773 1774 D->addAttr(::new (S.Context) 1775 VecReturnAttr(Attr.getRange(), S.Context, 1776 Attr.getAttributeSpellingListIndex())); 1777 } 1778 1779 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D, 1780 const AttributeList &Attr) { 1781 if (isa<ParmVarDecl>(D)) { 1782 // [[carries_dependency]] can only be applied to a parameter if it is a 1783 // parameter of a function declaration or lambda. 1784 if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) { 1785 S.Diag(Attr.getLoc(), 1786 diag::err_carries_dependency_param_not_function_decl); 1787 return; 1788 } 1789 } 1790 1791 D->addAttr(::new (S.Context) CarriesDependencyAttr( 1792 Attr.getRange(), S.Context, 1793 Attr.getAttributeSpellingListIndex())); 1794 } 1795 1796 static void handleNotTailCalledAttr(Sema &S, Decl *D, 1797 const AttributeList &Attr) { 1798 if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(), 1799 Attr.getName())) 1800 return; 1801 1802 D->addAttr(::new (S.Context) NotTailCalledAttr( 1803 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 1804 } 1805 1806 static void handleDisableTailCallsAttr(Sema &S, Decl *D, 1807 const AttributeList &Attr) { 1808 if (checkAttrMutualExclusion<NakedAttr>(S, D, Attr.getRange(), 1809 Attr.getName())) 1810 return; 1811 1812 D->addAttr(::new (S.Context) DisableTailCallsAttr( 1813 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 1814 } 1815 1816 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1817 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 1818 if (VD->hasLocalStorage()) { 1819 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 1820 return; 1821 } 1822 } else if (!isFunctionOrMethod(D)) { 1823 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 1824 << Attr.getName() << ExpectedVariableOrFunction; 1825 return; 1826 } 1827 1828 D->addAttr(::new (S.Context) 1829 UsedAttr(Attr.getRange(), S.Context, 1830 Attr.getAttributeSpellingListIndex())); 1831 } 1832 1833 static void handleUnusedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1834 bool IsCXX1zAttr = Attr.isCXX11Attribute() && !Attr.getScopeName(); 1835 1836 if (IsCXX1zAttr && isa<VarDecl>(D)) { 1837 // The C++1z spelling of this attribute cannot be applied to a static data 1838 // member per [dcl.attr.unused]p2. 1839 if (cast<VarDecl>(D)->isStaticDataMember()) { 1840 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 1841 << Attr.getName() << ExpectedForMaybeUnused; 1842 return; 1843 } 1844 } 1845 1846 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn 1847 // about using it as an extension. 1848 if (!S.getLangOpts().CPlusPlus1z && IsCXX1zAttr) 1849 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName(); 1850 1851 D->addAttr(::new (S.Context) UnusedAttr( 1852 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 1853 } 1854 1855 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1856 uint32_t priority = ConstructorAttr::DefaultPriority; 1857 if (Attr.getNumArgs() && 1858 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority)) 1859 return; 1860 1861 D->addAttr(::new (S.Context) 1862 ConstructorAttr(Attr.getRange(), S.Context, priority, 1863 Attr.getAttributeSpellingListIndex())); 1864 } 1865 1866 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) { 1867 uint32_t priority = DestructorAttr::DefaultPriority; 1868 if (Attr.getNumArgs() && 1869 !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority)) 1870 return; 1871 1872 D->addAttr(::new (S.Context) 1873 DestructorAttr(Attr.getRange(), S.Context, priority, 1874 Attr.getAttributeSpellingListIndex())); 1875 } 1876 1877 template <typename AttrTy> 1878 static void handleAttrWithMessage(Sema &S, Decl *D, 1879 const AttributeList &Attr) { 1880 // Handle the case where the attribute has a text message. 1881 StringRef Str; 1882 if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 1883 return; 1884 1885 D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str, 1886 Attr.getAttributeSpellingListIndex())); 1887 } 1888 1889 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D, 1890 const AttributeList &Attr) { 1891 if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) { 1892 S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition) 1893 << Attr.getName() << Attr.getRange(); 1894 return; 1895 } 1896 1897 D->addAttr(::new (S.Context) 1898 ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context, 1899 Attr.getAttributeSpellingListIndex())); 1900 } 1901 1902 static bool checkAvailabilityAttr(Sema &S, SourceRange Range, 1903 IdentifierInfo *Platform, 1904 VersionTuple Introduced, 1905 VersionTuple Deprecated, 1906 VersionTuple Obsoleted) { 1907 StringRef PlatformName 1908 = AvailabilityAttr::getPrettyPlatformName(Platform->getName()); 1909 if (PlatformName.empty()) 1910 PlatformName = Platform->getName(); 1911 1912 // Ensure that Introduced <= Deprecated <= Obsoleted (although not all 1913 // of these steps are needed). 1914 if (!Introduced.empty() && !Deprecated.empty() && 1915 !(Introduced <= Deprecated)) { 1916 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 1917 << 1 << PlatformName << Deprecated.getAsString() 1918 << 0 << Introduced.getAsString(); 1919 return true; 1920 } 1921 1922 if (!Introduced.empty() && !Obsoleted.empty() && 1923 !(Introduced <= Obsoleted)) { 1924 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 1925 << 2 << PlatformName << Obsoleted.getAsString() 1926 << 0 << Introduced.getAsString(); 1927 return true; 1928 } 1929 1930 if (!Deprecated.empty() && !Obsoleted.empty() && 1931 !(Deprecated <= Obsoleted)) { 1932 S.Diag(Range.getBegin(), diag::warn_availability_version_ordering) 1933 << 2 << PlatformName << Obsoleted.getAsString() 1934 << 1 << Deprecated.getAsString(); 1935 return true; 1936 } 1937 1938 return false; 1939 } 1940 1941 /// \brief Check whether the two versions match. 1942 /// 1943 /// If either version tuple is empty, then they are assumed to match. If 1944 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y. 1945 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y, 1946 bool BeforeIsOkay) { 1947 if (X.empty() || Y.empty()) 1948 return true; 1949 1950 if (X == Y) 1951 return true; 1952 1953 if (BeforeIsOkay && X < Y) 1954 return true; 1955 1956 return false; 1957 } 1958 1959 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range, 1960 IdentifierInfo *Platform, 1961 bool Implicit, 1962 VersionTuple Introduced, 1963 VersionTuple Deprecated, 1964 VersionTuple Obsoleted, 1965 bool IsUnavailable, 1966 StringRef Message, 1967 bool IsStrict, 1968 StringRef Replacement, 1969 AvailabilityMergeKind AMK, 1970 unsigned AttrSpellingListIndex) { 1971 VersionTuple MergedIntroduced = Introduced; 1972 VersionTuple MergedDeprecated = Deprecated; 1973 VersionTuple MergedObsoleted = Obsoleted; 1974 bool FoundAny = false; 1975 bool OverrideOrImpl = false; 1976 switch (AMK) { 1977 case AMK_None: 1978 case AMK_Redeclaration: 1979 OverrideOrImpl = false; 1980 break; 1981 1982 case AMK_Override: 1983 case AMK_ProtocolImplementation: 1984 OverrideOrImpl = true; 1985 break; 1986 } 1987 1988 if (D->hasAttrs()) { 1989 AttrVec &Attrs = D->getAttrs(); 1990 for (unsigned i = 0, e = Attrs.size(); i != e;) { 1991 const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]); 1992 if (!OldAA) { 1993 ++i; 1994 continue; 1995 } 1996 1997 IdentifierInfo *OldPlatform = OldAA->getPlatform(); 1998 if (OldPlatform != Platform) { 1999 ++i; 2000 continue; 2001 } 2002 2003 // If there is an existing availability attribute for this platform that 2004 // is explicit and the new one is implicit use the explicit one and 2005 // discard the new implicit attribute. 2006 if (!OldAA->isImplicit() && Implicit) { 2007 return nullptr; 2008 } 2009 2010 // If there is an existing attribute for this platform that is implicit 2011 // and the new attribute is explicit then erase the old one and 2012 // continue processing the attributes. 2013 if (!Implicit && OldAA->isImplicit()) { 2014 Attrs.erase(Attrs.begin() + i); 2015 --e; 2016 continue; 2017 } 2018 2019 FoundAny = true; 2020 VersionTuple OldIntroduced = OldAA->getIntroduced(); 2021 VersionTuple OldDeprecated = OldAA->getDeprecated(); 2022 VersionTuple OldObsoleted = OldAA->getObsoleted(); 2023 bool OldIsUnavailable = OldAA->getUnavailable(); 2024 2025 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) || 2026 !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) || 2027 !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) || 2028 !(OldIsUnavailable == IsUnavailable || 2029 (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) { 2030 if (OverrideOrImpl) { 2031 int Which = -1; 2032 VersionTuple FirstVersion; 2033 VersionTuple SecondVersion; 2034 if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) { 2035 Which = 0; 2036 FirstVersion = OldIntroduced; 2037 SecondVersion = Introduced; 2038 } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) { 2039 Which = 1; 2040 FirstVersion = Deprecated; 2041 SecondVersion = OldDeprecated; 2042 } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) { 2043 Which = 2; 2044 FirstVersion = Obsoleted; 2045 SecondVersion = OldObsoleted; 2046 } 2047 2048 if (Which == -1) { 2049 Diag(OldAA->getLocation(), 2050 diag::warn_mismatched_availability_override_unavail) 2051 << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) 2052 << (AMK == AMK_Override); 2053 } else { 2054 Diag(OldAA->getLocation(), 2055 diag::warn_mismatched_availability_override) 2056 << Which 2057 << AvailabilityAttr::getPrettyPlatformName(Platform->getName()) 2058 << FirstVersion.getAsString() << SecondVersion.getAsString() 2059 << (AMK == AMK_Override); 2060 } 2061 if (AMK == AMK_Override) 2062 Diag(Range.getBegin(), diag::note_overridden_method); 2063 else 2064 Diag(Range.getBegin(), diag::note_protocol_method); 2065 } else { 2066 Diag(OldAA->getLocation(), diag::warn_mismatched_availability); 2067 Diag(Range.getBegin(), diag::note_previous_attribute); 2068 } 2069 2070 Attrs.erase(Attrs.begin() + i); 2071 --e; 2072 continue; 2073 } 2074 2075 VersionTuple MergedIntroduced2 = MergedIntroduced; 2076 VersionTuple MergedDeprecated2 = MergedDeprecated; 2077 VersionTuple MergedObsoleted2 = MergedObsoleted; 2078 2079 if (MergedIntroduced2.empty()) 2080 MergedIntroduced2 = OldIntroduced; 2081 if (MergedDeprecated2.empty()) 2082 MergedDeprecated2 = OldDeprecated; 2083 if (MergedObsoleted2.empty()) 2084 MergedObsoleted2 = OldObsoleted; 2085 2086 if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform, 2087 MergedIntroduced2, MergedDeprecated2, 2088 MergedObsoleted2)) { 2089 Attrs.erase(Attrs.begin() + i); 2090 --e; 2091 continue; 2092 } 2093 2094 MergedIntroduced = MergedIntroduced2; 2095 MergedDeprecated = MergedDeprecated2; 2096 MergedObsoleted = MergedObsoleted2; 2097 ++i; 2098 } 2099 } 2100 2101 if (FoundAny && 2102 MergedIntroduced == Introduced && 2103 MergedDeprecated == Deprecated && 2104 MergedObsoleted == Obsoleted) 2105 return nullptr; 2106 2107 // Only create a new attribute if !OverrideOrImpl, but we want to do 2108 // the checking. 2109 if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced, 2110 MergedDeprecated, MergedObsoleted) && 2111 !OverrideOrImpl) { 2112 auto *Avail = ::new (Context) AvailabilityAttr(Range, Context, Platform, 2113 Introduced, Deprecated, 2114 Obsoleted, IsUnavailable, Message, 2115 IsStrict, Replacement, 2116 AttrSpellingListIndex); 2117 Avail->setImplicit(Implicit); 2118 return Avail; 2119 } 2120 return nullptr; 2121 } 2122 2123 static void handleAvailabilityAttr(Sema &S, Decl *D, 2124 const AttributeList &Attr) { 2125 if (!checkAttributeNumArgs(S, Attr, 1)) 2126 return; 2127 IdentifierLoc *Platform = Attr.getArgAsIdent(0); 2128 unsigned Index = Attr.getAttributeSpellingListIndex(); 2129 2130 IdentifierInfo *II = Platform->Ident; 2131 if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty()) 2132 S.Diag(Platform->Loc, diag::warn_availability_unknown_platform) 2133 << Platform->Ident; 2134 2135 NamedDecl *ND = dyn_cast<NamedDecl>(D); 2136 if (!ND) { 2137 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 2138 return; 2139 } 2140 2141 AvailabilityChange Introduced = Attr.getAvailabilityIntroduced(); 2142 AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated(); 2143 AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted(); 2144 bool IsUnavailable = Attr.getUnavailableLoc().isValid(); 2145 bool IsStrict = Attr.getStrictLoc().isValid(); 2146 StringRef Str; 2147 if (const StringLiteral *SE = 2148 dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr())) 2149 Str = SE->getString(); 2150 StringRef Replacement; 2151 if (const StringLiteral *SE = 2152 dyn_cast_or_null<StringLiteral>(Attr.getReplacementExpr())) 2153 Replacement = SE->getString(); 2154 2155 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II, 2156 false/*Implicit*/, 2157 Introduced.Version, 2158 Deprecated.Version, 2159 Obsoleted.Version, 2160 IsUnavailable, Str, 2161 IsStrict, Replacement, 2162 Sema::AMK_None, 2163 Index); 2164 if (NewAttr) 2165 D->addAttr(NewAttr); 2166 2167 // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning 2168 // matches before the start of the watchOS platform. 2169 if (S.Context.getTargetInfo().getTriple().isWatchOS()) { 2170 IdentifierInfo *NewII = nullptr; 2171 if (II->getName() == "ios") 2172 NewII = &S.Context.Idents.get("watchos"); 2173 else if (II->getName() == "ios_app_extension") 2174 NewII = &S.Context.Idents.get("watchos_app_extension"); 2175 2176 if (NewII) { 2177 auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple { 2178 if (Version.empty()) 2179 return Version; 2180 auto Major = Version.getMajor(); 2181 auto NewMajor = Major >= 9 ? Major - 7 : 0; 2182 if (NewMajor >= 2) { 2183 if (Version.getMinor().hasValue()) { 2184 if (Version.getSubminor().hasValue()) 2185 return VersionTuple(NewMajor, Version.getMinor().getValue(), 2186 Version.getSubminor().getValue()); 2187 else 2188 return VersionTuple(NewMajor, Version.getMinor().getValue()); 2189 } 2190 } 2191 2192 return VersionTuple(2, 0); 2193 }; 2194 2195 auto NewIntroduced = adjustWatchOSVersion(Introduced.Version); 2196 auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version); 2197 auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version); 2198 2199 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, 2200 Attr.getRange(), 2201 NewII, 2202 true/*Implicit*/, 2203 NewIntroduced, 2204 NewDeprecated, 2205 NewObsoleted, 2206 IsUnavailable, Str, 2207 IsStrict, 2208 Replacement, 2209 Sema::AMK_None, 2210 Index); 2211 if (NewAttr) 2212 D->addAttr(NewAttr); 2213 } 2214 } else if (S.Context.getTargetInfo().getTriple().isTvOS()) { 2215 // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning 2216 // matches before the start of the tvOS platform. 2217 IdentifierInfo *NewII = nullptr; 2218 if (II->getName() == "ios") 2219 NewII = &S.Context.Idents.get("tvos"); 2220 else if (II->getName() == "ios_app_extension") 2221 NewII = &S.Context.Idents.get("tvos_app_extension"); 2222 2223 if (NewII) { 2224 AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, 2225 Attr.getRange(), 2226 NewII, 2227 true/*Implicit*/, 2228 Introduced.Version, 2229 Deprecated.Version, 2230 Obsoleted.Version, 2231 IsUnavailable, Str, 2232 IsStrict, 2233 Replacement, 2234 Sema::AMK_None, 2235 Index); 2236 if (NewAttr) 2237 D->addAttr(NewAttr); 2238 } 2239 } 2240 } 2241 2242 template <class T> 2243 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range, 2244 typename T::VisibilityType value, 2245 unsigned attrSpellingListIndex) { 2246 T *existingAttr = D->getAttr<T>(); 2247 if (existingAttr) { 2248 typename T::VisibilityType existingValue = existingAttr->getVisibility(); 2249 if (existingValue == value) 2250 return nullptr; 2251 S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility); 2252 S.Diag(range.getBegin(), diag::note_previous_attribute); 2253 D->dropAttr<T>(); 2254 } 2255 return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex); 2256 } 2257 2258 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range, 2259 VisibilityAttr::VisibilityType Vis, 2260 unsigned AttrSpellingListIndex) { 2261 return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis, 2262 AttrSpellingListIndex); 2263 } 2264 2265 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range, 2266 TypeVisibilityAttr::VisibilityType Vis, 2267 unsigned AttrSpellingListIndex) { 2268 return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis, 2269 AttrSpellingListIndex); 2270 } 2271 2272 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr, 2273 bool isTypeVisibility) { 2274 // Visibility attributes don't mean anything on a typedef. 2275 if (isa<TypedefNameDecl>(D)) { 2276 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored) 2277 << Attr.getName(); 2278 return; 2279 } 2280 2281 // 'type_visibility' can only go on a type or namespace. 2282 if (isTypeVisibility && 2283 !(isa<TagDecl>(D) || 2284 isa<ObjCInterfaceDecl>(D) || 2285 isa<NamespaceDecl>(D))) { 2286 S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type) 2287 << Attr.getName() << ExpectedTypeOrNamespace; 2288 return; 2289 } 2290 2291 // Check that the argument is a string literal. 2292 StringRef TypeStr; 2293 SourceLocation LiteralLoc; 2294 if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc)) 2295 return; 2296 2297 VisibilityAttr::VisibilityType type; 2298 if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) { 2299 S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) 2300 << Attr.getName() << TypeStr; 2301 return; 2302 } 2303 2304 // Complain about attempts to use protected visibility on targets 2305 // (like Darwin) that don't support it. 2306 if (type == VisibilityAttr::Protected && 2307 !S.Context.getTargetInfo().hasProtectedVisibility()) { 2308 S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility); 2309 type = VisibilityAttr::Default; 2310 } 2311 2312 unsigned Index = Attr.getAttributeSpellingListIndex(); 2313 clang::Attr *newAttr; 2314 if (isTypeVisibility) { 2315 newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(), 2316 (TypeVisibilityAttr::VisibilityType) type, 2317 Index); 2318 } else { 2319 newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index); 2320 } 2321 if (newAttr) 2322 D->addAttr(newAttr); 2323 } 2324 2325 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl, 2326 const AttributeList &Attr) { 2327 ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl); 2328 if (!Attr.isArgIdent(0)) { 2329 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2330 << Attr.getName() << 1 << AANT_ArgumentIdentifier; 2331 return; 2332 } 2333 2334 IdentifierLoc *IL = Attr.getArgAsIdent(0); 2335 ObjCMethodFamilyAttr::FamilyKind F; 2336 if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) { 2337 S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName() 2338 << IL->Ident; 2339 return; 2340 } 2341 2342 if (F == ObjCMethodFamilyAttr::OMF_init && 2343 !method->getReturnType()->isObjCObjectPointerType()) { 2344 S.Diag(method->getLocation(), diag::err_init_method_bad_return_type) 2345 << method->getReturnType(); 2346 // Ignore the attribute. 2347 return; 2348 } 2349 2350 method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(), 2351 S.Context, F, 2352 Attr.getAttributeSpellingListIndex())); 2353 } 2354 2355 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) { 2356 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 2357 QualType T = TD->getUnderlyingType(); 2358 if (!T->isCARCBridgableType()) { 2359 S.Diag(TD->getLocation(), diag::err_nsobject_attribute); 2360 return; 2361 } 2362 } 2363 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) { 2364 QualType T = PD->getType(); 2365 if (!T->isCARCBridgableType()) { 2366 S.Diag(PD->getLocation(), diag::err_nsobject_attribute); 2367 return; 2368 } 2369 } 2370 else { 2371 // It is okay to include this attribute on properties, e.g.: 2372 // 2373 // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject)); 2374 // 2375 // In this case it follows tradition and suppresses an error in the above 2376 // case. 2377 S.Diag(D->getLocation(), diag::warn_nsobject_attribute); 2378 } 2379 D->addAttr(::new (S.Context) 2380 ObjCNSObjectAttr(Attr.getRange(), S.Context, 2381 Attr.getAttributeSpellingListIndex())); 2382 } 2383 2384 static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) { 2385 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) { 2386 QualType T = TD->getUnderlyingType(); 2387 if (!T->isObjCObjectPointerType()) { 2388 S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute); 2389 return; 2390 } 2391 } else { 2392 S.Diag(D->getLocation(), diag::warn_independentclass_attribute); 2393 return; 2394 } 2395 D->addAttr(::new (S.Context) 2396 ObjCIndependentClassAttr(Attr.getRange(), S.Context, 2397 Attr.getAttributeSpellingListIndex())); 2398 } 2399 2400 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2401 if (!Attr.isArgIdent(0)) { 2402 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2403 << Attr.getName() << 1 << AANT_ArgumentIdentifier; 2404 return; 2405 } 2406 2407 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident; 2408 BlocksAttr::BlockType type; 2409 if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) { 2410 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 2411 << Attr.getName() << II; 2412 return; 2413 } 2414 2415 D->addAttr(::new (S.Context) 2416 BlocksAttr(Attr.getRange(), S.Context, type, 2417 Attr.getAttributeSpellingListIndex())); 2418 } 2419 2420 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2421 unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel; 2422 if (Attr.getNumArgs() > 0) { 2423 Expr *E = Attr.getArgAsExpr(0); 2424 llvm::APSInt Idx(32); 2425 if (E->isTypeDependent() || E->isValueDependent() || 2426 !E->isIntegerConstantExpr(Idx, S.Context)) { 2427 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2428 << Attr.getName() << 1 << AANT_ArgumentIntegerConstant 2429 << E->getSourceRange(); 2430 return; 2431 } 2432 2433 if (Idx.isSigned() && Idx.isNegative()) { 2434 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero) 2435 << E->getSourceRange(); 2436 return; 2437 } 2438 2439 sentinel = Idx.getZExtValue(); 2440 } 2441 2442 unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos; 2443 if (Attr.getNumArgs() > 1) { 2444 Expr *E = Attr.getArgAsExpr(1); 2445 llvm::APSInt Idx(32); 2446 if (E->isTypeDependent() || E->isValueDependent() || 2447 !E->isIntegerConstantExpr(Idx, S.Context)) { 2448 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2449 << Attr.getName() << 2 << AANT_ArgumentIntegerConstant 2450 << E->getSourceRange(); 2451 return; 2452 } 2453 nullPos = Idx.getZExtValue(); 2454 2455 if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) { 2456 // FIXME: This error message could be improved, it would be nice 2457 // to say what the bounds actually are. 2458 S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one) 2459 << E->getSourceRange(); 2460 return; 2461 } 2462 } 2463 2464 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 2465 const FunctionType *FT = FD->getType()->castAs<FunctionType>(); 2466 if (isa<FunctionNoProtoType>(FT)) { 2467 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments); 2468 return; 2469 } 2470 2471 if (!cast<FunctionProtoType>(FT)->isVariadic()) { 2472 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; 2473 return; 2474 } 2475 } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) { 2476 if (!MD->isVariadic()) { 2477 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0; 2478 return; 2479 } 2480 } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 2481 if (!BD->isVariadic()) { 2482 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1; 2483 return; 2484 } 2485 } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) { 2486 QualType Ty = V->getType(); 2487 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) { 2488 const FunctionType *FT = Ty->isFunctionPointerType() 2489 ? D->getFunctionType() 2490 : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>(); 2491 if (!cast<FunctionProtoType>(FT)->isVariadic()) { 2492 int m = Ty->isFunctionPointerType() ? 0 : 1; 2493 S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m; 2494 return; 2495 } 2496 } else { 2497 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 2498 << Attr.getName() << ExpectedFunctionMethodOrBlock; 2499 return; 2500 } 2501 } else { 2502 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 2503 << Attr.getName() << ExpectedFunctionMethodOrBlock; 2504 return; 2505 } 2506 D->addAttr(::new (S.Context) 2507 SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos, 2508 Attr.getAttributeSpellingListIndex())); 2509 } 2510 2511 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) { 2512 if (D->getFunctionType() && 2513 D->getFunctionType()->getReturnType()->isVoidType()) { 2514 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method) 2515 << Attr.getName() << 0; 2516 return; 2517 } 2518 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 2519 if (MD->getReturnType()->isVoidType()) { 2520 S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method) 2521 << Attr.getName() << 1; 2522 return; 2523 } 2524 2525 // If this is spelled as the standard C++1z attribute, but not in C++1z, warn 2526 // about using it as an extension. 2527 if (!S.getLangOpts().CPlusPlus1z && Attr.isCXX11Attribute() && 2528 !Attr.getScopeName()) 2529 S.Diag(Attr.getLoc(), diag::ext_cxx1z_attr) << Attr.getName(); 2530 2531 D->addAttr(::new (S.Context) 2532 WarnUnusedResultAttr(Attr.getRange(), S.Context, 2533 Attr.getAttributeSpellingListIndex())); 2534 } 2535 2536 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2537 // weak_import only applies to variable & function declarations. 2538 bool isDef = false; 2539 if (!D->canBeWeakImported(isDef)) { 2540 if (isDef) 2541 S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition) 2542 << "weak_import"; 2543 else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) || 2544 (S.Context.getTargetInfo().getTriple().isOSDarwin() && 2545 (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) { 2546 // Nothing to warn about here. 2547 } else 2548 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 2549 << Attr.getName() << ExpectedVariableOrFunction; 2550 2551 return; 2552 } 2553 2554 D->addAttr(::new (S.Context) 2555 WeakImportAttr(Attr.getRange(), S.Context, 2556 Attr.getAttributeSpellingListIndex())); 2557 } 2558 2559 // Handles reqd_work_group_size and work_group_size_hint. 2560 template <typename WorkGroupAttr> 2561 static void handleWorkGroupSize(Sema &S, Decl *D, 2562 const AttributeList &Attr) { 2563 uint32_t WGSize[3]; 2564 for (unsigned i = 0; i < 3; ++i) { 2565 const Expr *E = Attr.getArgAsExpr(i); 2566 if (!checkUInt32Argument(S, Attr, E, WGSize[i], i)) 2567 return; 2568 if (WGSize[i] == 0) { 2569 S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero) 2570 << Attr.getName() << E->getSourceRange(); 2571 return; 2572 } 2573 } 2574 2575 WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>(); 2576 if (Existing && !(Existing->getXDim() == WGSize[0] && 2577 Existing->getYDim() == WGSize[1] && 2578 Existing->getZDim() == WGSize[2])) 2579 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName(); 2580 2581 D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context, 2582 WGSize[0], WGSize[1], WGSize[2], 2583 Attr.getAttributeSpellingListIndex())); 2584 } 2585 2586 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) { 2587 if (!Attr.hasParsedType()) { 2588 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 2589 << Attr.getName() << 1; 2590 return; 2591 } 2592 2593 TypeSourceInfo *ParmTSI = nullptr; 2594 QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI); 2595 assert(ParmTSI && "no type source info for attribute argument"); 2596 2597 if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() && 2598 (ParmType->isBooleanType() || 2599 !ParmType->isIntegralType(S.getASTContext()))) { 2600 S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint) 2601 << ParmType; 2602 return; 2603 } 2604 2605 if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) { 2606 if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) { 2607 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName(); 2608 return; 2609 } 2610 } 2611 2612 D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context, 2613 ParmTSI, 2614 Attr.getAttributeSpellingListIndex())); 2615 } 2616 2617 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range, 2618 StringRef Name, 2619 unsigned AttrSpellingListIndex) { 2620 if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) { 2621 if (ExistingAttr->getName() == Name) 2622 return nullptr; 2623 Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section); 2624 Diag(Range.getBegin(), diag::note_previous_attribute); 2625 return nullptr; 2626 } 2627 return ::new (Context) SectionAttr(Range, Context, Name, 2628 AttrSpellingListIndex); 2629 } 2630 2631 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) { 2632 std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName); 2633 if (!Error.empty()) { 2634 Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error; 2635 return false; 2636 } 2637 return true; 2638 } 2639 2640 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2641 // Make sure that there is a string literal as the sections's single 2642 // argument. 2643 StringRef Str; 2644 SourceLocation LiteralLoc; 2645 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc)) 2646 return; 2647 2648 if (!S.checkSectionName(LiteralLoc, Str)) 2649 return; 2650 2651 // If the target wants to validate the section specifier, make it happen. 2652 std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str); 2653 if (!Error.empty()) { 2654 S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) 2655 << Error; 2656 return; 2657 } 2658 2659 unsigned Index = Attr.getAttributeSpellingListIndex(); 2660 SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index); 2661 if (NewAttr) 2662 D->addAttr(NewAttr); 2663 } 2664 2665 // Check for things we'd like to warn about, no errors or validation for now. 2666 // TODO: Validation should use a backend target library that specifies 2667 // the allowable subtarget features and cpus. We could use something like a 2668 // TargetCodeGenInfo hook here to do validation. 2669 void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) { 2670 for (auto Str : {"tune=", "fpmath="}) 2671 if (AttrStr.find(Str) != StringRef::npos) 2672 Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str; 2673 } 2674 2675 static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2676 StringRef Str; 2677 SourceLocation LiteralLoc; 2678 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc)) 2679 return; 2680 S.checkTargetAttr(LiteralLoc, Str); 2681 unsigned Index = Attr.getAttributeSpellingListIndex(); 2682 TargetAttr *NewAttr = 2683 ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index); 2684 D->addAttr(NewAttr); 2685 } 2686 2687 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2688 VarDecl *VD = cast<VarDecl>(D); 2689 if (!VD->hasLocalStorage()) { 2690 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 2691 return; 2692 } 2693 2694 Expr *E = Attr.getArgAsExpr(0); 2695 SourceLocation Loc = E->getExprLoc(); 2696 FunctionDecl *FD = nullptr; 2697 DeclarationNameInfo NI; 2698 2699 // gcc only allows for simple identifiers. Since we support more than gcc, we 2700 // will warn the user. 2701 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 2702 if (DRE->hasQualifier()) 2703 S.Diag(Loc, diag::warn_cleanup_ext); 2704 FD = dyn_cast<FunctionDecl>(DRE->getDecl()); 2705 NI = DRE->getNameInfo(); 2706 if (!FD) { 2707 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1 2708 << NI.getName(); 2709 return; 2710 } 2711 } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) { 2712 if (ULE->hasExplicitTemplateArgs()) 2713 S.Diag(Loc, diag::warn_cleanup_ext); 2714 FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true); 2715 NI = ULE->getNameInfo(); 2716 if (!FD) { 2717 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2 2718 << NI.getName(); 2719 if (ULE->getType() == S.Context.OverloadTy) 2720 S.NoteAllOverloadCandidates(ULE); 2721 return; 2722 } 2723 } else { 2724 S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0; 2725 return; 2726 } 2727 2728 if (FD->getNumParams() != 1) { 2729 S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg) 2730 << NI.getName(); 2731 return; 2732 } 2733 2734 // We're currently more strict than GCC about what function types we accept. 2735 // If this ever proves to be a problem it should be easy to fix. 2736 QualType Ty = S.Context.getPointerType(VD->getType()); 2737 QualType ParamTy = FD->getParamDecl(0)->getType(); 2738 if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(), 2739 ParamTy, Ty) != Sema::Compatible) { 2740 S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type) 2741 << NI.getName() << ParamTy << Ty; 2742 return; 2743 } 2744 2745 D->addAttr(::new (S.Context) 2746 CleanupAttr(Attr.getRange(), S.Context, FD, 2747 Attr.getAttributeSpellingListIndex())); 2748 } 2749 2750 /// Handle __attribute__((format_arg((idx)))) attribute based on 2751 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 2752 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2753 Expr *IdxExpr = Attr.getArgAsExpr(0); 2754 uint64_t Idx; 2755 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx)) 2756 return; 2757 2758 // Make sure the format string is really a string. 2759 QualType Ty = getFunctionOrMethodParamType(D, Idx); 2760 2761 bool NotNSStringTy = !isNSStringType(Ty, S.Context); 2762 if (NotNSStringTy && 2763 !isCFStringType(Ty, S.Context) && 2764 (!Ty->isPointerType() || 2765 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) { 2766 S.Diag(Attr.getLoc(), diag::err_format_attribute_not) 2767 << "a string type" << IdxExpr->getSourceRange() 2768 << getFunctionOrMethodParamRange(D, 0); 2769 return; 2770 } 2771 Ty = getFunctionOrMethodResultType(D); 2772 if (!isNSStringType(Ty, S.Context) && 2773 !isCFStringType(Ty, S.Context) && 2774 (!Ty->isPointerType() || 2775 !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) { 2776 S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not) 2777 << (NotNSStringTy ? "string type" : "NSString") 2778 << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0); 2779 return; 2780 } 2781 2782 // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex 2783 // because that has corrected for the implicit this parameter, and is zero- 2784 // based. The attribute expects what the user wrote explicitly. 2785 llvm::APSInt Val; 2786 IdxExpr->EvaluateAsInt(Val, S.Context); 2787 2788 D->addAttr(::new (S.Context) 2789 FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(), 2790 Attr.getAttributeSpellingListIndex())); 2791 } 2792 2793 enum FormatAttrKind { 2794 CFStringFormat, 2795 NSStringFormat, 2796 StrftimeFormat, 2797 SupportedFormat, 2798 IgnoredFormat, 2799 InvalidFormat 2800 }; 2801 2802 /// getFormatAttrKind - Map from format attribute names to supported format 2803 /// types. 2804 static FormatAttrKind getFormatAttrKind(StringRef Format) { 2805 return llvm::StringSwitch<FormatAttrKind>(Format) 2806 // Check for formats that get handled specially. 2807 .Case("NSString", NSStringFormat) 2808 .Case("CFString", CFStringFormat) 2809 .Case("strftime", StrftimeFormat) 2810 2811 // Otherwise, check for supported formats. 2812 .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat) 2813 .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat) 2814 .Case("kprintf", SupportedFormat) // OpenBSD. 2815 .Case("freebsd_kprintf", SupportedFormat) // FreeBSD. 2816 .Case("os_trace", SupportedFormat) 2817 2818 .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat) 2819 .Default(InvalidFormat); 2820 } 2821 2822 /// Handle __attribute__((init_priority(priority))) attributes based on 2823 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html 2824 static void handleInitPriorityAttr(Sema &S, Decl *D, 2825 const AttributeList &Attr) { 2826 if (!S.getLangOpts().CPlusPlus) { 2827 S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName(); 2828 return; 2829 } 2830 2831 if (S.getCurFunctionOrMethodDecl()) { 2832 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr); 2833 Attr.setInvalid(); 2834 return; 2835 } 2836 QualType T = cast<VarDecl>(D)->getType(); 2837 if (S.Context.getAsArrayType(T)) 2838 T = S.Context.getBaseElementType(T); 2839 if (!T->getAs<RecordType>()) { 2840 S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr); 2841 Attr.setInvalid(); 2842 return; 2843 } 2844 2845 Expr *E = Attr.getArgAsExpr(0); 2846 uint32_t prioritynum; 2847 if (!checkUInt32Argument(S, Attr, E, prioritynum)) { 2848 Attr.setInvalid(); 2849 return; 2850 } 2851 2852 if (prioritynum < 101 || prioritynum > 65535) { 2853 S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range) 2854 << E->getSourceRange() << Attr.getName() << 101 << 65535; 2855 Attr.setInvalid(); 2856 return; 2857 } 2858 D->addAttr(::new (S.Context) 2859 InitPriorityAttr(Attr.getRange(), S.Context, prioritynum, 2860 Attr.getAttributeSpellingListIndex())); 2861 } 2862 2863 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range, 2864 IdentifierInfo *Format, int FormatIdx, 2865 int FirstArg, 2866 unsigned AttrSpellingListIndex) { 2867 // Check whether we already have an equivalent format attribute. 2868 for (auto *F : D->specific_attrs<FormatAttr>()) { 2869 if (F->getType() == Format && 2870 F->getFormatIdx() == FormatIdx && 2871 F->getFirstArg() == FirstArg) { 2872 // If we don't have a valid location for this attribute, adopt the 2873 // location. 2874 if (F->getLocation().isInvalid()) 2875 F->setRange(Range); 2876 return nullptr; 2877 } 2878 } 2879 2880 return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx, 2881 FirstArg, AttrSpellingListIndex); 2882 } 2883 2884 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on 2885 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html 2886 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) { 2887 if (!Attr.isArgIdent(0)) { 2888 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 2889 << Attr.getName() << 1 << AANT_ArgumentIdentifier; 2890 return; 2891 } 2892 2893 // In C++ the implicit 'this' function parameter also counts, and they are 2894 // counted from one. 2895 bool HasImplicitThisParam = isInstanceMethod(D); 2896 unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam; 2897 2898 IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident; 2899 StringRef Format = II->getName(); 2900 2901 if (normalizeName(Format)) { 2902 // If we've modified the string name, we need a new identifier for it. 2903 II = &S.Context.Idents.get(Format); 2904 } 2905 2906 // Check for supported formats. 2907 FormatAttrKind Kind = getFormatAttrKind(Format); 2908 2909 if (Kind == IgnoredFormat) 2910 return; 2911 2912 if (Kind == InvalidFormat) { 2913 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 2914 << Attr.getName() << II->getName(); 2915 return; 2916 } 2917 2918 // checks for the 2nd argument 2919 Expr *IdxExpr = Attr.getArgAsExpr(1); 2920 uint32_t Idx; 2921 if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2)) 2922 return; 2923 2924 if (Idx < 1 || Idx > NumArgs) { 2925 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 2926 << Attr.getName() << 2 << IdxExpr->getSourceRange(); 2927 return; 2928 } 2929 2930 // FIXME: Do we need to bounds check? 2931 unsigned ArgIdx = Idx - 1; 2932 2933 if (HasImplicitThisParam) { 2934 if (ArgIdx == 0) { 2935 S.Diag(Attr.getLoc(), 2936 diag::err_format_attribute_implicit_this_format_string) 2937 << IdxExpr->getSourceRange(); 2938 return; 2939 } 2940 ArgIdx--; 2941 } 2942 2943 // make sure the format string is really a string 2944 QualType Ty = getFunctionOrMethodParamType(D, ArgIdx); 2945 2946 if (Kind == CFStringFormat) { 2947 if (!isCFStringType(Ty, S.Context)) { 2948 S.Diag(Attr.getLoc(), diag::err_format_attribute_not) 2949 << "a CFString" << IdxExpr->getSourceRange() 2950 << getFunctionOrMethodParamRange(D, ArgIdx); 2951 return; 2952 } 2953 } else if (Kind == NSStringFormat) { 2954 // FIXME: do we need to check if the type is NSString*? What are the 2955 // semantics? 2956 if (!isNSStringType(Ty, S.Context)) { 2957 S.Diag(Attr.getLoc(), diag::err_format_attribute_not) 2958 << "an NSString" << IdxExpr->getSourceRange() 2959 << getFunctionOrMethodParamRange(D, ArgIdx); 2960 return; 2961 } 2962 } else if (!Ty->isPointerType() || 2963 !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) { 2964 S.Diag(Attr.getLoc(), diag::err_format_attribute_not) 2965 << "a string type" << IdxExpr->getSourceRange() 2966 << getFunctionOrMethodParamRange(D, ArgIdx); 2967 return; 2968 } 2969 2970 // check the 3rd argument 2971 Expr *FirstArgExpr = Attr.getArgAsExpr(2); 2972 uint32_t FirstArg; 2973 if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3)) 2974 return; 2975 2976 // check if the function is variadic if the 3rd argument non-zero 2977 if (FirstArg != 0) { 2978 if (isFunctionOrMethodVariadic(D)) { 2979 ++NumArgs; // +1 for ... 2980 } else { 2981 S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic); 2982 return; 2983 } 2984 } 2985 2986 // strftime requires FirstArg to be 0 because it doesn't read from any 2987 // variable the input is just the current time + the format string. 2988 if (Kind == StrftimeFormat) { 2989 if (FirstArg != 0) { 2990 S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter) 2991 << FirstArgExpr->getSourceRange(); 2992 return; 2993 } 2994 // if 0 it disables parameter checking (to use with e.g. va_list) 2995 } else if (FirstArg != 0 && FirstArg != NumArgs) { 2996 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 2997 << Attr.getName() << 3 << FirstArgExpr->getSourceRange(); 2998 return; 2999 } 3000 3001 FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II, 3002 Idx, FirstArg, 3003 Attr.getAttributeSpellingListIndex()); 3004 if (NewAttr) 3005 D->addAttr(NewAttr); 3006 } 3007 3008 static void handleTransparentUnionAttr(Sema &S, Decl *D, 3009 const AttributeList &Attr) { 3010 // Try to find the underlying union declaration. 3011 RecordDecl *RD = nullptr; 3012 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D); 3013 if (TD && TD->getUnderlyingType()->isUnionType()) 3014 RD = TD->getUnderlyingType()->getAsUnionType()->getDecl(); 3015 else 3016 RD = dyn_cast<RecordDecl>(D); 3017 3018 if (!RD || !RD->isUnion()) { 3019 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 3020 << Attr.getName() << ExpectedUnion; 3021 return; 3022 } 3023 3024 if (!RD->isCompleteDefinition()) { 3025 S.Diag(Attr.getLoc(), 3026 diag::warn_transparent_union_attribute_not_definition); 3027 return; 3028 } 3029 3030 RecordDecl::field_iterator Field = RD->field_begin(), 3031 FieldEnd = RD->field_end(); 3032 if (Field == FieldEnd) { 3033 S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields); 3034 return; 3035 } 3036 3037 FieldDecl *FirstField = *Field; 3038 QualType FirstType = FirstField->getType(); 3039 if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) { 3040 S.Diag(FirstField->getLocation(), 3041 diag::warn_transparent_union_attribute_floating) 3042 << FirstType->isVectorType() << FirstType; 3043 return; 3044 } 3045 3046 uint64_t FirstSize = S.Context.getTypeSize(FirstType); 3047 uint64_t FirstAlign = S.Context.getTypeAlign(FirstType); 3048 for (; Field != FieldEnd; ++Field) { 3049 QualType FieldType = Field->getType(); 3050 // FIXME: this isn't fully correct; we also need to test whether the 3051 // members of the union would all have the same calling convention as the 3052 // first member of the union. Checking just the size and alignment isn't 3053 // sufficient (consider structs passed on the stack instead of in registers 3054 // as an example). 3055 if (S.Context.getTypeSize(FieldType) != FirstSize || 3056 S.Context.getTypeAlign(FieldType) > FirstAlign) { 3057 // Warn if we drop the attribute. 3058 bool isSize = S.Context.getTypeSize(FieldType) != FirstSize; 3059 unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType) 3060 : S.Context.getTypeAlign(FieldType); 3061 S.Diag(Field->getLocation(), 3062 diag::warn_transparent_union_attribute_field_size_align) 3063 << isSize << Field->getDeclName() << FieldBits; 3064 unsigned FirstBits = isSize? FirstSize : FirstAlign; 3065 S.Diag(FirstField->getLocation(), 3066 diag::note_transparent_union_first_field_size_align) 3067 << isSize << FirstBits; 3068 return; 3069 } 3070 } 3071 3072 RD->addAttr(::new (S.Context) 3073 TransparentUnionAttr(Attr.getRange(), S.Context, 3074 Attr.getAttributeSpellingListIndex())); 3075 } 3076 3077 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3078 // Make sure that there is a string literal as the annotation's single 3079 // argument. 3080 StringRef Str; 3081 if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 3082 return; 3083 3084 // Don't duplicate annotations that are already set. 3085 for (const auto *I : D->specific_attrs<AnnotateAttr>()) { 3086 if (I->getAnnotation() == Str) 3087 return; 3088 } 3089 3090 D->addAttr(::new (S.Context) 3091 AnnotateAttr(Attr.getRange(), S.Context, Str, 3092 Attr.getAttributeSpellingListIndex())); 3093 } 3094 3095 static void handleAlignValueAttr(Sema &S, Decl *D, 3096 const AttributeList &Attr) { 3097 S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0), 3098 Attr.getAttributeSpellingListIndex()); 3099 } 3100 3101 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E, 3102 unsigned SpellingListIndex) { 3103 AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex); 3104 SourceLocation AttrLoc = AttrRange.getBegin(); 3105 3106 QualType T; 3107 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) 3108 T = TD->getUnderlyingType(); 3109 else if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) 3110 T = VD->getType(); 3111 else 3112 llvm_unreachable("Unknown decl type for align_value"); 3113 3114 if (!T->isDependentType() && !T->isAnyPointerType() && 3115 !T->isReferenceType() && !T->isMemberPointerType()) { 3116 Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only) 3117 << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange(); 3118 return; 3119 } 3120 3121 if (!E->isValueDependent()) { 3122 llvm::APSInt Alignment; 3123 ExprResult ICE 3124 = VerifyIntegerConstantExpression(E, &Alignment, 3125 diag::err_align_value_attribute_argument_not_int, 3126 /*AllowFold*/ false); 3127 if (ICE.isInvalid()) 3128 return; 3129 3130 if (!Alignment.isPowerOf2()) { 3131 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 3132 << E->getSourceRange(); 3133 return; 3134 } 3135 3136 D->addAttr(::new (Context) 3137 AlignValueAttr(AttrRange, Context, ICE.get(), 3138 SpellingListIndex)); 3139 return; 3140 } 3141 3142 // Save dependent expressions in the AST to be instantiated. 3143 D->addAttr(::new (Context) AlignValueAttr(TmpAttr)); 3144 } 3145 3146 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3147 // check the attribute arguments. 3148 if (Attr.getNumArgs() > 1) { 3149 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) 3150 << Attr.getName() << 1; 3151 return; 3152 } 3153 3154 if (Attr.getNumArgs() == 0) { 3155 D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context, 3156 true, nullptr, Attr.getAttributeSpellingListIndex())); 3157 return; 3158 } 3159 3160 Expr *E = Attr.getArgAsExpr(0); 3161 if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) { 3162 S.Diag(Attr.getEllipsisLoc(), 3163 diag::err_pack_expansion_without_parameter_packs); 3164 return; 3165 } 3166 3167 if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E)) 3168 return; 3169 3170 if (E->isValueDependent()) { 3171 if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) { 3172 if (!TND->getUnderlyingType()->isDependentType()) { 3173 S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name) 3174 << E->getSourceRange(); 3175 return; 3176 } 3177 } 3178 } 3179 3180 S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(), 3181 Attr.isPackExpansion()); 3182 } 3183 3184 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E, 3185 unsigned SpellingListIndex, bool IsPackExpansion) { 3186 AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex); 3187 SourceLocation AttrLoc = AttrRange.getBegin(); 3188 3189 // C++11 alignas(...) and C11 _Alignas(...) have additional requirements. 3190 if (TmpAttr.isAlignas()) { 3191 // C++11 [dcl.align]p1: 3192 // An alignment-specifier may be applied to a variable or to a class 3193 // data member, but it shall not be applied to a bit-field, a function 3194 // parameter, the formal parameter of a catch clause, or a variable 3195 // declared with the register storage class specifier. An 3196 // alignment-specifier may also be applied to the declaration of a class 3197 // or enumeration type. 3198 // C11 6.7.5/2: 3199 // An alignment attribute shall not be specified in a declaration of 3200 // a typedef, or a bit-field, or a function, or a parameter, or an 3201 // object declared with the register storage-class specifier. 3202 int DiagKind = -1; 3203 if (isa<ParmVarDecl>(D)) { 3204 DiagKind = 0; 3205 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) { 3206 if (VD->getStorageClass() == SC_Register) 3207 DiagKind = 1; 3208 if (VD->isExceptionVariable()) 3209 DiagKind = 2; 3210 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) { 3211 if (FD->isBitField()) 3212 DiagKind = 3; 3213 } else if (!isa<TagDecl>(D)) { 3214 Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr 3215 << (TmpAttr.isC11() ? ExpectedVariableOrField 3216 : ExpectedVariableFieldOrTag); 3217 return; 3218 } 3219 if (DiagKind != -1) { 3220 Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type) 3221 << &TmpAttr << DiagKind; 3222 return; 3223 } 3224 } 3225 3226 if (E->isTypeDependent() || E->isValueDependent()) { 3227 // Save dependent expressions in the AST to be instantiated. 3228 AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr); 3229 AA->setPackExpansion(IsPackExpansion); 3230 D->addAttr(AA); 3231 return; 3232 } 3233 3234 // FIXME: Cache the number on the Attr object? 3235 llvm::APSInt Alignment; 3236 ExprResult ICE 3237 = VerifyIntegerConstantExpression(E, &Alignment, 3238 diag::err_aligned_attribute_argument_not_int, 3239 /*AllowFold*/ false); 3240 if (ICE.isInvalid()) 3241 return; 3242 3243 uint64_t AlignVal = Alignment.getZExtValue(); 3244 3245 // C++11 [dcl.align]p2: 3246 // -- if the constant expression evaluates to zero, the alignment 3247 // specifier shall have no effect 3248 // C11 6.7.5p6: 3249 // An alignment specification of zero has no effect. 3250 if (!(TmpAttr.isAlignas() && !Alignment)) { 3251 if (!llvm::isPowerOf2_64(AlignVal)) { 3252 Diag(AttrLoc, diag::err_alignment_not_power_of_two) 3253 << E->getSourceRange(); 3254 return; 3255 } 3256 } 3257 3258 // Alignment calculations can wrap around if it's greater than 2**28. 3259 unsigned MaxValidAlignment = 3260 Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192 3261 : 268435456; 3262 if (AlignVal > MaxValidAlignment) { 3263 Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment 3264 << E->getSourceRange(); 3265 return; 3266 } 3267 3268 if (Context.getTargetInfo().isTLSSupported()) { 3269 unsigned MaxTLSAlign = 3270 Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign()) 3271 .getQuantity(); 3272 auto *VD = dyn_cast<VarDecl>(D); 3273 if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD && 3274 VD->getTLSKind() != VarDecl::TLS_None) { 3275 Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum) 3276 << (unsigned)AlignVal << VD << MaxTLSAlign; 3277 return; 3278 } 3279 } 3280 3281 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true, 3282 ICE.get(), SpellingListIndex); 3283 AA->setPackExpansion(IsPackExpansion); 3284 D->addAttr(AA); 3285 } 3286 3287 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS, 3288 unsigned SpellingListIndex, bool IsPackExpansion) { 3289 // FIXME: Cache the number on the Attr object if non-dependent? 3290 // FIXME: Perform checking of type validity 3291 AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS, 3292 SpellingListIndex); 3293 AA->setPackExpansion(IsPackExpansion); 3294 D->addAttr(AA); 3295 } 3296 3297 void Sema::CheckAlignasUnderalignment(Decl *D) { 3298 assert(D->hasAttrs() && "no attributes on decl"); 3299 3300 QualType UnderlyingTy, DiagTy; 3301 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 3302 UnderlyingTy = DiagTy = VD->getType(); 3303 } else { 3304 UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D)); 3305 if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) 3306 UnderlyingTy = ED->getIntegerType(); 3307 } 3308 if (DiagTy->isDependentType() || DiagTy->isIncompleteType()) 3309 return; 3310 3311 // C++11 [dcl.align]p5, C11 6.7.5/4: 3312 // The combined effect of all alignment attributes in a declaration shall 3313 // not specify an alignment that is less strict than the alignment that 3314 // would otherwise be required for the entity being declared. 3315 AlignedAttr *AlignasAttr = nullptr; 3316 unsigned Align = 0; 3317 for (auto *I : D->specific_attrs<AlignedAttr>()) { 3318 if (I->isAlignmentDependent()) 3319 return; 3320 if (I->isAlignas()) 3321 AlignasAttr = I; 3322 Align = std::max(Align, I->getAlignment(Context)); 3323 } 3324 3325 if (AlignasAttr && Align) { 3326 CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align); 3327 CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy); 3328 if (NaturalAlign > RequestedAlign) 3329 Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned) 3330 << DiagTy << (unsigned)NaturalAlign.getQuantity(); 3331 } 3332 } 3333 3334 bool Sema::checkMSInheritanceAttrOnDefinition( 3335 CXXRecordDecl *RD, SourceRange Range, bool BestCase, 3336 MSInheritanceAttr::Spelling SemanticSpelling) { 3337 assert(RD->hasDefinition() && "RD has no definition!"); 3338 3339 // We may not have seen base specifiers or any virtual methods yet. We will 3340 // have to wait until the record is defined to catch any mismatches. 3341 if (!RD->getDefinition()->isCompleteDefinition()) 3342 return false; 3343 3344 // The unspecified model never matches what a definition could need. 3345 if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance) 3346 return false; 3347 3348 if (BestCase) { 3349 if (RD->calculateInheritanceModel() == SemanticSpelling) 3350 return false; 3351 } else { 3352 if (RD->calculateInheritanceModel() <= SemanticSpelling) 3353 return false; 3354 } 3355 3356 Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance) 3357 << 0 /*definition*/; 3358 Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) 3359 << RD->getNameAsString(); 3360 return true; 3361 } 3362 3363 /// parseModeAttrArg - Parses attribute mode string and returns parsed type 3364 /// attribute. 3365 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth, 3366 bool &IntegerMode, bool &ComplexMode) { 3367 IntegerMode = true; 3368 ComplexMode = false; 3369 switch (Str.size()) { 3370 case 2: 3371 switch (Str[0]) { 3372 case 'Q': 3373 DestWidth = 8; 3374 break; 3375 case 'H': 3376 DestWidth = 16; 3377 break; 3378 case 'S': 3379 DestWidth = 32; 3380 break; 3381 case 'D': 3382 DestWidth = 64; 3383 break; 3384 case 'X': 3385 DestWidth = 96; 3386 break; 3387 case 'T': 3388 DestWidth = 128; 3389 break; 3390 } 3391 if (Str[1] == 'F') { 3392 IntegerMode = false; 3393 } else if (Str[1] == 'C') { 3394 IntegerMode = false; 3395 ComplexMode = true; 3396 } else if (Str[1] != 'I') { 3397 DestWidth = 0; 3398 } 3399 break; 3400 case 4: 3401 // FIXME: glibc uses 'word' to define register_t; this is narrower than a 3402 // pointer on PIC16 and other embedded platforms. 3403 if (Str == "word") 3404 DestWidth = S.Context.getTargetInfo().getRegisterWidth(); 3405 else if (Str == "byte") 3406 DestWidth = S.Context.getTargetInfo().getCharWidth(); 3407 break; 3408 case 7: 3409 if (Str == "pointer") 3410 DestWidth = S.Context.getTargetInfo().getPointerWidth(0); 3411 break; 3412 case 11: 3413 if (Str == "unwind_word") 3414 DestWidth = S.Context.getTargetInfo().getUnwindWordWidth(); 3415 break; 3416 } 3417 } 3418 3419 /// handleModeAttr - This attribute modifies the width of a decl with primitive 3420 /// type. 3421 /// 3422 /// Despite what would be logical, the mode attribute is a decl attribute, not a 3423 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be 3424 /// HImode, not an intermediate pointer. 3425 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3426 // This attribute isn't documented, but glibc uses it. It changes 3427 // the width of an int or unsigned int to the specified size. 3428 if (!Attr.isArgIdent(0)) { 3429 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName() 3430 << AANT_ArgumentIdentifier; 3431 return; 3432 } 3433 3434 IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident; 3435 3436 S.AddModeAttr(Attr.getRange(), D, Name, Attr.getAttributeSpellingListIndex()); 3437 } 3438 3439 void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name, 3440 unsigned SpellingListIndex, bool InInstantiation) { 3441 StringRef Str = Name->getName(); 3442 normalizeName(Str); 3443 SourceLocation AttrLoc = AttrRange.getBegin(); 3444 3445 unsigned DestWidth = 0; 3446 bool IntegerMode = true; 3447 bool ComplexMode = false; 3448 llvm::APInt VectorSize(64, 0); 3449 if (Str.size() >= 4 && Str[0] == 'V') { 3450 // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2). 3451 size_t StrSize = Str.size(); 3452 size_t VectorStringLength = 0; 3453 while ((VectorStringLength + 1) < StrSize && 3454 isdigit(Str[VectorStringLength + 1])) 3455 ++VectorStringLength; 3456 if (VectorStringLength && 3457 !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) && 3458 VectorSize.isPowerOf2()) { 3459 parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth, 3460 IntegerMode, ComplexMode); 3461 // Avoid duplicate warning from template instantiation. 3462 if (!InInstantiation) 3463 Diag(AttrLoc, diag::warn_vector_mode_deprecated); 3464 } else { 3465 VectorSize = 0; 3466 } 3467 } 3468 3469 if (!VectorSize) 3470 parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode); 3471 3472 // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t 3473 // and friends, at least with glibc. 3474 // FIXME: Make sure floating-point mappings are accurate 3475 // FIXME: Support XF and TF types 3476 if (!DestWidth) { 3477 Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name; 3478 return; 3479 } 3480 3481 QualType OldTy; 3482 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) 3483 OldTy = TD->getUnderlyingType(); 3484 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) { 3485 // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'. 3486 // Try to get type from enum declaration, default to int. 3487 OldTy = ED->getIntegerType(); 3488 if (OldTy.isNull()) 3489 OldTy = Context.IntTy; 3490 } else 3491 OldTy = cast<ValueDecl>(D)->getType(); 3492 3493 if (OldTy->isDependentType()) { 3494 D->addAttr(::new (Context) 3495 ModeAttr(AttrRange, Context, Name, SpellingListIndex)); 3496 return; 3497 } 3498 3499 // Base type can also be a vector type (see PR17453). 3500 // Distinguish between base type and base element type. 3501 QualType OldElemTy = OldTy; 3502 if (const VectorType *VT = OldTy->getAs<VectorType>()) 3503 OldElemTy = VT->getElementType(); 3504 3505 // GCC allows 'mode' attribute on enumeration types (even incomplete), except 3506 // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete 3507 // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected. 3508 if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) && 3509 VectorSize.getBoolValue()) { 3510 Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange; 3511 return; 3512 } 3513 bool IntegralOrAnyEnumType = 3514 OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>(); 3515 3516 if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() && 3517 !IntegralOrAnyEnumType) 3518 Diag(AttrLoc, diag::err_mode_not_primitive); 3519 else if (IntegerMode) { 3520 if (!IntegralOrAnyEnumType) 3521 Diag(AttrLoc, diag::err_mode_wrong_type); 3522 } else if (ComplexMode) { 3523 if (!OldElemTy->isComplexType()) 3524 Diag(AttrLoc, diag::err_mode_wrong_type); 3525 } else { 3526 if (!OldElemTy->isFloatingType()) 3527 Diag(AttrLoc, diag::err_mode_wrong_type); 3528 } 3529 3530 QualType NewElemTy; 3531 3532 if (IntegerMode) 3533 NewElemTy = Context.getIntTypeForBitwidth(DestWidth, 3534 OldElemTy->isSignedIntegerType()); 3535 else 3536 NewElemTy = Context.getRealTypeForBitwidth(DestWidth); 3537 3538 if (NewElemTy.isNull()) { 3539 Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name; 3540 return; 3541 } 3542 3543 if (ComplexMode) { 3544 NewElemTy = Context.getComplexType(NewElemTy); 3545 } 3546 3547 QualType NewTy = NewElemTy; 3548 if (VectorSize.getBoolValue()) { 3549 NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(), 3550 VectorType::GenericVector); 3551 } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) { 3552 // Complex machine mode does not support base vector types. 3553 if (ComplexMode) { 3554 Diag(AttrLoc, diag::err_complex_mode_vector_type); 3555 return; 3556 } 3557 unsigned NumElements = Context.getTypeSize(OldElemTy) * 3558 OldVT->getNumElements() / 3559 Context.getTypeSize(NewElemTy); 3560 NewTy = 3561 Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind()); 3562 } 3563 3564 if (NewTy.isNull()) { 3565 Diag(AttrLoc, diag::err_mode_wrong_type); 3566 return; 3567 } 3568 3569 // Install the new type. 3570 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) 3571 TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy); 3572 else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) 3573 ED->setIntegerType(NewTy); 3574 else 3575 cast<ValueDecl>(D)->setType(NewTy); 3576 3577 D->addAttr(::new (Context) 3578 ModeAttr(AttrRange, Context, Name, SpellingListIndex)); 3579 } 3580 3581 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3582 D->addAttr(::new (S.Context) 3583 NoDebugAttr(Attr.getRange(), S.Context, 3584 Attr.getAttributeSpellingListIndex())); 3585 } 3586 3587 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range, 3588 IdentifierInfo *Ident, 3589 unsigned AttrSpellingListIndex) { 3590 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) { 3591 Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident; 3592 Diag(Optnone->getLocation(), diag::note_conflicting_attribute); 3593 return nullptr; 3594 } 3595 3596 if (D->hasAttr<AlwaysInlineAttr>()) 3597 return nullptr; 3598 3599 return ::new (Context) AlwaysInlineAttr(Range, Context, 3600 AttrSpellingListIndex); 3601 } 3602 3603 CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range, 3604 IdentifierInfo *Ident, 3605 unsigned AttrSpellingListIndex) { 3606 if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident)) 3607 return nullptr; 3608 3609 return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex); 3610 } 3611 3612 InternalLinkageAttr * 3613 Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range, 3614 IdentifierInfo *Ident, 3615 unsigned AttrSpellingListIndex) { 3616 if (auto VD = dyn_cast<VarDecl>(D)) { 3617 // Attribute applies to Var but not any subclass of it (like ParmVar, 3618 // ImplicitParm or VarTemplateSpecialization). 3619 if (VD->getKind() != Decl::Var) { 3620 Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type) 3621 << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass 3622 : ExpectedVariableOrFunction); 3623 return nullptr; 3624 } 3625 // Attribute does not apply to non-static local variables. 3626 if (VD->hasLocalStorage()) { 3627 Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage); 3628 return nullptr; 3629 } 3630 } 3631 3632 if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident)) 3633 return nullptr; 3634 3635 return ::new (Context) 3636 InternalLinkageAttr(Range, Context, AttrSpellingListIndex); 3637 } 3638 3639 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range, 3640 unsigned AttrSpellingListIndex) { 3641 if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) { 3642 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'"; 3643 Diag(Optnone->getLocation(), diag::note_conflicting_attribute); 3644 return nullptr; 3645 } 3646 3647 if (D->hasAttr<MinSizeAttr>()) 3648 return nullptr; 3649 3650 return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex); 3651 } 3652 3653 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range, 3654 unsigned AttrSpellingListIndex) { 3655 if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) { 3656 Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline; 3657 Diag(Range.getBegin(), diag::note_conflicting_attribute); 3658 D->dropAttr<AlwaysInlineAttr>(); 3659 } 3660 if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) { 3661 Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize; 3662 Diag(Range.getBegin(), diag::note_conflicting_attribute); 3663 D->dropAttr<MinSizeAttr>(); 3664 } 3665 3666 if (D->hasAttr<OptimizeNoneAttr>()) 3667 return nullptr; 3668 3669 return ::new (Context) OptimizeNoneAttr(Range, Context, 3670 AttrSpellingListIndex); 3671 } 3672 3673 static void handleAlwaysInlineAttr(Sema &S, Decl *D, 3674 const AttributeList &Attr) { 3675 if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(), 3676 Attr.getName())) 3677 return; 3678 3679 if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr( 3680 D, Attr.getRange(), Attr.getName(), 3681 Attr.getAttributeSpellingListIndex())) 3682 D->addAttr(Inline); 3683 } 3684 3685 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3686 if (MinSizeAttr *MinSize = S.mergeMinSizeAttr( 3687 D, Attr.getRange(), Attr.getAttributeSpellingListIndex())) 3688 D->addAttr(MinSize); 3689 } 3690 3691 static void handleOptimizeNoneAttr(Sema &S, Decl *D, 3692 const AttributeList &Attr) { 3693 if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr( 3694 D, Attr.getRange(), Attr.getAttributeSpellingListIndex())) 3695 D->addAttr(Optnone); 3696 } 3697 3698 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3699 if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, Attr.getRange(), 3700 Attr.getName()) || 3701 checkAttrMutualExclusion<CUDAHostAttr>(S, D, Attr.getRange(), 3702 Attr.getName())) { 3703 return; 3704 } 3705 FunctionDecl *FD = cast<FunctionDecl>(D); 3706 if (!FD->getReturnType()->isVoidType()) { 3707 SourceRange RTRange = FD->getReturnTypeSourceRange(); 3708 S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return) 3709 << FD->getType() 3710 << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void") 3711 : FixItHint()); 3712 return; 3713 } 3714 if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) { 3715 if (Method->isInstance()) { 3716 S.Diag(Method->getLocStart(), diag::err_kern_is_nonstatic_method) 3717 << Method; 3718 return; 3719 } 3720 S.Diag(Method->getLocStart(), diag::warn_kern_is_method) << Method; 3721 } 3722 // Only warn for "inline" when compiling for host, to cut down on noise. 3723 if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice) 3724 S.Diag(FD->getLocStart(), diag::warn_kern_is_inline) << FD; 3725 3726 D->addAttr(::new (S.Context) 3727 CUDAGlobalAttr(Attr.getRange(), S.Context, 3728 Attr.getAttributeSpellingListIndex())); 3729 } 3730 3731 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3732 FunctionDecl *Fn = cast<FunctionDecl>(D); 3733 if (!Fn->isInlineSpecified()) { 3734 S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline); 3735 return; 3736 } 3737 3738 D->addAttr(::new (S.Context) 3739 GNUInlineAttr(Attr.getRange(), S.Context, 3740 Attr.getAttributeSpellingListIndex())); 3741 } 3742 3743 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) { 3744 if (hasDeclarator(D)) return; 3745 3746 // Diagnostic is emitted elsewhere: here we store the (valid) Attr 3747 // in the Decl node for syntactic reasoning, e.g., pretty-printing. 3748 CallingConv CC; 3749 if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr)) 3750 return; 3751 3752 if (!isa<ObjCMethodDecl>(D)) { 3753 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 3754 << Attr.getName() << ExpectedFunctionOrMethod; 3755 return; 3756 } 3757 3758 switch (Attr.getKind()) { 3759 case AttributeList::AT_FastCall: 3760 D->addAttr(::new (S.Context) 3761 FastCallAttr(Attr.getRange(), S.Context, 3762 Attr.getAttributeSpellingListIndex())); 3763 return; 3764 case AttributeList::AT_StdCall: 3765 D->addAttr(::new (S.Context) 3766 StdCallAttr(Attr.getRange(), S.Context, 3767 Attr.getAttributeSpellingListIndex())); 3768 return; 3769 case AttributeList::AT_ThisCall: 3770 D->addAttr(::new (S.Context) 3771 ThisCallAttr(Attr.getRange(), S.Context, 3772 Attr.getAttributeSpellingListIndex())); 3773 return; 3774 case AttributeList::AT_CDecl: 3775 D->addAttr(::new (S.Context) 3776 CDeclAttr(Attr.getRange(), S.Context, 3777 Attr.getAttributeSpellingListIndex())); 3778 return; 3779 case AttributeList::AT_Pascal: 3780 D->addAttr(::new (S.Context) 3781 PascalAttr(Attr.getRange(), S.Context, 3782 Attr.getAttributeSpellingListIndex())); 3783 return; 3784 case AttributeList::AT_SwiftCall: 3785 D->addAttr(::new (S.Context) 3786 SwiftCallAttr(Attr.getRange(), S.Context, 3787 Attr.getAttributeSpellingListIndex())); 3788 return; 3789 case AttributeList::AT_VectorCall: 3790 D->addAttr(::new (S.Context) 3791 VectorCallAttr(Attr.getRange(), S.Context, 3792 Attr.getAttributeSpellingListIndex())); 3793 return; 3794 case AttributeList::AT_MSABI: 3795 D->addAttr(::new (S.Context) 3796 MSABIAttr(Attr.getRange(), S.Context, 3797 Attr.getAttributeSpellingListIndex())); 3798 return; 3799 case AttributeList::AT_SysVABI: 3800 D->addAttr(::new (S.Context) 3801 SysVABIAttr(Attr.getRange(), S.Context, 3802 Attr.getAttributeSpellingListIndex())); 3803 return; 3804 case AttributeList::AT_Pcs: { 3805 PcsAttr::PCSType PCS; 3806 switch (CC) { 3807 case CC_AAPCS: 3808 PCS = PcsAttr::AAPCS; 3809 break; 3810 case CC_AAPCS_VFP: 3811 PCS = PcsAttr::AAPCS_VFP; 3812 break; 3813 default: 3814 llvm_unreachable("unexpected calling convention in pcs attribute"); 3815 } 3816 3817 D->addAttr(::new (S.Context) 3818 PcsAttr(Attr.getRange(), S.Context, PCS, 3819 Attr.getAttributeSpellingListIndex())); 3820 return; 3821 } 3822 case AttributeList::AT_IntelOclBicc: 3823 D->addAttr(::new (S.Context) 3824 IntelOclBiccAttr(Attr.getRange(), S.Context, 3825 Attr.getAttributeSpellingListIndex())); 3826 return; 3827 case AttributeList::AT_PreserveMost: 3828 D->addAttr(::new (S.Context) PreserveMostAttr( 3829 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 3830 return; 3831 case AttributeList::AT_PreserveAll: 3832 D->addAttr(::new (S.Context) PreserveAllAttr( 3833 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 3834 return; 3835 default: 3836 llvm_unreachable("unexpected attribute kind"); 3837 } 3838 } 3839 3840 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC, 3841 const FunctionDecl *FD) { 3842 if (attr.isInvalid()) 3843 return true; 3844 3845 if (attr.hasProcessingCache()) { 3846 CC = (CallingConv) attr.getProcessingCache(); 3847 return false; 3848 } 3849 3850 unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0; 3851 if (!checkAttributeNumArgs(*this, attr, ReqArgs)) { 3852 attr.setInvalid(); 3853 return true; 3854 } 3855 3856 // TODO: diagnose uses of these conventions on the wrong target. 3857 switch (attr.getKind()) { 3858 case AttributeList::AT_CDecl: CC = CC_C; break; 3859 case AttributeList::AT_FastCall: CC = CC_X86FastCall; break; 3860 case AttributeList::AT_StdCall: CC = CC_X86StdCall; break; 3861 case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break; 3862 case AttributeList::AT_Pascal: CC = CC_X86Pascal; break; 3863 case AttributeList::AT_SwiftCall: CC = CC_Swift; break; 3864 case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break; 3865 case AttributeList::AT_MSABI: 3866 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C : 3867 CC_X86_64Win64; 3868 break; 3869 case AttributeList::AT_SysVABI: 3870 CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV : 3871 CC_C; 3872 break; 3873 case AttributeList::AT_Pcs: { 3874 StringRef StrRef; 3875 if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) { 3876 attr.setInvalid(); 3877 return true; 3878 } 3879 if (StrRef == "aapcs") { 3880 CC = CC_AAPCS; 3881 break; 3882 } else if (StrRef == "aapcs-vfp") { 3883 CC = CC_AAPCS_VFP; 3884 break; 3885 } 3886 3887 attr.setInvalid(); 3888 Diag(attr.getLoc(), diag::err_invalid_pcs); 3889 return true; 3890 } 3891 case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break; 3892 case AttributeList::AT_PreserveMost: CC = CC_PreserveMost; break; 3893 case AttributeList::AT_PreserveAll: CC = CC_PreserveAll; break; 3894 default: llvm_unreachable("unexpected attribute kind"); 3895 } 3896 3897 const TargetInfo &TI = Context.getTargetInfo(); 3898 TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC); 3899 if (A != TargetInfo::CCCR_OK) { 3900 if (A == TargetInfo::CCCR_Warning) 3901 Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName(); 3902 3903 // This convention is not valid for the target. Use the default function or 3904 // method calling convention. 3905 bool IsCXXMethod = false, IsVariadic = false; 3906 if (FD) { 3907 IsCXXMethod = FD->isCXXInstanceMember(); 3908 IsVariadic = FD->isVariadic(); 3909 } 3910 CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod); 3911 } 3912 3913 attr.setProcessingCache((unsigned) CC); 3914 return false; 3915 } 3916 3917 /// Pointer-like types in the default address space. 3918 static bool isValidSwiftContextType(QualType type) { 3919 if (!type->hasPointerRepresentation()) 3920 return type->isDependentType(); 3921 return type->getPointeeType().getAddressSpace() == 0; 3922 } 3923 3924 /// Pointers and references in the default address space. 3925 static bool isValidSwiftIndirectResultType(QualType type) { 3926 if (auto ptrType = type->getAs<PointerType>()) { 3927 type = ptrType->getPointeeType(); 3928 } else if (auto refType = type->getAs<ReferenceType>()) { 3929 type = refType->getPointeeType(); 3930 } else { 3931 return type->isDependentType(); 3932 } 3933 return type.getAddressSpace() == 0; 3934 } 3935 3936 /// Pointers and references to pointers in the default address space. 3937 static bool isValidSwiftErrorResultType(QualType type) { 3938 if (auto ptrType = type->getAs<PointerType>()) { 3939 type = ptrType->getPointeeType(); 3940 } else if (auto refType = type->getAs<ReferenceType>()) { 3941 type = refType->getPointeeType(); 3942 } else { 3943 return type->isDependentType(); 3944 } 3945 if (!type.getQualifiers().empty()) 3946 return false; 3947 return isValidSwiftContextType(type); 3948 } 3949 3950 static void handleParameterABIAttr(Sema &S, Decl *D, const AttributeList &attr, 3951 ParameterABI abi) { 3952 S.AddParameterABIAttr(attr.getRange(), D, abi, 3953 attr.getAttributeSpellingListIndex()); 3954 } 3955 3956 void Sema::AddParameterABIAttr(SourceRange range, Decl *D, ParameterABI abi, 3957 unsigned spellingIndex) { 3958 3959 QualType type = cast<ParmVarDecl>(D)->getType(); 3960 3961 if (auto existingAttr = D->getAttr<ParameterABIAttr>()) { 3962 if (existingAttr->getABI() != abi) { 3963 Diag(range.getBegin(), diag::err_attributes_are_not_compatible) 3964 << getParameterABISpelling(abi) << existingAttr; 3965 Diag(existingAttr->getLocation(), diag::note_conflicting_attribute); 3966 return; 3967 } 3968 } 3969 3970 switch (abi) { 3971 case ParameterABI::Ordinary: 3972 llvm_unreachable("explicit attribute for ordinary parameter ABI?"); 3973 3974 case ParameterABI::SwiftContext: 3975 if (!isValidSwiftContextType(type)) { 3976 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) 3977 << getParameterABISpelling(abi) 3978 << /*pointer to pointer */ 0 << type; 3979 } 3980 D->addAttr(::new (Context) 3981 SwiftContextAttr(range, Context, spellingIndex)); 3982 return; 3983 3984 case ParameterABI::SwiftErrorResult: 3985 if (!isValidSwiftErrorResultType(type)) { 3986 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) 3987 << getParameterABISpelling(abi) 3988 << /*pointer to pointer */ 1 << type; 3989 } 3990 D->addAttr(::new (Context) 3991 SwiftErrorResultAttr(range, Context, spellingIndex)); 3992 return; 3993 3994 case ParameterABI::SwiftIndirectResult: 3995 if (!isValidSwiftIndirectResultType(type)) { 3996 Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type) 3997 << getParameterABISpelling(abi) 3998 << /*pointer*/ 0 << type; 3999 } 4000 D->addAttr(::new (Context) 4001 SwiftIndirectResultAttr(range, Context, spellingIndex)); 4002 return; 4003 } 4004 llvm_unreachable("bad parameter ABI attribute"); 4005 } 4006 4007 /// Checks a regparm attribute, returning true if it is ill-formed and 4008 /// otherwise setting numParams to the appropriate value. 4009 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) { 4010 if (Attr.isInvalid()) 4011 return true; 4012 4013 if (!checkAttributeNumArgs(*this, Attr, 1)) { 4014 Attr.setInvalid(); 4015 return true; 4016 } 4017 4018 uint32_t NP; 4019 Expr *NumParamsExpr = Attr.getArgAsExpr(0); 4020 if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) { 4021 Attr.setInvalid(); 4022 return true; 4023 } 4024 4025 if (Context.getTargetInfo().getRegParmMax() == 0) { 4026 Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform) 4027 << NumParamsExpr->getSourceRange(); 4028 Attr.setInvalid(); 4029 return true; 4030 } 4031 4032 numParams = NP; 4033 if (numParams > Context.getTargetInfo().getRegParmMax()) { 4034 Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number) 4035 << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange(); 4036 Attr.setInvalid(); 4037 return true; 4038 } 4039 4040 return false; 4041 } 4042 4043 // Checks whether an argument of launch_bounds attribute is 4044 // acceptable, performs implicit conversion to Rvalue, and returns 4045 // non-nullptr Expr result on success. Otherwise, it returns nullptr 4046 // and may output an error. 4047 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E, 4048 const CUDALaunchBoundsAttr &Attr, 4049 const unsigned Idx) { 4050 if (S.DiagnoseUnexpandedParameterPack(E)) 4051 return nullptr; 4052 4053 // Accept template arguments for now as they depend on something else. 4054 // We'll get to check them when they eventually get instantiated. 4055 if (E->isValueDependent()) 4056 return E; 4057 4058 llvm::APSInt I(64); 4059 if (!E->isIntegerConstantExpr(I, S.Context)) { 4060 S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type) 4061 << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange(); 4062 return nullptr; 4063 } 4064 // Make sure we can fit it in 32 bits. 4065 if (!I.isIntN(32)) { 4066 S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false) 4067 << 32 << /* Unsigned */ 1; 4068 return nullptr; 4069 } 4070 if (I < 0) 4071 S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative) 4072 << &Attr << Idx << E->getSourceRange(); 4073 4074 // We may need to perform implicit conversion of the argument. 4075 InitializedEntity Entity = InitializedEntity::InitializeParameter( 4076 S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false); 4077 ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E); 4078 assert(!ValArg.isInvalid() && 4079 "Unexpected PerformCopyInitialization() failure."); 4080 4081 return ValArg.getAs<Expr>(); 4082 } 4083 4084 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads, 4085 Expr *MinBlocks, unsigned SpellingListIndex) { 4086 CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks, 4087 SpellingListIndex); 4088 MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0); 4089 if (MaxThreads == nullptr) 4090 return; 4091 4092 if (MinBlocks) { 4093 MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1); 4094 if (MinBlocks == nullptr) 4095 return; 4096 } 4097 4098 D->addAttr(::new (Context) CUDALaunchBoundsAttr( 4099 AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex)); 4100 } 4101 4102 static void handleLaunchBoundsAttr(Sema &S, Decl *D, 4103 const AttributeList &Attr) { 4104 if (!checkAttributeAtLeastNumArgs(S, Attr, 1) || 4105 !checkAttributeAtMostNumArgs(S, Attr, 2)) 4106 return; 4107 4108 S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0), 4109 Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr, 4110 Attr.getAttributeSpellingListIndex()); 4111 } 4112 4113 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D, 4114 const AttributeList &Attr) { 4115 if (!Attr.isArgIdent(0)) { 4116 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 4117 << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier; 4118 return; 4119 } 4120 4121 if (!checkAttributeNumArgs(S, Attr, 3)) 4122 return; 4123 4124 IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident; 4125 4126 if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) { 4127 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type) 4128 << Attr.getName() << ExpectedFunctionOrMethod; 4129 return; 4130 } 4131 4132 uint64_t ArgumentIdx; 4133 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1), 4134 ArgumentIdx)) 4135 return; 4136 4137 uint64_t TypeTagIdx; 4138 if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2), 4139 TypeTagIdx)) 4140 return; 4141 4142 bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag"); 4143 if (IsPointer) { 4144 // Ensure that buffer has a pointer type. 4145 QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx); 4146 if (!BufferTy->isPointerType()) { 4147 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only) 4148 << Attr.getName() << 0; 4149 } 4150 } 4151 4152 D->addAttr(::new (S.Context) 4153 ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind, 4154 ArgumentIdx, TypeTagIdx, IsPointer, 4155 Attr.getAttributeSpellingListIndex())); 4156 } 4157 4158 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D, 4159 const AttributeList &Attr) { 4160 if (!Attr.isArgIdent(0)) { 4161 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type) 4162 << Attr.getName() << 1 << AANT_ArgumentIdentifier; 4163 return; 4164 } 4165 4166 if (!checkAttributeNumArgs(S, Attr, 1)) 4167 return; 4168 4169 if (!isa<VarDecl>(D)) { 4170 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type) 4171 << Attr.getName() << ExpectedVariable; 4172 return; 4173 } 4174 4175 IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident; 4176 TypeSourceInfo *MatchingCTypeLoc = nullptr; 4177 S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc); 4178 assert(MatchingCTypeLoc && "no type source info for attribute argument"); 4179 4180 D->addAttr(::new (S.Context) 4181 TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind, 4182 MatchingCTypeLoc, 4183 Attr.getLayoutCompatible(), 4184 Attr.getMustBeNull(), 4185 Attr.getAttributeSpellingListIndex())); 4186 } 4187 4188 //===----------------------------------------------------------------------===// 4189 // Checker-specific attribute handlers. 4190 //===----------------------------------------------------------------------===// 4191 4192 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) { 4193 return type->isDependentType() || 4194 type->isObjCRetainableType(); 4195 } 4196 4197 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) { 4198 return type->isDependentType() || 4199 type->isObjCObjectPointerType() || 4200 S.Context.isObjCNSObjectType(type); 4201 } 4202 4203 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) { 4204 return type->isDependentType() || 4205 type->isPointerType() || 4206 isValidSubjectOfNSAttribute(S, type); 4207 } 4208 4209 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4210 S.AddNSConsumedAttr(Attr.getRange(), D, Attr.getAttributeSpellingListIndex(), 4211 Attr.getKind() == AttributeList::AT_NSConsumed, 4212 /*template instantiation*/ false); 4213 } 4214 4215 void Sema::AddNSConsumedAttr(SourceRange attrRange, Decl *D, 4216 unsigned spellingIndex, bool isNSConsumed, 4217 bool isTemplateInstantiation) { 4218 ParmVarDecl *param = cast<ParmVarDecl>(D); 4219 bool typeOK; 4220 4221 if (isNSConsumed) { 4222 typeOK = isValidSubjectOfNSAttribute(*this, param->getType()); 4223 } else { 4224 typeOK = isValidSubjectOfCFAttribute(*this, param->getType()); 4225 } 4226 4227 if (!typeOK) { 4228 // These attributes are normally just advisory, but in ARC, ns_consumed 4229 // is significant. Allow non-dependent code to contain inappropriate 4230 // attributes even in ARC, but require template instantiations to be 4231 // set up correctly. 4232 Diag(D->getLocStart(), 4233 (isTemplateInstantiation && isNSConsumed && 4234 getLangOpts().ObjCAutoRefCount 4235 ? diag::err_ns_attribute_wrong_parameter_type 4236 : diag::warn_ns_attribute_wrong_parameter_type)) 4237 << attrRange 4238 << (isNSConsumed ? "ns_consumed" : "cf_consumed") 4239 << (isNSConsumed ? /*objc pointers*/ 0 : /*cf pointers*/ 1); 4240 return; 4241 } 4242 4243 if (isNSConsumed) 4244 param->addAttr(::new (Context) 4245 NSConsumedAttr(attrRange, Context, spellingIndex)); 4246 else 4247 param->addAttr(::new (Context) 4248 CFConsumedAttr(attrRange, Context, spellingIndex)); 4249 } 4250 4251 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D, 4252 const AttributeList &Attr) { 4253 QualType returnType; 4254 4255 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) 4256 returnType = MD->getReturnType(); 4257 else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) && 4258 (Attr.getKind() == AttributeList::AT_NSReturnsRetained)) 4259 return; // ignore: was handled as a type attribute 4260 else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) 4261 returnType = PD->getType(); 4262 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 4263 returnType = FD->getReturnType(); 4264 else if (auto *Param = dyn_cast<ParmVarDecl>(D)) { 4265 returnType = Param->getType()->getPointeeType(); 4266 if (returnType.isNull()) { 4267 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type) 4268 << Attr.getName() << /*pointer-to-CF*/2 4269 << Attr.getRange(); 4270 return; 4271 } 4272 } else { 4273 AttributeDeclKind ExpectedDeclKind; 4274 switch (Attr.getKind()) { 4275 default: llvm_unreachable("invalid ownership attribute"); 4276 case AttributeList::AT_NSReturnsRetained: 4277 case AttributeList::AT_NSReturnsAutoreleased: 4278 case AttributeList::AT_NSReturnsNotRetained: 4279 ExpectedDeclKind = ExpectedFunctionOrMethod; 4280 break; 4281 4282 case AttributeList::AT_CFReturnsRetained: 4283 case AttributeList::AT_CFReturnsNotRetained: 4284 ExpectedDeclKind = ExpectedFunctionMethodOrParameter; 4285 break; 4286 } 4287 S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type) 4288 << Attr.getRange() << Attr.getName() << ExpectedDeclKind; 4289 return; 4290 } 4291 4292 bool typeOK; 4293 bool cf; 4294 switch (Attr.getKind()) { 4295 default: llvm_unreachable("invalid ownership attribute"); 4296 case AttributeList::AT_NSReturnsRetained: 4297 typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType); 4298 cf = false; 4299 break; 4300 4301 case AttributeList::AT_NSReturnsAutoreleased: 4302 case AttributeList::AT_NSReturnsNotRetained: 4303 typeOK = isValidSubjectOfNSAttribute(S, returnType); 4304 cf = false; 4305 break; 4306 4307 case AttributeList::AT_CFReturnsRetained: 4308 case AttributeList::AT_CFReturnsNotRetained: 4309 typeOK = isValidSubjectOfCFAttribute(S, returnType); 4310 cf = true; 4311 break; 4312 } 4313 4314 if (!typeOK) { 4315 if (isa<ParmVarDecl>(D)) { 4316 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type) 4317 << Attr.getName() << /*pointer-to-CF*/2 4318 << Attr.getRange(); 4319 } else { 4320 // Needs to be kept in sync with warn_ns_attribute_wrong_return_type. 4321 enum : unsigned { 4322 Function, 4323 Method, 4324 Property 4325 } SubjectKind = Function; 4326 if (isa<ObjCMethodDecl>(D)) 4327 SubjectKind = Method; 4328 else if (isa<ObjCPropertyDecl>(D)) 4329 SubjectKind = Property; 4330 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type) 4331 << Attr.getName() << SubjectKind << cf 4332 << Attr.getRange(); 4333 } 4334 return; 4335 } 4336 4337 switch (Attr.getKind()) { 4338 default: 4339 llvm_unreachable("invalid ownership attribute"); 4340 case AttributeList::AT_NSReturnsAutoreleased: 4341 D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr( 4342 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 4343 return; 4344 case AttributeList::AT_CFReturnsNotRetained: 4345 D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr( 4346 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 4347 return; 4348 case AttributeList::AT_NSReturnsNotRetained: 4349 D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr( 4350 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 4351 return; 4352 case AttributeList::AT_CFReturnsRetained: 4353 D->addAttr(::new (S.Context) CFReturnsRetainedAttr( 4354 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 4355 return; 4356 case AttributeList::AT_NSReturnsRetained: 4357 D->addAttr(::new (S.Context) NSReturnsRetainedAttr( 4358 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 4359 return; 4360 }; 4361 } 4362 4363 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D, 4364 const AttributeList &attr) { 4365 const int EP_ObjCMethod = 1; 4366 const int EP_ObjCProperty = 2; 4367 4368 SourceLocation loc = attr.getLoc(); 4369 QualType resultType; 4370 if (isa<ObjCMethodDecl>(D)) 4371 resultType = cast<ObjCMethodDecl>(D)->getReturnType(); 4372 else 4373 resultType = cast<ObjCPropertyDecl>(D)->getType(); 4374 4375 if (!resultType->isReferenceType() && 4376 (!resultType->isPointerType() || resultType->isObjCRetainableType())) { 4377 S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type) 4378 << SourceRange(loc) 4379 << attr.getName() 4380 << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty) 4381 << /*non-retainable pointer*/ 2; 4382 4383 // Drop the attribute. 4384 return; 4385 } 4386 4387 D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr( 4388 attr.getRange(), S.Context, attr.getAttributeSpellingListIndex())); 4389 } 4390 4391 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D, 4392 const AttributeList &attr) { 4393 ObjCMethodDecl *method = cast<ObjCMethodDecl>(D); 4394 4395 DeclContext *DC = method->getDeclContext(); 4396 if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) { 4397 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol) 4398 << attr.getName() << 0; 4399 S.Diag(PDecl->getLocation(), diag::note_protocol_decl); 4400 return; 4401 } 4402 if (method->getMethodFamily() == OMF_dealloc) { 4403 S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol) 4404 << attr.getName() << 1; 4405 return; 4406 } 4407 4408 method->addAttr(::new (S.Context) 4409 ObjCRequiresSuperAttr(attr.getRange(), S.Context, 4410 attr.getAttributeSpellingListIndex())); 4411 } 4412 4413 static void handleCFAuditedTransferAttr(Sema &S, Decl *D, 4414 const AttributeList &Attr) { 4415 if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(), 4416 Attr.getName())) 4417 return; 4418 4419 D->addAttr(::new (S.Context) 4420 CFAuditedTransferAttr(Attr.getRange(), S.Context, 4421 Attr.getAttributeSpellingListIndex())); 4422 } 4423 4424 static void handleCFUnknownTransferAttr(Sema &S, Decl *D, 4425 const AttributeList &Attr) { 4426 if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(), 4427 Attr.getName())) 4428 return; 4429 4430 D->addAttr(::new (S.Context) 4431 CFUnknownTransferAttr(Attr.getRange(), S.Context, 4432 Attr.getAttributeSpellingListIndex())); 4433 } 4434 4435 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D, 4436 const AttributeList &Attr) { 4437 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr; 4438 4439 if (!Parm) { 4440 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0; 4441 return; 4442 } 4443 4444 // Typedefs only allow objc_bridge(id) and have some additional checking. 4445 if (auto TD = dyn_cast<TypedefNameDecl>(D)) { 4446 if (!Parm->Ident->isStr("id")) { 4447 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id) 4448 << Attr.getName(); 4449 return; 4450 } 4451 4452 // Only allow 'cv void *'. 4453 QualType T = TD->getUnderlyingType(); 4454 if (!T->isVoidPointerType()) { 4455 S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer); 4456 return; 4457 } 4458 } 4459 4460 D->addAttr(::new (S.Context) 4461 ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident, 4462 Attr.getAttributeSpellingListIndex())); 4463 } 4464 4465 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D, 4466 const AttributeList &Attr) { 4467 IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr; 4468 4469 if (!Parm) { 4470 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0; 4471 return; 4472 } 4473 4474 D->addAttr(::new (S.Context) 4475 ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident, 4476 Attr.getAttributeSpellingListIndex())); 4477 } 4478 4479 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D, 4480 const AttributeList &Attr) { 4481 IdentifierInfo *RelatedClass = 4482 Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr; 4483 if (!RelatedClass) { 4484 S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0; 4485 return; 4486 } 4487 IdentifierInfo *ClassMethod = 4488 Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr; 4489 IdentifierInfo *InstanceMethod = 4490 Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr; 4491 D->addAttr(::new (S.Context) 4492 ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass, 4493 ClassMethod, InstanceMethod, 4494 Attr.getAttributeSpellingListIndex())); 4495 } 4496 4497 static void handleObjCDesignatedInitializer(Sema &S, Decl *D, 4498 const AttributeList &Attr) { 4499 ObjCInterfaceDecl *IFace; 4500 if (ObjCCategoryDecl *CatDecl = 4501 dyn_cast<ObjCCategoryDecl>(D->getDeclContext())) 4502 IFace = CatDecl->getClassInterface(); 4503 else 4504 IFace = cast<ObjCInterfaceDecl>(D->getDeclContext()); 4505 4506 if (!IFace) 4507 return; 4508 4509 IFace->setHasDesignatedInitializers(); 4510 D->addAttr(::new (S.Context) 4511 ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context, 4512 Attr.getAttributeSpellingListIndex())); 4513 } 4514 4515 static void handleObjCRuntimeName(Sema &S, Decl *D, 4516 const AttributeList &Attr) { 4517 StringRef MetaDataName; 4518 if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName)) 4519 return; 4520 D->addAttr(::new (S.Context) 4521 ObjCRuntimeNameAttr(Attr.getRange(), S.Context, 4522 MetaDataName, 4523 Attr.getAttributeSpellingListIndex())); 4524 } 4525 4526 // When a user wants to use objc_boxable with a union or struct 4527 // but they don't have access to the declaration (legacy/third-party code) 4528 // then they can 'enable' this feature with a typedef: 4529 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct; 4530 static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) { 4531 bool notify = false; 4532 4533 RecordDecl *RD = dyn_cast<RecordDecl>(D); 4534 if (RD && RD->getDefinition()) { 4535 RD = RD->getDefinition(); 4536 notify = true; 4537 } 4538 4539 if (RD) { 4540 ObjCBoxableAttr *BoxableAttr = ::new (S.Context) 4541 ObjCBoxableAttr(Attr.getRange(), S.Context, 4542 Attr.getAttributeSpellingListIndex()); 4543 RD->addAttr(BoxableAttr); 4544 if (notify) { 4545 // we need to notify ASTReader/ASTWriter about 4546 // modification of existing declaration 4547 if (ASTMutationListener *L = S.getASTMutationListener()) 4548 L->AddedAttributeToRecord(BoxableAttr, RD); 4549 } 4550 } 4551 } 4552 4553 static void handleObjCOwnershipAttr(Sema &S, Decl *D, 4554 const AttributeList &Attr) { 4555 if (hasDeclarator(D)) return; 4556 4557 S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type) 4558 << Attr.getRange() << Attr.getName() << ExpectedVariable; 4559 } 4560 4561 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D, 4562 const AttributeList &Attr) { 4563 ValueDecl *vd = cast<ValueDecl>(D); 4564 QualType type = vd->getType(); 4565 4566 if (!type->isDependentType() && 4567 !type->isObjCLifetimeType()) { 4568 S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type) 4569 << type; 4570 return; 4571 } 4572 4573 Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime(); 4574 4575 // If we have no lifetime yet, check the lifetime we're presumably 4576 // going to infer. 4577 if (lifetime == Qualifiers::OCL_None && !type->isDependentType()) 4578 lifetime = type->getObjCARCImplicitLifetime(); 4579 4580 switch (lifetime) { 4581 case Qualifiers::OCL_None: 4582 assert(type->isDependentType() && 4583 "didn't infer lifetime for non-dependent type?"); 4584 break; 4585 4586 case Qualifiers::OCL_Weak: // meaningful 4587 case Qualifiers::OCL_Strong: // meaningful 4588 break; 4589 4590 case Qualifiers::OCL_ExplicitNone: 4591 case Qualifiers::OCL_Autoreleasing: 4592 S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless) 4593 << (lifetime == Qualifiers::OCL_Autoreleasing); 4594 break; 4595 } 4596 4597 D->addAttr(::new (S.Context) 4598 ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context, 4599 Attr.getAttributeSpellingListIndex())); 4600 } 4601 4602 //===----------------------------------------------------------------------===// 4603 // Microsoft specific attribute handlers. 4604 //===----------------------------------------------------------------------===// 4605 4606 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4607 if (!S.LangOpts.CPlusPlus) { 4608 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang) 4609 << Attr.getName() << AttributeLangSupport::C; 4610 return; 4611 } 4612 4613 if (!isa<CXXRecordDecl>(D)) { 4614 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 4615 << Attr.getName() << ExpectedClass; 4616 return; 4617 } 4618 4619 StringRef StrRef; 4620 SourceLocation LiteralLoc; 4621 if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc)) 4622 return; 4623 4624 // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or 4625 // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former. 4626 if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}') 4627 StrRef = StrRef.drop_front().drop_back(); 4628 4629 // Validate GUID length. 4630 if (StrRef.size() != 36) { 4631 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 4632 return; 4633 } 4634 4635 for (unsigned i = 0; i < 36; ++i) { 4636 if (i == 8 || i == 13 || i == 18 || i == 23) { 4637 if (StrRef[i] != '-') { 4638 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 4639 return; 4640 } 4641 } else if (!isHexDigit(StrRef[i])) { 4642 S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid); 4643 return; 4644 } 4645 } 4646 4647 D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context, StrRef, 4648 Attr.getAttributeSpellingListIndex())); 4649 } 4650 4651 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4652 if (!S.LangOpts.CPlusPlus) { 4653 S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang) 4654 << Attr.getName() << AttributeLangSupport::C; 4655 return; 4656 } 4657 MSInheritanceAttr *IA = S.mergeMSInheritanceAttr( 4658 D, Attr.getRange(), /*BestCase=*/true, 4659 Attr.getAttributeSpellingListIndex(), 4660 (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling()); 4661 if (IA) { 4662 D->addAttr(IA); 4663 S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D)); 4664 } 4665 } 4666 4667 static void handleDeclspecThreadAttr(Sema &S, Decl *D, 4668 const AttributeList &Attr) { 4669 VarDecl *VD = cast<VarDecl>(D); 4670 if (!S.Context.getTargetInfo().isTLSSupported()) { 4671 S.Diag(Attr.getLoc(), diag::err_thread_unsupported); 4672 return; 4673 } 4674 if (VD->getTSCSpec() != TSCS_unspecified) { 4675 S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable); 4676 return; 4677 } 4678 if (VD->hasLocalStorage()) { 4679 S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)"; 4680 return; 4681 } 4682 VD->addAttr(::new (S.Context) ThreadAttr( 4683 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 4684 } 4685 4686 static void handleAbiTagAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4687 SmallVector<StringRef, 4> Tags; 4688 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) { 4689 StringRef Tag; 4690 if (!S.checkStringLiteralArgumentAttr(Attr, I, Tag)) 4691 return; 4692 Tags.push_back(Tag); 4693 } 4694 4695 if (const auto *NS = dyn_cast<NamespaceDecl>(D)) { 4696 if (!NS->isInline()) { 4697 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 0; 4698 return; 4699 } 4700 if (NS->isAnonymousNamespace()) { 4701 S.Diag(Attr.getLoc(), diag::warn_attr_abi_tag_namespace) << 1; 4702 return; 4703 } 4704 if (Attr.getNumArgs() == 0) 4705 Tags.push_back(NS->getName()); 4706 } else if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 4707 return; 4708 4709 // Store tags sorted and without duplicates. 4710 std::sort(Tags.begin(), Tags.end()); 4711 Tags.erase(std::unique(Tags.begin(), Tags.end()), Tags.end()); 4712 4713 D->addAttr(::new (S.Context) 4714 AbiTagAttr(Attr.getRange(), S.Context, Tags.data(), Tags.size(), 4715 Attr.getAttributeSpellingListIndex())); 4716 4717 // FIXME: remove this warning as soon as mangled part is ready. 4718 S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored) 4719 << Attr.getName(); 4720 } 4721 4722 static void handleARMInterruptAttr(Sema &S, Decl *D, 4723 const AttributeList &Attr) { 4724 // Check the attribute arguments. 4725 if (Attr.getNumArgs() > 1) { 4726 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) 4727 << Attr.getName() << 1; 4728 return; 4729 } 4730 4731 StringRef Str; 4732 SourceLocation ArgLoc; 4733 4734 if (Attr.getNumArgs() == 0) 4735 Str = ""; 4736 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc)) 4737 return; 4738 4739 ARMInterruptAttr::InterruptType Kind; 4740 if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { 4741 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 4742 << Attr.getName() << Str << ArgLoc; 4743 return; 4744 } 4745 4746 unsigned Index = Attr.getAttributeSpellingListIndex(); 4747 D->addAttr(::new (S.Context) 4748 ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index)); 4749 } 4750 4751 static void handleMSP430InterruptAttr(Sema &S, Decl *D, 4752 const AttributeList &Attr) { 4753 if (!checkAttributeNumArgs(S, Attr, 1)) 4754 return; 4755 4756 if (!Attr.isArgExpr(0)) { 4757 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName() 4758 << AANT_ArgumentIntegerConstant; 4759 return; 4760 } 4761 4762 // FIXME: Check for decl - it should be void ()(void). 4763 4764 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 4765 llvm::APSInt NumParams(32); 4766 if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) { 4767 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) 4768 << Attr.getName() << AANT_ArgumentIntegerConstant 4769 << NumParamsExpr->getSourceRange(); 4770 return; 4771 } 4772 4773 unsigned Num = NumParams.getLimitedValue(255); 4774 if ((Num & 1) || Num > 30) { 4775 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 4776 << Attr.getName() << (int)NumParams.getSExtValue() 4777 << NumParamsExpr->getSourceRange(); 4778 return; 4779 } 4780 4781 D->addAttr(::new (S.Context) 4782 MSP430InterruptAttr(Attr.getLoc(), S.Context, Num, 4783 Attr.getAttributeSpellingListIndex())); 4784 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 4785 } 4786 4787 static void handleMipsInterruptAttr(Sema &S, Decl *D, 4788 const AttributeList &Attr) { 4789 // Only one optional argument permitted. 4790 if (Attr.getNumArgs() > 1) { 4791 S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments) 4792 << Attr.getName() << 1; 4793 return; 4794 } 4795 4796 StringRef Str; 4797 SourceLocation ArgLoc; 4798 4799 if (Attr.getNumArgs() == 0) 4800 Str = ""; 4801 else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc)) 4802 return; 4803 4804 // Semantic checks for a function with the 'interrupt' attribute for MIPS: 4805 // a) Must be a function. 4806 // b) Must have no parameters. 4807 // c) Must have the 'void' return type. 4808 // d) Cannot have the 'mips16' attribute, as that instruction set 4809 // lacks the 'eret' instruction. 4810 // e) The attribute itself must either have no argument or one of the 4811 // valid interrupt types, see [MipsInterruptDocs]. 4812 4813 if (!isFunctionOrMethod(D)) { 4814 S.Diag(D->getLocation(), diag::warn_attribute_wrong_decl_type) 4815 << "'interrupt'" << ExpectedFunctionOrMethod; 4816 return; 4817 } 4818 4819 if (hasFunctionProto(D) && getFunctionOrMethodNumParams(D) != 0) { 4820 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute) 4821 << 0; 4822 return; 4823 } 4824 4825 if (!getFunctionOrMethodResultType(D)->isVoidType()) { 4826 S.Diag(D->getLocation(), diag::warn_mips_interrupt_attribute) 4827 << 1; 4828 return; 4829 } 4830 4831 if (checkAttrMutualExclusion<Mips16Attr>(S, D, Attr.getRange(), 4832 Attr.getName())) 4833 return; 4834 4835 MipsInterruptAttr::InterruptType Kind; 4836 if (!MipsInterruptAttr::ConvertStrToInterruptType(Str, Kind)) { 4837 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 4838 << Attr.getName() << "'" + std::string(Str) + "'"; 4839 return; 4840 } 4841 4842 D->addAttr(::new (S.Context) MipsInterruptAttr( 4843 Attr.getLoc(), S.Context, Kind, Attr.getAttributeSpellingListIndex())); 4844 } 4845 4846 static void handleAnyX86InterruptAttr(Sema &S, Decl *D, 4847 const AttributeList &Attr) { 4848 // Semantic checks for a function with the 'interrupt' attribute. 4849 // a) Must be a function. 4850 // b) Must have the 'void' return type. 4851 // c) Must take 1 or 2 arguments. 4852 // d) The 1st argument must be a pointer. 4853 // e) The 2nd argument (if any) must be an unsigned integer. 4854 if (!isFunctionOrMethod(D) || !hasFunctionProto(D) || isInstanceMethod(D) || 4855 CXXMethodDecl::isStaticOverloadedOperator( 4856 cast<NamedDecl>(D)->getDeclName().getCXXOverloadedOperator())) { 4857 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 4858 << Attr.getName() << ExpectedFunctionWithProtoType; 4859 return; 4860 } 4861 // Interrupt handler must have void return type. 4862 if (!getFunctionOrMethodResultType(D)->isVoidType()) { 4863 S.Diag(getFunctionOrMethodResultSourceRange(D).getBegin(), 4864 diag::err_anyx86_interrupt_attribute) 4865 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 4866 ? 0 4867 : 1) 4868 << 0; 4869 return; 4870 } 4871 // Interrupt handler must have 1 or 2 parameters. 4872 unsigned NumParams = getFunctionOrMethodNumParams(D); 4873 if (NumParams < 1 || NumParams > 2) { 4874 S.Diag(D->getLocStart(), diag::err_anyx86_interrupt_attribute) 4875 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 4876 ? 0 4877 : 1) 4878 << 1; 4879 return; 4880 } 4881 // The first argument must be a pointer. 4882 if (!getFunctionOrMethodParamType(D, 0)->isPointerType()) { 4883 S.Diag(getFunctionOrMethodParamRange(D, 0).getBegin(), 4884 diag::err_anyx86_interrupt_attribute) 4885 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 4886 ? 0 4887 : 1) 4888 << 2; 4889 return; 4890 } 4891 // The second argument, if present, must be an unsigned integer. 4892 unsigned TypeSize = 4893 S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86_64 4894 ? 64 4895 : 32; 4896 if (NumParams == 2 && 4897 (!getFunctionOrMethodParamType(D, 1)->isUnsignedIntegerType() || 4898 S.Context.getTypeSize(getFunctionOrMethodParamType(D, 1)) != TypeSize)) { 4899 S.Diag(getFunctionOrMethodParamRange(D, 1).getBegin(), 4900 diag::err_anyx86_interrupt_attribute) 4901 << (S.Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86 4902 ? 0 4903 : 1) 4904 << 3 << S.Context.getIntTypeForBitwidth(TypeSize, /*Signed=*/false); 4905 return; 4906 } 4907 D->addAttr(::new (S.Context) AnyX86InterruptAttr( 4908 Attr.getLoc(), S.Context, Attr.getAttributeSpellingListIndex())); 4909 D->addAttr(UsedAttr::CreateImplicit(S.Context)); 4910 } 4911 4912 static void handleInterruptAttr(Sema &S, Decl *D, const AttributeList &Attr) { 4913 // Dispatch the interrupt attribute based on the current target. 4914 switch (S.Context.getTargetInfo().getTriple().getArch()) { 4915 case llvm::Triple::msp430: 4916 handleMSP430InterruptAttr(S, D, Attr); 4917 break; 4918 case llvm::Triple::mipsel: 4919 case llvm::Triple::mips: 4920 handleMipsInterruptAttr(S, D, Attr); 4921 break; 4922 case llvm::Triple::x86: 4923 case llvm::Triple::x86_64: 4924 handleAnyX86InterruptAttr(S, D, Attr); 4925 break; 4926 default: 4927 handleARMInterruptAttr(S, D, Attr); 4928 break; 4929 } 4930 } 4931 4932 static void handleAMDGPUNumVGPRAttr(Sema &S, Decl *D, 4933 const AttributeList &Attr) { 4934 uint32_t NumRegs; 4935 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 4936 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs)) 4937 return; 4938 4939 D->addAttr(::new (S.Context) 4940 AMDGPUNumVGPRAttr(Attr.getLoc(), S.Context, 4941 NumRegs, 4942 Attr.getAttributeSpellingListIndex())); 4943 } 4944 4945 static void handleAMDGPUNumSGPRAttr(Sema &S, Decl *D, 4946 const AttributeList &Attr) { 4947 uint32_t NumRegs; 4948 Expr *NumRegsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 4949 if (!checkUInt32Argument(S, Attr, NumRegsExpr, NumRegs)) 4950 return; 4951 4952 D->addAttr(::new (S.Context) 4953 AMDGPUNumSGPRAttr(Attr.getLoc(), S.Context, 4954 NumRegs, 4955 Attr.getAttributeSpellingListIndex())); 4956 } 4957 4958 static void handleX86ForceAlignArgPointerAttr(Sema &S, Decl *D, 4959 const AttributeList& Attr) { 4960 // If we try to apply it to a function pointer, don't warn, but don't 4961 // do anything, either. It doesn't matter anyway, because there's nothing 4962 // special about calling a force_align_arg_pointer function. 4963 ValueDecl *VD = dyn_cast<ValueDecl>(D); 4964 if (VD && VD->getType()->isFunctionPointerType()) 4965 return; 4966 // Also don't warn on function pointer typedefs. 4967 TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D); 4968 if (TD && (TD->getUnderlyingType()->isFunctionPointerType() || 4969 TD->getUnderlyingType()->isFunctionType())) 4970 return; 4971 // Attribute can only be applied to function types. 4972 if (!isa<FunctionDecl>(D)) { 4973 S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type) 4974 << Attr.getName() << /* function */0; 4975 return; 4976 } 4977 4978 D->addAttr(::new (S.Context) 4979 X86ForceAlignArgPointerAttr(Attr.getRange(), S.Context, 4980 Attr.getAttributeSpellingListIndex())); 4981 } 4982 4983 static void handleLayoutVersion(Sema &S, Decl *D, const AttributeList &Attr) { 4984 uint32_t Version; 4985 Expr *VersionExpr = static_cast<Expr *>(Attr.getArgAsExpr(0)); 4986 if (!checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), Version)) 4987 return; 4988 4989 // TODO: Investigate what happens with the next major version of MSVC. 4990 if (Version != LangOptions::MSVC2015) { 4991 S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds) 4992 << Attr.getName() << Version << VersionExpr->getSourceRange(); 4993 return; 4994 } 4995 4996 D->addAttr(::new (S.Context) 4997 LayoutVersionAttr(Attr.getRange(), S.Context, Version, 4998 Attr.getAttributeSpellingListIndex())); 4999 } 5000 5001 DLLImportAttr *Sema::mergeDLLImportAttr(Decl *D, SourceRange Range, 5002 unsigned AttrSpellingListIndex) { 5003 if (D->hasAttr<DLLExportAttr>()) { 5004 Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'dllimport'"; 5005 return nullptr; 5006 } 5007 5008 if (D->hasAttr<DLLImportAttr>()) 5009 return nullptr; 5010 5011 return ::new (Context) DLLImportAttr(Range, Context, AttrSpellingListIndex); 5012 } 5013 5014 DLLExportAttr *Sema::mergeDLLExportAttr(Decl *D, SourceRange Range, 5015 unsigned AttrSpellingListIndex) { 5016 if (DLLImportAttr *Import = D->getAttr<DLLImportAttr>()) { 5017 Diag(Import->getLocation(), diag::warn_attribute_ignored) << Import; 5018 D->dropAttr<DLLImportAttr>(); 5019 } 5020 5021 if (D->hasAttr<DLLExportAttr>()) 5022 return nullptr; 5023 5024 return ::new (Context) DLLExportAttr(Range, Context, AttrSpellingListIndex); 5025 } 5026 5027 static void handleDLLAttr(Sema &S, Decl *D, const AttributeList &A) { 5028 if (isa<ClassTemplatePartialSpecializationDecl>(D) && 5029 S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5030 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored) 5031 << A.getName(); 5032 return; 5033 } 5034 5035 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5036 if (FD->isInlined() && A.getKind() == AttributeList::AT_DLLImport && 5037 !S.Context.getTargetInfo().getCXXABI().isMicrosoft()) { 5038 // MinGW doesn't allow dllimport on inline functions. 5039 S.Diag(A.getRange().getBegin(), diag::warn_attribute_ignored_on_inline) 5040 << A.getName(); 5041 return; 5042 } 5043 } 5044 5045 if (auto *MD = dyn_cast<CXXMethodDecl>(D)) { 5046 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft() && 5047 MD->getParent()->isLambda()) { 5048 S.Diag(A.getRange().getBegin(), diag::err_attribute_dll_lambda) << A.getName(); 5049 return; 5050 } 5051 } 5052 5053 unsigned Index = A.getAttributeSpellingListIndex(); 5054 Attr *NewAttr = A.getKind() == AttributeList::AT_DLLExport 5055 ? (Attr *)S.mergeDLLExportAttr(D, A.getRange(), Index) 5056 : (Attr *)S.mergeDLLImportAttr(D, A.getRange(), Index); 5057 if (NewAttr) 5058 D->addAttr(NewAttr); 5059 } 5060 5061 MSInheritanceAttr * 5062 Sema::mergeMSInheritanceAttr(Decl *D, SourceRange Range, bool BestCase, 5063 unsigned AttrSpellingListIndex, 5064 MSInheritanceAttr::Spelling SemanticSpelling) { 5065 if (MSInheritanceAttr *IA = D->getAttr<MSInheritanceAttr>()) { 5066 if (IA->getSemanticSpelling() == SemanticSpelling) 5067 return nullptr; 5068 Diag(IA->getLocation(), diag::err_mismatched_ms_inheritance) 5069 << 1 /*previous declaration*/; 5070 Diag(Range.getBegin(), diag::note_previous_ms_inheritance); 5071 D->dropAttr<MSInheritanceAttr>(); 5072 } 5073 5074 CXXRecordDecl *RD = cast<CXXRecordDecl>(D); 5075 if (RD->hasDefinition()) { 5076 if (checkMSInheritanceAttrOnDefinition(RD, Range, BestCase, 5077 SemanticSpelling)) { 5078 return nullptr; 5079 } 5080 } else { 5081 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) { 5082 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance) 5083 << 1 /*partial specialization*/; 5084 return nullptr; 5085 } 5086 if (RD->getDescribedClassTemplate()) { 5087 Diag(Range.getBegin(), diag::warn_ignored_ms_inheritance) 5088 << 0 /*primary template*/; 5089 return nullptr; 5090 } 5091 } 5092 5093 return ::new (Context) 5094 MSInheritanceAttr(Range, Context, BestCase, AttrSpellingListIndex); 5095 } 5096 5097 static void handleCapabilityAttr(Sema &S, Decl *D, const AttributeList &Attr) { 5098 // The capability attributes take a single string parameter for the name of 5099 // the capability they represent. The lockable attribute does not take any 5100 // parameters. However, semantically, both attributes represent the same 5101 // concept, and so they use the same semantic attribute. Eventually, the 5102 // lockable attribute will be removed. 5103 // 5104 // For backward compatibility, any capability which has no specified string 5105 // literal will be considered a "mutex." 5106 StringRef N("mutex"); 5107 SourceLocation LiteralLoc; 5108 if (Attr.getKind() == AttributeList::AT_Capability && 5109 !S.checkStringLiteralArgumentAttr(Attr, 0, N, &LiteralLoc)) 5110 return; 5111 5112 // Currently, there are only two names allowed for a capability: role and 5113 // mutex (case insensitive). Diagnose other capability names. 5114 if (!N.equals_lower("mutex") && !N.equals_lower("role")) 5115 S.Diag(LiteralLoc, diag::warn_invalid_capability_name) << N; 5116 5117 D->addAttr(::new (S.Context) CapabilityAttr(Attr.getRange(), S.Context, N, 5118 Attr.getAttributeSpellingListIndex())); 5119 } 5120 5121 static void handleAssertCapabilityAttr(Sema &S, Decl *D, 5122 const AttributeList &Attr) { 5123 D->addAttr(::new (S.Context) AssertCapabilityAttr(Attr.getRange(), S.Context, 5124 Attr.getArgAsExpr(0), 5125 Attr.getAttributeSpellingListIndex())); 5126 } 5127 5128 static void handleAcquireCapabilityAttr(Sema &S, Decl *D, 5129 const AttributeList &Attr) { 5130 SmallVector<Expr*, 1> Args; 5131 if (!checkLockFunAttrCommon(S, D, Attr, Args)) 5132 return; 5133 5134 D->addAttr(::new (S.Context) AcquireCapabilityAttr(Attr.getRange(), 5135 S.Context, 5136 Args.data(), Args.size(), 5137 Attr.getAttributeSpellingListIndex())); 5138 } 5139 5140 static void handleTryAcquireCapabilityAttr(Sema &S, Decl *D, 5141 const AttributeList &Attr) { 5142 SmallVector<Expr*, 2> Args; 5143 if (!checkTryLockFunAttrCommon(S, D, Attr, Args)) 5144 return; 5145 5146 D->addAttr(::new (S.Context) TryAcquireCapabilityAttr(Attr.getRange(), 5147 S.Context, 5148 Attr.getArgAsExpr(0), 5149 Args.data(), 5150 Args.size(), 5151 Attr.getAttributeSpellingListIndex())); 5152 } 5153 5154 static void handleReleaseCapabilityAttr(Sema &S, Decl *D, 5155 const AttributeList &Attr) { 5156 // Check that all arguments are lockable objects. 5157 SmallVector<Expr *, 1> Args; 5158 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, true); 5159 5160 D->addAttr(::new (S.Context) ReleaseCapabilityAttr( 5161 Attr.getRange(), S.Context, Args.data(), Args.size(), 5162 Attr.getAttributeSpellingListIndex())); 5163 } 5164 5165 static void handleRequiresCapabilityAttr(Sema &S, Decl *D, 5166 const AttributeList &Attr) { 5167 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 5168 return; 5169 5170 // check that all arguments are lockable objects 5171 SmallVector<Expr*, 1> Args; 5172 checkAttrArgsAreCapabilityObjs(S, D, Attr, Args); 5173 if (Args.empty()) 5174 return; 5175 5176 RequiresCapabilityAttr *RCA = ::new (S.Context) 5177 RequiresCapabilityAttr(Attr.getRange(), S.Context, Args.data(), 5178 Args.size(), Attr.getAttributeSpellingListIndex()); 5179 5180 D->addAttr(RCA); 5181 } 5182 5183 static void handleDeprecatedAttr(Sema &S, Decl *D, const AttributeList &Attr) { 5184 if (auto *NSD = dyn_cast<NamespaceDecl>(D)) { 5185 if (NSD->isAnonymousNamespace()) { 5186 S.Diag(Attr.getLoc(), diag::warn_deprecated_anonymous_namespace); 5187 // Do not want to attach the attribute to the namespace because that will 5188 // cause confusing diagnostic reports for uses of declarations within the 5189 // namespace. 5190 return; 5191 } 5192 } 5193 5194 // Handle the cases where the attribute has a text message. 5195 StringRef Str, Replacement; 5196 if (Attr.isArgExpr(0) && Attr.getArgAsExpr(0) && 5197 !S.checkStringLiteralArgumentAttr(Attr, 0, Str)) 5198 return; 5199 5200 // Only support a single optional message for Declspec and CXX11. 5201 if (Attr.isDeclspecAttribute() || Attr.isCXX11Attribute()) 5202 checkAttributeAtMostNumArgs(S, Attr, 1); 5203 else if (Attr.isArgExpr(1) && Attr.getArgAsExpr(1) && 5204 !S.checkStringLiteralArgumentAttr(Attr, 1, Replacement)) 5205 return; 5206 5207 if (!S.getLangOpts().CPlusPlus14) 5208 if (Attr.isCXX11Attribute() && 5209 !(Attr.hasScope() && Attr.getScopeName()->isStr("gnu"))) 5210 S.Diag(Attr.getLoc(), diag::ext_cxx14_attr) << Attr.getName(); 5211 5212 D->addAttr(::new (S.Context) DeprecatedAttr(Attr.getRange(), S.Context, Str, 5213 Replacement, 5214 Attr.getAttributeSpellingListIndex())); 5215 } 5216 5217 static void handleNoSanitizeAttr(Sema &S, Decl *D, const AttributeList &Attr) { 5218 if (!checkAttributeAtLeastNumArgs(S, Attr, 1)) 5219 return; 5220 5221 std::vector<StringRef> Sanitizers; 5222 5223 for (unsigned I = 0, E = Attr.getNumArgs(); I != E; ++I) { 5224 StringRef SanitizerName; 5225 SourceLocation LiteralLoc; 5226 5227 if (!S.checkStringLiteralArgumentAttr(Attr, I, SanitizerName, &LiteralLoc)) 5228 return; 5229 5230 if (parseSanitizerValue(SanitizerName, /*AllowGroups=*/true) == 0) 5231 S.Diag(LiteralLoc, diag::warn_unknown_sanitizer_ignored) << SanitizerName; 5232 5233 Sanitizers.push_back(SanitizerName); 5234 } 5235 5236 D->addAttr(::new (S.Context) NoSanitizeAttr( 5237 Attr.getRange(), S.Context, Sanitizers.data(), Sanitizers.size(), 5238 Attr.getAttributeSpellingListIndex())); 5239 } 5240 5241 static void handleNoSanitizeSpecificAttr(Sema &S, Decl *D, 5242 const AttributeList &Attr) { 5243 StringRef AttrName = Attr.getName()->getName(); 5244 normalizeName(AttrName); 5245 StringRef SanitizerName = 5246 llvm::StringSwitch<StringRef>(AttrName) 5247 .Case("no_address_safety_analysis", "address") 5248 .Case("no_sanitize_address", "address") 5249 .Case("no_sanitize_thread", "thread") 5250 .Case("no_sanitize_memory", "memory"); 5251 D->addAttr(::new (S.Context) 5252 NoSanitizeAttr(Attr.getRange(), S.Context, &SanitizerName, 1, 5253 Attr.getAttributeSpellingListIndex())); 5254 } 5255 5256 static void handleInternalLinkageAttr(Sema &S, Decl *D, 5257 const AttributeList &Attr) { 5258 if (InternalLinkageAttr *Internal = 5259 S.mergeInternalLinkageAttr(D, Attr.getRange(), Attr.getName(), 5260 Attr.getAttributeSpellingListIndex())) 5261 D->addAttr(Internal); 5262 } 5263 5264 static void handleOpenCLNoSVMAttr(Sema &S, Decl *D, const AttributeList &Attr) { 5265 if (S.LangOpts.OpenCLVersion != 200) 5266 S.Diag(Attr.getLoc(), diag::err_attribute_requires_opencl_version) 5267 << Attr.getName() << "2.0" << 0; 5268 else 5269 S.Diag(Attr.getLoc(), diag::warn_opencl_attr_deprecated_ignored) 5270 << Attr.getName() << "2.0"; 5271 } 5272 5273 /// Handles semantic checking for features that are common to all attributes, 5274 /// such as checking whether a parameter was properly specified, or the correct 5275 /// number of arguments were passed, etc. 5276 static bool handleCommonAttributeFeatures(Sema &S, Scope *scope, Decl *D, 5277 const AttributeList &Attr) { 5278 // Several attributes carry different semantics than the parsing requires, so 5279 // those are opted out of the common handling. 5280 // 5281 // We also bail on unknown and ignored attributes because those are handled 5282 // as part of the target-specific handling logic. 5283 if (Attr.hasCustomParsing() || 5284 Attr.getKind() == AttributeList::UnknownAttribute) 5285 return false; 5286 5287 // Check whether the attribute requires specific language extensions to be 5288 // enabled. 5289 if (!Attr.diagnoseLangOpts(S)) 5290 return true; 5291 5292 if (Attr.getMinArgs() == Attr.getMaxArgs()) { 5293 // If there are no optional arguments, then checking for the argument count 5294 // is trivial. 5295 if (!checkAttributeNumArgs(S, Attr, Attr.getMinArgs())) 5296 return true; 5297 } else { 5298 // There are optional arguments, so checking is slightly more involved. 5299 if (Attr.getMinArgs() && 5300 !checkAttributeAtLeastNumArgs(S, Attr, Attr.getMinArgs())) 5301 return true; 5302 else if (!Attr.hasVariadicArg() && Attr.getMaxArgs() && 5303 !checkAttributeAtMostNumArgs(S, Attr, Attr.getMaxArgs())) 5304 return true; 5305 } 5306 5307 // Check whether the attribute appertains to the given subject. 5308 if (!Attr.diagnoseAppertainsTo(S, D)) 5309 return true; 5310 5311 return false; 5312 } 5313 5314 static void handleOpenCLAccessAttr(Sema &S, Decl *D, 5315 const AttributeList &Attr) { 5316 if (D->isInvalidDecl()) 5317 return; 5318 5319 // Check if there is only one access qualifier. 5320 if (D->hasAttr<OpenCLAccessAttr>()) { 5321 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers) 5322 << D->getSourceRange(); 5323 D->setInvalidDecl(true); 5324 return; 5325 } 5326 5327 // OpenCL v2.0 s6.6 - read_write can be used for image types to specify that an 5328 // image object can be read and written. 5329 // OpenCL v2.0 s6.13.6 - A kernel cannot read from and write to the same pipe 5330 // object. Using the read_write (or __read_write) qualifier with the pipe 5331 // qualifier is a compilation error. 5332 if (const ParmVarDecl *PDecl = dyn_cast<ParmVarDecl>(D)) { 5333 const Type *DeclTy = PDecl->getType().getCanonicalType().getTypePtr(); 5334 if (Attr.getName()->getName().find("read_write") != StringRef::npos) { 5335 if (S.getLangOpts().OpenCLVersion < 200 || DeclTy->isPipeType()) { 5336 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_read_write) 5337 << Attr.getName() << PDecl->getType() << DeclTy->isImageType(); 5338 D->setInvalidDecl(true); 5339 return; 5340 } 5341 } 5342 } 5343 5344 D->addAttr(::new (S.Context) OpenCLAccessAttr( 5345 Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex())); 5346 } 5347 5348 //===----------------------------------------------------------------------===// 5349 // Top Level Sema Entry Points 5350 //===----------------------------------------------------------------------===// 5351 5352 /// ProcessDeclAttribute - Apply the specific attribute to the specified decl if 5353 /// the attribute applies to decls. If the attribute is a type attribute, just 5354 /// silently ignore it if a GNU attribute. 5355 static void ProcessDeclAttribute(Sema &S, Scope *scope, Decl *D, 5356 const AttributeList &Attr, 5357 bool IncludeCXX11Attributes) { 5358 if (Attr.isInvalid() || Attr.getKind() == AttributeList::IgnoredAttribute) 5359 return; 5360 5361 // Ignore C++11 attributes on declarator chunks: they appertain to the type 5362 // instead. 5363 if (Attr.isCXX11Attribute() && !IncludeCXX11Attributes) 5364 return; 5365 5366 // Unknown attributes are automatically warned on. Target-specific attributes 5367 // which do not apply to the current target architecture are treated as 5368 // though they were unknown attributes. 5369 if (Attr.getKind() == AttributeList::UnknownAttribute || 5370 !Attr.existsInTarget(S.Context.getTargetInfo())) { 5371 S.Diag(Attr.getLoc(), Attr.isDeclspecAttribute() 5372 ? diag::warn_unhandled_ms_attribute_ignored 5373 : diag::warn_unknown_attribute_ignored) 5374 << Attr.getName(); 5375 return; 5376 } 5377 5378 if (handleCommonAttributeFeatures(S, scope, D, Attr)) 5379 return; 5380 5381 switch (Attr.getKind()) { 5382 default: 5383 if (!Attr.isStmtAttr()) { 5384 // Type attributes are handled elsewhere; silently move on. 5385 assert(Attr.isTypeAttr() && "Non-type attribute not handled"); 5386 break; 5387 } 5388 S.Diag(Attr.getLoc(), diag::err_stmt_attribute_invalid_on_decl) 5389 << Attr.getName() << D->getLocation(); 5390 break; 5391 case AttributeList::AT_Interrupt: 5392 handleInterruptAttr(S, D, Attr); 5393 break; 5394 case AttributeList::AT_X86ForceAlignArgPointer: 5395 handleX86ForceAlignArgPointerAttr(S, D, Attr); 5396 break; 5397 case AttributeList::AT_DLLExport: 5398 case AttributeList::AT_DLLImport: 5399 handleDLLAttr(S, D, Attr); 5400 break; 5401 case AttributeList::AT_Mips16: 5402 handleSimpleAttributeWithExclusions<Mips16Attr, MipsInterruptAttr>(S, D, 5403 Attr); 5404 break; 5405 case AttributeList::AT_NoMips16: 5406 handleSimpleAttribute<NoMips16Attr>(S, D, Attr); 5407 break; 5408 case AttributeList::AT_AMDGPUNumVGPR: 5409 handleAMDGPUNumVGPRAttr(S, D, Attr); 5410 break; 5411 case AttributeList::AT_AMDGPUNumSGPR: 5412 handleAMDGPUNumSGPRAttr(S, D, Attr); 5413 break; 5414 case AttributeList::AT_IBAction: 5415 handleSimpleAttribute<IBActionAttr>(S, D, Attr); 5416 break; 5417 case AttributeList::AT_IBOutlet: 5418 handleIBOutlet(S, D, Attr); 5419 break; 5420 case AttributeList::AT_IBOutletCollection: 5421 handleIBOutletCollection(S, D, Attr); 5422 break; 5423 case AttributeList::AT_IFunc: 5424 handleIFuncAttr(S, D, Attr); 5425 break; 5426 case AttributeList::AT_Alias: 5427 handleAliasAttr(S, D, Attr); 5428 break; 5429 case AttributeList::AT_Aligned: 5430 handleAlignedAttr(S, D, Attr); 5431 break; 5432 case AttributeList::AT_AlignValue: 5433 handleAlignValueAttr(S, D, Attr); 5434 break; 5435 case AttributeList::AT_AlwaysInline: 5436 handleAlwaysInlineAttr(S, D, Attr); 5437 break; 5438 case AttributeList::AT_AnalyzerNoReturn: 5439 handleAnalyzerNoReturnAttr(S, D, Attr); 5440 break; 5441 case AttributeList::AT_TLSModel: 5442 handleTLSModelAttr(S, D, Attr); 5443 break; 5444 case AttributeList::AT_Annotate: 5445 handleAnnotateAttr(S, D, Attr); 5446 break; 5447 case AttributeList::AT_Availability: 5448 handleAvailabilityAttr(S, D, Attr); 5449 break; 5450 case AttributeList::AT_CarriesDependency: 5451 handleDependencyAttr(S, scope, D, Attr); 5452 break; 5453 case AttributeList::AT_Common: 5454 handleCommonAttr(S, D, Attr); 5455 break; 5456 case AttributeList::AT_CUDAConstant: 5457 handleSimpleAttributeWithExclusions<CUDAConstantAttr, CUDASharedAttr>(S, D, 5458 Attr); 5459 break; 5460 case AttributeList::AT_PassObjectSize: 5461 handlePassObjectSizeAttr(S, D, Attr); 5462 break; 5463 case AttributeList::AT_Constructor: 5464 handleConstructorAttr(S, D, Attr); 5465 break; 5466 case AttributeList::AT_CXX11NoReturn: 5467 handleSimpleAttribute<CXX11NoReturnAttr>(S, D, Attr); 5468 break; 5469 case AttributeList::AT_Deprecated: 5470 handleDeprecatedAttr(S, D, Attr); 5471 break; 5472 case AttributeList::AT_Destructor: 5473 handleDestructorAttr(S, D, Attr); 5474 break; 5475 case AttributeList::AT_EnableIf: 5476 handleEnableIfAttr(S, D, Attr); 5477 break; 5478 case AttributeList::AT_ExtVectorType: 5479 handleExtVectorTypeAttr(S, scope, D, Attr); 5480 break; 5481 case AttributeList::AT_MinSize: 5482 handleMinSizeAttr(S, D, Attr); 5483 break; 5484 case AttributeList::AT_OptimizeNone: 5485 handleOptimizeNoneAttr(S, D, Attr); 5486 break; 5487 case AttributeList::AT_FlagEnum: 5488 handleSimpleAttribute<FlagEnumAttr>(S, D, Attr); 5489 break; 5490 case AttributeList::AT_Flatten: 5491 handleSimpleAttribute<FlattenAttr>(S, D, Attr); 5492 break; 5493 case AttributeList::AT_Format: 5494 handleFormatAttr(S, D, Attr); 5495 break; 5496 case AttributeList::AT_FormatArg: 5497 handleFormatArgAttr(S, D, Attr); 5498 break; 5499 case AttributeList::AT_CUDAGlobal: 5500 handleGlobalAttr(S, D, Attr); 5501 break; 5502 case AttributeList::AT_CUDADevice: 5503 handleSimpleAttributeWithExclusions<CUDADeviceAttr, CUDAGlobalAttr>(S, D, 5504 Attr); 5505 break; 5506 case AttributeList::AT_CUDAHost: 5507 handleSimpleAttributeWithExclusions<CUDAHostAttr, CUDAGlobalAttr>(S, D, 5508 Attr); 5509 break; 5510 case AttributeList::AT_GNUInline: 5511 handleGNUInlineAttr(S, D, Attr); 5512 break; 5513 case AttributeList::AT_CUDALaunchBounds: 5514 handleLaunchBoundsAttr(S, D, Attr); 5515 break; 5516 case AttributeList::AT_Restrict: 5517 handleRestrictAttr(S, D, Attr); 5518 break; 5519 case AttributeList::AT_MayAlias: 5520 handleSimpleAttribute<MayAliasAttr>(S, D, Attr); 5521 break; 5522 case AttributeList::AT_Mode: 5523 handleModeAttr(S, D, Attr); 5524 break; 5525 case AttributeList::AT_NoAlias: 5526 handleSimpleAttribute<NoAliasAttr>(S, D, Attr); 5527 break; 5528 case AttributeList::AT_NoCommon: 5529 handleSimpleAttribute<NoCommonAttr>(S, D, Attr); 5530 break; 5531 case AttributeList::AT_NoSplitStack: 5532 handleSimpleAttribute<NoSplitStackAttr>(S, D, Attr); 5533 break; 5534 case AttributeList::AT_NonNull: 5535 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D)) 5536 handleNonNullAttrParameter(S, PVD, Attr); 5537 else 5538 handleNonNullAttr(S, D, Attr); 5539 break; 5540 case AttributeList::AT_ReturnsNonNull: 5541 handleReturnsNonNullAttr(S, D, Attr); 5542 break; 5543 case AttributeList::AT_AssumeAligned: 5544 handleAssumeAlignedAttr(S, D, Attr); 5545 break; 5546 case AttributeList::AT_Overloadable: 5547 handleSimpleAttribute<OverloadableAttr>(S, D, Attr); 5548 break; 5549 case AttributeList::AT_Ownership: 5550 handleOwnershipAttr(S, D, Attr); 5551 break; 5552 case AttributeList::AT_Cold: 5553 handleColdAttr(S, D, Attr); 5554 break; 5555 case AttributeList::AT_Hot: 5556 handleHotAttr(S, D, Attr); 5557 break; 5558 case AttributeList::AT_Naked: 5559 handleNakedAttr(S, D, Attr); 5560 break; 5561 case AttributeList::AT_NoReturn: 5562 handleNoReturnAttr(S, D, Attr); 5563 break; 5564 case AttributeList::AT_NoThrow: 5565 handleSimpleAttribute<NoThrowAttr>(S, D, Attr); 5566 break; 5567 case AttributeList::AT_CUDAShared: 5568 handleSimpleAttributeWithExclusions<CUDASharedAttr, CUDAConstantAttr>(S, D, 5569 Attr); 5570 break; 5571 case AttributeList::AT_VecReturn: 5572 handleVecReturnAttr(S, D, Attr); 5573 break; 5574 case AttributeList::AT_ObjCOwnership: 5575 handleObjCOwnershipAttr(S, D, Attr); 5576 break; 5577 case AttributeList::AT_ObjCPreciseLifetime: 5578 handleObjCPreciseLifetimeAttr(S, D, Attr); 5579 break; 5580 case AttributeList::AT_ObjCReturnsInnerPointer: 5581 handleObjCReturnsInnerPointerAttr(S, D, Attr); 5582 break; 5583 case AttributeList::AT_ObjCRequiresSuper: 5584 handleObjCRequiresSuperAttr(S, D, Attr); 5585 break; 5586 case AttributeList::AT_ObjCBridge: 5587 handleObjCBridgeAttr(S, scope, D, Attr); 5588 break; 5589 case AttributeList::AT_ObjCBridgeMutable: 5590 handleObjCBridgeMutableAttr(S, scope, D, Attr); 5591 break; 5592 case AttributeList::AT_ObjCBridgeRelated: 5593 handleObjCBridgeRelatedAttr(S, scope, D, Attr); 5594 break; 5595 case AttributeList::AT_ObjCDesignatedInitializer: 5596 handleObjCDesignatedInitializer(S, D, Attr); 5597 break; 5598 case AttributeList::AT_ObjCRuntimeName: 5599 handleObjCRuntimeName(S, D, Attr); 5600 break; 5601 case AttributeList::AT_ObjCRuntimeVisible: 5602 handleSimpleAttribute<ObjCRuntimeVisibleAttr>(S, D, Attr); 5603 break; 5604 case AttributeList::AT_ObjCBoxable: 5605 handleObjCBoxable(S, D, Attr); 5606 break; 5607 case AttributeList::AT_CFAuditedTransfer: 5608 handleCFAuditedTransferAttr(S, D, Attr); 5609 break; 5610 case AttributeList::AT_CFUnknownTransfer: 5611 handleCFUnknownTransferAttr(S, D, Attr); 5612 break; 5613 case AttributeList::AT_CFConsumed: 5614 case AttributeList::AT_NSConsumed: 5615 handleNSConsumedAttr(S, D, Attr); 5616 break; 5617 case AttributeList::AT_NSConsumesSelf: 5618 handleSimpleAttribute<NSConsumesSelfAttr>(S, D, Attr); 5619 break; 5620 case AttributeList::AT_NSReturnsAutoreleased: 5621 case AttributeList::AT_NSReturnsNotRetained: 5622 case AttributeList::AT_CFReturnsNotRetained: 5623 case AttributeList::AT_NSReturnsRetained: 5624 case AttributeList::AT_CFReturnsRetained: 5625 handleNSReturnsRetainedAttr(S, D, Attr); 5626 break; 5627 case AttributeList::AT_WorkGroupSizeHint: 5628 handleWorkGroupSize<WorkGroupSizeHintAttr>(S, D, Attr); 5629 break; 5630 case AttributeList::AT_ReqdWorkGroupSize: 5631 handleWorkGroupSize<ReqdWorkGroupSizeAttr>(S, D, Attr); 5632 break; 5633 case AttributeList::AT_VecTypeHint: 5634 handleVecTypeHint(S, D, Attr); 5635 break; 5636 case AttributeList::AT_InitPriority: 5637 handleInitPriorityAttr(S, D, Attr); 5638 break; 5639 case AttributeList::AT_Packed: 5640 handlePackedAttr(S, D, Attr); 5641 break; 5642 case AttributeList::AT_Section: 5643 handleSectionAttr(S, D, Attr); 5644 break; 5645 case AttributeList::AT_Target: 5646 handleTargetAttr(S, D, Attr); 5647 break; 5648 case AttributeList::AT_Unavailable: 5649 handleAttrWithMessage<UnavailableAttr>(S, D, Attr); 5650 break; 5651 case AttributeList::AT_ArcWeakrefUnavailable: 5652 handleSimpleAttribute<ArcWeakrefUnavailableAttr>(S, D, Attr); 5653 break; 5654 case AttributeList::AT_ObjCRootClass: 5655 handleSimpleAttribute<ObjCRootClassAttr>(S, D, Attr); 5656 break; 5657 case AttributeList::AT_ObjCExplicitProtocolImpl: 5658 handleObjCSuppresProtocolAttr(S, D, Attr); 5659 break; 5660 case AttributeList::AT_ObjCRequiresPropertyDefs: 5661 handleSimpleAttribute<ObjCRequiresPropertyDefsAttr>(S, D, Attr); 5662 break; 5663 case AttributeList::AT_Unused: 5664 handleUnusedAttr(S, D, Attr); 5665 break; 5666 case AttributeList::AT_ReturnsTwice: 5667 handleSimpleAttribute<ReturnsTwiceAttr>(S, D, Attr); 5668 break; 5669 case AttributeList::AT_NotTailCalled: 5670 handleNotTailCalledAttr(S, D, Attr); 5671 break; 5672 case AttributeList::AT_DisableTailCalls: 5673 handleDisableTailCallsAttr(S, D, Attr); 5674 break; 5675 case AttributeList::AT_Used: 5676 handleUsedAttr(S, D, Attr); 5677 break; 5678 case AttributeList::AT_Visibility: 5679 handleVisibilityAttr(S, D, Attr, false); 5680 break; 5681 case AttributeList::AT_TypeVisibility: 5682 handleVisibilityAttr(S, D, Attr, true); 5683 break; 5684 case AttributeList::AT_WarnUnused: 5685 handleSimpleAttribute<WarnUnusedAttr>(S, D, Attr); 5686 break; 5687 case AttributeList::AT_WarnUnusedResult: 5688 handleWarnUnusedResult(S, D, Attr); 5689 break; 5690 case AttributeList::AT_Weak: 5691 handleSimpleAttribute<WeakAttr>(S, D, Attr); 5692 break; 5693 case AttributeList::AT_WeakRef: 5694 handleWeakRefAttr(S, D, Attr); 5695 break; 5696 case AttributeList::AT_WeakImport: 5697 handleWeakImportAttr(S, D, Attr); 5698 break; 5699 case AttributeList::AT_TransparentUnion: 5700 handleTransparentUnionAttr(S, D, Attr); 5701 break; 5702 case AttributeList::AT_ObjCException: 5703 handleSimpleAttribute<ObjCExceptionAttr>(S, D, Attr); 5704 break; 5705 case AttributeList::AT_ObjCMethodFamily: 5706 handleObjCMethodFamilyAttr(S, D, Attr); 5707 break; 5708 case AttributeList::AT_ObjCNSObject: 5709 handleObjCNSObject(S, D, Attr); 5710 break; 5711 case AttributeList::AT_ObjCIndependentClass: 5712 handleObjCIndependentClass(S, D, Attr); 5713 break; 5714 case AttributeList::AT_Blocks: 5715 handleBlocksAttr(S, D, Attr); 5716 break; 5717 case AttributeList::AT_Sentinel: 5718 handleSentinelAttr(S, D, Attr); 5719 break; 5720 case AttributeList::AT_Const: 5721 handleSimpleAttribute<ConstAttr>(S, D, Attr); 5722 break; 5723 case AttributeList::AT_Pure: 5724 handleSimpleAttribute<PureAttr>(S, D, Attr); 5725 break; 5726 case AttributeList::AT_Cleanup: 5727 handleCleanupAttr(S, D, Attr); 5728 break; 5729 case AttributeList::AT_NoDebug: 5730 handleNoDebugAttr(S, D, Attr); 5731 break; 5732 case AttributeList::AT_NoDuplicate: 5733 handleSimpleAttribute<NoDuplicateAttr>(S, D, Attr); 5734 break; 5735 case AttributeList::AT_NoInline: 5736 handleSimpleAttribute<NoInlineAttr>(S, D, Attr); 5737 break; 5738 case AttributeList::AT_NoInstrumentFunction: // Interacts with -pg. 5739 handleSimpleAttribute<NoInstrumentFunctionAttr>(S, D, Attr); 5740 break; 5741 case AttributeList::AT_StdCall: 5742 case AttributeList::AT_CDecl: 5743 case AttributeList::AT_FastCall: 5744 case AttributeList::AT_ThisCall: 5745 case AttributeList::AT_Pascal: 5746 case AttributeList::AT_SwiftCall: 5747 case AttributeList::AT_VectorCall: 5748 case AttributeList::AT_MSABI: 5749 case AttributeList::AT_SysVABI: 5750 case AttributeList::AT_Pcs: 5751 case AttributeList::AT_IntelOclBicc: 5752 case AttributeList::AT_PreserveMost: 5753 case AttributeList::AT_PreserveAll: 5754 handleCallConvAttr(S, D, Attr); 5755 break; 5756 case AttributeList::AT_OpenCLKernel: 5757 handleSimpleAttribute<OpenCLKernelAttr>(S, D, Attr); 5758 break; 5759 case AttributeList::AT_OpenCLAccess: 5760 handleOpenCLAccessAttr(S, D, Attr); 5761 break; 5762 case AttributeList::AT_OpenCLNoSVM: 5763 handleOpenCLNoSVMAttr(S, D, Attr); 5764 break; 5765 case AttributeList::AT_SwiftContext: 5766 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftContext); 5767 break; 5768 case AttributeList::AT_SwiftErrorResult: 5769 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftErrorResult); 5770 break; 5771 case AttributeList::AT_SwiftIndirectResult: 5772 handleParameterABIAttr(S, D, Attr, ParameterABI::SwiftIndirectResult); 5773 break; 5774 case AttributeList::AT_InternalLinkage: 5775 handleInternalLinkageAttr(S, D, Attr); 5776 break; 5777 case AttributeList::AT_LTOVisibilityPublic: 5778 handleSimpleAttribute<LTOVisibilityPublicAttr>(S, D, Attr); 5779 break; 5780 5781 // Microsoft attributes: 5782 case AttributeList::AT_EmptyBases: 5783 handleSimpleAttribute<EmptyBasesAttr>(S, D, Attr); 5784 break; 5785 case AttributeList::AT_LayoutVersion: 5786 handleLayoutVersion(S, D, Attr); 5787 break; 5788 case AttributeList::AT_MSNoVTable: 5789 handleSimpleAttribute<MSNoVTableAttr>(S, D, Attr); 5790 break; 5791 case AttributeList::AT_MSStruct: 5792 handleSimpleAttribute<MSStructAttr>(S, D, Attr); 5793 break; 5794 case AttributeList::AT_Uuid: 5795 handleUuidAttr(S, D, Attr); 5796 break; 5797 case AttributeList::AT_MSInheritance: 5798 handleMSInheritanceAttr(S, D, Attr); 5799 break; 5800 case AttributeList::AT_SelectAny: 5801 handleSimpleAttribute<SelectAnyAttr>(S, D, Attr); 5802 break; 5803 case AttributeList::AT_Thread: 5804 handleDeclspecThreadAttr(S, D, Attr); 5805 break; 5806 5807 case AttributeList::AT_AbiTag: 5808 handleAbiTagAttr(S, D, Attr); 5809 break; 5810 5811 // Thread safety attributes: 5812 case AttributeList::AT_AssertExclusiveLock: 5813 handleAssertExclusiveLockAttr(S, D, Attr); 5814 break; 5815 case AttributeList::AT_AssertSharedLock: 5816 handleAssertSharedLockAttr(S, D, Attr); 5817 break; 5818 case AttributeList::AT_GuardedVar: 5819 handleSimpleAttribute<GuardedVarAttr>(S, D, Attr); 5820 break; 5821 case AttributeList::AT_PtGuardedVar: 5822 handlePtGuardedVarAttr(S, D, Attr); 5823 break; 5824 case AttributeList::AT_ScopedLockable: 5825 handleSimpleAttribute<ScopedLockableAttr>(S, D, Attr); 5826 break; 5827 case AttributeList::AT_NoSanitize: 5828 handleNoSanitizeAttr(S, D, Attr); 5829 break; 5830 case AttributeList::AT_NoSanitizeSpecific: 5831 handleNoSanitizeSpecificAttr(S, D, Attr); 5832 break; 5833 case AttributeList::AT_NoThreadSafetyAnalysis: 5834 handleSimpleAttribute<NoThreadSafetyAnalysisAttr>(S, D, Attr); 5835 break; 5836 case AttributeList::AT_GuardedBy: 5837 handleGuardedByAttr(S, D, Attr); 5838 break; 5839 case AttributeList::AT_PtGuardedBy: 5840 handlePtGuardedByAttr(S, D, Attr); 5841 break; 5842 case AttributeList::AT_ExclusiveTrylockFunction: 5843 handleExclusiveTrylockFunctionAttr(S, D, Attr); 5844 break; 5845 case AttributeList::AT_LockReturned: 5846 handleLockReturnedAttr(S, D, Attr); 5847 break; 5848 case AttributeList::AT_LocksExcluded: 5849 handleLocksExcludedAttr(S, D, Attr); 5850 break; 5851 case AttributeList::AT_SharedTrylockFunction: 5852 handleSharedTrylockFunctionAttr(S, D, Attr); 5853 break; 5854 case AttributeList::AT_AcquiredBefore: 5855 handleAcquiredBeforeAttr(S, D, Attr); 5856 break; 5857 case AttributeList::AT_AcquiredAfter: 5858 handleAcquiredAfterAttr(S, D, Attr); 5859 break; 5860 5861 // Capability analysis attributes. 5862 case AttributeList::AT_Capability: 5863 case AttributeList::AT_Lockable: 5864 handleCapabilityAttr(S, D, Attr); 5865 break; 5866 case AttributeList::AT_RequiresCapability: 5867 handleRequiresCapabilityAttr(S, D, Attr); 5868 break; 5869 5870 case AttributeList::AT_AssertCapability: 5871 handleAssertCapabilityAttr(S, D, Attr); 5872 break; 5873 case AttributeList::AT_AcquireCapability: 5874 handleAcquireCapabilityAttr(S, D, Attr); 5875 break; 5876 case AttributeList::AT_ReleaseCapability: 5877 handleReleaseCapabilityAttr(S, D, Attr); 5878 break; 5879 case AttributeList::AT_TryAcquireCapability: 5880 handleTryAcquireCapabilityAttr(S, D, Attr); 5881 break; 5882 5883 // Consumed analysis attributes. 5884 case AttributeList::AT_Consumable: 5885 handleConsumableAttr(S, D, Attr); 5886 break; 5887 case AttributeList::AT_ConsumableAutoCast: 5888 handleSimpleAttribute<ConsumableAutoCastAttr>(S, D, Attr); 5889 break; 5890 case AttributeList::AT_ConsumableSetOnRead: 5891 handleSimpleAttribute<ConsumableSetOnReadAttr>(S, D, Attr); 5892 break; 5893 case AttributeList::AT_CallableWhen: 5894 handleCallableWhenAttr(S, D, Attr); 5895 break; 5896 case AttributeList::AT_ParamTypestate: 5897 handleParamTypestateAttr(S, D, Attr); 5898 break; 5899 case AttributeList::AT_ReturnTypestate: 5900 handleReturnTypestateAttr(S, D, Attr); 5901 break; 5902 case AttributeList::AT_SetTypestate: 5903 handleSetTypestateAttr(S, D, Attr); 5904 break; 5905 case AttributeList::AT_TestTypestate: 5906 handleTestTypestateAttr(S, D, Attr); 5907 break; 5908 5909 // Type safety attributes. 5910 case AttributeList::AT_ArgumentWithTypeTag: 5911 handleArgumentWithTypeTagAttr(S, D, Attr); 5912 break; 5913 case AttributeList::AT_TypeTagForDatatype: 5914 handleTypeTagForDatatypeAttr(S, D, Attr); 5915 break; 5916 5917 case AttributeList::AT_RenderScriptKernel: 5918 handleSimpleAttribute<RenderScriptKernelAttr>(S, D, Attr); 5919 break; 5920 } 5921 } 5922 5923 /// ProcessDeclAttributeList - Apply all the decl attributes in the specified 5924 /// attribute list to the specified decl, ignoring any type attributes. 5925 void Sema::ProcessDeclAttributeList(Scope *S, Decl *D, 5926 const AttributeList *AttrList, 5927 bool IncludeCXX11Attributes) { 5928 for (const AttributeList* l = AttrList; l; l = l->getNext()) 5929 ProcessDeclAttribute(*this, S, D, *l, IncludeCXX11Attributes); 5930 5931 // FIXME: We should be able to handle these cases in TableGen. 5932 // GCC accepts 5933 // static int a9 __attribute__((weakref)); 5934 // but that looks really pointless. We reject it. 5935 if (D->hasAttr<WeakRefAttr>() && !D->hasAttr<AliasAttr>()) { 5936 Diag(AttrList->getLoc(), diag::err_attribute_weakref_without_alias) 5937 << cast<NamedDecl>(D); 5938 D->dropAttr<WeakRefAttr>(); 5939 return; 5940 } 5941 5942 // FIXME: We should be able to handle this in TableGen as well. It would be 5943 // good to have a way to specify "these attributes must appear as a group", 5944 // for these. Additionally, it would be good to have a way to specify "these 5945 // attribute must never appear as a group" for attributes like cold and hot. 5946 if (!D->hasAttr<OpenCLKernelAttr>()) { 5947 // These attributes cannot be applied to a non-kernel function. 5948 if (Attr *A = D->getAttr<ReqdWorkGroupSizeAttr>()) { 5949 // FIXME: This emits a different error message than 5950 // diag::err_attribute_wrong_decl_type + ExpectedKernelFunction. 5951 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 5952 D->setInvalidDecl(); 5953 } else if (Attr *A = D->getAttr<WorkGroupSizeHintAttr>()) { 5954 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 5955 D->setInvalidDecl(); 5956 } else if (Attr *A = D->getAttr<VecTypeHintAttr>()) { 5957 Diag(D->getLocation(), diag::err_opencl_kernel_attr) << A; 5958 D->setInvalidDecl(); 5959 } else if (Attr *A = D->getAttr<AMDGPUNumVGPRAttr>()) { 5960 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 5961 << A << ExpectedKernelFunction; 5962 D->setInvalidDecl(); 5963 } else if (Attr *A = D->getAttr<AMDGPUNumSGPRAttr>()) { 5964 Diag(D->getLocation(), diag::err_attribute_wrong_decl_type) 5965 << A << ExpectedKernelFunction; 5966 D->setInvalidDecl(); 5967 } 5968 } 5969 } 5970 5971 // Annotation attributes are the only attributes allowed after an access 5972 // specifier. 5973 bool Sema::ProcessAccessDeclAttributeList(AccessSpecDecl *ASDecl, 5974 const AttributeList *AttrList) { 5975 for (const AttributeList* l = AttrList; l; l = l->getNext()) { 5976 if (l->getKind() == AttributeList::AT_Annotate) { 5977 ProcessDeclAttribute(*this, nullptr, ASDecl, *l, l->isCXX11Attribute()); 5978 } else { 5979 Diag(l->getLoc(), diag::err_only_annotate_after_access_spec); 5980 return true; 5981 } 5982 } 5983 5984 return false; 5985 } 5986 5987 /// checkUnusedDeclAttributes - Check a list of attributes to see if it 5988 /// contains any decl attributes that we should warn about. 5989 static void checkUnusedDeclAttributes(Sema &S, const AttributeList *A) { 5990 for ( ; A; A = A->getNext()) { 5991 // Only warn if the attribute is an unignored, non-type attribute. 5992 if (A->isUsedAsTypeAttr() || A->isInvalid()) continue; 5993 if (A->getKind() == AttributeList::IgnoredAttribute) continue; 5994 5995 if (A->getKind() == AttributeList::UnknownAttribute) { 5996 S.Diag(A->getLoc(), diag::warn_unknown_attribute_ignored) 5997 << A->getName() << A->getRange(); 5998 } else { 5999 S.Diag(A->getLoc(), diag::warn_attribute_not_on_decl) 6000 << A->getName() << A->getRange(); 6001 } 6002 } 6003 } 6004 6005 /// checkUnusedDeclAttributes - Given a declarator which is not being 6006 /// used to build a declaration, complain about any decl attributes 6007 /// which might be lying around on it. 6008 void Sema::checkUnusedDeclAttributes(Declarator &D) { 6009 ::checkUnusedDeclAttributes(*this, D.getDeclSpec().getAttributes().getList()); 6010 ::checkUnusedDeclAttributes(*this, D.getAttributes()); 6011 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) 6012 ::checkUnusedDeclAttributes(*this, D.getTypeObject(i).getAttrs()); 6013 } 6014 6015 /// DeclClonePragmaWeak - clone existing decl (maybe definition), 6016 /// \#pragma weak needs a non-definition decl and source may not have one. 6017 NamedDecl * Sema::DeclClonePragmaWeak(NamedDecl *ND, IdentifierInfo *II, 6018 SourceLocation Loc) { 6019 assert(isa<FunctionDecl>(ND) || isa<VarDecl>(ND)); 6020 NamedDecl *NewD = nullptr; 6021 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 6022 FunctionDecl *NewFD; 6023 // FIXME: Missing call to CheckFunctionDeclaration(). 6024 // FIXME: Mangling? 6025 // FIXME: Is the qualifier info correct? 6026 // FIXME: Is the DeclContext correct? 6027 NewFD = FunctionDecl::Create(FD->getASTContext(), FD->getDeclContext(), 6028 Loc, Loc, DeclarationName(II), 6029 FD->getType(), FD->getTypeSourceInfo(), 6030 SC_None, false/*isInlineSpecified*/, 6031 FD->hasPrototype(), 6032 false/*isConstexprSpecified*/); 6033 NewD = NewFD; 6034 6035 if (FD->getQualifier()) 6036 NewFD->setQualifierInfo(FD->getQualifierLoc()); 6037 6038 // Fake up parameter variables; they are declared as if this were 6039 // a typedef. 6040 QualType FDTy = FD->getType(); 6041 if (const FunctionProtoType *FT = FDTy->getAs<FunctionProtoType>()) { 6042 SmallVector<ParmVarDecl*, 16> Params; 6043 for (const auto &AI : FT->param_types()) { 6044 ParmVarDecl *Param = BuildParmVarDeclForTypedef(NewFD, Loc, AI); 6045 Param->setScopeInfo(0, Params.size()); 6046 Params.push_back(Param); 6047 } 6048 NewFD->setParams(Params); 6049 } 6050 } else if (VarDecl *VD = dyn_cast<VarDecl>(ND)) { 6051 NewD = VarDecl::Create(VD->getASTContext(), VD->getDeclContext(), 6052 VD->getInnerLocStart(), VD->getLocation(), II, 6053 VD->getType(), VD->getTypeSourceInfo(), 6054 VD->getStorageClass()); 6055 if (VD->getQualifier()) { 6056 VarDecl *NewVD = cast<VarDecl>(NewD); 6057 NewVD->setQualifierInfo(VD->getQualifierLoc()); 6058 } 6059 } 6060 return NewD; 6061 } 6062 6063 /// DeclApplyPragmaWeak - A declaration (maybe definition) needs \#pragma weak 6064 /// applied to it, possibly with an alias. 6065 void Sema::DeclApplyPragmaWeak(Scope *S, NamedDecl *ND, WeakInfo &W) { 6066 if (W.getUsed()) return; // only do this once 6067 W.setUsed(true); 6068 if (W.getAlias()) { // clone decl, impersonate __attribute(weak,alias(...)) 6069 IdentifierInfo *NDId = ND->getIdentifier(); 6070 NamedDecl *NewD = DeclClonePragmaWeak(ND, W.getAlias(), W.getLocation()); 6071 NewD->addAttr(AliasAttr::CreateImplicit(Context, NDId->getName(), 6072 W.getLocation())); 6073 NewD->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation())); 6074 WeakTopLevelDecl.push_back(NewD); 6075 // FIXME: "hideous" code from Sema::LazilyCreateBuiltin 6076 // to insert Decl at TU scope, sorry. 6077 DeclContext *SavedContext = CurContext; 6078 CurContext = Context.getTranslationUnitDecl(); 6079 NewD->setDeclContext(CurContext); 6080 NewD->setLexicalDeclContext(CurContext); 6081 PushOnScopeChains(NewD, S); 6082 CurContext = SavedContext; 6083 } else { // just add weak to existing 6084 ND->addAttr(WeakAttr::CreateImplicit(Context, W.getLocation())); 6085 } 6086 } 6087 6088 void Sema::ProcessPragmaWeak(Scope *S, Decl *D) { 6089 // It's valid to "forward-declare" #pragma weak, in which case we 6090 // have to do this. 6091 LoadExternalWeakUndeclaredIdentifiers(); 6092 if (!WeakUndeclaredIdentifiers.empty()) { 6093 NamedDecl *ND = nullptr; 6094 if (VarDecl *VD = dyn_cast<VarDecl>(D)) 6095 if (VD->isExternC()) 6096 ND = VD; 6097 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 6098 if (FD->isExternC()) 6099 ND = FD; 6100 if (ND) { 6101 if (IdentifierInfo *Id = ND->getIdentifier()) { 6102 auto I = WeakUndeclaredIdentifiers.find(Id); 6103 if (I != WeakUndeclaredIdentifiers.end()) { 6104 WeakInfo W = I->second; 6105 DeclApplyPragmaWeak(S, ND, W); 6106 WeakUndeclaredIdentifiers[Id] = W; 6107 } 6108 } 6109 } 6110 } 6111 } 6112 6113 /// ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in 6114 /// it, apply them to D. This is a bit tricky because PD can have attributes 6115 /// specified in many different places, and we need to find and apply them all. 6116 void Sema::ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD) { 6117 // Apply decl attributes from the DeclSpec if present. 6118 if (const AttributeList *Attrs = PD.getDeclSpec().getAttributes().getList()) 6119 ProcessDeclAttributeList(S, D, Attrs); 6120 6121 // Walk the declarator structure, applying decl attributes that were in a type 6122 // position to the decl itself. This handles cases like: 6123 // int *__attr__(x)** D; 6124 // when X is a decl attribute. 6125 for (unsigned i = 0, e = PD.getNumTypeObjects(); i != e; ++i) 6126 if (const AttributeList *Attrs = PD.getTypeObject(i).getAttrs()) 6127 ProcessDeclAttributeList(S, D, Attrs, /*IncludeCXX11Attributes=*/false); 6128 6129 // Finally, apply any attributes on the decl itself. 6130 if (const AttributeList *Attrs = PD.getAttributes()) 6131 ProcessDeclAttributeList(S, D, Attrs); 6132 } 6133 6134 /// Is the given declaration allowed to use a forbidden type? 6135 /// If so, it'll still be annotated with an attribute that makes it 6136 /// illegal to actually use. 6137 static bool isForbiddenTypeAllowed(Sema &S, Decl *decl, 6138 const DelayedDiagnostic &diag, 6139 UnavailableAttr::ImplicitReason &reason) { 6140 // Private ivars are always okay. Unfortunately, people don't 6141 // always properly make their ivars private, even in system headers. 6142 // Plus we need to make fields okay, too. 6143 if (!isa<FieldDecl>(decl) && !isa<ObjCPropertyDecl>(decl) && 6144 !isa<FunctionDecl>(decl)) 6145 return false; 6146 6147 // Silently accept unsupported uses of __weak in both user and system 6148 // declarations when it's been disabled, for ease of integration with 6149 // -fno-objc-arc files. We do have to take some care against attempts 6150 // to define such things; for now, we've only done that for ivars 6151 // and properties. 6152 if ((isa<ObjCIvarDecl>(decl) || isa<ObjCPropertyDecl>(decl))) { 6153 if (diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_disabled || 6154 diag.getForbiddenTypeDiagnostic() == diag::err_arc_weak_no_runtime) { 6155 reason = UnavailableAttr::IR_ForbiddenWeak; 6156 return true; 6157 } 6158 } 6159 6160 // Allow all sorts of things in system headers. 6161 if (S.Context.getSourceManager().isInSystemHeader(decl->getLocation())) { 6162 // Currently, all the failures dealt with this way are due to ARC 6163 // restrictions. 6164 reason = UnavailableAttr::IR_ARCForbiddenType; 6165 return true; 6166 } 6167 6168 return false; 6169 } 6170 6171 /// Handle a delayed forbidden-type diagnostic. 6172 static void handleDelayedForbiddenType(Sema &S, DelayedDiagnostic &diag, 6173 Decl *decl) { 6174 auto reason = UnavailableAttr::IR_None; 6175 if (decl && isForbiddenTypeAllowed(S, decl, diag, reason)) { 6176 assert(reason && "didn't set reason?"); 6177 decl->addAttr(UnavailableAttr::CreateImplicit(S.Context, "", reason, 6178 diag.Loc)); 6179 return; 6180 } 6181 if (S.getLangOpts().ObjCAutoRefCount) 6182 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(decl)) { 6183 // FIXME: we may want to suppress diagnostics for all 6184 // kind of forbidden type messages on unavailable functions. 6185 if (FD->hasAttr<UnavailableAttr>() && 6186 diag.getForbiddenTypeDiagnostic() == 6187 diag::err_arc_array_param_no_ownership) { 6188 diag.Triggered = true; 6189 return; 6190 } 6191 } 6192 6193 S.Diag(diag.Loc, diag.getForbiddenTypeDiagnostic()) 6194 << diag.getForbiddenTypeOperand() << diag.getForbiddenTypeArgument(); 6195 diag.Triggered = true; 6196 } 6197 6198 static bool isDeclDeprecated(Decl *D) { 6199 do { 6200 if (D->isDeprecated()) 6201 return true; 6202 // A category implicitly has the availability of the interface. 6203 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D)) 6204 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface()) 6205 return Interface->isDeprecated(); 6206 } while ((D = cast_or_null<Decl>(D->getDeclContext()))); 6207 return false; 6208 } 6209 6210 static bool isDeclUnavailable(Decl *D) { 6211 do { 6212 if (D->isUnavailable()) 6213 return true; 6214 // A category implicitly has the availability of the interface. 6215 if (const ObjCCategoryDecl *CatD = dyn_cast<ObjCCategoryDecl>(D)) 6216 if (const ObjCInterfaceDecl *Interface = CatD->getClassInterface()) 6217 return Interface->isUnavailable(); 6218 } while ((D = cast_or_null<Decl>(D->getDeclContext()))); 6219 return false; 6220 } 6221 6222 static const AvailabilityAttr *getAttrForPlatform(ASTContext &Context, 6223 const Decl *D) { 6224 // Check each AvailabilityAttr to find the one for this platform. 6225 for (const auto *A : D->attrs()) { 6226 if (const auto *Avail = dyn_cast<AvailabilityAttr>(A)) { 6227 // FIXME: this is copied from CheckAvailability. We should try to 6228 // de-duplicate. 6229 6230 // Check if this is an App Extension "platform", and if so chop off 6231 // the suffix for matching with the actual platform. 6232 StringRef ActualPlatform = Avail->getPlatform()->getName(); 6233 StringRef RealizedPlatform = ActualPlatform; 6234 if (Context.getLangOpts().AppExt) { 6235 size_t suffix = RealizedPlatform.rfind("_app_extension"); 6236 if (suffix != StringRef::npos) 6237 RealizedPlatform = RealizedPlatform.slice(0, suffix); 6238 } 6239 6240 StringRef TargetPlatform = Context.getTargetInfo().getPlatformName(); 6241 6242 // Match the platform name. 6243 if (RealizedPlatform == TargetPlatform) 6244 return Avail; 6245 } 6246 } 6247 return nullptr; 6248 } 6249 6250 static void DoEmitAvailabilityWarning(Sema &S, Sema::AvailabilityDiagnostic K, 6251 Decl *Ctx, const NamedDecl *D, 6252 StringRef Message, SourceLocation Loc, 6253 const ObjCInterfaceDecl *UnknownObjCClass, 6254 const ObjCPropertyDecl *ObjCProperty, 6255 bool ObjCPropertyAccess) { 6256 // Diagnostics for deprecated or unavailable. 6257 unsigned diag, diag_message, diag_fwdclass_message; 6258 unsigned diag_available_here = diag::note_availability_specified_here; 6259 6260 // Matches 'diag::note_property_attribute' options. 6261 unsigned property_note_select; 6262 6263 // Matches diag::note_availability_specified_here. 6264 unsigned available_here_select_kind; 6265 6266 // Don't warn if our current context is deprecated or unavailable. 6267 switch (K) { 6268 case Sema::AD_Deprecation: 6269 if (isDeclDeprecated(Ctx) || isDeclUnavailable(Ctx)) 6270 return; 6271 diag = !ObjCPropertyAccess ? diag::warn_deprecated 6272 : diag::warn_property_method_deprecated; 6273 diag_message = diag::warn_deprecated_message; 6274 diag_fwdclass_message = diag::warn_deprecated_fwdclass_message; 6275 property_note_select = /* deprecated */ 0; 6276 available_here_select_kind = /* deprecated */ 2; 6277 break; 6278 6279 case Sema::AD_Unavailable: 6280 if (isDeclUnavailable(Ctx)) 6281 return; 6282 diag = !ObjCPropertyAccess ? diag::err_unavailable 6283 : diag::err_property_method_unavailable; 6284 diag_message = diag::err_unavailable_message; 6285 diag_fwdclass_message = diag::warn_unavailable_fwdclass_message; 6286 property_note_select = /* unavailable */ 1; 6287 available_here_select_kind = /* unavailable */ 0; 6288 6289 if (auto attr = D->getAttr<UnavailableAttr>()) { 6290 if (attr->isImplicit() && attr->getImplicitReason()) { 6291 // Most of these failures are due to extra restrictions in ARC; 6292 // reflect that in the primary diagnostic when applicable. 6293 auto flagARCError = [&] { 6294 if (S.getLangOpts().ObjCAutoRefCount && 6295 S.getSourceManager().isInSystemHeader(D->getLocation())) 6296 diag = diag::err_unavailable_in_arc; 6297 }; 6298 6299 switch (attr->getImplicitReason()) { 6300 case UnavailableAttr::IR_None: break; 6301 6302 case UnavailableAttr::IR_ARCForbiddenType: 6303 flagARCError(); 6304 diag_available_here = diag::note_arc_forbidden_type; 6305 break; 6306 6307 case UnavailableAttr::IR_ForbiddenWeak: 6308 if (S.getLangOpts().ObjCWeakRuntime) 6309 diag_available_here = diag::note_arc_weak_disabled; 6310 else 6311 diag_available_here = diag::note_arc_weak_no_runtime; 6312 break; 6313 6314 case UnavailableAttr::IR_ARCForbiddenConversion: 6315 flagARCError(); 6316 diag_available_here = diag::note_performs_forbidden_arc_conversion; 6317 break; 6318 6319 case UnavailableAttr::IR_ARCInitReturnsUnrelated: 6320 flagARCError(); 6321 diag_available_here = diag::note_arc_init_returns_unrelated; 6322 break; 6323 6324 case UnavailableAttr::IR_ARCFieldWithOwnership: 6325 flagARCError(); 6326 diag_available_here = diag::note_arc_field_with_ownership; 6327 break; 6328 } 6329 } 6330 } 6331 break; 6332 6333 case Sema::AD_Partial: 6334 diag = diag::warn_partial_availability; 6335 diag_message = diag::warn_partial_message; 6336 diag_fwdclass_message = diag::warn_partial_fwdclass_message; 6337 property_note_select = /* partial */ 2; 6338 available_here_select_kind = /* partial */ 3; 6339 break; 6340 } 6341 6342 CharSourceRange UseRange; 6343 StringRef Replacement; 6344 if (K == Sema::AD_Deprecation) { 6345 if (auto attr = D->getAttr<DeprecatedAttr>()) 6346 Replacement = attr->getReplacement(); 6347 if (auto attr = getAttrForPlatform(S.Context, D)) 6348 Replacement = attr->getReplacement(); 6349 6350 if (!Replacement.empty()) 6351 UseRange = 6352 CharSourceRange::getCharRange(Loc, S.getLocForEndOfToken(Loc)); 6353 } 6354 6355 if (!Message.empty()) { 6356 S.Diag(Loc, diag_message) << D << Message 6357 << (UseRange.isValid() ? 6358 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint()); 6359 if (ObjCProperty) 6360 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute) 6361 << ObjCProperty->getDeclName() << property_note_select; 6362 } else if (!UnknownObjCClass) { 6363 S.Diag(Loc, diag) << D 6364 << (UseRange.isValid() ? 6365 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint()); 6366 if (ObjCProperty) 6367 S.Diag(ObjCProperty->getLocation(), diag::note_property_attribute) 6368 << ObjCProperty->getDeclName() << property_note_select; 6369 } else { 6370 S.Diag(Loc, diag_fwdclass_message) << D 6371 << (UseRange.isValid() ? 6372 FixItHint::CreateReplacement(UseRange, Replacement) : FixItHint()); 6373 S.Diag(UnknownObjCClass->getLocation(), diag::note_forward_class); 6374 } 6375 6376 // The declaration can have multiple availability attributes, we are looking 6377 // at one of them. 6378 const AvailabilityAttr *A = getAttrForPlatform(S.Context, D); 6379 if (A && A->isInherited()) { 6380 for (const Decl *Redecl = D->getMostRecentDecl(); Redecl; 6381 Redecl = Redecl->getPreviousDecl()) { 6382 const AvailabilityAttr *AForRedecl = getAttrForPlatform(S.Context, 6383 Redecl); 6384 if (AForRedecl && !AForRedecl->isInherited()) { 6385 // If D is a declaration with inherited attributes, the note should 6386 // point to the declaration with actual attributes. 6387 S.Diag(Redecl->getLocation(), diag_available_here) << D 6388 << available_here_select_kind; 6389 break; 6390 } 6391 } 6392 } 6393 else 6394 S.Diag(D->getLocation(), diag_available_here) 6395 << D << available_here_select_kind; 6396 6397 if (K == Sema::AD_Partial) 6398 S.Diag(Loc, diag::note_partial_availability_silence) << D; 6399 } 6400 6401 static void handleDelayedAvailabilityCheck(Sema &S, DelayedDiagnostic &DD, 6402 Decl *Ctx) { 6403 assert(DD.Kind == DelayedDiagnostic::Deprecation || 6404 DD.Kind == DelayedDiagnostic::Unavailable); 6405 Sema::AvailabilityDiagnostic AD = DD.Kind == DelayedDiagnostic::Deprecation 6406 ? Sema::AD_Deprecation 6407 : Sema::AD_Unavailable; 6408 DD.Triggered = true; 6409 DoEmitAvailabilityWarning( 6410 S, AD, Ctx, DD.getDeprecationDecl(), DD.getDeprecationMessage(), DD.Loc, 6411 DD.getUnknownObjCClass(), DD.getObjCProperty(), false); 6412 } 6413 6414 void Sema::PopParsingDeclaration(ParsingDeclState state, Decl *decl) { 6415 assert(DelayedDiagnostics.getCurrentPool()); 6416 DelayedDiagnosticPool &poppedPool = *DelayedDiagnostics.getCurrentPool(); 6417 DelayedDiagnostics.popWithoutEmitting(state); 6418 6419 // When delaying diagnostics to run in the context of a parsed 6420 // declaration, we only want to actually emit anything if parsing 6421 // succeeds. 6422 if (!decl) return; 6423 6424 // We emit all the active diagnostics in this pool or any of its 6425 // parents. In general, we'll get one pool for the decl spec 6426 // and a child pool for each declarator; in a decl group like: 6427 // deprecated_typedef foo, *bar, baz(); 6428 // only the declarator pops will be passed decls. This is correct; 6429 // we really do need to consider delayed diagnostics from the decl spec 6430 // for each of the different declarations. 6431 const DelayedDiagnosticPool *pool = &poppedPool; 6432 do { 6433 for (DelayedDiagnosticPool::pool_iterator 6434 i = pool->pool_begin(), e = pool->pool_end(); i != e; ++i) { 6435 // This const_cast is a bit lame. Really, Triggered should be mutable. 6436 DelayedDiagnostic &diag = const_cast<DelayedDiagnostic&>(*i); 6437 if (diag.Triggered) 6438 continue; 6439 6440 switch (diag.Kind) { 6441 case DelayedDiagnostic::Deprecation: 6442 case DelayedDiagnostic::Unavailable: 6443 // Don't bother giving deprecation/unavailable diagnostics if 6444 // the decl is invalid. 6445 if (!decl->isInvalidDecl()) 6446 handleDelayedAvailabilityCheck(*this, diag, decl); 6447 break; 6448 6449 case DelayedDiagnostic::Access: 6450 HandleDelayedAccessCheck(diag, decl); 6451 break; 6452 6453 case DelayedDiagnostic::ForbiddenType: 6454 handleDelayedForbiddenType(*this, diag, decl); 6455 break; 6456 } 6457 } 6458 } while ((pool = pool->getParent())); 6459 } 6460 6461 /// Given a set of delayed diagnostics, re-emit them as if they had 6462 /// been delayed in the current context instead of in the given pool. 6463 /// Essentially, this just moves them to the current pool. 6464 void Sema::redelayDiagnostics(DelayedDiagnosticPool &pool) { 6465 DelayedDiagnosticPool *curPool = DelayedDiagnostics.getCurrentPool(); 6466 assert(curPool && "re-emitting in undelayed context not supported"); 6467 curPool->steal(pool); 6468 } 6469 6470 void Sema::EmitAvailabilityWarning(AvailabilityDiagnostic AD, 6471 NamedDecl *D, StringRef Message, 6472 SourceLocation Loc, 6473 const ObjCInterfaceDecl *UnknownObjCClass, 6474 const ObjCPropertyDecl *ObjCProperty, 6475 bool ObjCPropertyAccess) { 6476 // Delay if we're currently parsing a declaration. 6477 if (DelayedDiagnostics.shouldDelayDiagnostics() && AD != AD_Partial) { 6478 DelayedDiagnostics.add(DelayedDiagnostic::makeAvailability( 6479 AD, Loc, D, UnknownObjCClass, ObjCProperty, Message, 6480 ObjCPropertyAccess)); 6481 return; 6482 } 6483 6484 Decl *Ctx = cast<Decl>(getCurLexicalContext()); 6485 DoEmitAvailabilityWarning(*this, AD, Ctx, D, Message, Loc, UnknownObjCClass, 6486 ObjCProperty, ObjCPropertyAccess); 6487 } 6488