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