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