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