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