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