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