Home | History | Annotate | Download | only in Sema
      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/ASTContext.h"
     16 #include "clang/AST/CXXInheritance.h"
     17 #include "clang/AST/DeclCXX.h"
     18 #include "clang/AST/DeclObjC.h"
     19 #include "clang/AST/DeclTemplate.h"
     20 #include "clang/AST/Expr.h"
     21 #include "clang/AST/ExprCXX.h"
     22 #include "clang/AST/Mangle.h"
     23 #include "clang/AST/ASTMutationListener.h"
     24 #include "clang/Basic/CharInfo.h"
     25 #include "clang/Basic/SourceManager.h"
     26 #include "clang/Basic/TargetInfo.h"
     27 #include "clang/Lex/Preprocessor.h"
     28 #include "clang/Sema/DeclSpec.h"
     29 #include "clang/Sema/DelayedDiagnostic.h"
     30 #include "clang/Sema/Lookup.h"
     31 #include "clang/Sema/Scope.h"
     32 #include "llvm/ADT/StringExtras.h"
     33 #include "llvm/Support/MathExtras.h"
     34 using namespace clang;
     35 using namespace sema;
     36 
     37 namespace AttributeLangSupport {
     38   enum LANG {
     39     C,
     40     Cpp,
     41     ObjC
     42   };
     43 }
     44 
     45 //===----------------------------------------------------------------------===//
     46 //  Helper functions
     47 //===----------------------------------------------------------------------===//
     48 
     49 /// isFunctionOrMethod - Return true if the given decl has function
     50 /// type (function or function-typed variable) or an Objective-C
     51 /// method.
     52 static bool isFunctionOrMethod(const Decl *D) {
     53   return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
     54 }
     55 /// \brief Return true if the given decl has function type (function or
     56 /// function-typed variable) or an Objective-C method or a block.
     57 static bool isFunctionOrMethodOrBlock(const Decl *D) {
     58   return isFunctionOrMethod(D) || isa<BlockDecl>(D);
     59 }
     60 
     61 /// Return true if the given decl has a declarator that should have
     62 /// been processed by Sema::GetTypeForDeclarator.
     63 static bool hasDeclarator(const Decl *D) {
     64   // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
     65   return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
     66          isa<ObjCPropertyDecl>(D);
     67 }
     68 
     69 /// hasFunctionProto - Return true if the given decl has a argument
     70 /// information. This decl should have already passed
     71 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
     72 static bool hasFunctionProto(const Decl *D) {
     73   if (const FunctionType *FnTy = D->getFunctionType())
     74     return isa<FunctionProtoType>(FnTy);
     75   return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
     76 }
     77 
     78 /// getFunctionOrMethodNumParams - Return number of function or method
     79 /// parameters. It is an error to call this on a K&R function (use
     80 /// hasFunctionProto first).
     81 static unsigned getFunctionOrMethodNumParams(const Decl *D) {
     82   if (const FunctionType *FnTy = D->getFunctionType())
     83     return cast<FunctionProtoType>(FnTy)->getNumParams();
     84   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
     85     return BD->getNumParams();
     86   return cast<ObjCMethodDecl>(D)->param_size();
     87 }
     88 
     89 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
     90   if (const FunctionType *FnTy = D->getFunctionType())
     91     return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
     92   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
     93     return BD->getParamDecl(Idx)->getType();
     94 
     95   return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
     96 }
     97 
     98 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
     99   if (const auto *FD = dyn_cast<FunctionDecl>(D))
    100     return FD->getParamDecl(Idx)->getSourceRange();
    101   if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
    102     return MD->parameters()[Idx]->getSourceRange();
    103   if (const auto *BD = dyn_cast<BlockDecl>(D))
    104     return BD->getParamDecl(Idx)->getSourceRange();
    105   return SourceRange();
    106 }
    107 
    108 static QualType getFunctionOrMethodResultType(const Decl *D) {
    109   if (const FunctionType *FnTy = D->getFunctionType())
    110     return cast<FunctionType>(FnTy)->getReturnType();
    111   return cast<ObjCMethodDecl>(D)->getReturnType();
    112 }
    113 
    114 static SourceRange getFunctionOrMethodResultSourceRange(const Decl *D) {
    115   if (const auto *FD = dyn_cast<FunctionDecl>(D))
    116     return FD->getReturnTypeSourceRange();
    117   if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
    118     return MD->getReturnTypeSourceRange();
    119   return SourceRange();
    120 }
    121 
    122 static bool isFunctionOrMethodVariadic(const Decl *D) {
    123   if (const FunctionType *FnTy = D->getFunctionType()) {
    124     const FunctionProtoType *proto = cast<FunctionProtoType>(FnTy);
    125     return proto->isVariadic();
    126   }
    127   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D))
    128     return BD->isVariadic();
    129 
    130   return cast<ObjCMethodDecl>(D)->isVariadic();
    131 }
    132 
    133 static bool isInstanceMethod(const Decl *D) {
    134   if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(D))
    135     return MethodDecl->isInstance();
    136   return false;
    137 }
    138 
    139 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
    140   const ObjCObjectPointerType *PT = T->getAs<ObjCObjectPointerType>();
    141   if (!PT)
    142     return false;
    143 
    144   ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
    145   if (!Cls)
    146     return false;
    147 
    148   IdentifierInfo* ClsName = Cls->getIdentifier();
    149 
    150   // FIXME: Should we walk the chain of classes?
    151   return ClsName == &Ctx.Idents.get("NSString") ||
    152          ClsName == &Ctx.Idents.get("NSMutableString");
    153 }
    154 
    155 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
    156   const PointerType *PT = T->getAs<PointerType>();
    157   if (!PT)
    158     return false;
    159 
    160   const RecordType *RT = PT->getPointeeType()->getAs<RecordType>();
    161   if (!RT)
    162     return false;
    163 
    164   const RecordDecl *RD = RT->getDecl();
    165   if (RD->getTagKind() != TTK_Struct)
    166     return false;
    167 
    168   return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
    169 }
    170 
    171 static unsigned getNumAttributeArgs(const AttributeList &Attr) {
    172   // FIXME: Include the type in the argument list.
    173   return Attr.getNumArgs() + Attr.hasParsedType();
    174 }
    175 
    176 template <typename Compare>
    177 static bool checkAttributeNumArgsImpl(Sema &S, const AttributeList &Attr,
    178                                       unsigned Num, unsigned Diag,
    179                                       Compare Comp) {
    180   if (Comp(getNumAttributeArgs(Attr), Num)) {
    181     S.Diag(Attr.getLoc(), Diag) << Attr.getName() << Num;
    182     return false;
    183   }
    184 
    185   return true;
    186 }
    187 
    188 /// \brief Check if the attribute has exactly as many args as Num. May
    189 /// output an error.
    190 static bool checkAttributeNumArgs(Sema &S, const AttributeList &Attr,
    191                                   unsigned Num) {
    192   return checkAttributeNumArgsImpl(S, Attr, Num,
    193                                    diag::err_attribute_wrong_number_arguments,
    194                                    std::not_equal_to<unsigned>());
    195 }
    196 
    197 /// \brief Check if the attribute has at least as many args as Num. May
    198 /// output an error.
    199 static bool checkAttributeAtLeastNumArgs(Sema &S, const AttributeList &Attr,
    200                                          unsigned Num) {
    201   return checkAttributeNumArgsImpl(S, Attr, Num,
    202                                    diag::err_attribute_too_few_arguments,
    203                                    std::less<unsigned>());
    204 }
    205 
    206 /// \brief Check if the attribute has at most as many args as Num. May
    207 /// output an error.
    208 static bool checkAttributeAtMostNumArgs(Sema &S, const AttributeList &Attr,
    209                                          unsigned Num) {
    210   return checkAttributeNumArgsImpl(S, Attr, Num,
    211                                    diag::err_attribute_too_many_arguments,
    212                                    std::greater<unsigned>());
    213 }
    214 
    215 /// \brief If Expr is a valid integer constant, get the value of the integer
    216 /// expression and return success or failure. May output an error.
    217 static bool checkUInt32Argument(Sema &S, const AttributeList &Attr,
    218                                 const Expr *Expr, uint32_t &Val,
    219                                 unsigned Idx = UINT_MAX) {
    220   llvm::APSInt I(32);
    221   if (Expr->isTypeDependent() || Expr->isValueDependent() ||
    222       !Expr->isIntegerConstantExpr(I, S.Context)) {
    223     if (Idx != UINT_MAX)
    224       S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
    225         << Attr.getName() << Idx << AANT_ArgumentIntegerConstant
    226         << Expr->getSourceRange();
    227     else
    228       S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
    229         << Attr.getName() << AANT_ArgumentIntegerConstant
    230         << Expr->getSourceRange();
    231     return false;
    232   }
    233 
    234   if (!I.isIntN(32)) {
    235     S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
    236         << I.toString(10, false) << 32 << /* Unsigned */ 1;
    237     return false;
    238   }
    239 
    240   Val = (uint32_t)I.getZExtValue();
    241   return true;
    242 }
    243 
    244 /// \brief Diagnose mutually exclusive attributes when present on a given
    245 /// declaration. Returns true if diagnosed.
    246 template <typename AttrTy>
    247 static bool checkAttrMutualExclusion(Sema &S, Decl *D, SourceRange Range,
    248                                      IdentifierInfo *Ident) {
    249   if (AttrTy *A = D->getAttr<AttrTy>()) {
    250     S.Diag(Range.getBegin(), diag::err_attributes_are_not_compatible) << Ident
    251                                                                       << A;
    252     S.Diag(A->getLocation(), diag::note_conflicting_attribute);
    253     return true;
    254   }
    255   return false;
    256 }
    257 
    258 /// \brief Check if IdxExpr is a valid parameter index for a function or
    259 /// instance method D.  May output an error.
    260 ///
    261 /// \returns true if IdxExpr is a valid index.
    262 static bool checkFunctionOrMethodParameterIndex(Sema &S, const Decl *D,
    263                                                 const AttributeList &Attr,
    264                                                 unsigned AttrArgNum,
    265                                                 const Expr *IdxExpr,
    266                                                 uint64_t &Idx) {
    267   assert(isFunctionOrMethodOrBlock(D));
    268 
    269   // In C++ the implicit 'this' function parameter also counts.
    270   // Parameters are counted from one.
    271   bool HP = hasFunctionProto(D);
    272   bool HasImplicitThisParam = isInstanceMethod(D);
    273   bool IV = HP && isFunctionOrMethodVariadic(D);
    274   unsigned NumParams =
    275       (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
    276 
    277   llvm::APSInt IdxInt;
    278   if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
    279       !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
    280     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
    281       << Attr.getName() << AttrArgNum << AANT_ArgumentIntegerConstant
    282       << IdxExpr->getSourceRange();
    283     return false;
    284   }
    285 
    286   Idx = IdxInt.getLimitedValue();
    287   if (Idx < 1 || (!IV && Idx > NumParams)) {
    288     S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
    289       << Attr.getName() << AttrArgNum << IdxExpr->getSourceRange();
    290     return false;
    291   }
    292   Idx--; // Convert to zero-based.
    293   if (HasImplicitThisParam) {
    294     if (Idx == 0) {
    295       S.Diag(Attr.getLoc(),
    296              diag::err_attribute_invalid_implicit_this_argument)
    297         << Attr.getName() << IdxExpr->getSourceRange();
    298       return false;
    299     }
    300     --Idx;
    301   }
    302 
    303   return true;
    304 }
    305 
    306 /// \brief Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
    307 /// If not emit an error and return false. If the argument is an identifier it
    308 /// will emit an error with a fixit hint and treat it as if it was a string
    309 /// literal.
    310 bool Sema::checkStringLiteralArgumentAttr(const AttributeList &Attr,
    311                                           unsigned ArgNum, StringRef &Str,
    312                                           SourceLocation *ArgLocation) {
    313   // Look for identifiers. If we have one emit a hint to fix it to a literal.
    314   if (Attr.isArgIdent(ArgNum)) {
    315     IdentifierLoc *Loc = Attr.getArgAsIdent(ArgNum);
    316     Diag(Loc->Loc, diag::err_attribute_argument_type)
    317         << Attr.getName() << AANT_ArgumentString
    318         << FixItHint::CreateInsertion(Loc->Loc, "\"")
    319         << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
    320     Str = Loc->Ident->getName();
    321     if (ArgLocation)
    322       *ArgLocation = Loc->Loc;
    323     return true;
    324   }
    325 
    326   // Now check for an actual string literal.
    327   Expr *ArgExpr = Attr.getArgAsExpr(ArgNum);
    328   StringLiteral *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
    329   if (ArgLocation)
    330     *ArgLocation = ArgExpr->getLocStart();
    331 
    332   if (!Literal || !Literal->isAscii()) {
    333     Diag(ArgExpr->getLocStart(), diag::err_attribute_argument_type)
    334         << Attr.getName() << AANT_ArgumentString;
    335     return false;
    336   }
    337 
    338   Str = Literal->getString();
    339   return true;
    340 }
    341 
    342 /// \brief Applies the given attribute to the Decl without performing any
    343 /// additional semantic checking.
    344 template <typename AttrType>
    345 static void handleSimpleAttribute(Sema &S, Decl *D,
    346                                   const AttributeList &Attr) {
    347   D->addAttr(::new (S.Context) AttrType(Attr.getRange(), S.Context,
    348                                         Attr.getAttributeSpellingListIndex()));
    349 }
    350 
    351 /// \brief Check if the passed-in expression is of type int or bool.
    352 static bool isIntOrBool(Expr *Exp) {
    353   QualType QT = Exp->getType();
    354   return QT->isBooleanType() || QT->isIntegerType();
    355 }
    356 
    357 
    358 // Check to see if the type is a smart pointer of some kind.  We assume
    359 // it's a smart pointer if it defines both operator-> and operator*.
    360 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
    361   DeclContextLookupResult Res1 = RT->getDecl()->lookup(
    362       S.Context.DeclarationNames.getCXXOperatorName(OO_Star));
    363   if (Res1.empty())
    364     return false;
    365 
    366   DeclContextLookupResult Res2 = RT->getDecl()->lookup(
    367       S.Context.DeclarationNames.getCXXOperatorName(OO_Arrow));
    368   if (Res2.empty())
    369     return false;
    370 
    371   return true;
    372 }
    373 
    374 /// \brief Check if passed in Decl is a pointer type.
    375 /// Note that this function may produce an error message.
    376 /// \return true if the Decl is a pointer type; false otherwise
    377 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
    378                                        const AttributeList &Attr) {
    379   const ValueDecl *vd = cast<ValueDecl>(D);
    380   QualType QT = vd->getType();
    381   if (QT->isAnyPointerType())
    382     return true;
    383 
    384   if (const RecordType *RT = QT->getAs<RecordType>()) {
    385     // If it's an incomplete type, it could be a smart pointer; skip it.
    386     // (We don't want to force template instantiation if we can avoid it,
    387     // since that would alter the order in which templates are instantiated.)
    388     if (RT->isIncompleteType())
    389       return true;
    390 
    391     if (threadSafetyCheckIsSmartPointer(S, RT))
    392       return true;
    393   }
    394 
    395   S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_pointer)
    396     << Attr.getName() << QT;
    397   return false;
    398 }
    399 
    400 /// \brief Checks that the passed in QualType either is of RecordType or points
    401 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
    402 static const RecordType *getRecordType(QualType QT) {
    403   if (const RecordType *RT = QT->getAs<RecordType>())
    404     return RT;
    405 
    406   // Now check if we point to record type.
    407   if (const PointerType *PT = QT->getAs<PointerType>())
    408     return PT->getPointeeType()->getAs<RecordType>();
    409 
    410   return nullptr;
    411 }
    412 
    413 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
    414   const RecordType *RT = getRecordType(Ty);
    415 
    416   if (!RT)
    417     return false;
    418 
    419   // Don't check for the capability if the class hasn't been defined yet.
    420   if (RT->isIncompleteType())
    421     return true;
    422 
    423   // Allow smart pointers to be used as capability objects.
    424   // FIXME -- Check the type that the smart pointer points to.
    425   if (threadSafetyCheckIsSmartPointer(S, RT))
    426     return true;
    427 
    428   // Check if the record itself has a capability.
    429   RecordDecl *RD = RT->getDecl();
    430   if (RD->hasAttr<CapabilityAttr>())
    431     return true;
    432 
    433   // Else check if any base classes have a capability.
    434   if (CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
    435     CXXBasePaths BPaths(false, false);
    436     if (CRD->lookupInBases([](const CXXBaseSpecifier *BS, CXXBasePath &) {
    437           const auto *Type = BS->getType()->getAs<RecordType>();
    438           return Type->getDecl()->hasAttr<CapabilityAttr>();
    439         }, BPaths))
    440       return true;
    441   }
    442   return false;
    443 }
    444 
    445 static bool checkTypedefTypeForCapability(QualType Ty) {
    446   const auto *TD = Ty->getAs<TypedefType>();
    447   if (!TD)
    448     return false;
    449 
    450   TypedefNameDecl *TN = TD->getDecl();
    451   if (!TN)
    452     return false;
    453 
    454   return TN->hasAttr<CapabilityAttr>();
    455 }
    456 
    457 static bool typeHasCapability(Sema &S, QualType Ty) {
    458   if (checkTypedefTypeForCapability(Ty))
    459     return true;
    460 
    461   if (checkRecordTypeForCapability(S, Ty))
    462     return true;
    463 
    464   return false;
    465 }
    466 
    467 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
    468   // Capability expressions are simple expressions involving the boolean logic
    469   // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
    470   // a DeclRefExpr is found, its type should be checked to determine whether it
    471   // is a capability or not.
    472 
    473   if (const auto *E = dyn_cast<DeclRefExpr>(Ex))
    474     return typeHasCapability(S, E->getType());
    475   else if (const auto *E = dyn_cast<CastExpr>(Ex))
    476     return isCapabilityExpr(S, E->getSubExpr());
    477   else if (const auto *E = dyn_cast<ParenExpr>(Ex))
    478     return isCapabilityExpr(S, E->getSubExpr());
    479   else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
    480     if (E->getOpcode() == UO_LNot)
    481       return isCapabilityExpr(S, E->getSubExpr());
    482     return false;
    483   } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
    484     if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
    485       return isCapabilityExpr(S, E->getLHS()) &&
    486              isCapabilityExpr(S, E->getRHS());
    487     return false;
    488   }
    489 
    490   return false;
    491 }
    492 
    493 /// \brief Checks that all attribute arguments, starting from Sidx, resolve to
    494 /// a capability object.
    495 /// \param Sidx The attribute argument index to start checking with.
    496 /// \param ParamIdxOk Whether an argument can be indexing into a function
    497 /// parameter list.
    498 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
    499                                            const AttributeList &Attr,
    500                                            SmallVectorImpl<Expr *> &Args,
    501                                            int Sidx = 0,
    502                                            bool ParamIdxOk = false) {
    503   for (unsigned Idx = Sidx; Idx < Attr.getNumArgs(); ++Idx) {
    504     Expr *ArgExp = Attr.getArgAsExpr(Idx);
    505 
    506     if (ArgExp->isTypeDependent()) {
    507       // FIXME -- need to check this again on template instantiation
    508       Args.push_back(ArgExp);
    509       continue;
    510     }
    511 
    512     if (StringLiteral *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
    513       if (StrLit->getLength() == 0 ||
    514           (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
    515         // Pass empty strings to the analyzer without warnings.
    516         // Treat "*" as the universal lock.
    517         Args.push_back(ArgExp);
    518         continue;
    519       }
    520 
    521       // We allow constant strings to be used as a placeholder for expressions
    522       // that are not valid C++ syntax, but warn that they are ignored.
    523       S.Diag(Attr.getLoc(), diag::warn_thread_attribute_ignored) <<
    524         Attr.getName();
    525       Args.push_back(ArgExp);
    526       continue;
    527     }
    528 
    529     QualType ArgTy = ArgExp->getType();
    530 
    531     // A pointer to member expression of the form  &MyClass::mu is treated
    532     // specially -- we need to look at the type of the member.
    533     if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(ArgExp))
    534       if (UOp->getOpcode() == UO_AddrOf)
    535         if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
    536           if (DRE->getDecl()->isCXXInstanceMember())
    537             ArgTy = DRE->getDecl()->getType();
    538 
    539     // First see if we can just cast to record type, or pointer to record type.
    540     const RecordType *RT = getRecordType(ArgTy);
    541 
    542     // Now check if we index into a record type function param.
    543     if(!RT && ParamIdxOk) {
    544       FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
    545       IntegerLiteral *IL = dyn_cast<IntegerLiteral>(ArgExp);
    546       if(FD && IL) {
    547         unsigned int NumParams = FD->getNumParams();
    548         llvm::APInt ArgValue = IL->getValue();
    549         uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
    550         uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
    551         if(!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
    552           S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_range)
    553             << Attr.getName() << Idx + 1 << NumParams;
    554           continue;
    555         }
    556         ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
    557       }
    558     }
    559 
    560     // If the type does not have a capability, see if the components of the
    561     // expression have capabilities. This allows for writing C code where the
    562     // capability may be on the type, and the expression is a capability
    563     // boolean logic expression. Eg) requires_capability(A || B && !C)
    564     if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
    565       S.Diag(Attr.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
    566           << Attr.getName() << ArgTy;
    567 
    568     Args.push_back(ArgExp);
    569   }
    570 }
    571 
    572 //===----------------------------------------------------------------------===//
    573 // Attribute Implementations
    574 //===----------------------------------------------------------------------===//
    575 
    576 static void handlePtGuardedVarAttr(Sema &S, Decl *D,
    577                                    const AttributeList &Attr) {
    578   if (!threadSafetyCheckIsPointer(S, D, Attr))
    579     return;
    580 
    581   D->addAttr(::new (S.Context)
    582              PtGuardedVarAttr(Attr.getRange(), S.Context,
    583                               Attr.getAttributeSpellingListIndex()));
    584 }
    585 
    586 static bool checkGuardedByAttrCommon(Sema &S, Decl *D,
    587                                      const AttributeList &Attr,
    588                                      Expr* &Arg) {
    589   SmallVector<Expr*, 1> Args;
    590   // check that all arguments are lockable objects
    591   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
    592   unsigned Size = Args.size();
    593   if (Size != 1)
    594     return false;
    595 
    596   Arg = Args[0];
    597 
    598   return true;
    599 }
    600 
    601 static void handleGuardedByAttr(Sema &S, Decl *D, const AttributeList &Attr) {
    602   Expr *Arg = nullptr;
    603   if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
    604     return;
    605 
    606   D->addAttr(::new (S.Context) GuardedByAttr(Attr.getRange(), S.Context, Arg,
    607                                         Attr.getAttributeSpellingListIndex()));
    608 }
    609 
    610 static void handlePtGuardedByAttr(Sema &S, Decl *D,
    611                                   const AttributeList &Attr) {
    612   Expr *Arg = nullptr;
    613   if (!checkGuardedByAttrCommon(S, D, Attr, Arg))
    614     return;
    615 
    616   if (!threadSafetyCheckIsPointer(S, D, Attr))
    617     return;
    618 
    619   D->addAttr(::new (S.Context) PtGuardedByAttr(Attr.getRange(),
    620                                                S.Context, Arg,
    621                                         Attr.getAttributeSpellingListIndex()));
    622 }
    623 
    624 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D,
    625                                         const AttributeList &Attr,
    626                                         SmallVectorImpl<Expr *> &Args) {
    627   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
    628     return false;
    629 
    630   // Check that this attribute only applies to lockable types.
    631   QualType QT = cast<ValueDecl>(D)->getType();
    632   if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
    633     S.Diag(Attr.getLoc(), diag::warn_thread_attribute_decl_not_lockable)
    634       << Attr.getName();
    635     return false;
    636   }
    637 
    638   // Check that all arguments are lockable objects.
    639   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
    640   if (Args.empty())
    641     return false;
    642 
    643   return true;
    644 }
    645 
    646 static void handleAcquiredAfterAttr(Sema &S, Decl *D,
    647                                     const AttributeList &Attr) {
    648   SmallVector<Expr*, 1> Args;
    649   if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
    650     return;
    651 
    652   Expr **StartArg = &Args[0];
    653   D->addAttr(::new (S.Context)
    654              AcquiredAfterAttr(Attr.getRange(), S.Context,
    655                                StartArg, Args.size(),
    656                                Attr.getAttributeSpellingListIndex()));
    657 }
    658 
    659 static void handleAcquiredBeforeAttr(Sema &S, Decl *D,
    660                                      const AttributeList &Attr) {
    661   SmallVector<Expr*, 1> Args;
    662   if (!checkAcquireOrderAttrCommon(S, D, Attr, Args))
    663     return;
    664 
    665   Expr **StartArg = &Args[0];
    666   D->addAttr(::new (S.Context)
    667              AcquiredBeforeAttr(Attr.getRange(), S.Context,
    668                                 StartArg, Args.size(),
    669                                 Attr.getAttributeSpellingListIndex()));
    670 }
    671 
    672 static bool checkLockFunAttrCommon(Sema &S, Decl *D,
    673                                    const AttributeList &Attr,
    674                                    SmallVectorImpl<Expr *> &Args) {
    675   // zero or more arguments ok
    676   // check that all arguments are lockable objects
    677   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 0, /*ParamIdxOk=*/true);
    678 
    679   return true;
    680 }
    681 
    682 static void handleAssertSharedLockAttr(Sema &S, Decl *D,
    683                                        const AttributeList &Attr) {
    684   SmallVector<Expr*, 1> Args;
    685   if (!checkLockFunAttrCommon(S, D, Attr, Args))
    686     return;
    687 
    688   unsigned Size = Args.size();
    689   Expr **StartArg = Size == 0 ? nullptr : &Args[0];
    690   D->addAttr(::new (S.Context)
    691              AssertSharedLockAttr(Attr.getRange(), S.Context, StartArg, Size,
    692                                   Attr.getAttributeSpellingListIndex()));
    693 }
    694 
    695 static void handleAssertExclusiveLockAttr(Sema &S, Decl *D,
    696                                           const AttributeList &Attr) {
    697   SmallVector<Expr*, 1> Args;
    698   if (!checkLockFunAttrCommon(S, D, Attr, Args))
    699     return;
    700 
    701   unsigned Size = Args.size();
    702   Expr **StartArg = Size == 0 ? nullptr : &Args[0];
    703   D->addAttr(::new (S.Context)
    704              AssertExclusiveLockAttr(Attr.getRange(), S.Context,
    705                                      StartArg, Size,
    706                                      Attr.getAttributeSpellingListIndex()));
    707 }
    708 
    709 
    710 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D,
    711                                       const AttributeList &Attr,
    712                                       SmallVectorImpl<Expr *> &Args) {
    713   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
    714     return false;
    715 
    716   if (!isIntOrBool(Attr.getArgAsExpr(0))) {
    717     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
    718       << Attr.getName() << 1 << AANT_ArgumentIntOrBool;
    719     return false;
    720   }
    721 
    722   // check that all arguments are lockable objects
    723   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args, 1);
    724 
    725   return true;
    726 }
    727 
    728 static void handleSharedTrylockFunctionAttr(Sema &S, Decl *D,
    729                                             const AttributeList &Attr) {
    730   SmallVector<Expr*, 2> Args;
    731   if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
    732     return;
    733 
    734   D->addAttr(::new (S.Context)
    735              SharedTrylockFunctionAttr(Attr.getRange(), S.Context,
    736                                        Attr.getArgAsExpr(0),
    737                                        Args.data(), Args.size(),
    738                                        Attr.getAttributeSpellingListIndex()));
    739 }
    740 
    741 static void handleExclusiveTrylockFunctionAttr(Sema &S, Decl *D,
    742                                                const AttributeList &Attr) {
    743   SmallVector<Expr*, 2> Args;
    744   if (!checkTryLockFunAttrCommon(S, D, Attr, Args))
    745     return;
    746 
    747   D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
    748       Attr.getRange(), S.Context, Attr.getArgAsExpr(0), Args.data(),
    749       Args.size(), Attr.getAttributeSpellingListIndex()));
    750 }
    751 
    752 static void handleLockReturnedAttr(Sema &S, Decl *D,
    753                                    const AttributeList &Attr) {
    754   // check that the argument is lockable object
    755   SmallVector<Expr*, 1> Args;
    756   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
    757   unsigned Size = Args.size();
    758   if (Size == 0)
    759     return;
    760 
    761   D->addAttr(::new (S.Context)
    762              LockReturnedAttr(Attr.getRange(), S.Context, Args[0],
    763                               Attr.getAttributeSpellingListIndex()));
    764 }
    765 
    766 static void handleLocksExcludedAttr(Sema &S, Decl *D,
    767                                     const AttributeList &Attr) {
    768   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
    769     return;
    770 
    771   // check that all arguments are lockable objects
    772   SmallVector<Expr*, 1> Args;
    773   checkAttrArgsAreCapabilityObjs(S, D, Attr, Args);
    774   unsigned Size = Args.size();
    775   if (Size == 0)
    776     return;
    777   Expr **StartArg = &Args[0];
    778 
    779   D->addAttr(::new (S.Context)
    780              LocksExcludedAttr(Attr.getRange(), S.Context, StartArg, Size,
    781                                Attr.getAttributeSpellingListIndex()));
    782 }
    783 
    784 static void handleEnableIfAttr(Sema &S, Decl *D, const AttributeList &Attr) {
    785   Expr *Cond = Attr.getArgAsExpr(0);
    786   if (!Cond->isTypeDependent()) {
    787     ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
    788     if (Converted.isInvalid())
    789       return;
    790     Cond = Converted.get();
    791   }
    792 
    793   StringRef Msg;
    794   if (!S.checkStringLiteralArgumentAttr(Attr, 1, Msg))
    795     return;
    796 
    797   SmallVector<PartialDiagnosticAt, 8> Diags;
    798   if (!Cond->isValueDependent() &&
    799       !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
    800                                                 Diags)) {
    801     S.Diag(Attr.getLoc(), diag::err_enable_if_never_constant_expr);
    802     for (int I = 0, N = Diags.size(); I != N; ++I)
    803       S.Diag(Diags[I].first, Diags[I].second);
    804     return;
    805   }
    806 
    807   D->addAttr(::new (S.Context)
    808              EnableIfAttr(Attr.getRange(), S.Context, Cond, Msg,
    809                           Attr.getAttributeSpellingListIndex()));
    810 }
    811 
    812 static void handlePassObjectSizeAttr(Sema &S, Decl *D,
    813                                      const AttributeList &Attr) {
    814   if (D->hasAttr<PassObjectSizeAttr>()) {
    815     S.Diag(D->getLocStart(), diag::err_attribute_only_once_per_parameter)
    816         << Attr.getName();
    817     return;
    818   }
    819 
    820   Expr *E = Attr.getArgAsExpr(0);
    821   uint32_t Type;
    822   if (!checkUInt32Argument(S, Attr, E, Type, /*Idx=*/1))
    823     return;
    824 
    825   // pass_object_size's argument is passed in as the second argument of
    826   // __builtin_object_size. So, it has the same constraints as that second
    827   // argument; namely, it must be in the range [0, 3].
    828   if (Type > 3) {
    829     S.Diag(E->getLocStart(), diag::err_attribute_argument_outof_range)
    830         << Attr.getName() << 0 << 3 << E->getSourceRange();
    831     return;
    832   }
    833 
    834   // pass_object_size is only supported on constant pointer parameters; as a
    835   // kindness to users, we allow the parameter to be non-const for declarations.
    836   // At this point, we have no clue if `D` belongs to a function declaration or
    837   // definition, so we defer the constness check until later.
    838   if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
    839     S.Diag(D->getLocStart(), diag::err_attribute_pointers_only)
    840         << Attr.getName() << 1;
    841     return;
    842   }
    843 
    844   D->addAttr(::new (S.Context)
    845                  PassObjectSizeAttr(Attr.getRange(), S.Context, (int)Type,
    846                                     Attr.getAttributeSpellingListIndex()));
    847 }
    848 
    849 static void handleConsumableAttr(Sema &S, Decl *D, const AttributeList &Attr) {
    850   ConsumableAttr::ConsumedState DefaultState;
    851 
    852   if (Attr.isArgIdent(0)) {
    853     IdentifierLoc *IL = Attr.getArgAsIdent(0);
    854     if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
    855                                                    DefaultState)) {
    856       S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
    857         << Attr.getName() << IL->Ident;
    858       return;
    859     }
    860   } else {
    861     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
    862         << Attr.getName() << AANT_ArgumentIdentifier;
    863     return;
    864   }
    865 
    866   D->addAttr(::new (S.Context)
    867              ConsumableAttr(Attr.getRange(), S.Context, DefaultState,
    868                             Attr.getAttributeSpellingListIndex()));
    869 }
    870 
    871 
    872 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
    873                                         const AttributeList &Attr) {
    874   ASTContext &CurrContext = S.getASTContext();
    875   QualType ThisType = MD->getThisType(CurrContext)->getPointeeType();
    876 
    877   if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
    878     if (!RD->hasAttr<ConsumableAttr>()) {
    879       S.Diag(Attr.getLoc(), diag::warn_attr_on_unconsumable_class) <<
    880         RD->getNameAsString();
    881 
    882       return false;
    883     }
    884   }
    885 
    886   return true;
    887 }
    888 
    889 
    890 static void handleCallableWhenAttr(Sema &S, Decl *D,
    891                                    const AttributeList &Attr) {
    892   if (!checkAttributeAtLeastNumArgs(S, Attr, 1))
    893     return;
    894 
    895   if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
    896     return;
    897 
    898   SmallVector<CallableWhenAttr::ConsumedState, 3> States;
    899   for (unsigned ArgIndex = 0; ArgIndex < Attr.getNumArgs(); ++ArgIndex) {
    900     CallableWhenAttr::ConsumedState CallableState;
    901 
    902     StringRef StateString;
    903     SourceLocation Loc;
    904     if (Attr.isArgIdent(ArgIndex)) {
    905       IdentifierLoc *Ident = Attr.getArgAsIdent(ArgIndex);
    906       StateString = Ident->Ident->getName();
    907       Loc = Ident->Loc;
    908     } else {
    909       if (!S.checkStringLiteralArgumentAttr(Attr, ArgIndex, StateString, &Loc))
    910         return;
    911     }
    912 
    913     if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
    914                                                      CallableState)) {
    915       S.Diag(Loc, diag::warn_attribute_type_not_supported)
    916         << Attr.getName() << StateString;
    917       return;
    918     }
    919 
    920     States.push_back(CallableState);
    921   }
    922 
    923   D->addAttr(::new (S.Context)
    924              CallableWhenAttr(Attr.getRange(), S.Context, States.data(),
    925                States.size(), Attr.getAttributeSpellingListIndex()));
    926 }
    927 
    928 
    929 static void handleParamTypestateAttr(Sema &S, Decl *D,
    930                                     const AttributeList &Attr) {
    931   ParamTypestateAttr::ConsumedState ParamState;
    932 
    933   if (Attr.isArgIdent(0)) {
    934     IdentifierLoc *Ident = Attr.getArgAsIdent(0);
    935     StringRef StateString = Ident->Ident->getName();
    936 
    937     if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
    938                                                        ParamState)) {
    939       S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
    940         << Attr.getName() << StateString;
    941       return;
    942     }
    943   } else {
    944     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
    945       Attr.getName() << AANT_ArgumentIdentifier;
    946     return;
    947   }
    948 
    949   // FIXME: This check is currently being done in the analysis.  It can be
    950   //        enabled here only after the parser propagates attributes at
    951   //        template specialization definition, not declaration.
    952   //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
    953   //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
    954   //
    955   //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
    956   //    S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
    957   //      ReturnType.getAsString();
    958   //    return;
    959   //}
    960 
    961   D->addAttr(::new (S.Context)
    962              ParamTypestateAttr(Attr.getRange(), S.Context, ParamState,
    963                                 Attr.getAttributeSpellingListIndex()));
    964 }
    965 
    966 
    967 static void handleReturnTypestateAttr(Sema &S, Decl *D,
    968                                       const AttributeList &Attr) {
    969   ReturnTypestateAttr::ConsumedState ReturnState;
    970 
    971   if (Attr.isArgIdent(0)) {
    972     IdentifierLoc *IL = Attr.getArgAsIdent(0);
    973     if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
    974                                                         ReturnState)) {
    975       S.Diag(IL->Loc, diag::warn_attribute_type_not_supported)
    976         << Attr.getName() << IL->Ident;
    977       return;
    978     }
    979   } else {
    980     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
    981       Attr.getName() << AANT_ArgumentIdentifier;
    982     return;
    983   }
    984 
    985   // FIXME: This check is currently being done in the analysis.  It can be
    986   //        enabled here only after the parser propagates attributes at
    987   //        template specialization definition, not declaration.
    988   //QualType ReturnType;
    989   //
    990   //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
    991   //  ReturnType = Param->getType();
    992   //
    993   //} else if (const CXXConstructorDecl *Constructor =
    994   //             dyn_cast<CXXConstructorDecl>(D)) {
    995   //  ReturnType = Constructor->getThisType(S.getASTContext())->getPointeeType();
    996   //
    997   //} else {
    998   //
    999   //  ReturnType = cast<FunctionDecl>(D)->getCallResultType();
   1000   //}
   1001   //
   1002   //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
   1003   //
   1004   //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
   1005   //    S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
   1006   //      ReturnType.getAsString();
   1007   //    return;
   1008   //}
   1009 
   1010   D->addAttr(::new (S.Context)
   1011              ReturnTypestateAttr(Attr.getRange(), S.Context, ReturnState,
   1012                                  Attr.getAttributeSpellingListIndex()));
   1013 }
   1014 
   1015 
   1016 static void handleSetTypestateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   1017   if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
   1018     return;
   1019 
   1020   SetTypestateAttr::ConsumedState NewState;
   1021   if (Attr.isArgIdent(0)) {
   1022     IdentifierLoc *Ident = Attr.getArgAsIdent(0);
   1023     StringRef Param = Ident->Ident->getName();
   1024     if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
   1025       S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
   1026         << Attr.getName() << Param;
   1027       return;
   1028     }
   1029   } else {
   1030     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
   1031       Attr.getName() << AANT_ArgumentIdentifier;
   1032     return;
   1033   }
   1034 
   1035   D->addAttr(::new (S.Context)
   1036              SetTypestateAttr(Attr.getRange(), S.Context, NewState,
   1037                               Attr.getAttributeSpellingListIndex()));
   1038 }
   1039 
   1040 static void handleTestTypestateAttr(Sema &S, Decl *D,
   1041                                     const AttributeList &Attr) {
   1042   if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), Attr))
   1043     return;
   1044 
   1045   TestTypestateAttr::ConsumedState TestState;
   1046   if (Attr.isArgIdent(0)) {
   1047     IdentifierLoc *Ident = Attr.getArgAsIdent(0);
   1048     StringRef Param = Ident->Ident->getName();
   1049     if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
   1050       S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
   1051         << Attr.getName() << Param;
   1052       return;
   1053     }
   1054   } else {
   1055     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) <<
   1056       Attr.getName() << AANT_ArgumentIdentifier;
   1057     return;
   1058   }
   1059 
   1060   D->addAttr(::new (S.Context)
   1061              TestTypestateAttr(Attr.getRange(), S.Context, TestState,
   1062                                 Attr.getAttributeSpellingListIndex()));
   1063 }
   1064 
   1065 static void handleExtVectorTypeAttr(Sema &S, Scope *scope, Decl *D,
   1066                                     const AttributeList &Attr) {
   1067   // Remember this typedef decl, we will need it later for diagnostics.
   1068   S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
   1069 }
   1070 
   1071 static void handlePackedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   1072   if (TagDecl *TD = dyn_cast<TagDecl>(D))
   1073     TD->addAttr(::new (S.Context) PackedAttr(Attr.getRange(), S.Context,
   1074                                         Attr.getAttributeSpellingListIndex()));
   1075   else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
   1076     // Report warning about changed offset in the newer compiler versions.
   1077     if (!FD->getType()->isDependentType() &&
   1078         !FD->getType()->isIncompleteType() && FD->isBitField() &&
   1079         S.Context.getTypeAlign(FD->getType()) <= 8)
   1080       S.Diag(Attr.getLoc(), diag::warn_attribute_packed_for_bitfield);
   1081 
   1082     FD->addAttr(::new (S.Context) PackedAttr(
   1083         Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
   1084   } else
   1085     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
   1086 }
   1087 
   1088 static bool checkIBOutletCommon(Sema &S, Decl *D, const AttributeList &Attr) {
   1089   // The IBOutlet/IBOutletCollection attributes only apply to instance
   1090   // variables or properties of Objective-C classes.  The outlet must also
   1091   // have an object reference type.
   1092   if (const ObjCIvarDecl *VD = dyn_cast<ObjCIvarDecl>(D)) {
   1093     if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
   1094       S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
   1095         << Attr.getName() << VD->getType() << 0;
   1096       return false;
   1097     }
   1098   }
   1099   else if (const ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
   1100     if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
   1101       S.Diag(Attr.getLoc(), diag::warn_iboutlet_object_type)
   1102         << Attr.getName() << PD->getType() << 1;
   1103       return false;
   1104     }
   1105   }
   1106   else {
   1107     S.Diag(Attr.getLoc(), diag::warn_attribute_iboutlet) << Attr.getName();
   1108     return false;
   1109   }
   1110 
   1111   return true;
   1112 }
   1113 
   1114 static void handleIBOutlet(Sema &S, Decl *D, const AttributeList &Attr) {
   1115   if (!checkIBOutletCommon(S, D, Attr))
   1116     return;
   1117 
   1118   D->addAttr(::new (S.Context)
   1119              IBOutletAttr(Attr.getRange(), S.Context,
   1120                           Attr.getAttributeSpellingListIndex()));
   1121 }
   1122 
   1123 static void handleIBOutletCollection(Sema &S, Decl *D,
   1124                                      const AttributeList &Attr) {
   1125 
   1126   // The iboutletcollection attribute can have zero or one arguments.
   1127   if (Attr.getNumArgs() > 1) {
   1128     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
   1129       << Attr.getName() << 1;
   1130     return;
   1131   }
   1132 
   1133   if (!checkIBOutletCommon(S, D, Attr))
   1134     return;
   1135 
   1136   ParsedType PT;
   1137 
   1138   if (Attr.hasParsedType())
   1139     PT = Attr.getTypeArg();
   1140   else {
   1141     PT = S.getTypeName(S.Context.Idents.get("NSObject"), Attr.getLoc(),
   1142                        S.getScopeForContext(D->getDeclContext()->getParent()));
   1143     if (!PT) {
   1144       S.Diag(Attr.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
   1145       return;
   1146     }
   1147   }
   1148 
   1149   TypeSourceInfo *QTLoc = nullptr;
   1150   QualType QT = S.GetTypeFromParser(PT, &QTLoc);
   1151   if (!QTLoc)
   1152     QTLoc = S.Context.getTrivialTypeSourceInfo(QT, Attr.getLoc());
   1153 
   1154   // Diagnose use of non-object type in iboutletcollection attribute.
   1155   // FIXME. Gnu attribute extension ignores use of builtin types in
   1156   // attributes. So, __attribute__((iboutletcollection(char))) will be
   1157   // treated as __attribute__((iboutletcollection())).
   1158   if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
   1159     S.Diag(Attr.getLoc(),
   1160            QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
   1161                                : diag::err_iboutletcollection_type) << QT;
   1162     return;
   1163   }
   1164 
   1165   D->addAttr(::new (S.Context)
   1166              IBOutletCollectionAttr(Attr.getRange(), S.Context, QTLoc,
   1167                                     Attr.getAttributeSpellingListIndex()));
   1168 }
   1169 
   1170 bool Sema::isValidPointerAttrType(QualType T, bool RefOkay) {
   1171   if (RefOkay) {
   1172     if (T->isReferenceType())
   1173       return true;
   1174   } else {
   1175     T = T.getNonReferenceType();
   1176   }
   1177 
   1178   // The nonnull attribute, and other similar attributes, can be applied to a
   1179   // transparent union that contains a pointer type.
   1180   if (const RecordType *UT = T->getAsUnionType()) {
   1181     if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
   1182       RecordDecl *UD = UT->getDecl();
   1183       for (const auto *I : UD->fields()) {
   1184         QualType QT = I->getType();
   1185         if (QT->isAnyPointerType() || QT->isBlockPointerType())
   1186           return true;
   1187       }
   1188     }
   1189   }
   1190 
   1191   return T->isAnyPointerType() || T->isBlockPointerType();
   1192 }
   1193 
   1194 static bool attrNonNullArgCheck(Sema &S, QualType T, const AttributeList &Attr,
   1195                                 SourceRange AttrParmRange,
   1196                                 SourceRange TypeRange,
   1197                                 bool isReturnValue = false) {
   1198   if (!S.isValidPointerAttrType(T)) {
   1199     if (isReturnValue)
   1200       S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
   1201           << Attr.getName() << AttrParmRange << TypeRange;
   1202     else
   1203       S.Diag(Attr.getLoc(), diag::warn_attribute_pointers_only)
   1204           << Attr.getName() << AttrParmRange << TypeRange << 0;
   1205     return false;
   1206   }
   1207   return true;
   1208 }
   1209 
   1210 static void handleNonNullAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   1211   SmallVector<unsigned, 8> NonNullArgs;
   1212   for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
   1213     Expr *Ex = Attr.getArgAsExpr(I);
   1214     uint64_t Idx;
   1215     if (!checkFunctionOrMethodParameterIndex(S, D, Attr, I + 1, Ex, Idx))
   1216       return;
   1217 
   1218     // Is the function argument a pointer type?
   1219     if (Idx < getFunctionOrMethodNumParams(D) &&
   1220         !attrNonNullArgCheck(S, getFunctionOrMethodParamType(D, Idx), Attr,
   1221                              Ex->getSourceRange(),
   1222                              getFunctionOrMethodParamRange(D, Idx)))
   1223       continue;
   1224 
   1225     NonNullArgs.push_back(Idx);
   1226   }
   1227 
   1228   // If no arguments were specified to __attribute__((nonnull)) then all pointer
   1229   // arguments have a nonnull attribute; warn if there aren't any. Skip this
   1230   // check if the attribute came from a macro expansion or a template
   1231   // instantiation.
   1232   if (NonNullArgs.empty() && Attr.getLoc().isFileID() &&
   1233       S.ActiveTemplateInstantiations.empty()) {
   1234     bool AnyPointers = isFunctionOrMethodVariadic(D);
   1235     for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
   1236          I != E && !AnyPointers; ++I) {
   1237       QualType T = getFunctionOrMethodParamType(D, I);
   1238       if (T->isDependentType() || S.isValidPointerAttrType(T))
   1239         AnyPointers = true;
   1240     }
   1241 
   1242     if (!AnyPointers)
   1243       S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_no_pointers);
   1244   }
   1245 
   1246   unsigned *Start = NonNullArgs.data();
   1247   unsigned Size = NonNullArgs.size();
   1248   llvm::array_pod_sort(Start, Start + Size);
   1249   D->addAttr(::new (S.Context)
   1250              NonNullAttr(Attr.getRange(), S.Context, Start, Size,
   1251                          Attr.getAttributeSpellingListIndex()));
   1252 }
   1253 
   1254 static void handleNonNullAttrParameter(Sema &S, ParmVarDecl *D,
   1255                                        const AttributeList &Attr) {
   1256   if (Attr.getNumArgs() > 0) {
   1257     if (D->getFunctionType()) {
   1258       handleNonNullAttr(S, D, Attr);
   1259     } else {
   1260       S.Diag(Attr.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
   1261         << D->getSourceRange();
   1262     }
   1263     return;
   1264   }
   1265 
   1266   // Is the argument a pointer type?
   1267   if (!attrNonNullArgCheck(S, D->getType(), Attr, SourceRange(),
   1268                            D->getSourceRange()))
   1269     return;
   1270 
   1271   D->addAttr(::new (S.Context)
   1272              NonNullAttr(Attr.getRange(), S.Context, nullptr, 0,
   1273                          Attr.getAttributeSpellingListIndex()));
   1274 }
   1275 
   1276 static void handleReturnsNonNullAttr(Sema &S, Decl *D,
   1277                                      const AttributeList &Attr) {
   1278   QualType ResultType = getFunctionOrMethodResultType(D);
   1279   SourceRange SR = getFunctionOrMethodResultSourceRange(D);
   1280   if (!attrNonNullArgCheck(S, ResultType, Attr, SourceRange(), SR,
   1281                            /* isReturnValue */ true))
   1282     return;
   1283 
   1284   D->addAttr(::new (S.Context)
   1285             ReturnsNonNullAttr(Attr.getRange(), S.Context,
   1286                                Attr.getAttributeSpellingListIndex()));
   1287 }
   1288 
   1289 static void handleAssumeAlignedAttr(Sema &S, Decl *D,
   1290                                     const AttributeList &Attr) {
   1291   Expr *E = Attr.getArgAsExpr(0),
   1292        *OE = Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr;
   1293   S.AddAssumeAlignedAttr(Attr.getRange(), D, E, OE,
   1294                          Attr.getAttributeSpellingListIndex());
   1295 }
   1296 
   1297 void Sema::AddAssumeAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
   1298                                 Expr *OE, unsigned SpellingListIndex) {
   1299   QualType ResultType = getFunctionOrMethodResultType(D);
   1300   SourceRange SR = getFunctionOrMethodResultSourceRange(D);
   1301 
   1302   AssumeAlignedAttr TmpAttr(AttrRange, Context, E, OE, SpellingListIndex);
   1303   SourceLocation AttrLoc = AttrRange.getBegin();
   1304 
   1305   if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
   1306     Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
   1307       << &TmpAttr << AttrRange << SR;
   1308     return;
   1309   }
   1310 
   1311   if (!E->isValueDependent()) {
   1312     llvm::APSInt I(64);
   1313     if (!E->isIntegerConstantExpr(I, Context)) {
   1314       if (OE)
   1315         Diag(AttrLoc, diag::err_attribute_argument_n_type)
   1316           << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
   1317           << E->getSourceRange();
   1318       else
   1319         Diag(AttrLoc, diag::err_attribute_argument_type)
   1320           << &TmpAttr << AANT_ArgumentIntegerConstant
   1321           << E->getSourceRange();
   1322       return;
   1323     }
   1324 
   1325     if (!I.isPowerOf2()) {
   1326       Diag(AttrLoc, diag::err_alignment_not_power_of_two)
   1327         << E->getSourceRange();
   1328       return;
   1329     }
   1330   }
   1331 
   1332   if (OE) {
   1333     if (!OE->isValueDependent()) {
   1334       llvm::APSInt I(64);
   1335       if (!OE->isIntegerConstantExpr(I, Context)) {
   1336         Diag(AttrLoc, diag::err_attribute_argument_n_type)
   1337           << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
   1338           << OE->getSourceRange();
   1339         return;
   1340       }
   1341     }
   1342   }
   1343 
   1344   D->addAttr(::new (Context)
   1345             AssumeAlignedAttr(AttrRange, Context, E, OE, SpellingListIndex));
   1346 }
   1347 
   1348 /// Normalize the attribute, __foo__ becomes foo.
   1349 /// Returns true if normalization was applied.
   1350 static bool normalizeName(StringRef &AttrName) {
   1351   if (AttrName.size() > 4 && AttrName.startswith("__") &&
   1352       AttrName.endswith("__")) {
   1353     AttrName = AttrName.drop_front(2).drop_back(2);
   1354     return true;
   1355   }
   1356   return false;
   1357 }
   1358 
   1359 static void handleOwnershipAttr(Sema &S, Decl *D, const AttributeList &AL) {
   1360   // This attribute must be applied to a function declaration. The first
   1361   // argument to the attribute must be an identifier, the name of the resource,
   1362   // for example: malloc. The following arguments must be argument indexes, the
   1363   // arguments must be of integer type for Returns, otherwise of pointer type.
   1364   // The difference between Holds and Takes is that a pointer may still be used
   1365   // after being held. free() should be __attribute((ownership_takes)), whereas
   1366   // a list append function may well be __attribute((ownership_holds)).
   1367 
   1368   if (!AL.isArgIdent(0)) {
   1369     S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
   1370       << AL.getName() << 1 << AANT_ArgumentIdentifier;
   1371     return;
   1372   }
   1373 
   1374   // Figure out our Kind.
   1375   OwnershipAttr::OwnershipKind K =
   1376       OwnershipAttr(AL.getLoc(), S.Context, nullptr, nullptr, 0,
   1377                     AL.getAttributeSpellingListIndex()).getOwnKind();
   1378 
   1379   // Check arguments.
   1380   switch (K) {
   1381   case OwnershipAttr::Takes:
   1382   case OwnershipAttr::Holds:
   1383     if (AL.getNumArgs() < 2) {
   1384       S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments)
   1385         << AL.getName() << 2;
   1386       return;
   1387     }
   1388     break;
   1389   case OwnershipAttr::Returns:
   1390     if (AL.getNumArgs() > 2) {
   1391       S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments)
   1392         << AL.getName() << 1;
   1393       return;
   1394     }
   1395     break;
   1396   }
   1397 
   1398   IdentifierInfo *Module = AL.getArgAsIdent(0)->Ident;
   1399 
   1400   StringRef ModuleName = Module->getName();
   1401   if (normalizeName(ModuleName)) {
   1402     Module = &S.PP.getIdentifierTable().get(ModuleName);
   1403   }
   1404 
   1405   SmallVector<unsigned, 8> OwnershipArgs;
   1406   for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
   1407     Expr *Ex = AL.getArgAsExpr(i);
   1408     uint64_t Idx;
   1409     if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
   1410       return;
   1411 
   1412     // Is the function argument a pointer type?
   1413     QualType T = getFunctionOrMethodParamType(D, Idx);
   1414     int Err = -1;  // No error
   1415     switch (K) {
   1416       case OwnershipAttr::Takes:
   1417       case OwnershipAttr::Holds:
   1418         if (!T->isAnyPointerType() && !T->isBlockPointerType())
   1419           Err = 0;
   1420         break;
   1421       case OwnershipAttr::Returns:
   1422         if (!T->isIntegerType())
   1423           Err = 1;
   1424         break;
   1425     }
   1426     if (-1 != Err) {
   1427       S.Diag(AL.getLoc(), diag::err_ownership_type) << AL.getName() << Err
   1428         << Ex->getSourceRange();
   1429       return;
   1430     }
   1431 
   1432     // Check we don't have a conflict with another ownership attribute.
   1433     for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
   1434       // Cannot have two ownership attributes of different kinds for the same
   1435       // index.
   1436       if (I->getOwnKind() != K && I->args_end() !=
   1437           std::find(I->args_begin(), I->args_end(), Idx)) {
   1438         S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
   1439           << AL.getName() << I;
   1440         return;
   1441       } else if (K == OwnershipAttr::Returns &&
   1442                  I->getOwnKind() == OwnershipAttr::Returns) {
   1443         // A returns attribute conflicts with any other returns attribute using
   1444         // a different index. Note, diagnostic reporting is 1-based, but stored
   1445         // argument indexes are 0-based.
   1446         if (std::find(I->args_begin(), I->args_end(), Idx) == I->args_end()) {
   1447           S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
   1448               << *(I->args_begin()) + 1;
   1449           if (I->args_size())
   1450             S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
   1451                 << (unsigned)Idx + 1 << Ex->getSourceRange();
   1452           return;
   1453         }
   1454       }
   1455     }
   1456     OwnershipArgs.push_back(Idx);
   1457   }
   1458 
   1459   unsigned* start = OwnershipArgs.data();
   1460   unsigned size = OwnershipArgs.size();
   1461   llvm::array_pod_sort(start, start + size);
   1462 
   1463   D->addAttr(::new (S.Context)
   1464              OwnershipAttr(AL.getLoc(), S.Context, Module, start, size,
   1465                            AL.getAttributeSpellingListIndex()));
   1466 }
   1467 
   1468 static void handleWeakRefAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   1469   // Check the attribute arguments.
   1470   if (Attr.getNumArgs() > 1) {
   1471     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
   1472       << Attr.getName() << 1;
   1473     return;
   1474   }
   1475 
   1476   NamedDecl *nd = cast<NamedDecl>(D);
   1477 
   1478   // gcc rejects
   1479   // class c {
   1480   //   static int a __attribute__((weakref ("v2")));
   1481   //   static int b() __attribute__((weakref ("f3")));
   1482   // };
   1483   // and ignores the attributes of
   1484   // void f(void) {
   1485   //   static int a __attribute__((weakref ("v2")));
   1486   // }
   1487   // we reject them
   1488   const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
   1489   if (!Ctx->isFileContext()) {
   1490     S.Diag(Attr.getLoc(), diag::err_attribute_weakref_not_global_context)
   1491       << nd;
   1492     return;
   1493   }
   1494 
   1495   // The GCC manual says
   1496   //
   1497   // At present, a declaration to which `weakref' is attached can only
   1498   // be `static'.
   1499   //
   1500   // It also says
   1501   //
   1502   // Without a TARGET,
   1503   // given as an argument to `weakref' or to `alias', `weakref' is
   1504   // equivalent to `weak'.
   1505   //
   1506   // gcc 4.4.1 will accept
   1507   // int a7 __attribute__((weakref));
   1508   // as
   1509   // int a7 __attribute__((weak));
   1510   // This looks like a bug in gcc. We reject that for now. We should revisit
   1511   // it if this behaviour is actually used.
   1512 
   1513   // GCC rejects
   1514   // static ((alias ("y"), weakref)).
   1515   // Should we? How to check that weakref is before or after alias?
   1516 
   1517   // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
   1518   // of transforming it into an AliasAttr.  The WeakRefAttr never uses the
   1519   // StringRef parameter it was given anyway.
   1520   StringRef Str;
   1521   if (Attr.getNumArgs() && S.checkStringLiteralArgumentAttr(Attr, 0, Str))
   1522     // GCC will accept anything as the argument of weakref. Should we
   1523     // check for an existing decl?
   1524     D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
   1525                                         Attr.getAttributeSpellingListIndex()));
   1526 
   1527   D->addAttr(::new (S.Context)
   1528              WeakRefAttr(Attr.getRange(), S.Context,
   1529                          Attr.getAttributeSpellingListIndex()));
   1530 }
   1531 
   1532 static void handleAliasAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   1533   StringRef Str;
   1534   if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
   1535     return;
   1536 
   1537   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
   1538     S.Diag(Attr.getLoc(), diag::err_alias_not_supported_on_darwin);
   1539     return;
   1540   }
   1541 
   1542   // Aliases should be on declarations, not definitions.
   1543   if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
   1544     if (FD->isThisDeclarationADefinition()) {
   1545       S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << FD;
   1546       return;
   1547     }
   1548   } else {
   1549     const auto *VD = cast<VarDecl>(D);
   1550     if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
   1551       S.Diag(Attr.getLoc(), diag::err_alias_is_definition) << VD;
   1552       return;
   1553     }
   1554   }
   1555 
   1556   // FIXME: check if target symbol exists in current file
   1557 
   1558   D->addAttr(::new (S.Context) AliasAttr(Attr.getRange(), S.Context, Str,
   1559                                          Attr.getAttributeSpellingListIndex()));
   1560 }
   1561 
   1562 static void handleColdAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   1563   if (checkAttrMutualExclusion<HotAttr>(S, D, Attr.getRange(), Attr.getName()))
   1564     return;
   1565 
   1566   D->addAttr(::new (S.Context) ColdAttr(Attr.getRange(), S.Context,
   1567                                         Attr.getAttributeSpellingListIndex()));
   1568 }
   1569 
   1570 static void handleHotAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   1571   if (checkAttrMutualExclusion<ColdAttr>(S, D, Attr.getRange(), Attr.getName()))
   1572     return;
   1573 
   1574   D->addAttr(::new (S.Context) HotAttr(Attr.getRange(), S.Context,
   1575                                        Attr.getAttributeSpellingListIndex()));
   1576 }
   1577 
   1578 static void handleTLSModelAttr(Sema &S, Decl *D,
   1579                                const AttributeList &Attr) {
   1580   StringRef Model;
   1581   SourceLocation LiteralLoc;
   1582   // Check that it is a string.
   1583   if (!S.checkStringLiteralArgumentAttr(Attr, 0, Model, &LiteralLoc))
   1584     return;
   1585 
   1586   // Check that the value.
   1587   if (Model != "global-dynamic" && Model != "local-dynamic"
   1588       && Model != "initial-exec" && Model != "local-exec") {
   1589     S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
   1590     return;
   1591   }
   1592 
   1593   D->addAttr(::new (S.Context)
   1594              TLSModelAttr(Attr.getRange(), S.Context, Model,
   1595                           Attr.getAttributeSpellingListIndex()));
   1596 }
   1597 
   1598 static void handleKernelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   1599   if (!S.LangOpts.Renderscript) {
   1600     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
   1601     return;
   1602   }
   1603 
   1604   StringRef Kind;
   1605 
   1606   if (Attr.getNumArgs() == 1 &&
   1607       !S.checkStringLiteralArgumentAttr(Attr, 0, Kind)) {
   1608     return;
   1609   }
   1610 
   1611   D->addAttr(::new (S.Context)
   1612              KernelAttr(Attr.getRange(), S.Context, Kind,
   1613                         Attr.getAttributeSpellingListIndex()));
   1614 }
   1615 
   1616 static void handleRestrictAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   1617   QualType ResultType = getFunctionOrMethodResultType(D);
   1618   if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
   1619     D->addAttr(::new (S.Context) RestrictAttr(
   1620         Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
   1621     return;
   1622   }
   1623 
   1624   S.Diag(Attr.getLoc(), diag::warn_attribute_return_pointers_only)
   1625       << Attr.getName() << getFunctionOrMethodResultSourceRange(D);
   1626 }
   1627 
   1628 static void handleCommonAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   1629   if (S.LangOpts.CPlusPlus) {
   1630     S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
   1631         << Attr.getName() << AttributeLangSupport::Cpp;
   1632     return;
   1633   }
   1634 
   1635   if (CommonAttr *CA = S.mergeCommonAttr(D, Attr.getRange(), Attr.getName(),
   1636                                          Attr.getAttributeSpellingListIndex()))
   1637     D->addAttr(CA);
   1638 }
   1639 
   1640 static void handleNakedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   1641   if (checkAttrMutualExclusion<DisableTailCallsAttr>(S, D, Attr.getRange(),
   1642                                                      Attr.getName()))
   1643     return;
   1644 
   1645   D->addAttr(::new (S.Context) NakedAttr(Attr.getRange(), S.Context,
   1646                                          Attr.getAttributeSpellingListIndex()));
   1647 }
   1648 
   1649 static void handleNoReturnAttr(Sema &S, Decl *D, const AttributeList &attr) {
   1650   if (hasDeclarator(D)) return;
   1651 
   1652   if (S.CheckNoReturnAttr(attr)) return;
   1653 
   1654   if (!isa<ObjCMethodDecl>(D)) {
   1655     S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type)
   1656       << attr.getName() << ExpectedFunctionOrMethod;
   1657     return;
   1658   }
   1659 
   1660   D->addAttr(::new (S.Context)
   1661              NoReturnAttr(attr.getRange(), S.Context,
   1662                           attr.getAttributeSpellingListIndex()));
   1663 }
   1664 
   1665 bool Sema::CheckNoReturnAttr(const AttributeList &attr) {
   1666   if (!checkAttributeNumArgs(*this, attr, 0)) {
   1667     attr.setInvalid();
   1668     return true;
   1669   }
   1670 
   1671   return false;
   1672 }
   1673 
   1674 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D,
   1675                                        const AttributeList &Attr) {
   1676 
   1677   // The checking path for 'noreturn' and 'analyzer_noreturn' are different
   1678   // because 'analyzer_noreturn' does not impact the type.
   1679   if (!isFunctionOrMethodOrBlock(D)) {
   1680     ValueDecl *VD = dyn_cast<ValueDecl>(D);
   1681     if (!VD || (!VD->getType()->isBlockPointerType() &&
   1682                 !VD->getType()->isFunctionPointerType())) {
   1683       S.Diag(Attr.getLoc(),
   1684              Attr.isCXX11Attribute() ? diag::err_attribute_wrong_decl_type
   1685                                      : diag::warn_attribute_wrong_decl_type)
   1686         << Attr.getName() << ExpectedFunctionMethodOrBlock;
   1687       return;
   1688     }
   1689   }
   1690 
   1691   D->addAttr(::new (S.Context)
   1692              AnalyzerNoReturnAttr(Attr.getRange(), S.Context,
   1693                                   Attr.getAttributeSpellingListIndex()));
   1694 }
   1695 
   1696 // PS3 PPU-specific.
   1697 static void handleVecReturnAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   1698 /*
   1699   Returning a Vector Class in Registers
   1700 
   1701   According to the PPU ABI specifications, a class with a single member of
   1702   vector type is returned in memory when used as the return value of a function.
   1703   This results in inefficient code when implementing vector classes. To return
   1704   the value in a single vector register, add the vecreturn attribute to the
   1705   class definition. This attribute is also applicable to struct types.
   1706 
   1707   Example:
   1708 
   1709   struct Vector
   1710   {
   1711     __vector float xyzw;
   1712   } __attribute__((vecreturn));
   1713 
   1714   Vector Add(Vector lhs, Vector rhs)
   1715   {
   1716     Vector result;
   1717     result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
   1718     return result; // This will be returned in a register
   1719   }
   1720 */
   1721   if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
   1722     S.Diag(Attr.getLoc(), diag::err_repeat_attribute) << A;
   1723     return;
   1724   }
   1725 
   1726   RecordDecl *record = cast<RecordDecl>(D);
   1727   int count = 0;
   1728 
   1729   if (!isa<CXXRecordDecl>(record)) {
   1730     S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
   1731     return;
   1732   }
   1733 
   1734   if (!cast<CXXRecordDecl>(record)->isPOD()) {
   1735     S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
   1736     return;
   1737   }
   1738 
   1739   for (const auto *I : record->fields()) {
   1740     if ((count == 1) || !I->getType()->isVectorType()) {
   1741       S.Diag(Attr.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
   1742       return;
   1743     }
   1744     count++;
   1745   }
   1746 
   1747   D->addAttr(::new (S.Context)
   1748              VecReturnAttr(Attr.getRange(), S.Context,
   1749                            Attr.getAttributeSpellingListIndex()));
   1750 }
   1751 
   1752 static void handleDependencyAttr(Sema &S, Scope *Scope, Decl *D,
   1753                                  const AttributeList &Attr) {
   1754   if (isa<ParmVarDecl>(D)) {
   1755     // [[carries_dependency]] can only be applied to a parameter if it is a
   1756     // parameter of a function declaration or lambda.
   1757     if (!(Scope->getFlags() & clang::Scope::FunctionDeclarationScope)) {
   1758       S.Diag(Attr.getLoc(),
   1759              diag::err_carries_dependency_param_not_function_decl);
   1760       return;
   1761     }
   1762   }
   1763 
   1764   D->addAttr(::new (S.Context) CarriesDependencyAttr(
   1765                                    Attr.getRange(), S.Context,
   1766                                    Attr.getAttributeSpellingListIndex()));
   1767 }
   1768 
   1769 static void handleNotTailCalledAttr(Sema &S, Decl *D,
   1770                                     const AttributeList &Attr) {
   1771   if (checkAttrMutualExclusion<AlwaysInlineAttr>(S, D, Attr.getRange(),
   1772                                                  Attr.getName()))
   1773     return;
   1774 
   1775   D->addAttr(::new (S.Context) NotTailCalledAttr(
   1776       Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
   1777 }
   1778 
   1779 static void handleDisableTailCallsAttr(Sema &S, Decl *D,
   1780                                        const AttributeList &Attr) {
   1781   if (checkAttrMutualExclusion<NakedAttr>(S, D, Attr.getRange(),
   1782                                           Attr.getName()))
   1783     return;
   1784 
   1785   D->addAttr(::new (S.Context) DisableTailCallsAttr(
   1786       Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
   1787 }
   1788 
   1789 static void handleUsedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   1790   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
   1791     if (VD->hasLocalStorage()) {
   1792       S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
   1793       return;
   1794     }
   1795   } else if (!isFunctionOrMethod(D)) {
   1796     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
   1797       << Attr.getName() << ExpectedVariableOrFunction;
   1798     return;
   1799   }
   1800 
   1801   D->addAttr(::new (S.Context)
   1802              UsedAttr(Attr.getRange(), S.Context,
   1803                       Attr.getAttributeSpellingListIndex()));
   1804 }
   1805 
   1806 static void handleConstructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   1807   uint32_t priority = ConstructorAttr::DefaultPriority;
   1808   if (Attr.getNumArgs() &&
   1809       !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
   1810     return;
   1811 
   1812   D->addAttr(::new (S.Context)
   1813              ConstructorAttr(Attr.getRange(), S.Context, priority,
   1814                              Attr.getAttributeSpellingListIndex()));
   1815 }
   1816 
   1817 static void handleDestructorAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   1818   uint32_t priority = DestructorAttr::DefaultPriority;
   1819   if (Attr.getNumArgs() &&
   1820       !checkUInt32Argument(S, Attr, Attr.getArgAsExpr(0), priority))
   1821     return;
   1822 
   1823   D->addAttr(::new (S.Context)
   1824              DestructorAttr(Attr.getRange(), S.Context, priority,
   1825                             Attr.getAttributeSpellingListIndex()));
   1826 }
   1827 
   1828 template <typename AttrTy>
   1829 static void handleAttrWithMessage(Sema &S, Decl *D,
   1830                                   const AttributeList &Attr) {
   1831   // Handle the case where the attribute has a text message.
   1832   StringRef Str;
   1833   if (Attr.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(Attr, 0, Str))
   1834     return;
   1835 
   1836   D->addAttr(::new (S.Context) AttrTy(Attr.getRange(), S.Context, Str,
   1837                                       Attr.getAttributeSpellingListIndex()));
   1838 }
   1839 
   1840 static void handleObjCSuppresProtocolAttr(Sema &S, Decl *D,
   1841                                           const AttributeList &Attr) {
   1842   if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
   1843     S.Diag(Attr.getLoc(), diag::err_objc_attr_protocol_requires_definition)
   1844       << Attr.getName() << Attr.getRange();
   1845     return;
   1846   }
   1847 
   1848   D->addAttr(::new (S.Context)
   1849           ObjCExplicitProtocolImplAttr(Attr.getRange(), S.Context,
   1850                                        Attr.getAttributeSpellingListIndex()));
   1851 }
   1852 
   1853 static bool checkAvailabilityAttr(Sema &S, SourceRange Range,
   1854                                   IdentifierInfo *Platform,
   1855                                   VersionTuple Introduced,
   1856                                   VersionTuple Deprecated,
   1857                                   VersionTuple Obsoleted) {
   1858   StringRef PlatformName
   1859     = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
   1860   if (PlatformName.empty())
   1861     PlatformName = Platform->getName();
   1862 
   1863   // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
   1864   // of these steps are needed).
   1865   if (!Introduced.empty() && !Deprecated.empty() &&
   1866       !(Introduced <= Deprecated)) {
   1867     S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
   1868       << 1 << PlatformName << Deprecated.getAsString()
   1869       << 0 << Introduced.getAsString();
   1870     return true;
   1871   }
   1872 
   1873   if (!Introduced.empty() && !Obsoleted.empty() &&
   1874       !(Introduced <= Obsoleted)) {
   1875     S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
   1876       << 2 << PlatformName << Obsoleted.getAsString()
   1877       << 0 << Introduced.getAsString();
   1878     return true;
   1879   }
   1880 
   1881   if (!Deprecated.empty() && !Obsoleted.empty() &&
   1882       !(Deprecated <= Obsoleted)) {
   1883     S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
   1884       << 2 << PlatformName << Obsoleted.getAsString()
   1885       << 1 << Deprecated.getAsString();
   1886     return true;
   1887   }
   1888 
   1889   return false;
   1890 }
   1891 
   1892 /// \brief Check whether the two versions match.
   1893 ///
   1894 /// If either version tuple is empty, then they are assumed to match. If
   1895 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
   1896 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
   1897                           bool BeforeIsOkay) {
   1898   if (X.empty() || Y.empty())
   1899     return true;
   1900 
   1901   if (X == Y)
   1902     return true;
   1903 
   1904   if (BeforeIsOkay && X < Y)
   1905     return true;
   1906 
   1907   return false;
   1908 }
   1909 
   1910 AvailabilityAttr *Sema::mergeAvailabilityAttr(NamedDecl *D, SourceRange Range,
   1911                                               IdentifierInfo *Platform,
   1912                                               VersionTuple Introduced,
   1913                                               VersionTuple Deprecated,
   1914                                               VersionTuple Obsoleted,
   1915                                               bool IsUnavailable,
   1916                                               StringRef Message,
   1917                                               AvailabilityMergeKind AMK,
   1918                                               unsigned AttrSpellingListIndex) {
   1919   VersionTuple MergedIntroduced = Introduced;
   1920   VersionTuple MergedDeprecated = Deprecated;
   1921   VersionTuple MergedObsoleted = Obsoleted;
   1922   bool FoundAny = false;
   1923   bool OverrideOrImpl = false;
   1924   switch (AMK) {
   1925   case AMK_None:
   1926   case AMK_Redeclaration:
   1927     OverrideOrImpl = false;
   1928     break;
   1929 
   1930   case AMK_Override:
   1931   case AMK_ProtocolImplementation:
   1932     OverrideOrImpl = true;
   1933     break;
   1934   }
   1935 
   1936   if (D->hasAttrs()) {
   1937     AttrVec &Attrs = D->getAttrs();
   1938     for (unsigned i = 0, e = Attrs.size(); i != e;) {
   1939       const AvailabilityAttr *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
   1940       if (!OldAA) {
   1941         ++i;
   1942         continue;
   1943       }
   1944 
   1945       IdentifierInfo *OldPlatform = OldAA->getPlatform();
   1946       if (OldPlatform != Platform) {
   1947         ++i;
   1948         continue;
   1949       }
   1950 
   1951       // If there is an existing availability attribute for this platform that
   1952       // is explicit and the new one is implicit use the explicit one and
   1953       // discard the new implicit attribute.
   1954       if (OldAA->getRange().isValid() && Range.isInvalid()) {
   1955         return nullptr;
   1956       }
   1957 
   1958       // If there is an existing attribute for this platform that is implicit
   1959       // and the new attribute is explicit then erase the old one and
   1960       // continue processing the attributes.
   1961       if (Range.isValid() && OldAA->getRange().isInvalid()) {
   1962         Attrs.erase(Attrs.begin() + i);
   1963         --e;
   1964         continue;
   1965       }
   1966 
   1967       FoundAny = true;
   1968       VersionTuple OldIntroduced = OldAA->getIntroduced();
   1969       VersionTuple OldDeprecated = OldAA->getDeprecated();
   1970       VersionTuple OldObsoleted = OldAA->getObsoleted();
   1971       bool OldIsUnavailable = OldAA->getUnavailable();
   1972 
   1973       if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
   1974           !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
   1975           !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
   1976           !(OldIsUnavailable == IsUnavailable ||
   1977             (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
   1978         if (OverrideOrImpl) {
   1979           int Which = -1;
   1980           VersionTuple FirstVersion;
   1981           VersionTuple SecondVersion;
   1982           if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
   1983             Which = 0;
   1984             FirstVersion = OldIntroduced;
   1985             SecondVersion = Introduced;
   1986           } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
   1987             Which = 1;
   1988             FirstVersion = Deprecated;
   1989             SecondVersion = OldDeprecated;
   1990           } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
   1991             Which = 2;
   1992             FirstVersion = Obsoleted;
   1993             SecondVersion = OldObsoleted;
   1994           }
   1995 
   1996           if (Which == -1) {
   1997             Diag(OldAA->getLocation(),
   1998                  diag::warn_mismatched_availability_override_unavail)
   1999               << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
   2000               << (AMK == AMK_Override);
   2001           } else {
   2002             Diag(OldAA->getLocation(),
   2003                  diag::warn_mismatched_availability_override)
   2004               << Which
   2005               << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
   2006               << FirstVersion.getAsString() << SecondVersion.getAsString()
   2007               << (AMK == AMK_Override);
   2008           }
   2009           if (AMK == AMK_Override)
   2010             Diag(Range.getBegin(), diag::note_overridden_method);
   2011           else
   2012             Diag(Range.getBegin(), diag::note_protocol_method);
   2013         } else {
   2014           Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
   2015           Diag(Range.getBegin(), diag::note_previous_attribute);
   2016         }
   2017 
   2018         Attrs.erase(Attrs.begin() + i);
   2019         --e;
   2020         continue;
   2021       }
   2022 
   2023       VersionTuple MergedIntroduced2 = MergedIntroduced;
   2024       VersionTuple MergedDeprecated2 = MergedDeprecated;
   2025       VersionTuple MergedObsoleted2 = MergedObsoleted;
   2026 
   2027       if (MergedIntroduced2.empty())
   2028         MergedIntroduced2 = OldIntroduced;
   2029       if (MergedDeprecated2.empty())
   2030         MergedDeprecated2 = OldDeprecated;
   2031       if (MergedObsoleted2.empty())
   2032         MergedObsoleted2 = OldObsoleted;
   2033 
   2034       if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
   2035                                 MergedIntroduced2, MergedDeprecated2,
   2036                                 MergedObsoleted2)) {
   2037         Attrs.erase(Attrs.begin() + i);
   2038         --e;
   2039         continue;
   2040       }
   2041 
   2042       MergedIntroduced = MergedIntroduced2;
   2043       MergedDeprecated = MergedDeprecated2;
   2044       MergedObsoleted = MergedObsoleted2;
   2045       ++i;
   2046     }
   2047   }
   2048 
   2049   if (FoundAny &&
   2050       MergedIntroduced == Introduced &&
   2051       MergedDeprecated == Deprecated &&
   2052       MergedObsoleted == Obsoleted)
   2053     return nullptr;
   2054 
   2055   // Only create a new attribute if !OverrideOrImpl, but we want to do
   2056   // the checking.
   2057   if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
   2058                              MergedDeprecated, MergedObsoleted) &&
   2059       !OverrideOrImpl) {
   2060     return ::new (Context) AvailabilityAttr(Range, Context, Platform,
   2061                                             Introduced, Deprecated,
   2062                                             Obsoleted, IsUnavailable, Message,
   2063                                             AttrSpellingListIndex);
   2064   }
   2065   return nullptr;
   2066 }
   2067 
   2068 static void handleAvailabilityAttr(Sema &S, Decl *D,
   2069                                    const AttributeList &Attr) {
   2070   if (!checkAttributeNumArgs(S, Attr, 1))
   2071     return;
   2072   IdentifierLoc *Platform = Attr.getArgAsIdent(0);
   2073   unsigned Index = Attr.getAttributeSpellingListIndex();
   2074 
   2075   IdentifierInfo *II = Platform->Ident;
   2076   if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
   2077     S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
   2078       << Platform->Ident;
   2079 
   2080   NamedDecl *ND = dyn_cast<NamedDecl>(D);
   2081   if (!ND) {
   2082     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
   2083     return;
   2084   }
   2085 
   2086   AvailabilityChange Introduced = Attr.getAvailabilityIntroduced();
   2087   AvailabilityChange Deprecated = Attr.getAvailabilityDeprecated();
   2088   AvailabilityChange Obsoleted = Attr.getAvailabilityObsoleted();
   2089   bool IsUnavailable = Attr.getUnavailableLoc().isValid();
   2090   StringRef Str;
   2091   if (const StringLiteral *SE =
   2092           dyn_cast_or_null<StringLiteral>(Attr.getMessageExpr()))
   2093     Str = SE->getString();
   2094 
   2095   AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND, Attr.getRange(), II,
   2096                                                       Introduced.Version,
   2097                                                       Deprecated.Version,
   2098                                                       Obsoleted.Version,
   2099                                                       IsUnavailable, Str,
   2100                                                       Sema::AMK_None,
   2101                                                       Index);
   2102   if (NewAttr)
   2103     D->addAttr(NewAttr);
   2104 
   2105   // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
   2106   // matches before the start of the watchOS platform.
   2107   if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
   2108     IdentifierInfo *NewII = nullptr;
   2109     if (II->getName() == "ios")
   2110       NewII = &S.Context.Idents.get("watchos");
   2111     else if (II->getName() == "ios_app_extension")
   2112       NewII = &S.Context.Idents.get("watchos_app_extension");
   2113 
   2114     if (NewII) {
   2115         auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
   2116           if (Version.empty())
   2117             return Version;
   2118           auto Major = Version.getMajor();
   2119           auto NewMajor = Major >= 9 ? Major - 7 : 0;
   2120           if (NewMajor >= 2) {
   2121             if (Version.getMinor().hasValue()) {
   2122               if (Version.getSubminor().hasValue())
   2123                 return VersionTuple(NewMajor, Version.getMinor().getValue(),
   2124                                     Version.getSubminor().getValue());
   2125               else
   2126                 return VersionTuple(NewMajor, Version.getMinor().getValue());
   2127             }
   2128           }
   2129 
   2130           return VersionTuple(2, 0);
   2131         };
   2132 
   2133         auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
   2134         auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
   2135         auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
   2136 
   2137         AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
   2138                                                             SourceRange(),
   2139                                                             NewII,
   2140                                                             NewIntroduced,
   2141                                                             NewDeprecated,
   2142                                                             NewObsoleted,
   2143                                                             IsUnavailable, Str,
   2144                                                             Sema::AMK_None,
   2145                                                             Index);
   2146         if (NewAttr)
   2147           D->addAttr(NewAttr);
   2148       }
   2149   } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
   2150     // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
   2151     // matches before the start of the tvOS platform.
   2152     IdentifierInfo *NewII = nullptr;
   2153     if (II->getName() == "ios")
   2154       NewII = &S.Context.Idents.get("tvos");
   2155     else if (II->getName() == "ios_app_extension")
   2156       NewII = &S.Context.Idents.get("tvos_app_extension");
   2157 
   2158     if (NewII) {
   2159         AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(ND,
   2160                                                             SourceRange(),
   2161                                                             NewII,
   2162                                                             Introduced.Version,
   2163                                                             Deprecated.Version,
   2164                                                             Obsoleted.Version,
   2165                                                             IsUnavailable, Str,
   2166                                                             Sema::AMK_None,
   2167                                                             Index);
   2168         if (NewAttr)
   2169           D->addAttr(NewAttr);
   2170       }
   2171   }
   2172 }
   2173 
   2174 template <class T>
   2175 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
   2176                               typename T::VisibilityType value,
   2177                               unsigned attrSpellingListIndex) {
   2178   T *existingAttr = D->getAttr<T>();
   2179   if (existingAttr) {
   2180     typename T::VisibilityType existingValue = existingAttr->getVisibility();
   2181     if (existingValue == value)
   2182       return nullptr;
   2183     S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
   2184     S.Diag(range.getBegin(), diag::note_previous_attribute);
   2185     D->dropAttr<T>();
   2186   }
   2187   return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
   2188 }
   2189 
   2190 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
   2191                                           VisibilityAttr::VisibilityType Vis,
   2192                                           unsigned AttrSpellingListIndex) {
   2193   return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
   2194                                                AttrSpellingListIndex);
   2195 }
   2196 
   2197 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
   2198                                       TypeVisibilityAttr::VisibilityType Vis,
   2199                                       unsigned AttrSpellingListIndex) {
   2200   return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
   2201                                                    AttrSpellingListIndex);
   2202 }
   2203 
   2204 static void handleVisibilityAttr(Sema &S, Decl *D, const AttributeList &Attr,
   2205                                  bool isTypeVisibility) {
   2206   // Visibility attributes don't mean anything on a typedef.
   2207   if (isa<TypedefNameDecl>(D)) {
   2208     S.Diag(Attr.getRange().getBegin(), diag::warn_attribute_ignored)
   2209       << Attr.getName();
   2210     return;
   2211   }
   2212 
   2213   // 'type_visibility' can only go on a type or namespace.
   2214   if (isTypeVisibility &&
   2215       !(isa<TagDecl>(D) ||
   2216         isa<ObjCInterfaceDecl>(D) ||
   2217         isa<NamespaceDecl>(D))) {
   2218     S.Diag(Attr.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
   2219       << Attr.getName() << ExpectedTypeOrNamespace;
   2220     return;
   2221   }
   2222 
   2223   // Check that the argument is a string literal.
   2224   StringRef TypeStr;
   2225   SourceLocation LiteralLoc;
   2226   if (!S.checkStringLiteralArgumentAttr(Attr, 0, TypeStr, &LiteralLoc))
   2227     return;
   2228 
   2229   VisibilityAttr::VisibilityType type;
   2230   if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
   2231     S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported)
   2232       << Attr.getName() << TypeStr;
   2233     return;
   2234   }
   2235 
   2236   // Complain about attempts to use protected visibility on targets
   2237   // (like Darwin) that don't support it.
   2238   if (type == VisibilityAttr::Protected &&
   2239       !S.Context.getTargetInfo().hasProtectedVisibility()) {
   2240     S.Diag(Attr.getLoc(), diag::warn_attribute_protected_visibility);
   2241     type = VisibilityAttr::Default;
   2242   }
   2243 
   2244   unsigned Index = Attr.getAttributeSpellingListIndex();
   2245   clang::Attr *newAttr;
   2246   if (isTypeVisibility) {
   2247     newAttr = S.mergeTypeVisibilityAttr(D, Attr.getRange(),
   2248                                     (TypeVisibilityAttr::VisibilityType) type,
   2249                                         Index);
   2250   } else {
   2251     newAttr = S.mergeVisibilityAttr(D, Attr.getRange(), type, Index);
   2252   }
   2253   if (newAttr)
   2254     D->addAttr(newAttr);
   2255 }
   2256 
   2257 static void handleObjCMethodFamilyAttr(Sema &S, Decl *decl,
   2258                                        const AttributeList &Attr) {
   2259   ObjCMethodDecl *method = cast<ObjCMethodDecl>(decl);
   2260   if (!Attr.isArgIdent(0)) {
   2261     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
   2262       << Attr.getName() << 1 << AANT_ArgumentIdentifier;
   2263     return;
   2264   }
   2265 
   2266   IdentifierLoc *IL = Attr.getArgAsIdent(0);
   2267   ObjCMethodFamilyAttr::FamilyKind F;
   2268   if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
   2269     S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << Attr.getName()
   2270       << IL->Ident;
   2271     return;
   2272   }
   2273 
   2274   if (F == ObjCMethodFamilyAttr::OMF_init &&
   2275       !method->getReturnType()->isObjCObjectPointerType()) {
   2276     S.Diag(method->getLocation(), diag::err_init_method_bad_return_type)
   2277         << method->getReturnType();
   2278     // Ignore the attribute.
   2279     return;
   2280   }
   2281 
   2282   method->addAttr(new (S.Context) ObjCMethodFamilyAttr(Attr.getRange(),
   2283                                                        S.Context, F,
   2284                                         Attr.getAttributeSpellingListIndex()));
   2285 }
   2286 
   2287 static void handleObjCNSObject(Sema &S, Decl *D, const AttributeList &Attr) {
   2288   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
   2289     QualType T = TD->getUnderlyingType();
   2290     if (!T->isCARCBridgableType()) {
   2291       S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
   2292       return;
   2293     }
   2294   }
   2295   else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D)) {
   2296     QualType T = PD->getType();
   2297     if (!T->isCARCBridgableType()) {
   2298       S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
   2299       return;
   2300     }
   2301   }
   2302   else {
   2303     // It is okay to include this attribute on properties, e.g.:
   2304     //
   2305     //  @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
   2306     //
   2307     // In this case it follows tradition and suppresses an error in the above
   2308     // case.
   2309     S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
   2310   }
   2311   D->addAttr(::new (S.Context)
   2312              ObjCNSObjectAttr(Attr.getRange(), S.Context,
   2313                               Attr.getAttributeSpellingListIndex()));
   2314 }
   2315 
   2316 static void handleObjCIndependentClass(Sema &S, Decl *D, const AttributeList &Attr) {
   2317   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
   2318     QualType T = TD->getUnderlyingType();
   2319     if (!T->isObjCObjectPointerType()) {
   2320       S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
   2321       return;
   2322     }
   2323   } else {
   2324     S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
   2325     return;
   2326   }
   2327   D->addAttr(::new (S.Context)
   2328              ObjCIndependentClassAttr(Attr.getRange(), S.Context,
   2329                               Attr.getAttributeSpellingListIndex()));
   2330 }
   2331 
   2332 static void handleBlocksAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   2333   if (!Attr.isArgIdent(0)) {
   2334     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
   2335       << Attr.getName() << 1 << AANT_ArgumentIdentifier;
   2336     return;
   2337   }
   2338 
   2339   IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
   2340   BlocksAttr::BlockType type;
   2341   if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
   2342     S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
   2343       << Attr.getName() << II;
   2344     return;
   2345   }
   2346 
   2347   D->addAttr(::new (S.Context)
   2348              BlocksAttr(Attr.getRange(), S.Context, type,
   2349                         Attr.getAttributeSpellingListIndex()));
   2350 }
   2351 
   2352 static void handleSentinelAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   2353   unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
   2354   if (Attr.getNumArgs() > 0) {
   2355     Expr *E = Attr.getArgAsExpr(0);
   2356     llvm::APSInt Idx(32);
   2357     if (E->isTypeDependent() || E->isValueDependent() ||
   2358         !E->isIntegerConstantExpr(Idx, S.Context)) {
   2359       S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
   2360         << Attr.getName() << 1 << AANT_ArgumentIntegerConstant
   2361         << E->getSourceRange();
   2362       return;
   2363     }
   2364 
   2365     if (Idx.isSigned() && Idx.isNegative()) {
   2366       S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_less_than_zero)
   2367         << E->getSourceRange();
   2368       return;
   2369     }
   2370 
   2371     sentinel = Idx.getZExtValue();
   2372   }
   2373 
   2374   unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
   2375   if (Attr.getNumArgs() > 1) {
   2376     Expr *E = Attr.getArgAsExpr(1);
   2377     llvm::APSInt Idx(32);
   2378     if (E->isTypeDependent() || E->isValueDependent() ||
   2379         !E->isIntegerConstantExpr(Idx, S.Context)) {
   2380       S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
   2381         << Attr.getName() << 2 << AANT_ArgumentIntegerConstant
   2382         << E->getSourceRange();
   2383       return;
   2384     }
   2385     nullPos = Idx.getZExtValue();
   2386 
   2387     if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
   2388       // FIXME: This error message could be improved, it would be nice
   2389       // to say what the bounds actually are.
   2390       S.Diag(Attr.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
   2391         << E->getSourceRange();
   2392       return;
   2393     }
   2394   }
   2395 
   2396   if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
   2397     const FunctionType *FT = FD->getType()->castAs<FunctionType>();
   2398     if (isa<FunctionNoProtoType>(FT)) {
   2399       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_named_arguments);
   2400       return;
   2401     }
   2402 
   2403     if (!cast<FunctionProtoType>(FT)->isVariadic()) {
   2404       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
   2405       return;
   2406     }
   2407   } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
   2408     if (!MD->isVariadic()) {
   2409       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
   2410       return;
   2411     }
   2412   } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
   2413     if (!BD->isVariadic()) {
   2414       S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
   2415       return;
   2416     }
   2417   } else if (const VarDecl *V = dyn_cast<VarDecl>(D)) {
   2418     QualType Ty = V->getType();
   2419     if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
   2420       const FunctionType *FT = Ty->isFunctionPointerType()
   2421        ? D->getFunctionType()
   2422        : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
   2423       if (!cast<FunctionProtoType>(FT)->isVariadic()) {
   2424         int m = Ty->isFunctionPointerType() ? 0 : 1;
   2425         S.Diag(Attr.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
   2426         return;
   2427       }
   2428     } else {
   2429       S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
   2430         << Attr.getName() << ExpectedFunctionMethodOrBlock;
   2431       return;
   2432     }
   2433   } else {
   2434     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
   2435       << Attr.getName() << ExpectedFunctionMethodOrBlock;
   2436     return;
   2437   }
   2438   D->addAttr(::new (S.Context)
   2439              SentinelAttr(Attr.getRange(), S.Context, sentinel, nullPos,
   2440                           Attr.getAttributeSpellingListIndex()));
   2441 }
   2442 
   2443 static void handleWarnUnusedResult(Sema &S, Decl *D, const AttributeList &Attr) {
   2444   if (D->getFunctionType() &&
   2445       D->getFunctionType()->getReturnType()->isVoidType()) {
   2446     S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
   2447       << Attr.getName() << 0;
   2448     return;
   2449   }
   2450   if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
   2451     if (MD->getReturnType()->isVoidType()) {
   2452       S.Diag(Attr.getLoc(), diag::warn_attribute_void_function_method)
   2453       << Attr.getName() << 1;
   2454       return;
   2455     }
   2456 
   2457   D->addAttr(::new (S.Context)
   2458              WarnUnusedResultAttr(Attr.getRange(), S.Context,
   2459                                   Attr.getAttributeSpellingListIndex()));
   2460 }
   2461 
   2462 static void handleWeakImportAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   2463   // weak_import only applies to variable & function declarations.
   2464   bool isDef = false;
   2465   if (!D->canBeWeakImported(isDef)) {
   2466     if (isDef)
   2467       S.Diag(Attr.getLoc(), diag::warn_attribute_invalid_on_definition)
   2468         << "weak_import";
   2469     else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
   2470              (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
   2471               (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
   2472       // Nothing to warn about here.
   2473     } else
   2474       S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
   2475         << Attr.getName() << ExpectedVariableOrFunction;
   2476 
   2477     return;
   2478   }
   2479 
   2480   D->addAttr(::new (S.Context)
   2481              WeakImportAttr(Attr.getRange(), S.Context,
   2482                             Attr.getAttributeSpellingListIndex()));
   2483 }
   2484 
   2485 // Handles reqd_work_group_size and work_group_size_hint.
   2486 template <typename WorkGroupAttr>
   2487 static void handleWorkGroupSize(Sema &S, Decl *D,
   2488                                 const AttributeList &Attr) {
   2489   uint32_t WGSize[3];
   2490   for (unsigned i = 0; i < 3; ++i) {
   2491     const Expr *E = Attr.getArgAsExpr(i);
   2492     if (!checkUInt32Argument(S, Attr, E, WGSize[i], i))
   2493       return;
   2494     if (WGSize[i] == 0) {
   2495       S.Diag(Attr.getLoc(), diag::err_attribute_argument_is_zero)
   2496         << Attr.getName() << E->getSourceRange();
   2497       return;
   2498     }
   2499   }
   2500 
   2501   WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
   2502   if (Existing && !(Existing->getXDim() == WGSize[0] &&
   2503                     Existing->getYDim() == WGSize[1] &&
   2504                     Existing->getZDim() == WGSize[2]))
   2505     S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
   2506 
   2507   D->addAttr(::new (S.Context) WorkGroupAttr(Attr.getRange(), S.Context,
   2508                                              WGSize[0], WGSize[1], WGSize[2],
   2509                                        Attr.getAttributeSpellingListIndex()));
   2510 }
   2511 
   2512 static void handleVecTypeHint(Sema &S, Decl *D, const AttributeList &Attr) {
   2513   if (!Attr.hasParsedType()) {
   2514     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
   2515       << Attr.getName() << 1;
   2516     return;
   2517   }
   2518 
   2519   TypeSourceInfo *ParmTSI = nullptr;
   2520   QualType ParmType = S.GetTypeFromParser(Attr.getTypeArg(), &ParmTSI);
   2521   assert(ParmTSI && "no type source info for attribute argument");
   2522 
   2523   if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
   2524       (ParmType->isBooleanType() ||
   2525        !ParmType->isIntegralType(S.getASTContext()))) {
   2526     S.Diag(Attr.getLoc(), diag::err_attribute_argument_vec_type_hint)
   2527         << ParmType;
   2528     return;
   2529   }
   2530 
   2531   if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
   2532     if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
   2533       S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute) << Attr.getName();
   2534       return;
   2535     }
   2536   }
   2537 
   2538   D->addAttr(::new (S.Context) VecTypeHintAttr(Attr.getLoc(), S.Context,
   2539                                                ParmTSI,
   2540                                         Attr.getAttributeSpellingListIndex()));
   2541 }
   2542 
   2543 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
   2544                                     StringRef Name,
   2545                                     unsigned AttrSpellingListIndex) {
   2546   if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
   2547     if (ExistingAttr->getName() == Name)
   2548       return nullptr;
   2549     Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section);
   2550     Diag(Range.getBegin(), diag::note_previous_attribute);
   2551     return nullptr;
   2552   }
   2553   return ::new (Context) SectionAttr(Range, Context, Name,
   2554                                      AttrSpellingListIndex);
   2555 }
   2556 
   2557 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
   2558   std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
   2559   if (!Error.empty()) {
   2560     Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error;
   2561     return false;
   2562   }
   2563   return true;
   2564 }
   2565 
   2566 static void handleSectionAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   2567   // Make sure that there is a string literal as the sections's single
   2568   // argument.
   2569   StringRef Str;
   2570   SourceLocation LiteralLoc;
   2571   if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
   2572     return;
   2573 
   2574   if (!S.checkSectionName(LiteralLoc, Str))
   2575     return;
   2576 
   2577   // If the target wants to validate the section specifier, make it happen.
   2578   std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
   2579   if (!Error.empty()) {
   2580     S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
   2581     << Error;
   2582     return;
   2583   }
   2584 
   2585   unsigned Index = Attr.getAttributeSpellingListIndex();
   2586   SectionAttr *NewAttr = S.mergeSectionAttr(D, Attr.getRange(), Str, Index);
   2587   if (NewAttr)
   2588     D->addAttr(NewAttr);
   2589 }
   2590 
   2591 // Check for things we'd like to warn about, no errors or validation for now.
   2592 // TODO: Validation should use a backend target library that specifies
   2593 // the allowable subtarget features and cpus. We could use something like a
   2594 // TargetCodeGenInfo hook here to do validation.
   2595 void Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
   2596   for (auto Str : {"tune=", "fpmath="})
   2597     if (AttrStr.find(Str) != StringRef::npos)
   2598       Diag(LiteralLoc, diag::warn_unsupported_target_attribute) << Str;
   2599 }
   2600 
   2601 static void handleTargetAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   2602   StringRef Str;
   2603   SourceLocation LiteralLoc;
   2604   if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &LiteralLoc))
   2605     return;
   2606   S.checkTargetAttr(LiteralLoc, Str);
   2607   unsigned Index = Attr.getAttributeSpellingListIndex();
   2608   TargetAttr *NewAttr =
   2609       ::new (S.Context) TargetAttr(Attr.getRange(), S.Context, Str, Index);
   2610   D->addAttr(NewAttr);
   2611 }
   2612 
   2613 
   2614 static void handleCleanupAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   2615   VarDecl *VD = cast<VarDecl>(D);
   2616   if (!VD->hasLocalStorage()) {
   2617     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
   2618     return;
   2619   }
   2620 
   2621   Expr *E = Attr.getArgAsExpr(0);
   2622   SourceLocation Loc = E->getExprLoc();
   2623   FunctionDecl *FD = nullptr;
   2624   DeclarationNameInfo NI;
   2625 
   2626   // gcc only allows for simple identifiers. Since we support more than gcc, we
   2627   // will warn the user.
   2628   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
   2629     if (DRE->hasQualifier())
   2630       S.Diag(Loc, diag::warn_cleanup_ext);
   2631     FD = dyn_cast<FunctionDecl>(DRE->getDecl());
   2632     NI = DRE->getNameInfo();
   2633     if (!FD) {
   2634       S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
   2635         << NI.getName();
   2636       return;
   2637     }
   2638   } else if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
   2639     if (ULE->hasExplicitTemplateArgs())
   2640       S.Diag(Loc, diag::warn_cleanup_ext);
   2641     FD = S.ResolveSingleFunctionTemplateSpecialization(ULE, true);
   2642     NI = ULE->getNameInfo();
   2643     if (!FD) {
   2644       S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
   2645         << NI.getName();
   2646       if (ULE->getType() == S.Context.OverloadTy)
   2647         S.NoteAllOverloadCandidates(ULE);
   2648       return;
   2649     }
   2650   } else {
   2651     S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
   2652     return;
   2653   }
   2654 
   2655   if (FD->getNumParams() != 1) {
   2656     S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
   2657       << NI.getName();
   2658     return;
   2659   }
   2660 
   2661   // We're currently more strict than GCC about what function types we accept.
   2662   // If this ever proves to be a problem it should be easy to fix.
   2663   QualType Ty = S.Context.getPointerType(VD->getType());
   2664   QualType ParamTy = FD->getParamDecl(0)->getType();
   2665   if (S.CheckAssignmentConstraints(FD->getParamDecl(0)->getLocation(),
   2666                                    ParamTy, Ty) != Sema::Compatible) {
   2667     S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
   2668       << NI.getName() << ParamTy << Ty;
   2669     return;
   2670   }
   2671 
   2672   D->addAttr(::new (S.Context)
   2673              CleanupAttr(Attr.getRange(), S.Context, FD,
   2674                          Attr.getAttributeSpellingListIndex()));
   2675 }
   2676 
   2677 /// Handle __attribute__((format_arg((idx)))) attribute based on
   2678 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
   2679 static void handleFormatArgAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   2680   Expr *IdxExpr = Attr.getArgAsExpr(0);
   2681   uint64_t Idx;
   2682   if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 1, IdxExpr, Idx))
   2683     return;
   2684 
   2685   // Make sure the format string is really a string.
   2686   QualType Ty = getFunctionOrMethodParamType(D, Idx);
   2687 
   2688   bool NotNSStringTy = !isNSStringType(Ty, S.Context);
   2689   if (NotNSStringTy &&
   2690       !isCFStringType(Ty, S.Context) &&
   2691       (!Ty->isPointerType() ||
   2692        !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
   2693     S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
   2694         << "a string type" << IdxExpr->getSourceRange()
   2695         << getFunctionOrMethodParamRange(D, 0);
   2696     return;
   2697   }
   2698   Ty = getFunctionOrMethodResultType(D);
   2699   if (!isNSStringType(Ty, S.Context) &&
   2700       !isCFStringType(Ty, S.Context) &&
   2701       (!Ty->isPointerType() ||
   2702        !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
   2703     S.Diag(Attr.getLoc(), diag::err_format_attribute_result_not)
   2704         << (NotNSStringTy ? "string type" : "NSString")
   2705         << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
   2706     return;
   2707   }
   2708 
   2709   // We cannot use the Idx returned from checkFunctionOrMethodParameterIndex
   2710   // because that has corrected for the implicit this parameter, and is zero-
   2711   // based.  The attribute expects what the user wrote explicitly.
   2712   llvm::APSInt Val;
   2713   IdxExpr->EvaluateAsInt(Val, S.Context);
   2714 
   2715   D->addAttr(::new (S.Context)
   2716              FormatArgAttr(Attr.getRange(), S.Context, Val.getZExtValue(),
   2717                            Attr.getAttributeSpellingListIndex()));
   2718 }
   2719 
   2720 enum FormatAttrKind {
   2721   CFStringFormat,
   2722   NSStringFormat,
   2723   StrftimeFormat,
   2724   SupportedFormat,
   2725   IgnoredFormat,
   2726   InvalidFormat
   2727 };
   2728 
   2729 /// getFormatAttrKind - Map from format attribute names to supported format
   2730 /// types.
   2731 static FormatAttrKind getFormatAttrKind(StringRef Format) {
   2732   return llvm::StringSwitch<FormatAttrKind>(Format)
   2733     // Check for formats that get handled specially.
   2734     .Case("NSString", NSStringFormat)
   2735     .Case("CFString", CFStringFormat)
   2736     .Case("strftime", StrftimeFormat)
   2737 
   2738     // Otherwise, check for supported formats.
   2739     .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
   2740     .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
   2741     .Case("kprintf", SupportedFormat) // OpenBSD.
   2742     .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
   2743     .Case("os_trace", SupportedFormat)
   2744 
   2745     .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
   2746     .Default(InvalidFormat);
   2747 }
   2748 
   2749 /// Handle __attribute__((init_priority(priority))) attributes based on
   2750 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
   2751 static void handleInitPriorityAttr(Sema &S, Decl *D,
   2752                                    const AttributeList &Attr) {
   2753   if (!S.getLangOpts().CPlusPlus) {
   2754     S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) << Attr.getName();
   2755     return;
   2756   }
   2757 
   2758   if (S.getCurFunctionOrMethodDecl()) {
   2759     S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
   2760     Attr.setInvalid();
   2761     return;
   2762   }
   2763   QualType T = cast<VarDecl>(D)->getType();
   2764   if (S.Context.getAsArrayType(T))
   2765     T = S.Context.getBaseElementType(T);
   2766   if (!T->getAs<RecordType>()) {
   2767     S.Diag(Attr.getLoc(), diag::err_init_priority_object_attr);
   2768     Attr.setInvalid();
   2769     return;
   2770   }
   2771 
   2772   Expr *E = Attr.getArgAsExpr(0);
   2773   uint32_t prioritynum;
   2774   if (!checkUInt32Argument(S, Attr, E, prioritynum)) {
   2775     Attr.setInvalid();
   2776     return;
   2777   }
   2778 
   2779   if (prioritynum < 101 || prioritynum > 65535) {
   2780     S.Diag(Attr.getLoc(), diag::err_attribute_argument_outof_range)
   2781       << E->getSourceRange() << Attr.getName() << 101 << 65535;
   2782     Attr.setInvalid();
   2783     return;
   2784   }
   2785   D->addAttr(::new (S.Context)
   2786              InitPriorityAttr(Attr.getRange(), S.Context, prioritynum,
   2787                               Attr.getAttributeSpellingListIndex()));
   2788 }
   2789 
   2790 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
   2791                                   IdentifierInfo *Format, int FormatIdx,
   2792                                   int FirstArg,
   2793                                   unsigned AttrSpellingListIndex) {
   2794   // Check whether we already have an equivalent format attribute.
   2795   for (auto *F : D->specific_attrs<FormatAttr>()) {
   2796     if (F->getType() == Format &&
   2797         F->getFormatIdx() == FormatIdx &&
   2798         F->getFirstArg() == FirstArg) {
   2799       // If we don't have a valid location for this attribute, adopt the
   2800       // location.
   2801       if (F->getLocation().isInvalid())
   2802         F->setRange(Range);
   2803       return nullptr;
   2804     }
   2805   }
   2806 
   2807   return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
   2808                                     FirstArg, AttrSpellingListIndex);
   2809 }
   2810 
   2811 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
   2812 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
   2813 static void handleFormatAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   2814   if (!Attr.isArgIdent(0)) {
   2815     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
   2816       << Attr.getName() << 1 << AANT_ArgumentIdentifier;
   2817     return;
   2818   }
   2819 
   2820   // In C++ the implicit 'this' function parameter also counts, and they are
   2821   // counted from one.
   2822   bool HasImplicitThisParam = isInstanceMethod(D);
   2823   unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
   2824 
   2825   IdentifierInfo *II = Attr.getArgAsIdent(0)->Ident;
   2826   StringRef Format = II->getName();
   2827 
   2828   if (normalizeName(Format)) {
   2829     // If we've modified the string name, we need a new identifier for it.
   2830     II = &S.Context.Idents.get(Format);
   2831   }
   2832 
   2833   // Check for supported formats.
   2834   FormatAttrKind Kind = getFormatAttrKind(Format);
   2835 
   2836   if (Kind == IgnoredFormat)
   2837     return;
   2838 
   2839   if (Kind == InvalidFormat) {
   2840     S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
   2841       << Attr.getName() << II->getName();
   2842     return;
   2843   }
   2844 
   2845   // checks for the 2nd argument
   2846   Expr *IdxExpr = Attr.getArgAsExpr(1);
   2847   uint32_t Idx;
   2848   if (!checkUInt32Argument(S, Attr, IdxExpr, Idx, 2))
   2849     return;
   2850 
   2851   if (Idx < 1 || Idx > NumArgs) {
   2852     S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
   2853       << Attr.getName() << 2 << IdxExpr->getSourceRange();
   2854     return;
   2855   }
   2856 
   2857   // FIXME: Do we need to bounds check?
   2858   unsigned ArgIdx = Idx - 1;
   2859 
   2860   if (HasImplicitThisParam) {
   2861     if (ArgIdx == 0) {
   2862       S.Diag(Attr.getLoc(),
   2863              diag::err_format_attribute_implicit_this_format_string)
   2864         << IdxExpr->getSourceRange();
   2865       return;
   2866     }
   2867     ArgIdx--;
   2868   }
   2869 
   2870   // make sure the format string is really a string
   2871   QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
   2872 
   2873   if (Kind == CFStringFormat) {
   2874     if (!isCFStringType(Ty, S.Context)) {
   2875       S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
   2876         << "a CFString" << IdxExpr->getSourceRange()
   2877         << getFunctionOrMethodParamRange(D, ArgIdx);
   2878       return;
   2879     }
   2880   } else if (Kind == NSStringFormat) {
   2881     // FIXME: do we need to check if the type is NSString*?  What are the
   2882     // semantics?
   2883     if (!isNSStringType(Ty, S.Context)) {
   2884       S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
   2885         << "an NSString" << IdxExpr->getSourceRange()
   2886         << getFunctionOrMethodParamRange(D, ArgIdx);
   2887       return;
   2888     }
   2889   } else if (!Ty->isPointerType() ||
   2890              !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
   2891     S.Diag(Attr.getLoc(), diag::err_format_attribute_not)
   2892       << "a string type" << IdxExpr->getSourceRange()
   2893       << getFunctionOrMethodParamRange(D, ArgIdx);
   2894     return;
   2895   }
   2896 
   2897   // check the 3rd argument
   2898   Expr *FirstArgExpr = Attr.getArgAsExpr(2);
   2899   uint32_t FirstArg;
   2900   if (!checkUInt32Argument(S, Attr, FirstArgExpr, FirstArg, 3))
   2901     return;
   2902 
   2903   // check if the function is variadic if the 3rd argument non-zero
   2904   if (FirstArg != 0) {
   2905     if (isFunctionOrMethodVariadic(D)) {
   2906       ++NumArgs; // +1 for ...
   2907     } else {
   2908       S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
   2909       return;
   2910     }
   2911   }
   2912 
   2913   // strftime requires FirstArg to be 0 because it doesn't read from any
   2914   // variable the input is just the current time + the format string.
   2915   if (Kind == StrftimeFormat) {
   2916     if (FirstArg != 0) {
   2917       S.Diag(Attr.getLoc(), diag::err_format_strftime_third_parameter)
   2918         << FirstArgExpr->getSourceRange();
   2919       return;
   2920     }
   2921   // if 0 it disables parameter checking (to use with e.g. va_list)
   2922   } else if (FirstArg != 0 && FirstArg != NumArgs) {
   2923     S.Diag(Attr.getLoc(), diag::err_attribute_argument_out_of_bounds)
   2924       << Attr.getName() << 3 << FirstArgExpr->getSourceRange();
   2925     return;
   2926   }
   2927 
   2928   FormatAttr *NewAttr = S.mergeFormatAttr(D, Attr.getRange(), II,
   2929                                           Idx, FirstArg,
   2930                                           Attr.getAttributeSpellingListIndex());
   2931   if (NewAttr)
   2932     D->addAttr(NewAttr);
   2933 }
   2934 
   2935 static void handleTransparentUnionAttr(Sema &S, Decl *D,
   2936                                        const AttributeList &Attr) {
   2937   // Try to find the underlying union declaration.
   2938   RecordDecl *RD = nullptr;
   2939   TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D);
   2940   if (TD && TD->getUnderlyingType()->isUnionType())
   2941     RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
   2942   else
   2943     RD = dyn_cast<RecordDecl>(D);
   2944 
   2945   if (!RD || !RD->isUnion()) {
   2946     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
   2947       << Attr.getName() << ExpectedUnion;
   2948     return;
   2949   }
   2950 
   2951   if (!RD->isCompleteDefinition()) {
   2952     S.Diag(Attr.getLoc(),
   2953         diag::warn_transparent_union_attribute_not_definition);
   2954     return;
   2955   }
   2956 
   2957   RecordDecl::field_iterator Field = RD->field_begin(),
   2958                           FieldEnd = RD->field_end();
   2959   if (Field == FieldEnd) {
   2960     S.Diag(Attr.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
   2961     return;
   2962   }
   2963 
   2964   FieldDecl *FirstField = *Field;
   2965   QualType FirstType = FirstField->getType();
   2966   if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
   2967     S.Diag(FirstField->getLocation(),
   2968            diag::warn_transparent_union_attribute_floating)
   2969       << FirstType->isVectorType() << FirstType;
   2970     return;
   2971   }
   2972 
   2973   uint64_t FirstSize = S.Context.getTypeSize(FirstType);
   2974   uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
   2975   for (; Field != FieldEnd; ++Field) {
   2976     QualType FieldType = Field->getType();
   2977     // FIXME: this isn't fully correct; we also need to test whether the
   2978     // members of the union would all have the same calling convention as the
   2979     // first member of the union. Checking just the size and alignment isn't
   2980     // sufficient (consider structs passed on the stack instead of in registers
   2981     // as an example).
   2982     if (S.Context.getTypeSize(FieldType) != FirstSize ||
   2983         S.Context.getTypeAlign(FieldType) > FirstAlign) {
   2984       // Warn if we drop the attribute.
   2985       bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
   2986       unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
   2987                                  : S.Context.getTypeAlign(FieldType);
   2988       S.Diag(Field->getLocation(),
   2989           diag::warn_transparent_union_attribute_field_size_align)
   2990         << isSize << Field->getDeclName() << FieldBits;
   2991       unsigned FirstBits = isSize? FirstSize : FirstAlign;
   2992       S.Diag(FirstField->getLocation(),
   2993              diag::note_transparent_union_first_field_size_align)
   2994         << isSize << FirstBits;
   2995       return;
   2996     }
   2997   }
   2998 
   2999   RD->addAttr(::new (S.Context)
   3000               TransparentUnionAttr(Attr.getRange(), S.Context,
   3001                                    Attr.getAttributeSpellingListIndex()));
   3002 }
   3003 
   3004 static void handleAnnotateAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   3005   // Make sure that there is a string literal as the annotation's single
   3006   // argument.
   3007   StringRef Str;
   3008   if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str))
   3009     return;
   3010 
   3011   // Don't duplicate annotations that are already set.
   3012   for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
   3013     if (I->getAnnotation() == Str)
   3014       return;
   3015   }
   3016 
   3017   D->addAttr(::new (S.Context)
   3018              AnnotateAttr(Attr.getRange(), S.Context, Str,
   3019                           Attr.getAttributeSpellingListIndex()));
   3020 }
   3021 
   3022 static void handleAlignValueAttr(Sema &S, Decl *D,
   3023                                  const AttributeList &Attr) {
   3024   S.AddAlignValueAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
   3025                       Attr.getAttributeSpellingListIndex());
   3026 }
   3027 
   3028 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
   3029                              unsigned SpellingListIndex) {
   3030   AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
   3031   SourceLocation AttrLoc = AttrRange.getBegin();
   3032 
   3033   QualType T;
   3034   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
   3035     T = TD->getUnderlyingType();
   3036   else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
   3037     T = VD->getType();
   3038   else
   3039     llvm_unreachable("Unknown decl type for align_value");
   3040 
   3041   if (!T->isDependentType() && !T->isAnyPointerType() &&
   3042       !T->isReferenceType() && !T->isMemberPointerType()) {
   3043     Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
   3044       << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
   3045     return;
   3046   }
   3047 
   3048   if (!E->isValueDependent()) {
   3049     llvm::APSInt Alignment;
   3050     ExprResult ICE
   3051       = VerifyIntegerConstantExpression(E, &Alignment,
   3052           diag::err_align_value_attribute_argument_not_int,
   3053             /*AllowFold*/ false);
   3054     if (ICE.isInvalid())
   3055       return;
   3056 
   3057     if (!Alignment.isPowerOf2()) {
   3058       Diag(AttrLoc, diag::err_alignment_not_power_of_two)
   3059         << E->getSourceRange();
   3060       return;
   3061     }
   3062 
   3063     D->addAttr(::new (Context)
   3064                AlignValueAttr(AttrRange, Context, ICE.get(),
   3065                SpellingListIndex));
   3066     return;
   3067   }
   3068 
   3069   // Save dependent expressions in the AST to be instantiated.
   3070   D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
   3071   return;
   3072 }
   3073 
   3074 static void handleAlignedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   3075   // check the attribute arguments.
   3076   if (Attr.getNumArgs() > 1) {
   3077     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
   3078       << Attr.getName() << 1;
   3079     return;
   3080   }
   3081 
   3082   if (Attr.getNumArgs() == 0) {
   3083     D->addAttr(::new (S.Context) AlignedAttr(Attr.getRange(), S.Context,
   3084                true, nullptr, Attr.getAttributeSpellingListIndex()));
   3085     return;
   3086   }
   3087 
   3088   Expr *E = Attr.getArgAsExpr(0);
   3089   if (Attr.isPackExpansion() && !E->containsUnexpandedParameterPack()) {
   3090     S.Diag(Attr.getEllipsisLoc(),
   3091            diag::err_pack_expansion_without_parameter_packs);
   3092     return;
   3093   }
   3094 
   3095   if (!Attr.isPackExpansion() && S.DiagnoseUnexpandedParameterPack(E))
   3096     return;
   3097 
   3098   if (E->isValueDependent()) {
   3099     if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
   3100       if (!TND->getUnderlyingType()->isDependentType()) {
   3101         S.Diag(Attr.getLoc(), diag::err_alignment_dependent_typedef_name)
   3102             << E->getSourceRange();
   3103         return;
   3104       }
   3105     }
   3106   }
   3107 
   3108   S.AddAlignedAttr(Attr.getRange(), D, E, Attr.getAttributeSpellingListIndex(),
   3109                    Attr.isPackExpansion());
   3110 }
   3111 
   3112 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
   3113                           unsigned SpellingListIndex, bool IsPackExpansion) {
   3114   AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
   3115   SourceLocation AttrLoc = AttrRange.getBegin();
   3116 
   3117   // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
   3118   if (TmpAttr.isAlignas()) {
   3119     // C++11 [dcl.align]p1:
   3120     //   An alignment-specifier may be applied to a variable or to a class
   3121     //   data member, but it shall not be applied to a bit-field, a function
   3122     //   parameter, the formal parameter of a catch clause, or a variable
   3123     //   declared with the register storage class specifier. An
   3124     //   alignment-specifier may also be applied to the declaration of a class
   3125     //   or enumeration type.
   3126     // C11 6.7.5/2:
   3127     //   An alignment attribute shall not be specified in a declaration of
   3128     //   a typedef, or a bit-field, or a function, or a parameter, or an
   3129     //   object declared with the register storage-class specifier.
   3130     int DiagKind = -1;
   3131     if (isa<ParmVarDecl>(D)) {
   3132       DiagKind = 0;
   3133     } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
   3134       if (VD->getStorageClass() == SC_Register)
   3135         DiagKind = 1;
   3136       if (VD->isExceptionVariable())
   3137         DiagKind = 2;
   3138     } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
   3139       if (FD->isBitField())
   3140         DiagKind = 3;
   3141     } else if (!isa<TagDecl>(D)) {
   3142       Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
   3143         << (TmpAttr.isC11() ? ExpectedVariableOrField
   3144                             : ExpectedVariableFieldOrTag);
   3145       return;
   3146     }
   3147     if (DiagKind != -1) {
   3148       Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
   3149         << &TmpAttr << DiagKind;
   3150       return;
   3151     }
   3152   }
   3153 
   3154   if (E->isTypeDependent() || E->isValueDependent()) {
   3155     // Save dependent expressions in the AST to be instantiated.
   3156     AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
   3157     AA->setPackExpansion(IsPackExpansion);
   3158     D->addAttr(AA);
   3159     return;
   3160   }
   3161 
   3162   // FIXME: Cache the number on the Attr object?
   3163   llvm::APSInt Alignment;
   3164   ExprResult ICE
   3165     = VerifyIntegerConstantExpression(E, &Alignment,
   3166         diag::err_aligned_attribute_argument_not_int,
   3167         /*AllowFold*/ false);
   3168   if (ICE.isInvalid())
   3169     return;
   3170 
   3171   uint64_t AlignVal = Alignment.getZExtValue();
   3172 
   3173   // C++11 [dcl.align]p2:
   3174   //   -- if the constant expression evaluates to zero, the alignment
   3175   //      specifier shall have no effect
   3176   // C11 6.7.5p6:
   3177   //   An alignment specification of zero has no effect.
   3178   if (!(TmpAttr.isAlignas() && !Alignment)) {
   3179     if (!llvm::isPowerOf2_64(AlignVal)) {
   3180       Diag(AttrLoc, diag::err_alignment_not_power_of_two)
   3181         << E->getSourceRange();
   3182       return;
   3183     }
   3184   }
   3185 
   3186   // Alignment calculations can wrap around if it's greater than 2**28.
   3187   unsigned MaxValidAlignment =
   3188       Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
   3189                                                               : 268435456;
   3190   if (AlignVal > MaxValidAlignment) {
   3191     Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
   3192                                                          << E->getSourceRange();
   3193     return;
   3194   }
   3195 
   3196   if (Context.getTargetInfo().isTLSSupported()) {
   3197     unsigned MaxTLSAlign =
   3198         Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
   3199             .getQuantity();
   3200     auto *VD = dyn_cast<VarDecl>(D);
   3201     if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
   3202         VD->getTLSKind() != VarDecl::TLS_None) {
   3203       Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
   3204           << (unsigned)AlignVal << VD << MaxTLSAlign;
   3205       return;
   3206     }
   3207   }
   3208 
   3209   AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
   3210                                                 ICE.get(), SpellingListIndex);
   3211   AA->setPackExpansion(IsPackExpansion);
   3212   D->addAttr(AA);
   3213 }
   3214 
   3215 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
   3216                           unsigned SpellingListIndex, bool IsPackExpansion) {
   3217   // FIXME: Cache the number on the Attr object if non-dependent?
   3218   // FIXME: Perform checking of type validity
   3219   AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
   3220                                                 SpellingListIndex);
   3221   AA->setPackExpansion(IsPackExpansion);
   3222   D->addAttr(AA);
   3223 }
   3224 
   3225 void Sema::CheckAlignasUnderalignment(Decl *D) {
   3226   assert(D->hasAttrs() && "no attributes on decl");
   3227 
   3228   QualType UnderlyingTy, DiagTy;
   3229   if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
   3230     UnderlyingTy = DiagTy = VD->getType();
   3231   } else {
   3232     UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
   3233     if (EnumDecl *ED = dyn_cast<EnumDecl>(D))
   3234       UnderlyingTy = ED->getIntegerType();
   3235   }
   3236   if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
   3237     return;
   3238 
   3239   // C++11 [dcl.align]p5, C11 6.7.5/4:
   3240   //   The combined effect of all alignment attributes in a declaration shall
   3241   //   not specify an alignment that is less strict than the alignment that
   3242   //   would otherwise be required for the entity being declared.
   3243   AlignedAttr *AlignasAttr = nullptr;
   3244   unsigned Align = 0;
   3245   for (auto *I : D->specific_attrs<AlignedAttr>()) {
   3246     if (I->isAlignmentDependent())
   3247       return;
   3248     if (I->isAlignas())
   3249       AlignasAttr = I;
   3250     Align = std::max(Align, I->getAlignment(Context));
   3251   }
   3252 
   3253   if (AlignasAttr && Align) {
   3254     CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
   3255     CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
   3256     if (NaturalAlign > RequestedAlign)
   3257       Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
   3258         << DiagTy << (unsigned)NaturalAlign.getQuantity();
   3259   }
   3260 }
   3261 
   3262 bool Sema::checkMSInheritanceAttrOnDefinition(
   3263     CXXRecordDecl *RD, SourceRange Range, bool BestCase,
   3264     MSInheritanceAttr::Spelling SemanticSpelling) {
   3265   assert(RD->hasDefinition() && "RD has no definition!");
   3266 
   3267   // We may not have seen base specifiers or any virtual methods yet.  We will
   3268   // have to wait until the record is defined to catch any mismatches.
   3269   if (!RD->getDefinition()->isCompleteDefinition())
   3270     return false;
   3271 
   3272   // The unspecified model never matches what a definition could need.
   3273   if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
   3274     return false;
   3275 
   3276   if (BestCase) {
   3277     if (RD->calculateInheritanceModel() == SemanticSpelling)
   3278       return false;
   3279   } else {
   3280     if (RD->calculateInheritanceModel() <= SemanticSpelling)
   3281       return false;
   3282   }
   3283 
   3284   Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
   3285       << 0 /*definition*/;
   3286   Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
   3287       << RD->getNameAsString();
   3288   return true;
   3289 }
   3290 
   3291 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
   3292 /// attribute.
   3293 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
   3294                              bool &IntegerMode, bool &ComplexMode) {
   3295   switch (Str.size()) {
   3296   case 2:
   3297     switch (Str[0]) {
   3298     case 'Q':
   3299       DestWidth = 8;
   3300       break;
   3301     case 'H':
   3302       DestWidth = 16;
   3303       break;
   3304     case 'S':
   3305       DestWidth = 32;
   3306       break;
   3307     case 'D':
   3308       DestWidth = 64;
   3309       break;
   3310     case 'X':
   3311       DestWidth = 96;
   3312       break;
   3313     case 'T':
   3314       DestWidth = 128;
   3315       break;
   3316     }
   3317     if (Str[1] == 'F') {
   3318       IntegerMode = false;
   3319     } else if (Str[1] == 'C') {
   3320       IntegerMode = false;
   3321       ComplexMode = true;
   3322     } else if (Str[1] != 'I') {
   3323       DestWidth = 0;
   3324     }
   3325     break;
   3326   case 4:
   3327     // FIXME: glibc uses 'word' to define register_t; this is narrower than a
   3328     // pointer on PIC16 and other embedded platforms.
   3329     if (Str == "word")
   3330       DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
   3331     else if (Str == "byte")
   3332       DestWidth = S.Context.getTargetInfo().getCharWidth();
   3333     break;
   3334   case 7:
   3335     if (Str == "pointer")
   3336       DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
   3337     break;
   3338   case 11:
   3339     if (Str == "unwind_word")
   3340       DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
   3341     break;
   3342   }
   3343 }
   3344 
   3345 /// handleModeAttr - This attribute modifies the width of a decl with primitive
   3346 /// type.
   3347 ///
   3348 /// Despite what would be logical, the mode attribute is a decl attribute, not a
   3349 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
   3350 /// HImode, not an intermediate pointer.
   3351 static void handleModeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   3352   // This attribute isn't documented, but glibc uses it.  It changes
   3353   // the width of an int or unsigned int to the specified size.
   3354   if (!Attr.isArgIdent(0)) {
   3355     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
   3356       << AANT_ArgumentIdentifier;
   3357     return;
   3358   }
   3359 
   3360   IdentifierInfo *Name = Attr.getArgAsIdent(0)->Ident;
   3361   StringRef Str = Name->getName();
   3362 
   3363   normalizeName(Str);
   3364 
   3365   unsigned DestWidth = 0;
   3366   bool IntegerMode = true;
   3367   bool ComplexMode = false;
   3368   llvm::APInt VectorSize(64, 0);
   3369   if (Str.size() >= 4 && Str[0] == 'V') {
   3370     // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
   3371     size_t StrSize = Str.size();
   3372     size_t VectorStringLength = 0;
   3373     while ((VectorStringLength + 1) < StrSize &&
   3374            isdigit(Str[VectorStringLength + 1]))
   3375       ++VectorStringLength;
   3376     if (VectorStringLength &&
   3377         !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
   3378         VectorSize.isPowerOf2()) {
   3379       parseModeAttrArg(S, Str.substr(VectorStringLength + 1), DestWidth,
   3380                        IntegerMode, ComplexMode);
   3381       S.Diag(Attr.getLoc(), diag::warn_vector_mode_deprecated);
   3382     } else {
   3383       VectorSize = 0;
   3384     }
   3385   }
   3386 
   3387   if (!VectorSize)
   3388     parseModeAttrArg(S, Str, DestWidth, IntegerMode, ComplexMode);
   3389 
   3390   QualType OldTy;
   3391   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
   3392     OldTy = TD->getUnderlyingType();
   3393   else if (ValueDecl *VD = dyn_cast<ValueDecl>(D))
   3394     OldTy = VD->getType();
   3395   else {
   3396     S.Diag(D->getLocation(), diag::err_attr_wrong_decl)
   3397       << Attr.getName() << Attr.getRange();
   3398     return;
   3399   }
   3400 
   3401   // Base type can also be a vector type (see PR17453).
   3402   // Distinguish between base type and base element type.
   3403   QualType OldElemTy = OldTy;
   3404   if (const VectorType *VT = OldTy->getAs<VectorType>())
   3405     OldElemTy = VT->getElementType();
   3406 
   3407   if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType())
   3408     S.Diag(Attr.getLoc(), diag::err_mode_not_primitive);
   3409   else if (IntegerMode) {
   3410     if (!OldElemTy->isIntegralOrEnumerationType())
   3411       S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
   3412   } else if (ComplexMode) {
   3413     if (!OldElemTy->isComplexType())
   3414       S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
   3415   } else {
   3416     if (!OldElemTy->isFloatingType())
   3417       S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
   3418   }
   3419 
   3420   // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
   3421   // and friends, at least with glibc.
   3422   // FIXME: Make sure floating-point mappings are accurate
   3423   // FIXME: Support XF and TF types
   3424   if (!DestWidth) {
   3425     S.Diag(Attr.getLoc(), diag::err_machine_mode) << 0 /*Unknown*/ << Name;
   3426     return;
   3427   }
   3428 
   3429   QualType NewElemTy;
   3430 
   3431   if (IntegerMode)
   3432     NewElemTy = S.Context.getIntTypeForBitwidth(
   3433         DestWidth, OldElemTy->isSignedIntegerType());
   3434   else
   3435     NewElemTy = S.Context.getRealTypeForBitwidth(DestWidth);
   3436 
   3437   if (NewElemTy.isNull()) {
   3438     S.Diag(Attr.getLoc(), diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
   3439     return;
   3440   }
   3441 
   3442   if (ComplexMode) {
   3443     NewElemTy = S.Context.getComplexType(NewElemTy);
   3444   }
   3445 
   3446   QualType NewTy = NewElemTy;
   3447   if (VectorSize.getBoolValue()) {
   3448     NewTy = S.Context.getVectorType(NewTy, VectorSize.getZExtValue(),
   3449                                     VectorType::GenericVector);
   3450   } else if (const VectorType *OldVT = OldTy->getAs<VectorType>()) {
   3451     // Complex machine mode does not support base vector types.
   3452     if (ComplexMode) {
   3453       S.Diag(Attr.getLoc(), diag::err_complex_mode_vector_type);
   3454       return;
   3455     }
   3456     unsigned NumElements = S.Context.getTypeSize(OldElemTy) *
   3457                            OldVT->getNumElements() /
   3458                            S.Context.getTypeSize(NewElemTy);
   3459     NewTy =
   3460         S.Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
   3461   }
   3462 
   3463   if (NewTy.isNull()) {
   3464     S.Diag(Attr.getLoc(), diag::err_mode_wrong_type);
   3465     return;
   3466   }
   3467 
   3468   // Install the new type.
   3469   if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D))
   3470     TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
   3471   else
   3472     cast<ValueDecl>(D)->setType(NewTy);
   3473 
   3474   D->addAttr(::new (S.Context)
   3475              ModeAttr(Attr.getRange(), S.Context, Name,
   3476                       Attr.getAttributeSpellingListIndex()));
   3477 }
   3478 
   3479 static void handleNoDebugAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   3480   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
   3481     if (!VD->hasGlobalStorage())
   3482       S.Diag(Attr.getLoc(),
   3483              diag::warn_attribute_requires_functions_or_static_globals)
   3484         << Attr.getName();
   3485   } else if (!isFunctionOrMethod(D)) {
   3486     S.Diag(Attr.getLoc(),
   3487            diag::warn_attribute_requires_functions_or_static_globals)
   3488       << Attr.getName();
   3489     return;
   3490   }
   3491 
   3492   D->addAttr(::new (S.Context)
   3493              NoDebugAttr(Attr.getRange(), S.Context,
   3494                          Attr.getAttributeSpellingListIndex()));
   3495 }
   3496 
   3497 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
   3498                                               IdentifierInfo *Ident,
   3499                                               unsigned AttrSpellingListIndex) {
   3500   if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
   3501     Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
   3502     Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
   3503     return nullptr;
   3504   }
   3505 
   3506   if (D->hasAttr<AlwaysInlineAttr>())
   3507     return nullptr;
   3508 
   3509   return ::new (Context) AlwaysInlineAttr(Range, Context,
   3510                                           AttrSpellingListIndex);
   3511 }
   3512 
   3513 CommonAttr *Sema::mergeCommonAttr(Decl *D, SourceRange Range,
   3514                                   IdentifierInfo *Ident,
   3515                                   unsigned AttrSpellingListIndex) {
   3516   if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, Range, Ident))
   3517     return nullptr;
   3518 
   3519   return ::new (Context) CommonAttr(Range, Context, AttrSpellingListIndex);
   3520 }
   3521 
   3522 InternalLinkageAttr *
   3523 Sema::mergeInternalLinkageAttr(Decl *D, SourceRange Range,
   3524                                IdentifierInfo *Ident,
   3525                                unsigned AttrSpellingListIndex) {
   3526   if (auto VD = dyn_cast<VarDecl>(D)) {
   3527     // Attribute applies to Var but not any subclass of it (like ParmVar,
   3528     // ImplicitParm or VarTemplateSpecialization).
   3529     if (VD->getKind() != Decl::Var) {
   3530       Diag(Range.getBegin(), diag::warn_attribute_wrong_decl_type)
   3531           << Ident << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
   3532                                                : ExpectedVariableOrFunction);
   3533       return nullptr;
   3534     }
   3535     // Attribute does not apply to non-static local variables.
   3536     if (VD->hasLocalStorage()) {
   3537       Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
   3538       return nullptr;
   3539     }
   3540   }
   3541 
   3542   if (checkAttrMutualExclusion<CommonAttr>(*this, D, Range, Ident))
   3543     return nullptr;
   3544 
   3545   return ::new (Context)
   3546       InternalLinkageAttr(Range, Context, AttrSpellingListIndex);
   3547 }
   3548 
   3549 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
   3550                                     unsigned AttrSpellingListIndex) {
   3551   if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
   3552     Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
   3553     Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
   3554     return nullptr;
   3555   }
   3556 
   3557   if (D->hasAttr<MinSizeAttr>())
   3558     return nullptr;
   3559 
   3560   return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
   3561 }
   3562 
   3563 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
   3564                                               unsigned AttrSpellingListIndex) {
   3565   if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
   3566     Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
   3567     Diag(Range.getBegin(), diag::note_conflicting_attribute);
   3568     D->dropAttr<AlwaysInlineAttr>();
   3569   }
   3570   if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
   3571     Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
   3572     Diag(Range.getBegin(), diag::note_conflicting_attribute);
   3573     D->dropAttr<MinSizeAttr>();
   3574   }
   3575 
   3576   if (D->hasAttr<OptimizeNoneAttr>())
   3577     return nullptr;
   3578 
   3579   return ::new (Context) OptimizeNoneAttr(Range, Context,
   3580                                           AttrSpellingListIndex);
   3581 }
   3582 
   3583 static void handleAlwaysInlineAttr(Sema &S, Decl *D,
   3584                                    const AttributeList &Attr) {
   3585   if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, Attr.getRange(),
   3586                                                   Attr.getName()))
   3587     return;
   3588 
   3589   if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
   3590           D, Attr.getRange(), Attr.getName(),
   3591           Attr.getAttributeSpellingListIndex()))
   3592     D->addAttr(Inline);
   3593 }
   3594 
   3595 static void handleMinSizeAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   3596   if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
   3597           D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
   3598     D->addAttr(MinSize);
   3599 }
   3600 
   3601 static void handleOptimizeNoneAttr(Sema &S, Decl *D,
   3602                                    const AttributeList &Attr) {
   3603   if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
   3604           D, Attr.getRange(), Attr.getAttributeSpellingListIndex()))
   3605     D->addAttr(Optnone);
   3606 }
   3607 
   3608 static void handleGlobalAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   3609   FunctionDecl *FD = cast<FunctionDecl>(D);
   3610   if (!FD->getReturnType()->isVoidType()) {
   3611     SourceRange RTRange = FD->getReturnTypeSourceRange();
   3612     S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
   3613         << FD->getType()
   3614         << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
   3615                               : FixItHint());
   3616     return;
   3617   }
   3618 
   3619   D->addAttr(::new (S.Context)
   3620               CUDAGlobalAttr(Attr.getRange(), S.Context,
   3621                              Attr.getAttributeSpellingListIndex()));
   3622 
   3623 }
   3624 
   3625 static void handleGNUInlineAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   3626   FunctionDecl *Fn = cast<FunctionDecl>(D);
   3627   if (!Fn->isInlineSpecified()) {
   3628     S.Diag(Attr.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
   3629     return;
   3630   }
   3631 
   3632   D->addAttr(::new (S.Context)
   3633              GNUInlineAttr(Attr.getRange(), S.Context,
   3634                            Attr.getAttributeSpellingListIndex()));
   3635 }
   3636 
   3637 static void handleCallConvAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   3638   if (hasDeclarator(D)) return;
   3639 
   3640   // Diagnostic is emitted elsewhere: here we store the (valid) Attr
   3641   // in the Decl node for syntactic reasoning, e.g., pretty-printing.
   3642   CallingConv CC;
   3643   if (S.CheckCallingConvAttr(Attr, CC, /*FD*/nullptr))
   3644     return;
   3645 
   3646   if (!isa<ObjCMethodDecl>(D)) {
   3647     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
   3648       << Attr.getName() << ExpectedFunctionOrMethod;
   3649     return;
   3650   }
   3651 
   3652   switch (Attr.getKind()) {
   3653   case AttributeList::AT_FastCall:
   3654     D->addAttr(::new (S.Context)
   3655                FastCallAttr(Attr.getRange(), S.Context,
   3656                             Attr.getAttributeSpellingListIndex()));
   3657     return;
   3658   case AttributeList::AT_StdCall:
   3659     D->addAttr(::new (S.Context)
   3660                StdCallAttr(Attr.getRange(), S.Context,
   3661                            Attr.getAttributeSpellingListIndex()));
   3662     return;
   3663   case AttributeList::AT_ThisCall:
   3664     D->addAttr(::new (S.Context)
   3665                ThisCallAttr(Attr.getRange(), S.Context,
   3666                             Attr.getAttributeSpellingListIndex()));
   3667     return;
   3668   case AttributeList::AT_CDecl:
   3669     D->addAttr(::new (S.Context)
   3670                CDeclAttr(Attr.getRange(), S.Context,
   3671                          Attr.getAttributeSpellingListIndex()));
   3672     return;
   3673   case AttributeList::AT_Pascal:
   3674     D->addAttr(::new (S.Context)
   3675                PascalAttr(Attr.getRange(), S.Context,
   3676                           Attr.getAttributeSpellingListIndex()));
   3677     return;
   3678   case AttributeList::AT_VectorCall:
   3679     D->addAttr(::new (S.Context)
   3680                VectorCallAttr(Attr.getRange(), S.Context,
   3681                               Attr.getAttributeSpellingListIndex()));
   3682     return;
   3683   case AttributeList::AT_MSABI:
   3684     D->addAttr(::new (S.Context)
   3685                MSABIAttr(Attr.getRange(), S.Context,
   3686                          Attr.getAttributeSpellingListIndex()));
   3687     return;
   3688   case AttributeList::AT_SysVABI:
   3689     D->addAttr(::new (S.Context)
   3690                SysVABIAttr(Attr.getRange(), S.Context,
   3691                            Attr.getAttributeSpellingListIndex()));
   3692     return;
   3693   case AttributeList::AT_Pcs: {
   3694     PcsAttr::PCSType PCS;
   3695     switch (CC) {
   3696     case CC_AAPCS:
   3697       PCS = PcsAttr::AAPCS;
   3698       break;
   3699     case CC_AAPCS_VFP:
   3700       PCS = PcsAttr::AAPCS_VFP;
   3701       break;
   3702     default:
   3703       llvm_unreachable("unexpected calling convention in pcs attribute");
   3704     }
   3705 
   3706     D->addAttr(::new (S.Context)
   3707                PcsAttr(Attr.getRange(), S.Context, PCS,
   3708                        Attr.getAttributeSpellingListIndex()));
   3709     return;
   3710   }
   3711   case AttributeList::AT_IntelOclBicc:
   3712     D->addAttr(::new (S.Context)
   3713                IntelOclBiccAttr(Attr.getRange(), S.Context,
   3714                                 Attr.getAttributeSpellingListIndex()));
   3715     return;
   3716 
   3717   default:
   3718     llvm_unreachable("unexpected attribute kind");
   3719   }
   3720 }
   3721 
   3722 bool Sema::CheckCallingConvAttr(const AttributeList &attr, CallingConv &CC,
   3723                                 const FunctionDecl *FD) {
   3724   if (attr.isInvalid())
   3725     return true;
   3726 
   3727   unsigned ReqArgs = attr.getKind() == AttributeList::AT_Pcs ? 1 : 0;
   3728   if (!checkAttributeNumArgs(*this, attr, ReqArgs)) {
   3729     attr.setInvalid();
   3730     return true;
   3731   }
   3732 
   3733   // TODO: diagnose uses of these conventions on the wrong target.
   3734   switch (attr.getKind()) {
   3735   case AttributeList::AT_CDecl: CC = CC_C; break;
   3736   case AttributeList::AT_FastCall: CC = CC_X86FastCall; break;
   3737   case AttributeList::AT_StdCall: CC = CC_X86StdCall; break;
   3738   case AttributeList::AT_ThisCall: CC = CC_X86ThisCall; break;
   3739   case AttributeList::AT_Pascal: CC = CC_X86Pascal; break;
   3740   case AttributeList::AT_VectorCall: CC = CC_X86VectorCall; break;
   3741   case AttributeList::AT_MSABI:
   3742     CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
   3743                                                              CC_X86_64Win64;
   3744     break;
   3745   case AttributeList::AT_SysVABI:
   3746     CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
   3747                                                              CC_C;
   3748     break;
   3749   case AttributeList::AT_Pcs: {
   3750     StringRef StrRef;
   3751     if (!checkStringLiteralArgumentAttr(attr, 0, StrRef)) {
   3752       attr.setInvalid();
   3753       return true;
   3754     }
   3755     if (StrRef == "aapcs") {
   3756       CC = CC_AAPCS;
   3757       break;
   3758     } else if (StrRef == "aapcs-vfp") {
   3759       CC = CC_AAPCS_VFP;
   3760       break;
   3761     }
   3762 
   3763     attr.setInvalid();
   3764     Diag(attr.getLoc(), diag::err_invalid_pcs);
   3765     return true;
   3766   }
   3767   case AttributeList::AT_IntelOclBicc: CC = CC_IntelOclBicc; break;
   3768   default: llvm_unreachable("unexpected attribute kind");
   3769   }
   3770 
   3771   const TargetInfo &TI = Context.getTargetInfo();
   3772   TargetInfo::CallingConvCheckResult A = TI.checkCallingConvention(CC);
   3773   if (A != TargetInfo::CCCR_OK) {
   3774     if (A == TargetInfo::CCCR_Warning)
   3775       Diag(attr.getLoc(), diag::warn_cconv_ignored) << attr.getName();
   3776 
   3777     // This convention is not valid for the target. Use the default function or
   3778     // method calling convention.
   3779     TargetInfo::CallingConvMethodType MT = TargetInfo::CCMT_Unknown;
   3780     if (FD)
   3781       MT = FD->isCXXInstanceMember() ? TargetInfo::CCMT_Member :
   3782                                     TargetInfo::CCMT_NonMember;
   3783     CC = TI.getDefaultCallingConv(MT);
   3784   }
   3785 
   3786   return false;
   3787 }
   3788 
   3789 /// Checks a regparm attribute, returning true if it is ill-formed and
   3790 /// otherwise setting numParams to the appropriate value.
   3791 bool Sema::CheckRegparmAttr(const AttributeList &Attr, unsigned &numParams) {
   3792   if (Attr.isInvalid())
   3793     return true;
   3794 
   3795   if (!checkAttributeNumArgs(*this, Attr, 1)) {
   3796     Attr.setInvalid();
   3797     return true;
   3798   }
   3799 
   3800   uint32_t NP;
   3801   Expr *NumParamsExpr = Attr.getArgAsExpr(0);
   3802   if (!checkUInt32Argument(*this, Attr, NumParamsExpr, NP)) {
   3803     Attr.setInvalid();
   3804     return true;
   3805   }
   3806 
   3807   if (Context.getTargetInfo().getRegParmMax() == 0) {
   3808     Diag(Attr.getLoc(), diag::err_attribute_regparm_wrong_platform)
   3809       << NumParamsExpr->getSourceRange();
   3810     Attr.setInvalid();
   3811     return true;
   3812   }
   3813 
   3814   numParams = NP;
   3815   if (numParams > Context.getTargetInfo().getRegParmMax()) {
   3816     Diag(Attr.getLoc(), diag::err_attribute_regparm_invalid_number)
   3817       << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
   3818     Attr.setInvalid();
   3819     return true;
   3820   }
   3821 
   3822   return false;
   3823 }
   3824 
   3825 // Checks whether an argument of launch_bounds attribute is acceptable
   3826 // May output an error.
   3827 static bool checkLaunchBoundsArgument(Sema &S, Expr *E,
   3828                                       const CUDALaunchBoundsAttr &Attr,
   3829                                       const unsigned Idx) {
   3830 
   3831   if (S.DiagnoseUnexpandedParameterPack(E))
   3832     return false;
   3833 
   3834   // Accept template arguments for now as they depend on something else.
   3835   // We'll get to check them when they eventually get instantiated.
   3836   if (E->isValueDependent())
   3837     return true;
   3838 
   3839   llvm::APSInt I(64);
   3840   if (!E->isIntegerConstantExpr(I, S.Context)) {
   3841     S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
   3842         << &Attr << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
   3843     return false;
   3844   }
   3845   // Make sure we can fit it in 32 bits.
   3846   if (!I.isIntN(32)) {
   3847     S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
   3848                                                      << 32 << /* Unsigned */ 1;
   3849     return false;
   3850   }
   3851   if (I < 0)
   3852     S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
   3853         << &Attr << Idx << E->getSourceRange();
   3854 
   3855   return true;
   3856 }
   3857 
   3858 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
   3859                                Expr *MinBlocks, unsigned SpellingListIndex) {
   3860   CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
   3861                                SpellingListIndex);
   3862 
   3863   if (!checkLaunchBoundsArgument(*this, MaxThreads, TmpAttr, 0))
   3864     return;
   3865 
   3866   if (MinBlocks && !checkLaunchBoundsArgument(*this, MinBlocks, TmpAttr, 1))
   3867     return;
   3868 
   3869   D->addAttr(::new (Context) CUDALaunchBoundsAttr(
   3870       AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
   3871 }
   3872 
   3873 static void handleLaunchBoundsAttr(Sema &S, Decl *D,
   3874                                    const AttributeList &Attr) {
   3875   if (!checkAttributeAtLeastNumArgs(S, Attr, 1) ||
   3876       !checkAttributeAtMostNumArgs(S, Attr, 2))
   3877     return;
   3878 
   3879   S.AddLaunchBoundsAttr(Attr.getRange(), D, Attr.getArgAsExpr(0),
   3880                         Attr.getNumArgs() > 1 ? Attr.getArgAsExpr(1) : nullptr,
   3881                         Attr.getAttributeSpellingListIndex());
   3882 }
   3883 
   3884 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
   3885                                           const AttributeList &Attr) {
   3886   if (!Attr.isArgIdent(0)) {
   3887     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
   3888       << Attr.getName() << /* arg num = */ 1 << AANT_ArgumentIdentifier;
   3889     return;
   3890   }
   3891 
   3892   if (!checkAttributeNumArgs(S, Attr, 3))
   3893     return;
   3894 
   3895   IdentifierInfo *ArgumentKind = Attr.getArgAsIdent(0)->Ident;
   3896 
   3897   if (!isFunctionOrMethod(D) || !hasFunctionProto(D)) {
   3898     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
   3899       << Attr.getName() << ExpectedFunctionOrMethod;
   3900     return;
   3901   }
   3902 
   3903   uint64_t ArgumentIdx;
   3904   if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 2, Attr.getArgAsExpr(1),
   3905                                            ArgumentIdx))
   3906     return;
   3907 
   3908   uint64_t TypeTagIdx;
   3909   if (!checkFunctionOrMethodParameterIndex(S, D, Attr, 3, Attr.getArgAsExpr(2),
   3910                                            TypeTagIdx))
   3911     return;
   3912 
   3913   bool IsPointer = (Attr.getName()->getName() == "pointer_with_type_tag");
   3914   if (IsPointer) {
   3915     // Ensure that buffer has a pointer type.
   3916     QualType BufferTy = getFunctionOrMethodParamType(D, ArgumentIdx);
   3917     if (!BufferTy->isPointerType()) {
   3918       S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
   3919         << Attr.getName() << 0;
   3920     }
   3921   }
   3922 
   3923   D->addAttr(::new (S.Context)
   3924              ArgumentWithTypeTagAttr(Attr.getRange(), S.Context, ArgumentKind,
   3925                                      ArgumentIdx, TypeTagIdx, IsPointer,
   3926                                      Attr.getAttributeSpellingListIndex()));
   3927 }
   3928 
   3929 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
   3930                                          const AttributeList &Attr) {
   3931   if (!Attr.isArgIdent(0)) {
   3932     S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_type)
   3933       << Attr.getName() << 1 << AANT_ArgumentIdentifier;
   3934     return;
   3935   }
   3936 
   3937   if (!checkAttributeNumArgs(S, Attr, 1))
   3938     return;
   3939 
   3940   if (!isa<VarDecl>(D)) {
   3941     S.Diag(Attr.getLoc(), diag::err_attribute_wrong_decl_type)
   3942       << Attr.getName() << ExpectedVariable;
   3943     return;
   3944   }
   3945 
   3946   IdentifierInfo *PointerKind = Attr.getArgAsIdent(0)->Ident;
   3947   TypeSourceInfo *MatchingCTypeLoc = nullptr;
   3948   S.GetTypeFromParser(Attr.getMatchingCType(), &MatchingCTypeLoc);
   3949   assert(MatchingCTypeLoc && "no type source info for attribute argument");
   3950 
   3951   D->addAttr(::new (S.Context)
   3952              TypeTagForDatatypeAttr(Attr.getRange(), S.Context, PointerKind,
   3953                                     MatchingCTypeLoc,
   3954                                     Attr.getLayoutCompatible(),
   3955                                     Attr.getMustBeNull(),
   3956                                     Attr.getAttributeSpellingListIndex()));
   3957 }
   3958 
   3959 //===----------------------------------------------------------------------===//
   3960 // Checker-specific attribute handlers.
   3961 //===----------------------------------------------------------------------===//
   3962 
   3963 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType type) {
   3964   return type->isDependentType() ||
   3965          type->isObjCRetainableType();
   3966 }
   3967 
   3968 static bool isValidSubjectOfNSAttribute(Sema &S, QualType type) {
   3969   return type->isDependentType() ||
   3970          type->isObjCObjectPointerType() ||
   3971          S.Context.isObjCNSObjectType(type);
   3972 }
   3973 static bool isValidSubjectOfCFAttribute(Sema &S, QualType type) {
   3974   return type->isDependentType() ||
   3975          type->isPointerType() ||
   3976          isValidSubjectOfNSAttribute(S, type);
   3977 }
   3978 
   3979 static void handleNSConsumedAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   3980   ParmVarDecl *param = cast<ParmVarDecl>(D);
   3981   bool typeOK, cf;
   3982 
   3983   if (Attr.getKind() == AttributeList::AT_NSConsumed) {
   3984     typeOK = isValidSubjectOfNSAttribute(S, param->getType());
   3985     cf = false;
   3986   } else {
   3987     typeOK = isValidSubjectOfCFAttribute(S, param->getType());
   3988     cf = true;
   3989   }
   3990 
   3991   if (!typeOK) {
   3992     S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
   3993       << Attr.getRange() << Attr.getName() << cf;
   3994     return;
   3995   }
   3996 
   3997   if (cf)
   3998     param->addAttr(::new (S.Context)
   3999                    CFConsumedAttr(Attr.getRange(), S.Context,
   4000                                   Attr.getAttributeSpellingListIndex()));
   4001   else
   4002     param->addAttr(::new (S.Context)
   4003                    NSConsumedAttr(Attr.getRange(), S.Context,
   4004                                   Attr.getAttributeSpellingListIndex()));
   4005 }
   4006 
   4007 static void handleNSReturnsRetainedAttr(Sema &S, Decl *D,
   4008                                         const AttributeList &Attr) {
   4009 
   4010   QualType returnType;
   4011 
   4012   if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D))
   4013     returnType = MD->getReturnType();
   4014   else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
   4015            (Attr.getKind() == AttributeList::AT_NSReturnsRetained))
   4016     return; // ignore: was handled as a type attribute
   4017   else if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(D))
   4018     returnType = PD->getType();
   4019   else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
   4020     returnType = FD->getReturnType();
   4021   else if (auto *Param = dyn_cast<ParmVarDecl>(D)) {
   4022     returnType = Param->getType()->getPointeeType();
   4023     if (returnType.isNull()) {
   4024       S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
   4025           << Attr.getName() << /*pointer-to-CF*/2
   4026           << Attr.getRange();
   4027       return;
   4028     }
   4029   } else {
   4030     AttributeDeclKind ExpectedDeclKind;
   4031     switch (Attr.getKind()) {
   4032     default: llvm_unreachable("invalid ownership attribute");
   4033     case AttributeList::AT_NSReturnsRetained:
   4034     case AttributeList::AT_NSReturnsAutoreleased:
   4035     case AttributeList::AT_NSReturnsNotRetained:
   4036       ExpectedDeclKind = ExpectedFunctionOrMethod;
   4037       break;
   4038 
   4039     case AttributeList::AT_CFReturnsRetained:
   4040     case AttributeList::AT_CFReturnsNotRetained:
   4041       ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
   4042       break;
   4043     }
   4044     S.Diag(D->getLocStart(), diag::warn_attribute_wrong_decl_type)
   4045         << Attr.getRange() << Attr.getName() << ExpectedDeclKind;
   4046     return;
   4047   }
   4048 
   4049   bool typeOK;
   4050   bool cf;
   4051   switch (Attr.getKind()) {
   4052   default: llvm_unreachable("invalid ownership attribute");
   4053   case AttributeList::AT_NSReturnsRetained:
   4054     typeOK = isValidSubjectOfNSReturnsRetainedAttribute(returnType);
   4055     cf = false;
   4056     break;
   4057 
   4058   case AttributeList::AT_NSReturnsAutoreleased:
   4059   case AttributeList::AT_NSReturnsNotRetained:
   4060     typeOK = isValidSubjectOfNSAttribute(S, returnType);
   4061     cf = false;
   4062     break;
   4063 
   4064   case AttributeList::AT_CFReturnsRetained:
   4065   case AttributeList::AT_CFReturnsNotRetained:
   4066     typeOK = isValidSubjectOfCFAttribute(S, returnType);
   4067     cf = true;
   4068     break;
   4069   }
   4070 
   4071   if (!typeOK) {
   4072     if (isa<ParmVarDecl>(D)) {
   4073       S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_parameter_type)
   4074           << Attr.getName() << /*pointer-to-CF*/2
   4075           << Attr.getRange();
   4076     } else {
   4077       // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
   4078       enum : unsigned {
   4079         Function,
   4080         Method,
   4081         Property
   4082       } SubjectKind = Function;
   4083       if (isa<ObjCMethodDecl>(D))
   4084         SubjectKind = Method;
   4085       else if (isa<ObjCPropertyDecl>(D))
   4086         SubjectKind = Property;
   4087       S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
   4088           << Attr.getName() << SubjectKind << cf
   4089           << Attr.getRange();
   4090     }
   4091     return;
   4092   }
   4093 
   4094   switch (Attr.getKind()) {
   4095     default:
   4096       llvm_unreachable("invalid ownership attribute");
   4097     case AttributeList::AT_NSReturnsAutoreleased:
   4098       D->addAttr(::new (S.Context) NSReturnsAutoreleasedAttr(
   4099           Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
   4100       return;
   4101     case AttributeList::AT_CFReturnsNotRetained:
   4102       D->addAttr(::new (S.Context) CFReturnsNotRetainedAttr(
   4103           Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
   4104       return;
   4105     case AttributeList::AT_NSReturnsNotRetained:
   4106       D->addAttr(::new (S.Context) NSReturnsNotRetainedAttr(
   4107           Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
   4108       return;
   4109     case AttributeList::AT_CFReturnsRetained:
   4110       D->addAttr(::new (S.Context) CFReturnsRetainedAttr(
   4111           Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
   4112       return;
   4113     case AttributeList::AT_NSReturnsRetained:
   4114       D->addAttr(::new (S.Context) NSReturnsRetainedAttr(
   4115           Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
   4116       return;
   4117   };
   4118 }
   4119 
   4120 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
   4121                                               const AttributeList &attr) {
   4122   const int EP_ObjCMethod = 1;
   4123   const int EP_ObjCProperty = 2;
   4124 
   4125   SourceLocation loc = attr.getLoc();
   4126   QualType resultType;
   4127   if (isa<ObjCMethodDecl>(D))
   4128     resultType = cast<ObjCMethodDecl>(D)->getReturnType();
   4129   else
   4130     resultType = cast<ObjCPropertyDecl>(D)->getType();
   4131 
   4132   if (!resultType->isReferenceType() &&
   4133       (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
   4134     S.Diag(D->getLocStart(), diag::warn_ns_attribute_wrong_return_type)
   4135       << SourceRange(loc)
   4136     << attr.getName()
   4137     << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
   4138     << /*non-retainable pointer*/ 2;
   4139 
   4140     // Drop the attribute.
   4141     return;
   4142   }
   4143 
   4144   D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
   4145       attr.getRange(), S.Context, attr.getAttributeSpellingListIndex()));
   4146 }
   4147 
   4148 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
   4149                                         const AttributeList &attr) {
   4150   ObjCMethodDecl *method = cast<ObjCMethodDecl>(D);
   4151 
   4152   DeclContext *DC = method->getDeclContext();
   4153   if (const ObjCProtocolDecl *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
   4154     S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
   4155     << attr.getName() << 0;
   4156     S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
   4157     return;
   4158   }
   4159   if (method->getMethodFamily() == OMF_dealloc) {
   4160     S.Diag(D->getLocStart(), diag::warn_objc_requires_super_protocol)
   4161     << attr.getName() << 1;
   4162     return;
   4163   }
   4164 
   4165   method->addAttr(::new (S.Context)
   4166                   ObjCRequiresSuperAttr(attr.getRange(), S.Context,
   4167                                         attr.getAttributeSpellingListIndex()));
   4168 }
   4169 
   4170 static void handleCFAuditedTransferAttr(Sema &S, Decl *D,
   4171                                         const AttributeList &Attr) {
   4172   if (checkAttrMutualExclusion<CFUnknownTransferAttr>(S, D, Attr.getRange(),
   4173                                                       Attr.getName()))
   4174     return;
   4175 
   4176   D->addAttr(::new (S.Context)
   4177              CFAuditedTransferAttr(Attr.getRange(), S.Context,
   4178                                    Attr.getAttributeSpellingListIndex()));
   4179 }
   4180 
   4181 static void handleCFUnknownTransferAttr(Sema &S, Decl *D,
   4182                                         const AttributeList &Attr) {
   4183   if (checkAttrMutualExclusion<CFAuditedTransferAttr>(S, D, Attr.getRange(),
   4184                                                       Attr.getName()))
   4185     return;
   4186 
   4187   D->addAttr(::new (S.Context)
   4188              CFUnknownTransferAttr(Attr.getRange(), S.Context,
   4189              Attr.getAttributeSpellingListIndex()));
   4190 }
   4191 
   4192 static void handleObjCBridgeAttr(Sema &S, Scope *Sc, Decl *D,
   4193                                 const AttributeList &Attr) {
   4194   IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
   4195 
   4196   if (!Parm) {
   4197     S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
   4198     return;
   4199   }
   4200 
   4201   // Typedefs only allow objc_bridge(id) and have some additional checking.
   4202   if (auto TD = dyn_cast<TypedefNameDecl>(D)) {
   4203     if (!Parm->Ident->isStr("id")) {
   4204       S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_id)
   4205         << Attr.getName();
   4206       return;
   4207     }
   4208 
   4209     // Only allow 'cv void *'.
   4210     QualType T = TD->getUnderlyingType();
   4211     if (!T->isVoidPointerType()) {
   4212       S.Diag(Attr.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
   4213       return;
   4214     }
   4215   }
   4216 
   4217   D->addAttr(::new (S.Context)
   4218              ObjCBridgeAttr(Attr.getRange(), S.Context, Parm->Ident,
   4219                            Attr.getAttributeSpellingListIndex()));
   4220 }
   4221 
   4222 static void handleObjCBridgeMutableAttr(Sema &S, Scope *Sc, Decl *D,
   4223                                         const AttributeList &Attr) {
   4224   IdentifierLoc * Parm = Attr.isArgIdent(0) ? Attr.getArgAsIdent(0) : nullptr;
   4225 
   4226   if (!Parm) {
   4227     S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
   4228     return;
   4229   }
   4230 
   4231   D->addAttr(::new (S.Context)
   4232              ObjCBridgeMutableAttr(Attr.getRange(), S.Context, Parm->Ident,
   4233                             Attr.getAttributeSpellingListIndex()));
   4234 }
   4235 
   4236 static void handleObjCBridgeRelatedAttr(Sema &S, Scope *Sc, Decl *D,
   4237                                  const AttributeList &Attr) {
   4238   IdentifierInfo *RelatedClass =
   4239     Attr.isArgIdent(0) ? Attr.getArgAsIdent(0)->Ident : nullptr;
   4240   if (!RelatedClass) {
   4241     S.Diag(D->getLocStart(), diag::err_objc_attr_not_id) << Attr.getName() << 0;
   4242     return;
   4243   }
   4244   IdentifierInfo *ClassMethod =
   4245     Attr.getArgAsIdent(1) ? Attr.getArgAsIdent(1)->Ident : nullptr;
   4246   IdentifierInfo *InstanceMethod =
   4247     Attr.getArgAsIdent(2) ? Attr.getArgAsIdent(2)->Ident : nullptr;
   4248   D->addAttr(::new (S.Context)
   4249              ObjCBridgeRelatedAttr(Attr.getRange(), S.Context, RelatedClass,
   4250                                    ClassMethod, InstanceMethod,
   4251                                    Attr.getAttributeSpellingListIndex()));
   4252 }
   4253 
   4254 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
   4255                                             const AttributeList &Attr) {
   4256   ObjCInterfaceDecl *IFace;
   4257   if (ObjCCategoryDecl *CatDecl =
   4258           dyn_cast<ObjCCategoryDecl>(D->getDeclContext()))
   4259     IFace = CatDecl->getClassInterface();
   4260   else
   4261     IFace = cast<ObjCInterfaceDecl>(D->getDeclContext());
   4262 
   4263   if (!IFace)
   4264     return;
   4265 
   4266   IFace->setHasDesignatedInitializers();
   4267   D->addAttr(::new (S.Context)
   4268                   ObjCDesignatedInitializerAttr(Attr.getRange(), S.Context,
   4269                                          Attr.getAttributeSpellingListIndex()));
   4270 }
   4271 
   4272 static void handleObjCRuntimeName(Sema &S, Decl *D,
   4273                                   const AttributeList &Attr) {
   4274   StringRef MetaDataName;
   4275   if (!S.checkStringLiteralArgumentAttr(Attr, 0, MetaDataName))
   4276     return;
   4277   D->addAttr(::new (S.Context)
   4278              ObjCRuntimeNameAttr(Attr.getRange(), S.Context,
   4279                                  MetaDataName,
   4280                                  Attr.getAttributeSpellingListIndex()));
   4281 }
   4282 
   4283 // when a user wants to use objc_boxable with a union or struct
   4284 // but she doesn't have access to the declaration (legacy/third-party code)
   4285 // then she can 'enable' this feature via trick with a typedef
   4286 // e.g.:
   4287 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
   4288 static void handleObjCBoxable(Sema &S, Decl *D, const AttributeList &Attr) {
   4289   bool notify = false;
   4290 
   4291   RecordDecl *RD = dyn_cast<RecordDecl>(D);
   4292   if (RD && RD->getDefinition()) {
   4293     RD = RD->getDefinition();
   4294     notify = true;
   4295   }
   4296 
   4297   if (RD) {
   4298     ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
   4299                           ObjCBoxableAttr(Attr.getRange(), S.Context,
   4300                                           Attr.getAttributeSpellingListIndex());
   4301     RD->addAttr(BoxableAttr);
   4302     if (notify) {
   4303       // we need to notify ASTReader/ASTWriter about
   4304       // modification of existing declaration
   4305       if (ASTMutationListener *L = S.getASTMutationListener())
   4306         L->AddedAttributeToRecord(BoxableAttr, RD);
   4307     }
   4308   }
   4309 }
   4310 
   4311 static void handleObjCOwnershipAttr(Sema &S, Decl *D,
   4312                                     const AttributeList &Attr) {
   4313   if (hasDeclarator(D)) return;
   4314 
   4315   S.Diag(D->getLocStart(), diag::err_attribute_wrong_decl_type)
   4316     << Attr.getRange() << Attr.getName() << ExpectedVariable;
   4317 }
   4318 
   4319 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
   4320                                           const AttributeList &Attr) {
   4321   ValueDecl *vd = cast<ValueDecl>(D);
   4322   QualType type = vd->getType();
   4323 
   4324   if (!type->isDependentType() &&
   4325       !type->isObjCLifetimeType()) {
   4326     S.Diag(Attr.getLoc(), diag::err_objc_precise_lifetime_bad_type)
   4327       << type;
   4328     return;
   4329   }
   4330 
   4331   Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
   4332 
   4333   // If we have no lifetime yet, check the lifetime we're presumably
   4334   // going to infer.
   4335   if (lifetime == Qualifiers::OCL_None && !type->isDependentType())
   4336     lifetime = type->getObjCARCImplicitLifetime();
   4337 
   4338   switch (lifetime) {
   4339   case Qualifiers::OCL_None:
   4340     assert(type->isDependentType() &&
   4341            "didn't infer lifetime for non-dependent type?");
   4342     break;
   4343 
   4344   case Qualifiers::OCL_Weak:   // meaningful
   4345   case Qualifiers::OCL_Strong: // meaningful
   4346     break;
   4347 
   4348   case Qualifiers::OCL_ExplicitNone:
   4349   case Qualifiers::OCL_Autoreleasing:
   4350     S.Diag(Attr.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
   4351       << (lifetime == Qualifiers::OCL_Autoreleasing);
   4352     break;
   4353   }
   4354 
   4355   D->addAttr(::new (S.Context)
   4356              ObjCPreciseLifetimeAttr(Attr.getRange(), S.Context,
   4357                                      Attr.getAttributeSpellingListIndex()));
   4358 }
   4359 
   4360 //===----------------------------------------------------------------------===//
   4361 // Microsoft specific attribute handlers.
   4362 //===----------------------------------------------------------------------===//
   4363 
   4364 static void handleUuidAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   4365   if (!S.LangOpts.CPlusPlus) {
   4366     S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
   4367       << Attr.getName() << AttributeLangSupport::C;
   4368     return;
   4369   }
   4370 
   4371   if (!isa<CXXRecordDecl>(D)) {
   4372     S.Diag(Attr.getLoc(), diag::warn_attribute_wrong_decl_type)
   4373       << Attr.getName() << ExpectedClass;
   4374     return;
   4375   }
   4376 
   4377   StringRef StrRef;
   4378   SourceLocation LiteralLoc;
   4379   if (!S.checkStringLiteralArgumentAttr(Attr, 0, StrRef, &LiteralLoc))
   4380     return;
   4381 
   4382   // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
   4383   // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
   4384   if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
   4385     StrRef = StrRef.drop_front().drop_back();
   4386 
   4387   // Validate GUID length.
   4388   if (StrRef.size() != 36) {
   4389     S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
   4390     return;
   4391   }
   4392 
   4393   for (unsigned i = 0; i < 36; ++i) {
   4394     if (i == 8 || i == 13 || i == 18 || i == 23) {
   4395       if (StrRef[i] != '-') {
   4396         S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
   4397         return;
   4398       }
   4399     } else if (!isHexDigit(StrRef[i])) {
   4400       S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
   4401       return;
   4402     }
   4403   }
   4404 
   4405   D->addAttr(::new (S.Context) UuidAttr(Attr.getRange(), S.Context, StrRef,
   4406                                         Attr.getAttributeSpellingListIndex()));
   4407 }
   4408 
   4409 static void handleMSInheritanceAttr(Sema &S, Decl *D, const AttributeList &Attr) {
   4410   if (!S.LangOpts.CPlusPlus) {
   4411     S.Diag(Attr.getLoc(), diag::err_attribute_not_supported_in_lang)
   4412       << Attr.getName() << AttributeLangSupport::C;
   4413     return;
   4414   }
   4415   MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
   4416       D, Attr.getRange(), /*BestCase=*/true,
   4417       Attr.getAttributeSpellingListIndex(),
   4418       (MSInheritanceAttr::Spelling)Attr.getSemanticSpelling());
   4419   if (IA)
   4420     D->addAttr(IA);
   4421 }
   4422 
   4423 static void handleDeclspecThreadAttr(Sema &S, Decl *D,
   4424                                      const AttributeList &Attr) {
   4425   VarDecl *VD = cast<VarDecl>(D);
   4426   if (!S.Context.getTargetInfo().isTLSSupported()) {
   4427     S.Diag(Attr.getLoc(), diag::err_thread_unsupported);
   4428     return;
   4429   }
   4430   if (VD->getTSCSpec() != TSCS_unspecified) {
   4431     S.Diag(Attr.getLoc(), diag::err_declspec_thread_on_thread_variable);
   4432     return;
   4433   }
   4434   if (VD->hasLocalStorage()) {
   4435     S.Diag(Attr.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
   4436     return;
   4437   }
   4438   VD->addAttr(::new (S.Context) ThreadAttr(
   4439       Attr.getRange(), S.Context, Attr.getAttributeSpellingListIndex()));
   4440 }
   4441 
   4442 static void handleARMInterruptAttr(Sema &S, Decl *D,
   4443                                    const AttributeList &Attr) {
   4444   // Check the attribute arguments.
   4445   if (Attr.getNumArgs() > 1) {
   4446     S.Diag(Attr.getLoc(), diag::err_attribute_too_many_arguments)
   4447       << Attr.getName() << 1;
   4448     return;
   4449   }
   4450 
   4451   StringRef Str;
   4452   SourceLocation ArgLoc;
   4453 
   4454   if (Attr.getNumArgs() == 0)
   4455     Str = "";
   4456   else if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
   4457     return;
   4458 
   4459   ARMInterruptAttr::InterruptType Kind;
   4460   if (!ARMInterruptAttr::ConvertStrToInterruptType(Str, Kind)) {
   4461     S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
   4462       << Attr.getName() << Str << ArgLoc;
   4463     return;
   4464   }
   4465 
   4466   unsigned Index = Attr.getAttributeSpellingListIndex();
   4467   D->addAttr(::new (S.Context)
   4468              ARMInterruptAttr(Attr.getLoc(), S.Context, Kind, Index));
   4469 }
   4470 
   4471 static void handleMSP430InterruptAttr(Sema &S, Decl *D,
   4472                                       const AttributeList &Attr) {
   4473   if (!checkAttributeNumArgs(S, Attr, 1))
   4474     return;
   4475 
   4476   if (!Attr.isArgExpr(0)) {
   4477     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type) << Attr.getName()
   4478       << AANT_ArgumentIntegerConstant;
   4479     return;
   4480   }
   4481 
   4482   // FIXME: Check for decl - it should be void ()(void).
   4483 
   4484   Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
   4485   llvm::APSInt NumParams(32);
   4486   if (!NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) {
   4487     S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
   4488       << Attr.getName() << AANT_ArgumentIntegerConstant
   4489       << NumParamsExpr->getSourceRange();
   4490     return;
   4491   }
   4492 
   4493   unsigned Num = NumParams.getLimitedValue(255);