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