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