clang  16.0.0git
SemaDeclAttr.cpp
Go to the documentation of this file.
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"
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"
24 #include "clang/AST/Type.h"
25 #include "clang/Basic/CharInfo.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Lex/Preprocessor.h"
34 #include "clang/Sema/DeclSpec.h"
37 #include "clang/Sema/Lookup.h"
38 #include "clang/Sema/ParsedAttr.h"
39 #include "clang/Sema/Scope.h"
40 #include "clang/Sema/ScopeInfo.h"
42 #include "llvm/ADT/Optional.h"
43 #include "llvm/ADT/STLExtras.h"
44 #include "llvm/ADT/StringExtras.h"
45 #include "llvm/IR/Assumptions.h"
46 #include "llvm/MC/MCSectionMachO.h"
47 #include "llvm/Support/Error.h"
48 #include "llvm/Support/MathExtras.h"
49 #include "llvm/Support/raw_ostream.h"
50 
51 using namespace clang;
52 using namespace sema;
53 
55  enum LANG {
56  C,
57  Cpp,
59  };
60 } // end namespace AttributeLangSupport
61 
62 //===----------------------------------------------------------------------===//
63 // Helper functions
64 //===----------------------------------------------------------------------===//
65 
66 /// isFunctionOrMethod - Return true if the given decl has function
67 /// type (function or function-typed variable) or an Objective-C
68 /// method.
69 static bool isFunctionOrMethod(const Decl *D) {
70  return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
71 }
72 
73 /// Return true if the given decl has function type (function or
74 /// function-typed variable) or an Objective-C method or a block.
75 static bool isFunctionOrMethodOrBlock(const Decl *D) {
76  return isFunctionOrMethod(D) || isa<BlockDecl>(D);
77 }
78 
79 /// Return true if the given decl has a declarator that should have
80 /// been processed by Sema::GetTypeForDeclarator.
81 static bool hasDeclarator(const Decl *D) {
82  // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
83  return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
84  isa<ObjCPropertyDecl>(D);
85 }
86 
87 /// hasFunctionProto - Return true if the given decl has a argument
88 /// information. This decl should have already passed
89 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
90 static bool hasFunctionProto(const Decl *D) {
91  if (const FunctionType *FnTy = D->getFunctionType())
92  return isa<FunctionProtoType>(FnTy);
93  return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
94 }
95 
96 /// getFunctionOrMethodNumParams - Return number of function or method
97 /// parameters. It is an error to call this on a K&R function (use
98 /// hasFunctionProto first).
99 static unsigned getFunctionOrMethodNumParams(const Decl *D) {
100  if (const FunctionType *FnTy = D->getFunctionType())
101  return cast<FunctionProtoType>(FnTy)->getNumParams();
102  if (const auto *BD = dyn_cast<BlockDecl>(D))
103  return BD->getNumParams();
104  return cast<ObjCMethodDecl>(D)->param_size();
105 }
106 
108  unsigned Idx) {
109  if (const auto *FD = dyn_cast<FunctionDecl>(D))
110  return FD->getParamDecl(Idx);
111  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
112  return MD->getParamDecl(Idx);
113  if (const auto *BD = dyn_cast<BlockDecl>(D))
114  return BD->getParamDecl(Idx);
115  return nullptr;
116 }
117 
118 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
119  if (const FunctionType *FnTy = D->getFunctionType())
120  return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
121  if (const auto *BD = dyn_cast<BlockDecl>(D))
122  return BD->getParamDecl(Idx)->getType();
123 
124  return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
125 }
126 
127 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
128  if (auto *PVD = getFunctionOrMethodParam(D, Idx))
129  return PVD->getSourceRange();
130  return SourceRange();
131 }
132 
134  if (const FunctionType *FnTy = D->getFunctionType())
135  return FnTy->getReturnType();
136  return cast<ObjCMethodDecl>(D)->getReturnType();
137 }
138 
140  if (const auto *FD = dyn_cast<FunctionDecl>(D))
141  return FD->getReturnTypeSourceRange();
142  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
143  return MD->getReturnTypeSourceRange();
144  return SourceRange();
145 }
146 
147 static bool isFunctionOrMethodVariadic(const Decl *D) {
148  if (const FunctionType *FnTy = D->getFunctionType())
149  return cast<FunctionProtoType>(FnTy)->isVariadic();
150  if (const auto *BD = dyn_cast<BlockDecl>(D))
151  return BD->isVariadic();
152  return cast<ObjCMethodDecl>(D)->isVariadic();
153 }
154 
155 static bool isInstanceMethod(const Decl *D) {
156  if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(D))
157  return MethodDecl->isInstance();
158  return false;
159 }
160 
161 static inline bool isNSStringType(QualType T, ASTContext &Ctx,
162  bool AllowNSAttributedString = false) {
163  const auto *PT = T->getAs<ObjCObjectPointerType>();
164  if (!PT)
165  return false;
166 
167  ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
168  if (!Cls)
169  return false;
170 
171  IdentifierInfo* ClsName = Cls->getIdentifier();
172 
173  if (AllowNSAttributedString &&
174  ClsName == &Ctx.Idents.get("NSAttributedString"))
175  return true;
176  // FIXME: Should we walk the chain of classes?
177  return ClsName == &Ctx.Idents.get("NSString") ||
178  ClsName == &Ctx.Idents.get("NSMutableString");
179 }
180 
181 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
182  const auto *PT = T->getAs<PointerType>();
183  if (!PT)
184  return false;
185 
186  const auto *RT = PT->getPointeeType()->getAs<RecordType>();
187  if (!RT)
188  return false;
189 
190  const RecordDecl *RD = RT->getDecl();
191  if (RD->getTagKind() != TTK_Struct)
192  return false;
193 
194  return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
195 }
196 
197 static unsigned getNumAttributeArgs(const ParsedAttr &AL) {
198  // FIXME: Include the type in the argument list.
199  return AL.getNumArgs() + AL.hasParsedType();
200 }
201 
202 /// A helper function to provide Attribute Location for the Attr types
203 /// AND the ParsedAttr.
204 template <typename AttrInfo>
205 static std::enable_if_t<std::is_base_of_v<Attr, AttrInfo>, SourceLocation>
206 getAttrLoc(const AttrInfo &AL) {
207  return AL.getLocation();
208 }
209 static SourceLocation getAttrLoc(const ParsedAttr &AL) { return AL.getLoc(); }
210 
211 /// If Expr is a valid integer constant, get the value of the integer
212 /// expression and return success or failure. May output an error.
213 ///
214 /// Negative argument is implicitly converted to unsigned, unless
215 /// \p StrictlyUnsigned is true.
216 template <typename AttrInfo>
217 static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr,
218  uint32_t &Val, unsigned Idx = UINT_MAX,
219  bool StrictlyUnsigned = false) {
221  if (Expr->isTypeDependent() ||
222  !(I = Expr->getIntegerConstantExpr(S.Context))) {
223  if (Idx != UINT_MAX)
224  S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
225  << &AI << Idx << AANT_ArgumentIntegerConstant
226  << Expr->getSourceRange();
227  else
228  S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
230  return false;
231  }
232 
233  if (!I->isIntN(32)) {
234  S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
235  << toString(*I, 10, false) << 32 << /* Unsigned */ 1;
236  return false;
237  }
238 
239  if (StrictlyUnsigned && I->isSigned() && I->isNegative()) {
240  S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
241  << &AI << /*non-negative*/ 1;
242  return false;
243  }
244 
245  Val = (uint32_t)I->getZExtValue();
246  return true;
247 }
248 
249 /// Wrapper around checkUInt32Argument, with an extra check to be sure
250 /// that the result will fit into a regular (signed) int. All args have the same
251 /// purpose as they do in checkUInt32Argument.
252 template <typename AttrInfo>
253 static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
254  int &Val, unsigned Idx = UINT_MAX) {
255  uint32_t UVal;
256  if (!checkUInt32Argument(S, AI, Expr, UVal, Idx))
257  return false;
258 
259  if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
260  llvm::APSInt I(32); // for toString
261  I = UVal;
262  S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
263  << toString(I, 10, false) << 32 << /* Unsigned */ 0;
264  return false;
265  }
266 
267  Val = UVal;
268  return true;
269 }
270 
271 /// Diagnose mutually exclusive attributes when present on a given
272 /// declaration. Returns true if diagnosed.
273 template <typename AttrTy>
274 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) {
275  if (const auto *A = D->getAttr<AttrTy>()) {
276  S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << A;
277  S.Diag(A->getLocation(), diag::note_conflicting_attribute);
278  return true;
279  }
280  return false;
281 }
282 
283 template <typename AttrTy>
284 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const Attr &AL) {
285  if (const auto *A = D->getAttr<AttrTy>()) {
286  S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible) << &AL
287  << A;
288  S.Diag(A->getLocation(), diag::note_conflicting_attribute);
289  return true;
290  }
291  return false;
292 }
293 
294 /// Check if IdxExpr is a valid parameter index for a function or
295 /// instance method D. May output an error.
296 ///
297 /// \returns true if IdxExpr is a valid index.
298 template <typename AttrInfo>
300  Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
301  const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) {
302  assert(isFunctionOrMethodOrBlock(D));
303 
304  // In C++ the implicit 'this' function parameter also counts.
305  // Parameters are counted from one.
306  bool HP = hasFunctionProto(D);
307  bool HasImplicitThisParam = isInstanceMethod(D);
308  bool IV = HP && isFunctionOrMethodVariadic(D);
309  unsigned NumParams =
310  (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
311 
312  Optional<llvm::APSInt> IdxInt;
313  if (IdxExpr->isTypeDependent() ||
314  !(IdxInt = IdxExpr->getIntegerConstantExpr(S.Context))) {
315  S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
316  << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
317  << IdxExpr->getSourceRange();
318  return false;
319  }
320 
321  unsigned IdxSource = IdxInt->getLimitedValue(UINT_MAX);
322  if (IdxSource < 1 || (!IV && IdxSource > NumParams)) {
323  S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
324  << &AI << AttrArgNum << IdxExpr->getSourceRange();
325  return false;
326  }
327  if (HasImplicitThisParam && !CanIndexImplicitThis) {
328  if (IdxSource == 1) {
329  S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
330  << &AI << IdxExpr->getSourceRange();
331  return false;
332  }
333  }
334 
335  Idx = ParamIdx(IdxSource, D);
336  return true;
337 }
338 
339 /// Check if the argument \p E is a ASCII string literal. If not emit an error
340 /// and return false, otherwise set \p Str to the value of the string literal
341 /// and return true.
343  const Expr *E, StringRef &Str,
344  SourceLocation *ArgLocation) {
345  const auto *Literal = dyn_cast<StringLiteral>(E->IgnoreParenCasts());
346  if (ArgLocation)
347  *ArgLocation = E->getBeginLoc();
348 
349  if (!Literal || !Literal->isOrdinary()) {
350  Diag(E->getBeginLoc(), diag::err_attribute_argument_type)
351  << CI << AANT_ArgumentString;
352  return false;
353  }
354 
355  Str = Literal->getString();
356  return true;
357 }
358 
359 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
360 /// If not emit an error and return false. If the argument is an identifier it
361 /// will emit an error with a fixit hint and treat it as if it was a string
362 /// literal.
363 bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
364  StringRef &Str,
365  SourceLocation *ArgLocation) {
366  // Look for identifiers. If we have one emit a hint to fix it to a literal.
367  if (AL.isArgIdent(ArgNum)) {
368  IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum);
369  Diag(Loc->Loc, diag::err_attribute_argument_type)
370  << AL << AANT_ArgumentString
371  << FixItHint::CreateInsertion(Loc->Loc, "\"")
372  << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
373  Str = Loc->Ident->getName();
374  if (ArgLocation)
375  *ArgLocation = Loc->Loc;
376  return true;
377  }
378 
379  // Now check for an actual string literal.
380  Expr *ArgExpr = AL.getArgAsExpr(ArgNum);
381  return checkStringLiteralArgumentAttr(AL, ArgExpr, Str, ArgLocation);
382 }
383 
384 /// Applies the given attribute to the Decl without performing any
385 /// additional semantic checking.
386 template <typename AttrType>
387 static void handleSimpleAttribute(Sema &S, Decl *D,
388  const AttributeCommonInfo &CI) {
389  D->addAttr(::new (S.Context) AttrType(S.Context, CI));
390 }
391 
392 template <typename... DiagnosticArgs>
393 static const Sema::SemaDiagnosticBuilder&
395  return Bldr;
396 }
397 
398 template <typename T, typename... DiagnosticArgs>
399 static const Sema::SemaDiagnosticBuilder&
401  DiagnosticArgs &&... ExtraArgs) {
402  return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
403  std::forward<DiagnosticArgs>(ExtraArgs)...);
404 }
405 
406 /// Add an attribute @c AttrType to declaration @c D, provided that
407 /// @c PassesCheck is true.
408 /// Otherwise, emit diagnostic @c DiagID, passing in all parameters
409 /// specified in @c ExtraArgs.
410 template <typename AttrType, typename... DiagnosticArgs>
412  const AttributeCommonInfo &CI,
413  bool PassesCheck, unsigned DiagID,
414  DiagnosticArgs &&... ExtraArgs) {
415  if (!PassesCheck) {
416  Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
417  appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
418  return;
419  }
420  handleSimpleAttribute<AttrType>(S, D, CI);
421 }
422 
423 /// Check if the passed-in expression is of type int or bool.
424 static bool isIntOrBool(Expr *Exp) {
425  QualType QT = Exp->getType();
426  return QT->isBooleanType() || QT->isIntegerType();
427 }
428 
429 
430 // Check to see if the type is a smart pointer of some kind. We assume
431 // it's a smart pointer if it defines both operator-> and operator*.
432 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
433  auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record,
435  DeclContextLookupResult Result =
437  return !Result.empty();
438  };
439 
440  const RecordDecl *Record = RT->getDecl();
441  bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
442  bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
443  if (foundStarOperator && foundArrowOperator)
444  return true;
445 
446  const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record);
447  if (!CXXRecord)
448  return false;
449 
450  for (auto BaseSpecifier : CXXRecord->bases()) {
451  if (!foundStarOperator)
452  foundStarOperator = IsOverloadedOperatorPresent(
453  BaseSpecifier.getType()->getAsRecordDecl(), OO_Star);
454  if (!foundArrowOperator)
455  foundArrowOperator = IsOverloadedOperatorPresent(
456  BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow);
457  }
458 
459  if (foundStarOperator && foundArrowOperator)
460  return true;
461 
462  return false;
463 }
464 
465 /// Check if passed in Decl is a pointer type.
466 /// Note that this function may produce an error message.
467 /// \return true if the Decl is a pointer type; false otherwise
468 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
469  const ParsedAttr &AL) {
470  const auto *VD = cast<ValueDecl>(D);
471  QualType QT = VD->getType();
472  if (QT->isAnyPointerType())
473  return true;
474 
475  if (const auto *RT = QT->getAs<RecordType>()) {
476  // If it's an incomplete type, it could be a smart pointer; skip it.
477  // (We don't want to force template instantiation if we can avoid it,
478  // since that would alter the order in which templates are instantiated.)
479  if (RT->isIncompleteType())
480  return true;
481 
483  return true;
484  }
485 
486  S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT;
487  return false;
488 }
489 
490 /// Checks that the passed in QualType either is of RecordType or points
491 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
492 static const RecordType *getRecordType(QualType QT) {
493  if (const auto *RT = QT->getAs<RecordType>())
494  return RT;
495 
496  // Now check if we point to record type.
497  if (const auto *PT = QT->getAs<PointerType>())
498  return PT->getPointeeType()->getAs<RecordType>();
499 
500  return nullptr;
501 }
502 
503 template <typename AttrType>
504 static bool checkRecordDeclForAttr(const RecordDecl *RD) {
505  // Check if the record itself has the attribute.
506  if (RD->hasAttr<AttrType>())
507  return true;
508 
509  // Else check if any base classes have the attribute.
510  if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
511  if (!CRD->forallBases([](const CXXRecordDecl *Base) {
512  return !Base->hasAttr<AttrType>();
513  }))
514  return true;
515  }
516  return false;
517 }
518 
520  const RecordType *RT = getRecordType(Ty);
521 
522  if (!RT)
523  return false;
524 
525  // Don't check for the capability if the class hasn't been defined yet.
526  if (RT->isIncompleteType())
527  return true;
528 
529  // Allow smart pointers to be used as capability objects.
530  // FIXME -- Check the type that the smart pointer points to.
532  return true;
533 
534  return checkRecordDeclForAttr<CapabilityAttr>(RT->getDecl());
535 }
536 
538  const auto *TD = Ty->getAs<TypedefType>();
539  if (!TD)
540  return false;
541 
542  TypedefNameDecl *TN = TD->getDecl();
543  if (!TN)
544  return false;
545 
546  return TN->hasAttr<CapabilityAttr>();
547 }
548 
549 static bool typeHasCapability(Sema &S, QualType Ty) {
551  return true;
552 
553  if (checkRecordTypeForCapability(S, Ty))
554  return true;
555 
556  return false;
557 }
558 
559 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
560  // Capability expressions are simple expressions involving the boolean logic
561  // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
562  // a DeclRefExpr is found, its type should be checked to determine whether it
563  // is a capability or not.
564 
565  if (const auto *E = dyn_cast<CastExpr>(Ex))
566  return isCapabilityExpr(S, E->getSubExpr());
567  else if (const auto *E = dyn_cast<ParenExpr>(Ex))
568  return isCapabilityExpr(S, E->getSubExpr());
569  else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
570  if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
571  E->getOpcode() == UO_Deref)
572  return isCapabilityExpr(S, E->getSubExpr());
573  return false;
574  } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
575  if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
576  return isCapabilityExpr(S, E->getLHS()) &&
577  isCapabilityExpr(S, E->getRHS());
578  return false;
579  }
580 
581  return typeHasCapability(S, Ex->getType());
582 }
583 
584 /// Checks that all attribute arguments, starting from Sidx, resolve to
585 /// a capability object.
586 /// \param Sidx The attribute argument index to start checking with.
587 /// \param ParamIdxOk Whether an argument can be indexing into a function
588 /// parameter list.
590  const ParsedAttr &AL,
592  unsigned Sidx = 0,
593  bool ParamIdxOk = false) {
594  if (Sidx == AL.getNumArgs()) {
595  // If we don't have any capability arguments, the attribute implicitly
596  // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
597  // a non-static method, and that the class is a (scoped) capability.
598  const auto *MD = dyn_cast<const CXXMethodDecl>(D);
599  if (MD && !MD->isStatic()) {
600  const CXXRecordDecl *RD = MD->getParent();
601  // FIXME -- need to check this again on template instantiation
602  if (!checkRecordDeclForAttr<CapabilityAttr>(RD) &&
603  !checkRecordDeclForAttr<ScopedLockableAttr>(RD))
604  S.Diag(AL.getLoc(),
605  diag::warn_thread_attribute_not_on_capability_member)
606  << AL << MD->getParent();
607  } else {
608  S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member)
609  << AL;
610  }
611  }
612 
613  for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) {
614  Expr *ArgExp = AL.getArgAsExpr(Idx);
615 
616  if (ArgExp->isTypeDependent()) {
617  // FIXME -- need to check this again on template instantiation
618  Args.push_back(ArgExp);
619  continue;
620  }
621 
622  if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
623  if (StrLit->getLength() == 0 ||
624  (StrLit->isOrdinary() && StrLit->getString() == StringRef("*"))) {
625  // Pass empty strings to the analyzer without warnings.
626  // Treat "*" as the universal lock.
627  Args.push_back(ArgExp);
628  continue;
629  }
630 
631  // We allow constant strings to be used as a placeholder for expressions
632  // that are not valid C++ syntax, but warn that they are ignored.
633  S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL;
634  Args.push_back(ArgExp);
635  continue;
636  }
637 
638  QualType ArgTy = ArgExp->getType();
639 
640  // A pointer to member expression of the form &MyClass::mu is treated
641  // specially -- we need to look at the type of the member.
642  if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp))
643  if (UOp->getOpcode() == UO_AddrOf)
644  if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
645  if (DRE->getDecl()->isCXXInstanceMember())
646  ArgTy = DRE->getDecl()->getType();
647 
648  // First see if we can just cast to record type, or pointer to record type.
649  const RecordType *RT = getRecordType(ArgTy);
650 
651  // Now check if we index into a record type function param.
652  if(!RT && ParamIdxOk) {
653  const auto *FD = dyn_cast<FunctionDecl>(D);
654  const auto *IL = dyn_cast<IntegerLiteral>(ArgExp);
655  if(FD && IL) {
656  unsigned int NumParams = FD->getNumParams();
657  llvm::APInt ArgValue = IL->getValue();
658  uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
659  uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
660  if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
661  S.Diag(AL.getLoc(),
662  diag::err_attribute_argument_out_of_bounds_extra_info)
663  << AL << Idx + 1 << NumParams;
664  continue;
665  }
666  ArgTy = FD->getParamDecl(ParamIdxFromZero)->getType();
667  }
668  }
669 
670  // If the type does not have a capability, see if the components of the
671  // expression have capabilities. This allows for writing C code where the
672  // capability may be on the type, and the expression is a capability
673  // boolean logic expression. Eg) requires_capability(A || B && !C)
674  if (!typeHasCapability(S, ArgTy) && !isCapabilityExpr(S, ArgExp))
675  S.Diag(AL.getLoc(), diag::warn_thread_attribute_argument_not_lockable)
676  << AL << ArgTy;
677 
678  Args.push_back(ArgExp);
679  }
680 }
681 
682 //===----------------------------------------------------------------------===//
683 // Attribute Implementations
684 //===----------------------------------------------------------------------===//
685 
686 static void handlePtGuardedVarAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
687  if (!threadSafetyCheckIsPointer(S, D, AL))
688  return;
689 
690  D->addAttr(::new (S.Context) PtGuardedVarAttr(S.Context, AL));
691 }
692 
693 static bool checkGuardedByAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
694  Expr *&Arg) {
696  // check that all arguments are lockable objects
697  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
698  unsigned Size = Args.size();
699  if (Size != 1)
700  return false;
701 
702  Arg = Args[0];
703 
704  return true;
705 }
706 
707 static void handleGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
708  Expr *Arg = nullptr;
709  if (!checkGuardedByAttrCommon(S, D, AL, Arg))
710  return;
711 
712  D->addAttr(::new (S.Context) GuardedByAttr(S.Context, AL, Arg));
713 }
714 
715 static void handlePtGuardedByAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
716  Expr *Arg = nullptr;
717  if (!checkGuardedByAttrCommon(S, D, AL, Arg))
718  return;
719 
720  if (!threadSafetyCheckIsPointer(S, D, AL))
721  return;
722 
723  D->addAttr(::new (S.Context) PtGuardedByAttr(S.Context, AL, Arg));
724 }
725 
726 static bool checkAcquireOrderAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
727  SmallVectorImpl<Expr *> &Args) {
728  if (!AL.checkAtLeastNumArgs(S, 1))
729  return false;
730 
731  // Check that this attribute only applies to lockable types.
732  QualType QT = cast<ValueDecl>(D)->getType();
733  if (!QT->isDependentType() && !typeHasCapability(S, QT)) {
734  S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_lockable) << AL;
735  return false;
736  }
737 
738  // Check that all arguments are lockable objects.
739  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
740  if (Args.empty())
741  return false;
742 
743  return true;
744 }
745 
746 static void handleAcquiredAfterAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
748  if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
749  return;
750 
751  Expr **StartArg = &Args[0];
752  D->addAttr(::new (S.Context)
753  AcquiredAfterAttr(S.Context, AL, StartArg, Args.size()));
754 }
755 
756 static void handleAcquiredBeforeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
758  if (!checkAcquireOrderAttrCommon(S, D, AL, Args))
759  return;
760 
761  Expr **StartArg = &Args[0];
762  D->addAttr(::new (S.Context)
763  AcquiredBeforeAttr(S.Context, AL, StartArg, Args.size()));
764 }
765 
766 static bool checkLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
767  SmallVectorImpl<Expr *> &Args) {
768  // zero or more arguments ok
769  // check that all arguments are lockable objects
770  checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 0, /*ParamIdxOk=*/true);
771 
772  return true;
773 }
774 
775 static void handleAssertSharedLockAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
777  if (!checkLockFunAttrCommon(S, D, AL, Args))
778  return;
779 
780  unsigned Size = Args.size();
781  Expr **StartArg = Size == 0 ? nullptr : &Args[0];
782  D->addAttr(::new (S.Context)
783  AssertSharedLockAttr(S.Context, AL, StartArg, Size));
784 }
785 
787  const ParsedAttr &AL) {
789  if (!checkLockFunAttrCommon(S, D, AL, Args))
790  return;
791 
792  unsigned Size = Args.size();
793  Expr **StartArg = Size == 0 ? nullptr : &Args[0];
794  D->addAttr(::new (S.Context)
795  AssertExclusiveLockAttr(S.Context, AL, StartArg, Size));
796 }
797 
798 /// Checks to be sure that the given parameter number is in bounds, and
799 /// is an integral type. Will emit appropriate diagnostics if this returns
800 /// false.
801 ///
802 /// AttrArgNo is used to actually retrieve the argument, so it's base-0.
803 template <typename AttrInfo>
804 static bool checkParamIsIntegerType(Sema &S, const Decl *D, const AttrInfo &AI,
805  unsigned AttrArgNo) {
806  assert(AI.isArgExpr(AttrArgNo) && "Expected expression argument");
807  Expr *AttrArg = AI.getArgAsExpr(AttrArgNo);
808  ParamIdx Idx;
809  if (!checkFunctionOrMethodParameterIndex(S, D, AI, AttrArgNo + 1, AttrArg,
810  Idx))
811  return false;
812 
814  if (!ParamTy->isIntegerType() && !ParamTy->isCharType()) {
815  SourceLocation SrcLoc = AttrArg->getBeginLoc();
816  S.Diag(SrcLoc, diag::err_attribute_integers_only)
817  << AI << getFunctionOrMethodParamRange(D, Idx.getASTIndex());
818  return false;
819  }
820  return true;
821 }
822 
823 static void handleAllocSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
824  if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 2))
825  return;
826 
827  assert(isFunctionOrMethod(D) && hasFunctionProto(D));
828 
830  if (!RetTy->isPointerType()) {
831  S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only) << AL;
832  return;
833  }
834 
835  const Expr *SizeExpr = AL.getArgAsExpr(0);
836  int SizeArgNoVal;
837  // Parameter indices are 1-indexed, hence Index=1
838  if (!checkPositiveIntArgument(S, AL, SizeExpr, SizeArgNoVal, /*Idx=*/1))
839  return;
840  if (!checkParamIsIntegerType(S, D, AL, /*AttrArgNo=*/0))
841  return;
842  ParamIdx SizeArgNo(SizeArgNoVal, D);
843 
844  ParamIdx NumberArgNo;
845  if (AL.getNumArgs() == 2) {
846  const Expr *NumberExpr = AL.getArgAsExpr(1);
847  int Val;
848  // Parameter indices are 1-based, hence Index=2
849  if (!checkPositiveIntArgument(S, AL, NumberExpr, Val, /*Idx=*/2))
850  return;
851  if (!checkParamIsIntegerType(S, D, AL, /*AttrArgNo=*/1))
852  return;
853  NumberArgNo = ParamIdx(Val, D);
854  }
855 
856  D->addAttr(::new (S.Context)
857  AllocSizeAttr(S.Context, AL, SizeArgNo, NumberArgNo));
858 }
859 
860 static bool checkTryLockFunAttrCommon(Sema &S, Decl *D, const ParsedAttr &AL,
861  SmallVectorImpl<Expr *> &Args) {
862  if (!AL.checkAtLeastNumArgs(S, 1))
863  return false;
864 
865  if (!isIntOrBool(AL.getArgAsExpr(0))) {
866  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
867  << AL << 1 << AANT_ArgumentIntOrBool;
868  return false;
869  }
870 
871  // check that all arguments are lockable objects
872  checkAttrArgsAreCapabilityObjs(S, D, AL, Args, 1);
873 
874  return true;
875 }
876 
878  const ParsedAttr &AL) {
880  if (!checkTryLockFunAttrCommon(S, D, AL, Args))
881  return;
882 
883  D->addAttr(::new (S.Context) SharedTrylockFunctionAttr(
884  S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
885 }
886 
888  const ParsedAttr &AL) {
890  if (!checkTryLockFunAttrCommon(S, D, AL, Args))
891  return;
892 
893  D->addAttr(::new (S.Context) ExclusiveTrylockFunctionAttr(
894  S.Context, AL, AL.getArgAsExpr(0), Args.data(), Args.size()));
895 }
896 
897 static void handleLockReturnedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
898  // check that the argument is lockable object
900  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
901  unsigned Size = Args.size();
902  if (Size == 0)
903  return;
904 
905  D->addAttr(::new (S.Context) LockReturnedAttr(S.Context, AL, Args[0]));
906 }
907 
908 static void handleLocksExcludedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
909  if (!AL.checkAtLeastNumArgs(S, 1))
910  return;
911 
912  // check that all arguments are lockable objects
914  checkAttrArgsAreCapabilityObjs(S, D, AL, Args);
915  unsigned Size = Args.size();
916  if (Size == 0)
917  return;
918  Expr **StartArg = &Args[0];
919 
920  D->addAttr(::new (S.Context)
921  LocksExcludedAttr(S.Context, AL, StartArg, Size));
922 }
923 
924 static bool checkFunctionConditionAttr(Sema &S, Decl *D, const ParsedAttr &AL,
925  Expr *&Cond, StringRef &Msg) {
926  Cond = AL.getArgAsExpr(0);
927  if (!Cond->isTypeDependent()) {
928  ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
929  if (Converted.isInvalid())
930  return false;
931  Cond = Converted.get();
932  }
933 
934  if (!S.checkStringLiteralArgumentAttr(AL, 1, Msg))
935  return false;
936 
937  if (Msg.empty())
938  Msg = "<no message provided>";
939 
941  if (isa<FunctionDecl>(D) && !Cond->isValueDependent() &&
942  !Expr::isPotentialConstantExprUnevaluated(Cond, cast<FunctionDecl>(D),
943  Diags)) {
944  S.Diag(AL.getLoc(), diag::err_attr_cond_never_constant_expr) << AL;
945  for (const PartialDiagnosticAt &PDiag : Diags)
946  S.Diag(PDiag.first, PDiag.second);
947  return false;
948  }
949  return true;
950 }
951 
952 static void handleEnableIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
953  S.Diag(AL.getLoc(), diag::ext_clang_enable_if);
954 
955  Expr *Cond;
956  StringRef Msg;
957  if (checkFunctionConditionAttr(S, D, AL, Cond, Msg))
958  D->addAttr(::new (S.Context) EnableIfAttr(S.Context, AL, Cond, Msg));
959 }
960 
961 static void handleErrorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
962  StringRef NewUserDiagnostic;
963  if (!S.checkStringLiteralArgumentAttr(AL, 0, NewUserDiagnostic))
964  return;
965  if (ErrorAttr *EA = S.mergeErrorAttr(D, AL, NewUserDiagnostic))
966  D->addAttr(EA);
967 }
968 
969 namespace {
970 /// Determines if a given Expr references any of the given function's
971 /// ParmVarDecls, or the function's implicit `this` parameter (if applicable).
972 class ArgumentDependenceChecker
973  : public RecursiveASTVisitor<ArgumentDependenceChecker> {
974 #ifndef NDEBUG
975  const CXXRecordDecl *ClassType;
976 #endif
978  bool Result;
979 
980 public:
981  ArgumentDependenceChecker(const FunctionDecl *FD) {
982 #ifndef NDEBUG
983  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
984  ClassType = MD->getParent();
985  else
986  ClassType = nullptr;
987 #endif
988  Parms.insert(FD->param_begin(), FD->param_end());
989  }
990 
991  bool referencesArgs(Expr *E) {
992  Result = false;
993  TraverseStmt(E);
994  return Result;
995  }
996 
997  bool VisitCXXThisExpr(CXXThisExpr *E) {
998  assert(E->getType()->getPointeeCXXRecordDecl() == ClassType &&
999  "`this` doesn't refer to the enclosing class?");
1000  Result = true;
1001  return false;
1002  }
1003 
1004  bool VisitDeclRefExpr(DeclRefExpr *DRE) {
1005  if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
1006  if (Parms.count(PVD)) {
1007  Result = true;
1008  return false;
1009  }
1010  return true;
1011  }
1012 };
1013 }
1014 
1016  const ParsedAttr &AL) {
1017  const auto *DeclFD = cast<FunctionDecl>(D);
1018 
1019  if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(DeclFD))
1020  if (!MethodDecl->isStatic()) {
1021  S.Diag(AL.getLoc(), diag::err_attribute_no_member_function) << AL;
1022  return;
1023  }
1024 
1025  auto DiagnoseType = [&](unsigned Index, AttributeArgumentNType T) {
1026  SourceLocation Loc = [&]() {
1027  auto Union = AL.getArg(Index - 1);
1028  if (Union.is<Expr *>())
1029  return Union.get<Expr *>()->getBeginLoc();
1030  return Union.get<IdentifierLoc *>()->Loc;
1031  }();
1032 
1033  S.Diag(Loc, diag::err_attribute_argument_n_type) << AL << Index << T;
1034  };
1035 
1036  FunctionDecl *AttrFD = [&]() -> FunctionDecl * {
1037  if (!AL.isArgExpr(0))
1038  return nullptr;
1039  auto *F = dyn_cast_or_null<DeclRefExpr>(AL.getArgAsExpr(0));
1040  if (!F)
1041  return nullptr;
1042  return dyn_cast_or_null<FunctionDecl>(F->getFoundDecl());
1043  }();
1044 
1045  if (!AttrFD || !AttrFD->getBuiltinID(true)) {
1046  DiagnoseType(1, AANT_ArgumentBuiltinFunction);
1047  return;
1048  }
1049 
1050  if (AttrFD->getNumParams() != AL.getNumArgs() - 1) {
1051  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments_for)
1052  << AL << AttrFD << AttrFD->getNumParams();
1053  return;
1054  }
1055 
1056  SmallVector<unsigned, 8> Indices;
1057 
1058  for (unsigned I = 1; I < AL.getNumArgs(); ++I) {
1059  if (!AL.isArgExpr(I)) {
1060  DiagnoseType(I + 1, AANT_ArgumentIntegerConstant);
1061  return;
1062  }
1063 
1064  const Expr *IndexExpr = AL.getArgAsExpr(I);
1065  uint32_t Index;
1066 
1067  if (!checkUInt32Argument(S, AL, IndexExpr, Index, I + 1, false))
1068  return;
1069 
1070  if (Index > DeclFD->getNumParams()) {
1071  S.Diag(AL.getLoc(), diag::err_attribute_bounds_for_function)
1072  << AL << Index << DeclFD << DeclFD->getNumParams();
1073  return;
1074  }
1075 
1076  QualType T1 = AttrFD->getParamDecl(I - 1)->getType();
1077  QualType T2 = DeclFD->getParamDecl(Index - 1)->getType();
1078 
1079  if (T1.getCanonicalType().getUnqualifiedType() !=
1081  S.Diag(IndexExpr->getBeginLoc(), diag::err_attribute_parameter_types)
1082  << AL << Index << DeclFD << T2 << I << AttrFD << T1;
1083  return;
1084  }
1085 
1086  Indices.push_back(Index - 1);
1087  }
1088 
1089  D->addAttr(::new (S.Context) DiagnoseAsBuiltinAttr(
1090  S.Context, AL, AttrFD, Indices.data(), Indices.size()));
1091 }
1092 
1093 static void handleDiagnoseIfAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1094  S.Diag(AL.getLoc(), diag::ext_clang_diagnose_if);
1095 
1096  Expr *Cond;
1097  StringRef Msg;
1098  if (!checkFunctionConditionAttr(S, D, AL, Cond, Msg))
1099  return;
1100 
1101  StringRef DiagTypeStr;
1102  if (!S.checkStringLiteralArgumentAttr(AL, 2, DiagTypeStr))
1103  return;
1104 
1105  DiagnoseIfAttr::DiagnosticType DiagType;
1106  if (!DiagnoseIfAttr::ConvertStrToDiagnosticType(DiagTypeStr, DiagType)) {
1107  S.Diag(AL.getArgAsExpr(2)->getBeginLoc(),
1108  diag::err_diagnose_if_invalid_diagnostic_type);
1109  return;
1110  }
1111 
1112  bool ArgDependent = false;
1113  if (const auto *FD = dyn_cast<FunctionDecl>(D))
1114  ArgDependent = ArgumentDependenceChecker(FD).referencesArgs(Cond);
1115  D->addAttr(::new (S.Context) DiagnoseIfAttr(
1116  S.Context, AL, Cond, Msg, DiagType, ArgDependent, cast<NamedDecl>(D)));
1117 }
1118 
1119 static void handleNoBuiltinAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1120  static constexpr const StringRef kWildcard = "*";
1121 
1123  bool HasWildcard = false;
1124 
1125  const auto AddBuiltinName = [&Names, &HasWildcard](StringRef Name) {
1126  if (Name == kWildcard)
1127  HasWildcard = true;
1128  Names.push_back(Name);
1129  };
1130 
1131  // Add previously defined attributes.
1132  if (const auto *NBA = D->getAttr<NoBuiltinAttr>())
1133  for (StringRef BuiltinName : NBA->builtinNames())
1134  AddBuiltinName(BuiltinName);
1135 
1136  // Add current attributes.
1137  if (AL.getNumArgs() == 0)
1138  AddBuiltinName(kWildcard);
1139  else
1140  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
1141  StringRef BuiltinName;
1142  SourceLocation LiteralLoc;
1143  if (!S.checkStringLiteralArgumentAttr(AL, I, BuiltinName, &LiteralLoc))
1144  return;
1145 
1146  if (Builtin::Context::isBuiltinFunc(BuiltinName))
1147  AddBuiltinName(BuiltinName);
1148  else
1149  S.Diag(LiteralLoc, diag::warn_attribute_no_builtin_invalid_builtin_name)
1150  << BuiltinName << AL;
1151  }
1152 
1153  // Repeating the same attribute is fine.
1154  llvm::sort(Names);
1155  Names.erase(std::unique(Names.begin(), Names.end()), Names.end());
1156 
1157  // Empty no_builtin must be on its own.
1158  if (HasWildcard && Names.size() > 1)
1159  S.Diag(D->getLocation(),
1160  diag::err_attribute_no_builtin_wildcard_or_builtin_name)
1161  << AL;
1162 
1163  if (D->hasAttr<NoBuiltinAttr>())
1164  D->dropAttr<NoBuiltinAttr>();
1165  D->addAttr(::new (S.Context)
1166  NoBuiltinAttr(S.Context, AL, Names.data(), Names.size()));
1167 }
1168 
1169 static void handlePassObjectSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1170  if (D->hasAttr<PassObjectSizeAttr>()) {
1171  S.Diag(D->getBeginLoc(), diag::err_attribute_only_once_per_parameter) << AL;
1172  return;
1173  }
1174 
1175  Expr *E = AL.getArgAsExpr(0);
1176  uint32_t Type;
1177  if (!checkUInt32Argument(S, AL, E, Type, /*Idx=*/1))
1178  return;
1179 
1180  // pass_object_size's argument is passed in as the second argument of
1181  // __builtin_object_size. So, it has the same constraints as that second
1182  // argument; namely, it must be in the range [0, 3].
1183  if (Type > 3) {
1184  S.Diag(E->getBeginLoc(), diag::err_attribute_argument_out_of_range)
1185  << AL << 0 << 3 << E->getSourceRange();
1186  return;
1187  }
1188 
1189  // pass_object_size is only supported on constant pointer parameters; as a
1190  // kindness to users, we allow the parameter to be non-const for declarations.
1191  // At this point, we have no clue if `D` belongs to a function declaration or
1192  // definition, so we defer the constness check until later.
1193  if (!cast<ParmVarDecl>(D)->getType()->isPointerType()) {
1194  S.Diag(D->getBeginLoc(), diag::err_attribute_pointers_only) << AL << 1;
1195  return;
1196  }
1197 
1198  D->addAttr(::new (S.Context) PassObjectSizeAttr(S.Context, AL, (int)Type));
1199 }
1200 
1201 static void handleConsumableAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1202  ConsumableAttr::ConsumedState DefaultState;
1203 
1204  if (AL.isArgIdent(0)) {
1205  IdentifierLoc *IL = AL.getArgAsIdent(0);
1206  if (!ConsumableAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1207  DefaultState)) {
1208  S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1209  << IL->Ident;
1210  return;
1211  }
1212  } else {
1213  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1214  << AL << AANT_ArgumentIdentifier;
1215  return;
1216  }
1217 
1218  D->addAttr(::new (S.Context) ConsumableAttr(S.Context, AL, DefaultState));
1219 }
1220 
1221 static bool checkForConsumableClass(Sema &S, const CXXMethodDecl *MD,
1222  const ParsedAttr &AL) {
1223  QualType ThisType = MD->getThisType()->getPointeeType();
1224 
1225  if (const CXXRecordDecl *RD = ThisType->getAsCXXRecordDecl()) {
1226  if (!RD->hasAttr<ConsumableAttr>()) {
1227  S.Diag(AL.getLoc(), diag::warn_attr_on_unconsumable_class) << RD;
1228 
1229  return false;
1230  }
1231  }
1232 
1233  return true;
1234 }
1235 
1236 static void handleCallableWhenAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1237  if (!AL.checkAtLeastNumArgs(S, 1))
1238  return;
1239 
1240  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1241  return;
1242 
1244  for (unsigned ArgIndex = 0; ArgIndex < AL.getNumArgs(); ++ArgIndex) {
1245  CallableWhenAttr::ConsumedState CallableState;
1246 
1247  StringRef StateString;
1248  SourceLocation Loc;
1249  if (AL.isArgIdent(ArgIndex)) {
1250  IdentifierLoc *Ident = AL.getArgAsIdent(ArgIndex);
1251  StateString = Ident->Ident->getName();
1252  Loc = Ident->Loc;
1253  } else {
1254  if (!S.checkStringLiteralArgumentAttr(AL, ArgIndex, StateString, &Loc))
1255  return;
1256  }
1257 
1258  if (!CallableWhenAttr::ConvertStrToConsumedState(StateString,
1259  CallableState)) {
1260  S.Diag(Loc, diag::warn_attribute_type_not_supported) << AL << StateString;
1261  return;
1262  }
1263 
1264  States.push_back(CallableState);
1265  }
1266 
1267  D->addAttr(::new (S.Context)
1268  CallableWhenAttr(S.Context, AL, States.data(), States.size()));
1269 }
1270 
1271 static void handleParamTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1273 
1274  if (AL.isArgIdent(0)) {
1275  IdentifierLoc *Ident = AL.getArgAsIdent(0);
1276  StringRef StateString = Ident->Ident->getName();
1277 
1278  if (!ParamTypestateAttr::ConvertStrToConsumedState(StateString,
1279  ParamState)) {
1280  S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported)
1281  << AL << StateString;
1282  return;
1283  }
1284  } else {
1285  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1286  << AL << AANT_ArgumentIdentifier;
1287  return;
1288  }
1289 
1290  // FIXME: This check is currently being done in the analysis. It can be
1291  // enabled here only after the parser propagates attributes at
1292  // template specialization definition, not declaration.
1293  //QualType ReturnType = cast<ParmVarDecl>(D)->getType();
1294  //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1295  //
1296  //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1297  // S.Diag(AL.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1298  // ReturnType.getAsString();
1299  // return;
1300  //}
1301 
1302  D->addAttr(::new (S.Context) ParamTypestateAttr(S.Context, AL, ParamState));
1303 }
1304 
1305 static void handleReturnTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1307 
1308  if (AL.isArgIdent(0)) {
1309  IdentifierLoc *IL = AL.getArgAsIdent(0);
1310  if (!ReturnTypestateAttr::ConvertStrToConsumedState(IL->Ident->getName(),
1311  ReturnState)) {
1312  S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL
1313  << IL->Ident;
1314  return;
1315  }
1316  } else {
1317  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1318  << AL << AANT_ArgumentIdentifier;
1319  return;
1320  }
1321 
1322  // FIXME: This check is currently being done in the analysis. It can be
1323  // enabled here only after the parser propagates attributes at
1324  // template specialization definition, not declaration.
1325  //QualType ReturnType;
1326  //
1327  //if (const ParmVarDecl *Param = dyn_cast<ParmVarDecl>(D)) {
1328  // ReturnType = Param->getType();
1329  //
1330  //} else if (const CXXConstructorDecl *Constructor =
1331  // dyn_cast<CXXConstructorDecl>(D)) {
1332  // ReturnType = Constructor->getThisType()->getPointeeType();
1333  //
1334  //} else {
1335  //
1336  // ReturnType = cast<FunctionDecl>(D)->getCallResultType();
1337  //}
1338  //
1339  //const CXXRecordDecl *RD = ReturnType->getAsCXXRecordDecl();
1340  //
1341  //if (!RD || !RD->hasAttr<ConsumableAttr>()) {
1342  // S.Diag(Attr.getLoc(), diag::warn_return_state_for_unconsumable_type) <<
1343  // ReturnType.getAsString();
1344  // return;
1345  //}
1346 
1347  D->addAttr(::new (S.Context) ReturnTypestateAttr(S.Context, AL, ReturnState));
1348 }
1349 
1350 static void handleSetTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1351  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1352  return;
1353 
1355  if (AL.isArgIdent(0)) {
1356  IdentifierLoc *Ident = AL.getArgAsIdent(0);
1357  StringRef Param = Ident->Ident->getName();
1358  if (!SetTypestateAttr::ConvertStrToConsumedState(Param, NewState)) {
1359  S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1360  << Param;
1361  return;
1362  }
1363  } else {
1364  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1365  << AL << AANT_ArgumentIdentifier;
1366  return;
1367  }
1368 
1369  D->addAttr(::new (S.Context) SetTypestateAttr(S.Context, AL, NewState));
1370 }
1371 
1372 static void handleTestTypestateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1373  if (!checkForConsumableClass(S, cast<CXXMethodDecl>(D), AL))
1374  return;
1375 
1377  if (AL.isArgIdent(0)) {
1378  IdentifierLoc *Ident = AL.getArgAsIdent(0);
1379  StringRef Param = Ident->Ident->getName();
1380  if (!TestTypestateAttr::ConvertStrToConsumedState(Param, TestState)) {
1381  S.Diag(Ident->Loc, diag::warn_attribute_type_not_supported) << AL
1382  << Param;
1383  return;
1384  }
1385  } else {
1386  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
1387  << AL << AANT_ArgumentIdentifier;
1388  return;
1389  }
1390 
1391  D->addAttr(::new (S.Context) TestTypestateAttr(S.Context, AL, TestState));
1392 }
1393 
1394 static void handleExtVectorTypeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1395  // Remember this typedef decl, we will need it later for diagnostics.
1396  S.ExtVectorDecls.push_back(cast<TypedefNameDecl>(D));
1397 }
1398 
1399 static void handlePackedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1400  if (auto *TD = dyn_cast<TagDecl>(D))
1401  TD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1402  else if (auto *FD = dyn_cast<FieldDecl>(D)) {
1403  bool BitfieldByteAligned = (!FD->getType()->isDependentType() &&
1404  !FD->getType()->isIncompleteType() &&
1405  FD->isBitField() &&
1406  S.Context.getTypeAlign(FD->getType()) <= 8);
1407 
1408  if (S.getASTContext().getTargetInfo().getTriple().isPS()) {
1409  if (BitfieldByteAligned)
1410  // The PS4/PS5 targets need to maintain ABI backwards compatibility.
1411  S.Diag(AL.getLoc(), diag::warn_attribute_ignored_for_field_of_type)
1412  << AL << FD->getType();
1413  else
1414  FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1415  } else {
1416  // Report warning about changed offset in the newer compiler versions.
1417  if (BitfieldByteAligned)
1418  S.Diag(AL.getLoc(), diag::warn_attribute_packed_for_bitfield);
1419 
1420  FD->addAttr(::new (S.Context) PackedAttr(S.Context, AL));
1421  }
1422 
1423  } else
1424  S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
1425 }
1426 
1427 static void handlePreferredName(Sema &S, Decl *D, const ParsedAttr &AL) {
1428  auto *RD = cast<CXXRecordDecl>(D);
1429  ClassTemplateDecl *CTD = RD->getDescribedClassTemplate();
1430  assert(CTD && "attribute does not appertain to this declaration");
1431 
1432  ParsedType PT = AL.getTypeArg();
1433  TypeSourceInfo *TSI = nullptr;
1434  QualType T = S.GetTypeFromParser(PT, &TSI);
1435  if (!TSI)
1436  TSI = S.Context.getTrivialTypeSourceInfo(T, AL.getLoc());
1437 
1438  if (!T.hasQualifiers() && T->isTypedefNameType()) {
1439  // Find the template name, if this type names a template specialization.
1440  const TemplateDecl *Template = nullptr;
1441  if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
1442  T->getAsCXXRecordDecl())) {
1443  Template = CTSD->getSpecializedTemplate();
1444  } else if (const auto *TST = T->getAs<TemplateSpecializationType>()) {
1445  while (TST && TST->isTypeAlias())
1446  TST = TST->getAliasedType()->getAs<TemplateSpecializationType>();
1447  if (TST)
1448  Template = TST->getTemplateName().getAsTemplateDecl();
1449  }
1450 
1451  if (Template && declaresSameEntity(Template, CTD)) {
1452  D->addAttr(::new (S.Context) PreferredNameAttr(S.Context, AL, TSI));
1453  return;
1454  }
1455  }
1456 
1457  S.Diag(AL.getLoc(), diag::err_attribute_preferred_name_arg_invalid)
1458  << T << CTD;
1459  if (const auto *TT = T->getAs<TypedefType>())
1460  S.Diag(TT->getDecl()->getLocation(), diag::note_entity_declared_at)
1461  << TT->getDecl();
1462 }
1463 
1464 static bool checkIBOutletCommon(Sema &S, Decl *D, const ParsedAttr &AL) {
1465  // The IBOutlet/IBOutletCollection attributes only apply to instance
1466  // variables or properties of Objective-C classes. The outlet must also
1467  // have an object reference type.
1468  if (const auto *VD = dyn_cast<ObjCIvarDecl>(D)) {
1469  if (!VD->getType()->getAs<ObjCObjectPointerType>()) {
1470  S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1471  << AL << VD->getType() << 0;
1472  return false;
1473  }
1474  }
1475  else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
1476  if (!PD->getType()->getAs<ObjCObjectPointerType>()) {
1477  S.Diag(AL.getLoc(), diag::warn_iboutlet_object_type)
1478  << AL << PD->getType() << 1;
1479  return false;
1480  }
1481  }
1482  else {
1483  S.Diag(AL.getLoc(), diag::warn_attribute_iboutlet) << AL;
1484  return false;
1485  }
1486 
1487  return true;
1488 }
1489 
1490 static void handleIBOutlet(Sema &S, Decl *D, const ParsedAttr &AL) {
1491  if (!checkIBOutletCommon(S, D, AL))
1492  return;
1493 
1494  D->addAttr(::new (S.Context) IBOutletAttr(S.Context, AL));
1495 }
1496 
1497 static void handleIBOutletCollection(Sema &S, Decl *D, const ParsedAttr &AL) {
1498 
1499  // The iboutletcollection attribute can have zero or one arguments.
1500  if (AL.getNumArgs() > 1) {
1501  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1502  return;
1503  }
1504 
1505  if (!checkIBOutletCommon(S, D, AL))
1506  return;
1507 
1508  ParsedType PT;
1509 
1510  if (AL.hasParsedType())
1511  PT = AL.getTypeArg();
1512  else {
1513  PT = S.getTypeName(S.Context.Idents.get("NSObject"), AL.getLoc(),
1515  if (!PT) {
1516  S.Diag(AL.getLoc(), diag::err_iboutletcollection_type) << "NSObject";
1517  return;
1518  }
1519  }
1520 
1521  TypeSourceInfo *QTLoc = nullptr;
1522  QualType QT = S.GetTypeFromParser(PT, &QTLoc);
1523  if (!QTLoc)
1524  QTLoc = S.Context.getTrivialTypeSourceInfo(QT, AL.getLoc());
1525 
1526  // Diagnose use of non-object type in iboutletcollection attribute.
1527  // FIXME. Gnu attribute extension ignores use of builtin types in
1528  // attributes. So, __attribute__((iboutletcollection(char))) will be
1529  // treated as __attribute__((iboutletcollection())).
1530  if (!QT->isObjCIdType() && !QT->isObjCObjectType()) {
1531  S.Diag(AL.getLoc(),
1532  QT->isBuiltinType() ? diag::err_iboutletcollection_builtintype
1533  : diag::err_iboutletcollection_type) << QT;
1534  return;
1535  }
1536 
1537  D->addAttr(::new (S.Context) IBOutletCollectionAttr(S.Context, AL, QTLoc));
1538 }
1539 
1541  if (RefOkay) {
1542  if (T->isReferenceType())
1543  return true;
1544  } else {
1545  T = T.getNonReferenceType();
1546  }
1547 
1548  // The nonnull attribute, and other similar attributes, can be applied to a
1549  // transparent union that contains a pointer type.
1550  if (const RecordType *UT = T->getAsUnionType()) {
1551  if (UT && UT->getDecl()->hasAttr<TransparentUnionAttr>()) {
1552  RecordDecl *UD = UT->getDecl();
1553  for (const auto *I : UD->fields()) {
1554  QualType QT = I->getType();
1555  if (QT->isAnyPointerType() || QT->isBlockPointerType())
1556  return true;
1557  }
1558  }
1559  }
1560 
1561  return T->isAnyPointerType() || T->isBlockPointerType();
1562 }
1563 
1564 static bool attrNonNullArgCheck(Sema &S, QualType T, const ParsedAttr &AL,
1565  SourceRange AttrParmRange,
1566  SourceRange TypeRange,
1567  bool isReturnValue = false) {
1568  if (!S.isValidPointerAttrType(T)) {
1569  if (isReturnValue)
1570  S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
1571  << AL << AttrParmRange << TypeRange;
1572  else
1573  S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1574  << AL << AttrParmRange << TypeRange << 0;
1575  return false;
1576  }
1577  return true;
1578 }
1579 
1580 static void handleNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1581  SmallVector<ParamIdx, 8> NonNullArgs;
1582  for (unsigned I = 0; I < AL.getNumArgs(); ++I) {
1583  Expr *Ex = AL.getArgAsExpr(I);
1584  ParamIdx Idx;
1585  if (!checkFunctionOrMethodParameterIndex(S, D, AL, I + 1, Ex, Idx))
1586  return;
1587 
1588  // Is the function argument a pointer type?
1589  if (Idx.getASTIndex() < getFunctionOrMethodNumParams(D) &&
1591  S, getFunctionOrMethodParamType(D, Idx.getASTIndex()), AL,
1592  Ex->getSourceRange(),
1594  continue;
1595 
1596  NonNullArgs.push_back(Idx);
1597  }
1598 
1599  // If no arguments were specified to __attribute__((nonnull)) then all pointer
1600  // arguments have a nonnull attribute; warn if there aren't any. Skip this
1601  // check if the attribute came from a macro expansion or a template
1602  // instantiation.
1603  if (NonNullArgs.empty() && AL.getLoc().isFileID() &&
1604  !S.inTemplateInstantiation()) {
1605  bool AnyPointers = isFunctionOrMethodVariadic(D);
1606  for (unsigned I = 0, E = getFunctionOrMethodNumParams(D);
1607  I != E && !AnyPointers; ++I) {
1609  if (T->isDependentType() || S.isValidPointerAttrType(T))
1610  AnyPointers = true;
1611  }
1612 
1613  if (!AnyPointers)
1614  S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_no_pointers);
1615  }
1616 
1617  ParamIdx *Start = NonNullArgs.data();
1618  unsigned Size = NonNullArgs.size();
1619  llvm::array_pod_sort(Start, Start + Size);
1620  D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, Start, Size));
1621 }
1622 
1624  const ParsedAttr &AL) {
1625  if (AL.getNumArgs() > 0) {
1626  if (D->getFunctionType()) {
1627  handleNonNullAttr(S, D, AL);
1628  } else {
1629  S.Diag(AL.getLoc(), diag::warn_attribute_nonnull_parm_no_args)
1630  << D->getSourceRange();
1631  }
1632  return;
1633  }
1634 
1635  // Is the argument a pointer type?
1636  if (!attrNonNullArgCheck(S, D->getType(), AL, SourceRange(),
1637  D->getSourceRange()))
1638  return;
1639 
1640  D->addAttr(::new (S.Context) NonNullAttr(S.Context, AL, nullptr, 0));
1641 }
1642 
1643 static void handleReturnsNonNullAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1644  QualType ResultType = getFunctionOrMethodResultType(D);
1646  if (!attrNonNullArgCheck(S, ResultType, AL, SourceRange(), SR,
1647  /* isReturnValue */ true))
1648  return;
1649 
1650  D->addAttr(::new (S.Context) ReturnsNonNullAttr(S.Context, AL));
1651 }
1652 
1653 static void handleNoEscapeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1654  if (D->isInvalidDecl())
1655  return;
1656 
1657  // noescape only applies to pointer types.
1658  QualType T = cast<ParmVarDecl>(D)->getType();
1659  if (!S.isValidPointerAttrType(T, /* RefOkay */ true)) {
1660  S.Diag(AL.getLoc(), diag::warn_attribute_pointers_only)
1661  << AL << AL.getRange() << 0;
1662  return;
1663  }
1664 
1665  D->addAttr(::new (S.Context) NoEscapeAttr(S.Context, AL));
1666 }
1667 
1668 static void handleAssumeAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1669  Expr *E = AL.getArgAsExpr(0),
1670  *OE = AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr;
1671  S.AddAssumeAlignedAttr(D, AL, E, OE);
1672 }
1673 
1674 static void handleAllocAlignAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1675  S.AddAllocAlignAttr(D, AL, AL.getArgAsExpr(0));
1676 }
1677 
1679  Expr *OE) {
1680  QualType ResultType = getFunctionOrMethodResultType(D);
1682 
1683  AssumeAlignedAttr TmpAttr(Context, CI, E, OE);
1684  SourceLocation AttrLoc = TmpAttr.getLocation();
1685 
1686  if (!isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1687  Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1688  << &TmpAttr << TmpAttr.getRange() << SR;
1689  return;
1690  }
1691 
1692  if (!E->isValueDependent()) {
1694  if (!(I = E->getIntegerConstantExpr(Context))) {
1695  if (OE)
1696  Diag(AttrLoc, diag::err_attribute_argument_n_type)
1697  << &TmpAttr << 1 << AANT_ArgumentIntegerConstant
1698  << E->getSourceRange();
1699  else
1700  Diag(AttrLoc, diag::err_attribute_argument_type)
1701  << &TmpAttr << AANT_ArgumentIntegerConstant
1702  << E->getSourceRange();
1703  return;
1704  }
1705 
1706  if (!I->isPowerOf2()) {
1707  Diag(AttrLoc, diag::err_alignment_not_power_of_two)
1708  << E->getSourceRange();
1709  return;
1710  }
1711 
1712  if (*I > Sema::MaximumAlignment)
1713  Diag(CI.getLoc(), diag::warn_assume_aligned_too_great)
1714  << CI.getRange() << Sema::MaximumAlignment;
1715  }
1716 
1717  if (OE && !OE->isValueDependent() && !OE->isIntegerConstantExpr(Context)) {
1718  Diag(AttrLoc, diag::err_attribute_argument_n_type)
1719  << &TmpAttr << 2 << AANT_ArgumentIntegerConstant
1720  << OE->getSourceRange();
1721  return;
1722  }
1723 
1724  D->addAttr(::new (Context) AssumeAlignedAttr(Context, CI, E, OE));
1725 }
1726 
1728  Expr *ParamExpr) {
1729  QualType ResultType = getFunctionOrMethodResultType(D);
1730 
1731  AllocAlignAttr TmpAttr(Context, CI, ParamIdx());
1732  SourceLocation AttrLoc = CI.getLoc();
1733 
1734  if (!ResultType->isDependentType() &&
1735  !isValidPointerAttrType(ResultType, /* RefOkay */ true)) {
1736  Diag(AttrLoc, diag::warn_attribute_return_pointers_refs_only)
1737  << &TmpAttr << CI.getRange() << getFunctionOrMethodResultSourceRange(D);
1738  return;
1739  }
1740 
1741  ParamIdx Idx;
1742  const auto *FuncDecl = cast<FunctionDecl>(D);
1743  if (!checkFunctionOrMethodParameterIndex(*this, FuncDecl, TmpAttr,
1744  /*AttrArgNum=*/1, ParamExpr, Idx))
1745  return;
1746 
1748  if (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
1749  !Ty->isAlignValT()) {
1750  Diag(ParamExpr->getBeginLoc(), diag::err_attribute_integers_only)
1751  << &TmpAttr
1752  << FuncDecl->getParamDecl(Idx.getASTIndex())->getSourceRange();
1753  return;
1754  }
1755 
1756  D->addAttr(::new (Context) AllocAlignAttr(Context, CI, Idx));
1757 }
1758 
1759 /// Check if \p AssumptionStr is a known assumption and warn if not.
1761  StringRef AssumptionStr) {
1762  if (llvm::KnownAssumptionStrings.count(AssumptionStr))
1763  return;
1764 
1765  unsigned BestEditDistance = 3;
1766  StringRef Suggestion;
1767  for (const auto &KnownAssumptionIt : llvm::KnownAssumptionStrings) {
1768  unsigned EditDistance =
1769  AssumptionStr.edit_distance(KnownAssumptionIt.getKey());
1770  if (EditDistance < BestEditDistance) {
1771  Suggestion = KnownAssumptionIt.getKey();
1772  BestEditDistance = EditDistance;
1773  }
1774  }
1775 
1776  if (!Suggestion.empty())
1777  S.Diag(Loc, diag::warn_assume_attribute_string_unknown_suggested)
1778  << AssumptionStr << Suggestion;
1779  else
1780  S.Diag(Loc, diag::warn_assume_attribute_string_unknown) << AssumptionStr;
1781 }
1782 
1783 static void handleAssumumptionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1784  // Handle the case where the attribute has a text message.
1785  StringRef Str;
1786  SourceLocation AttrStrLoc;
1787  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &AttrStrLoc))
1788  return;
1789 
1790  checkAssumptionAttr(S, AttrStrLoc, Str);
1791 
1792  D->addAttr(::new (S.Context) AssumptionAttr(S.Context, AL, Str));
1793 }
1794 
1795 /// Normalize the attribute, __foo__ becomes foo.
1796 /// Returns true if normalization was applied.
1797 static bool normalizeName(StringRef &AttrName) {
1798  if (AttrName.size() > 4 && AttrName.startswith("__") &&
1799  AttrName.endswith("__")) {
1800  AttrName = AttrName.drop_front(2).drop_back(2);
1801  return true;
1802  }
1803  return false;
1804 }
1805 
1806 static void handleOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1807  // This attribute must be applied to a function declaration. The first
1808  // argument to the attribute must be an identifier, the name of the resource,
1809  // for example: malloc. The following arguments must be argument indexes, the
1810  // arguments must be of integer type for Returns, otherwise of pointer type.
1811  // The difference between Holds and Takes is that a pointer may still be used
1812  // after being held. free() should be __attribute((ownership_takes)), whereas
1813  // a list append function may well be __attribute((ownership_holds)).
1814 
1815  if (!AL.isArgIdent(0)) {
1816  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
1817  << AL << 1 << AANT_ArgumentIdentifier;
1818  return;
1819  }
1820 
1821  // Figure out our Kind.
1822  OwnershipAttr::OwnershipKind K =
1823  OwnershipAttr(S.Context, AL, nullptr, nullptr, 0).getOwnKind();
1824 
1825  // Check arguments.
1826  switch (K) {
1827  case OwnershipAttr::Takes:
1828  case OwnershipAttr::Holds:
1829  if (AL.getNumArgs() < 2) {
1830  S.Diag(AL.getLoc(), diag::err_attribute_too_few_arguments) << AL << 2;
1831  return;
1832  }
1833  break;
1834  case OwnershipAttr::Returns:
1835  if (AL.getNumArgs() > 2) {
1836  S.Diag(AL.getLoc(), diag::err_attribute_too_many_arguments) << AL << 1;
1837  return;
1838  }
1839  break;
1840  }
1841 
1843 
1844  StringRef ModuleName = Module->getName();
1845  if (normalizeName(ModuleName)) {
1846  Module = &S.PP.getIdentifierTable().get(ModuleName);
1847  }
1848 
1849  SmallVector<ParamIdx, 8> OwnershipArgs;
1850  for (unsigned i = 1; i < AL.getNumArgs(); ++i) {
1851  Expr *Ex = AL.getArgAsExpr(i);
1852  ParamIdx Idx;
1853  if (!checkFunctionOrMethodParameterIndex(S, D, AL, i, Ex, Idx))
1854  return;
1855 
1856  // Is the function argument a pointer type?
1858  int Err = -1; // No error
1859  switch (K) {
1860  case OwnershipAttr::Takes:
1861  case OwnershipAttr::Holds:
1862  if (!T->isAnyPointerType() && !T->isBlockPointerType())
1863  Err = 0;
1864  break;
1865  case OwnershipAttr::Returns:
1866  if (!T->isIntegerType())
1867  Err = 1;
1868  break;
1869  }
1870  if (-1 != Err) {
1871  S.Diag(AL.getLoc(), diag::err_ownership_type) << AL << Err
1872  << Ex->getSourceRange();
1873  return;
1874  }
1875 
1876  // Check we don't have a conflict with another ownership attribute.
1877  for (const auto *I : D->specific_attrs<OwnershipAttr>()) {
1878  // Cannot have two ownership attributes of different kinds for the same
1879  // index.
1880  if (I->getOwnKind() != K && llvm::is_contained(I->args(), Idx)) {
1881  S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << I;
1882  return;
1883  } else if (K == OwnershipAttr::Returns &&
1884  I->getOwnKind() == OwnershipAttr::Returns) {
1885  // A returns attribute conflicts with any other returns attribute using
1886  // a different index.
1887  if (!llvm::is_contained(I->args(), Idx)) {
1888  S.Diag(I->getLocation(), diag::err_ownership_returns_index_mismatch)
1889  << I->args_begin()->getSourceIndex();
1890  if (I->args_size())
1891  S.Diag(AL.getLoc(), diag::note_ownership_returns_index_mismatch)
1892  << Idx.getSourceIndex() << Ex->getSourceRange();
1893  return;
1894  }
1895  }
1896  }
1897  OwnershipArgs.push_back(Idx);
1898  }
1899 
1900  ParamIdx *Start = OwnershipArgs.data();
1901  unsigned Size = OwnershipArgs.size();
1902  llvm::array_pod_sort(Start, Start + Size);
1903  D->addAttr(::new (S.Context)
1904  OwnershipAttr(S.Context, AL, Module, Start, Size));
1905 }
1906 
1907 static void handleWeakRefAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1908  // Check the attribute arguments.
1909  if (AL.getNumArgs() > 1) {
1910  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
1911  return;
1912  }
1913 
1914  // gcc rejects
1915  // class c {
1916  // static int a __attribute__((weakref ("v2")));
1917  // static int b() __attribute__((weakref ("f3")));
1918  // };
1919  // and ignores the attributes of
1920  // void f(void) {
1921  // static int a __attribute__((weakref ("v2")));
1922  // }
1923  // we reject them
1924  const DeclContext *Ctx = D->getDeclContext()->getRedeclContext();
1925  if (!Ctx->isFileContext()) {
1926  S.Diag(AL.getLoc(), diag::err_attribute_weakref_not_global_context)
1927  << cast<NamedDecl>(D);
1928  return;
1929  }
1930 
1931  // The GCC manual says
1932  //
1933  // At present, a declaration to which `weakref' is attached can only
1934  // be `static'.
1935  //
1936  // It also says
1937  //
1938  // Without a TARGET,
1939  // given as an argument to `weakref' or to `alias', `weakref' is
1940  // equivalent to `weak'.
1941  //
1942  // gcc 4.4.1 will accept
1943  // int a7 __attribute__((weakref));
1944  // as
1945  // int a7 __attribute__((weak));
1946  // This looks like a bug in gcc. We reject that for now. We should revisit
1947  // it if this behaviour is actually used.
1948 
1949  // GCC rejects
1950  // static ((alias ("y"), weakref)).
1951  // Should we? How to check that weakref is before or after alias?
1952 
1953  // FIXME: it would be good for us to keep the WeakRefAttr as-written instead
1954  // of transforming it into an AliasAttr. The WeakRefAttr never uses the
1955  // StringRef parameter it was given anyway.
1956  StringRef Str;
1957  if (AL.getNumArgs() && S.checkStringLiteralArgumentAttr(AL, 0, Str))
1958  // GCC will accept anything as the argument of weakref. Should we
1959  // check for an existing decl?
1960  D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
1961 
1962  D->addAttr(::new (S.Context) WeakRefAttr(S.Context, AL));
1963 }
1964 
1965 static void handleIFuncAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1966  StringRef Str;
1967  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1968  return;
1969 
1970  // Aliases should be on declarations, not definitions.
1971  const auto *FD = cast<FunctionDecl>(D);
1972  if (FD->isThisDeclarationADefinition()) {
1973  S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 1;
1974  return;
1975  }
1976 
1977  D->addAttr(::new (S.Context) IFuncAttr(S.Context, AL, Str));
1978 }
1979 
1980 static void handleAliasAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
1981  StringRef Str;
1982  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
1983  return;
1984 
1985  if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
1986  S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_darwin);
1987  return;
1988  }
1989  if (S.Context.getTargetInfo().getTriple().isNVPTX()) {
1990  S.Diag(AL.getLoc(), diag::err_alias_not_supported_on_nvptx);
1991  }
1992 
1993  // Aliases should be on declarations, not definitions.
1994  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
1995  if (FD->isThisDeclarationADefinition()) {
1996  S.Diag(AL.getLoc(), diag::err_alias_is_definition) << FD << 0;
1997  return;
1998  }
1999  } else {
2000  const auto *VD = cast<VarDecl>(D);
2001  if (VD->isThisDeclarationADefinition() && VD->isExternallyVisible()) {
2002  S.Diag(AL.getLoc(), diag::err_alias_is_definition) << VD << 0;
2003  return;
2004  }
2005  }
2006 
2007  // Mark target used to prevent unneeded-internal-declaration warnings.
2008  if (!S.LangOpts.CPlusPlus) {
2009  // FIXME: demangle Str for C++, as the attribute refers to the mangled
2010  // linkage name, not the pre-mangled identifier.
2011  const DeclarationNameInfo target(&S.Context.Idents.get(Str), AL.getLoc());
2012  LookupResult LR(S, target, Sema::LookupOrdinaryName);
2014  for (NamedDecl *ND : LR)
2015  ND->markUsed(S.Context);
2016  }
2017 
2018  D->addAttr(::new (S.Context) AliasAttr(S.Context, AL, Str));
2019 }
2020 
2021 static void handleTLSModelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2022  StringRef Model;
2023  SourceLocation LiteralLoc;
2024  // Check that it is a string.
2025  if (!S.checkStringLiteralArgumentAttr(AL, 0, Model, &LiteralLoc))
2026  return;
2027 
2028  // Check that the value.
2029  if (Model != "global-dynamic" && Model != "local-dynamic"
2030  && Model != "initial-exec" && Model != "local-exec") {
2031  S.Diag(LiteralLoc, diag::err_attr_tlsmodel_arg);
2032  return;
2033  }
2034 
2035  if (S.Context.getTargetInfo().getTriple().isOSAIX() &&
2036  Model != "global-dynamic") {
2037  S.Diag(LiteralLoc, diag::err_aix_attr_unsupported_tls_model) << Model;
2038  return;
2039  }
2040 
2041  D->addAttr(::new (S.Context) TLSModelAttr(S.Context, AL, Model));
2042 }
2043 
2044 static void handleRestrictAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2045  QualType ResultType = getFunctionOrMethodResultType(D);
2046  if (ResultType->isAnyPointerType() || ResultType->isBlockPointerType()) {
2047  D->addAttr(::new (S.Context) RestrictAttr(S.Context, AL));
2048  return;
2049  }
2050 
2051  S.Diag(AL.getLoc(), diag::warn_attribute_return_pointers_only)
2053 }
2054 
2055 static void handleCPUSpecificAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2056  // Ensure we don't combine these with themselves, since that causes some
2057  // confusing behavior.
2058  if (AL.getParsedKind() == ParsedAttr::AT_CPUDispatch) {
2059  if (checkAttrMutualExclusion<CPUSpecificAttr>(S, D, AL))
2060  return;
2061 
2062  if (const auto *Other = D->getAttr<CPUDispatchAttr>()) {
2063  S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
2064  S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
2065  return;
2066  }
2067  } else if (AL.getParsedKind() == ParsedAttr::AT_CPUSpecific) {
2068  if (checkAttrMutualExclusion<CPUDispatchAttr>(S, D, AL))
2069  return;
2070 
2071  if (const auto *Other = D->getAttr<CPUSpecificAttr>()) {
2072  S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
2073  S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
2074  return;
2075  }
2076  }
2077 
2078  FunctionDecl *FD = cast<FunctionDecl>(D);
2079 
2080  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
2081  if (MD->getParent()->isLambda()) {
2082  S.Diag(AL.getLoc(), diag::err_attribute_dll_lambda) << AL;
2083  return;
2084  }
2085  }
2086 
2087  if (!AL.checkAtLeastNumArgs(S, 1))
2088  return;
2089 
2091  for (unsigned ArgNo = 0; ArgNo < getNumAttributeArgs(AL); ++ArgNo) {
2092  if (!AL.isArgIdent(ArgNo)) {
2093  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
2094  << AL << AANT_ArgumentIdentifier;
2095  return;
2096  }
2097 
2098  IdentifierLoc *CPUArg = AL.getArgAsIdent(ArgNo);
2099  StringRef CPUName = CPUArg->Ident->getName().trim();
2100 
2102  S.Diag(CPUArg->Loc, diag::err_invalid_cpu_specific_dispatch_value)
2103  << CPUName << (AL.getKind() == ParsedAttr::AT_CPUDispatch);
2104  return;
2105  }
2106 
2107  const TargetInfo &Target = S.Context.getTargetInfo();
2108  if (llvm::any_of(CPUs, [CPUName, &Target](const IdentifierInfo *Cur) {
2109  return Target.CPUSpecificManglingCharacter(CPUName) ==
2110  Target.CPUSpecificManglingCharacter(Cur->getName());
2111  })) {
2112  S.Diag(AL.getLoc(), diag::warn_multiversion_duplicate_entries);
2113  return;
2114  }
2115  CPUs.push_back(CPUArg->Ident);
2116  }
2117 
2118  FD->setIsMultiVersion(true);
2119  if (AL.getKind() == ParsedAttr::AT_CPUSpecific)
2120  D->addAttr(::new (S.Context)
2121  CPUSpecificAttr(S.Context, AL, CPUs.data(), CPUs.size()));
2122  else
2123  D->addAttr(::new (S.Context)
2124  CPUDispatchAttr(S.Context, AL, CPUs.data(), CPUs.size()));
2125 }
2126 
2127 static void handleCommonAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2128  if (S.LangOpts.CPlusPlus) {
2129  S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
2130  << AL << AttributeLangSupport::Cpp;
2131  return;
2132  }
2133 
2134  D->addAttr(::new (S.Context) CommonAttr(S.Context, AL));
2135 }
2136 
2137 static void handleCmseNSEntryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2138  if (S.LangOpts.CPlusPlus && !D->getDeclContext()->isExternCContext()) {
2139  S.Diag(AL.getLoc(), diag::err_attribute_not_clinkage) << AL;
2140  return;
2141  }
2142 
2143  const auto *FD = cast<FunctionDecl>(D);
2144  if (!FD->isExternallyVisible()) {
2145  S.Diag(AL.getLoc(), diag::warn_attribute_cmse_entry_static);
2146  return;
2147  }
2148 
2149  D->addAttr(::new (S.Context) CmseNSEntryAttr(S.Context, AL));
2150 }
2151 
2152 static void handleNakedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2153  if (AL.isDeclspecAttribute()) {
2154  const auto &Triple = S.getASTContext().getTargetInfo().getTriple();
2155  const auto &Arch = Triple.getArch();
2156  if (Arch != llvm::Triple::x86 &&
2157  (Arch != llvm::Triple::arm && Arch != llvm::Triple::thumb)) {
2158  S.Diag(AL.getLoc(), diag::err_attribute_not_supported_on_arch)
2159  << AL << Triple.getArchName();
2160  return;
2161  }
2162 
2163  // This form is not allowed to be written on a member function (static or
2164  // nonstatic) when in Microsoft compatibility mode.
2165  if (S.getLangOpts().MSVCCompat && isa<CXXMethodDecl>(D)) {
2166  S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type_str)
2167  << AL << "non-member functions";
2168  return;
2169  }
2170  }
2171 
2172  D->addAttr(::new (S.Context) NakedAttr(S.Context, AL));
2173 }
2174 
2175 static void handleNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2176  if (hasDeclarator(D)) return;
2177 
2178  if (!isa<ObjCMethodDecl>(D)) {
2179  S.Diag(Attrs.getLoc(), diag::warn_attribute_wrong_decl_type)
2180  << Attrs << ExpectedFunctionOrMethod;
2181  return;
2182  }
2183 
2184  D->addAttr(::new (S.Context) NoReturnAttr(S.Context, Attrs));
2185 }
2186 
2187 static void handleStandardNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &A) {
2188  // The [[_Noreturn]] spelling is deprecated in C2x, so if that was used,
2189  // issue an appropriate diagnostic. However, don't issue a diagnostic if the
2190  // attribute name comes from a macro expansion. We don't want to punish users
2191  // who write [[noreturn]] after including <stdnoreturn.h> (where 'noreturn'
2192  // is defined as a macro which expands to '_Noreturn').
2193  if (!S.getLangOpts().CPlusPlus &&
2194  A.getSemanticSpelling() == CXX11NoReturnAttr::C2x_Noreturn &&
2195  !(A.getLoc().isMacroID() &&
2197  S.Diag(A.getLoc(), diag::warn_deprecated_noreturn_spelling) << A.getRange();
2198 
2199  D->addAttr(::new (S.Context) CXX11NoReturnAttr(S.Context, A));
2200 }
2201 
2202 static void handleNoCfCheckAttr(Sema &S, Decl *D, const ParsedAttr &Attrs) {
2203  if (!S.getLangOpts().CFProtectionBranch)
2204  S.Diag(Attrs.getLoc(), diag::warn_nocf_check_attribute_ignored);
2205  else
2206  handleSimpleAttribute<AnyX86NoCfCheckAttr>(S, D, Attrs);
2207 }
2208 
2209 bool Sema::CheckAttrNoArgs(const ParsedAttr &Attrs) {
2210  if (!Attrs.checkExactlyNumArgs(*this, 0)) {
2211  Attrs.setInvalid();
2212  return true;
2213  }
2214 
2215  return false;
2216 }
2217 
2219  // Check whether the attribute is valid on the current target.
2220  if (!AL.existsInTarget(Context.getTargetInfo())) {
2221  Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2222  << AL << AL.getRange();
2223  AL.setInvalid();
2224  return true;
2225  }
2226 
2227  return false;
2228 }
2229 
2230 static void handleAnalyzerNoReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2231 
2232  // The checking path for 'noreturn' and 'analyzer_noreturn' are different
2233  // because 'analyzer_noreturn' does not impact the type.
2234  if (!isFunctionOrMethodOrBlock(D)) {
2235  ValueDecl *VD = dyn_cast<ValueDecl>(D);
2236  if (!VD || (!VD->getType()->isBlockPointerType() &&
2237  !VD->getType()->isFunctionPointerType())) {
2239  ? diag::err_attribute_wrong_decl_type
2240  : diag::warn_attribute_wrong_decl_type)
2242  return;
2243  }
2244  }
2245 
2246  D->addAttr(::new (S.Context) AnalyzerNoReturnAttr(S.Context, AL));
2247 }
2248 
2249 // PS3 PPU-specific.
2250 static void handleVecReturnAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2251  /*
2252  Returning a Vector Class in Registers
2253 
2254  According to the PPU ABI specifications, a class with a single member of
2255  vector type is returned in memory when used as the return value of a
2256  function.
2257  This results in inefficient code when implementing vector classes. To return
2258  the value in a single vector register, add the vecreturn attribute to the
2259  class definition. This attribute is also applicable to struct types.
2260 
2261  Example:
2262 
2263  struct Vector
2264  {
2265  __vector float xyzw;
2266  } __attribute__((vecreturn));
2267 
2268  Vector Add(Vector lhs, Vector rhs)
2269  {
2270  Vector result;
2271  result.xyzw = vec_add(lhs.xyzw, rhs.xyzw);
2272  return result; // This will be returned in a register
2273  }
2274  */
2275  if (VecReturnAttr *A = D->getAttr<VecReturnAttr>()) {
2276  S.Diag(AL.getLoc(), diag::err_repeat_attribute) << A;
2277  return;
2278  }
2279 
2280  const auto *R = cast<RecordDecl>(D);
2281  int count = 0;
2282 
2283  if (!isa<CXXRecordDecl>(R)) {
2284  S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2285  return;
2286  }
2287 
2288  if (!cast<CXXRecordDecl>(R)->isPOD()) {
2289  S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_pod_record);
2290  return;
2291  }
2292 
2293  for (const auto *I : R->fields()) {
2294  if ((count == 1) || !I->getType()->isVectorType()) {
2295  S.Diag(AL.getLoc(), diag::err_attribute_vecreturn_only_vector_member);
2296  return;
2297  }
2298  count++;
2299  }
2300 
2301  D->addAttr(::new (S.Context) VecReturnAttr(S.Context, AL));
2302 }
2303 
2305  const ParsedAttr &AL) {
2306  if (isa<ParmVarDecl>(D)) {
2307  // [[carries_dependency]] can only be applied to a parameter if it is a
2308  // parameter of a function declaration or lambda.
2310  S.Diag(AL.getLoc(),
2311  diag::err_carries_dependency_param_not_function_decl);
2312  return;
2313  }
2314  }
2315 
2316  D->addAttr(::new (S.Context) CarriesDependencyAttr(S.Context, AL));
2317 }
2318 
2319 static void handleUnusedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2320  bool IsCXX17Attr = AL.isCXX11Attribute() && !AL.getScopeName();
2321 
2322  // If this is spelled as the standard C++17 attribute, but not in C++17, warn
2323  // about using it as an extension.
2324  if (!S.getLangOpts().CPlusPlus17 && IsCXX17Attr)
2325  S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2326 
2327  D->addAttr(::new (S.Context) UnusedAttr(S.Context, AL));
2328 }
2329 
2330 static void handleConstructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2331  uint32_t priority = ConstructorAttr::DefaultPriority;
2332  if (S.getLangOpts().HLSL && AL.getNumArgs()) {
2333  S.Diag(AL.getLoc(), diag::err_hlsl_init_priority_unsupported);
2334  return;
2335  }
2336  if (AL.getNumArgs() &&
2337  !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2338  return;
2339 
2340  D->addAttr(::new (S.Context) ConstructorAttr(S.Context, AL, priority));
2341 }
2342 
2343 static void handleDestructorAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2344  uint32_t priority = DestructorAttr::DefaultPriority;
2345  if (AL.getNumArgs() &&
2346  !checkUInt32Argument(S, AL, AL.getArgAsExpr(0), priority))
2347  return;
2348 
2349  D->addAttr(::new (S.Context) DestructorAttr(S.Context, AL, priority));
2350 }
2351 
2352 template <typename AttrTy>
2353 static void handleAttrWithMessage(Sema &S, Decl *D, const ParsedAttr &AL) {
2354  // Handle the case where the attribute has a text message.
2355  StringRef Str;
2356  if (AL.getNumArgs() == 1 && !S.checkStringLiteralArgumentAttr(AL, 0, Str))
2357  return;
2358 
2359  D->addAttr(::new (S.Context) AttrTy(S.Context, AL, Str));
2360 }
2361 
2363  const ParsedAttr &AL) {
2364  if (!cast<ObjCProtocolDecl>(D)->isThisDeclarationADefinition()) {
2365  S.Diag(AL.getLoc(), diag::err_objc_attr_protocol_requires_definition)
2366  << AL << AL.getRange();
2367  return;
2368  }
2369 
2370  D->addAttr(::new (S.Context) ObjCExplicitProtocolImplAttr(S.Context, AL));
2371 }
2372 
2374  IdentifierInfo *Platform,
2375  VersionTuple Introduced,
2376  VersionTuple Deprecated,
2377  VersionTuple Obsoleted) {
2378  StringRef PlatformName
2379  = AvailabilityAttr::getPrettyPlatformName(Platform->getName());
2380  if (PlatformName.empty())
2381  PlatformName = Platform->getName();
2382 
2383  // Ensure that Introduced <= Deprecated <= Obsoleted (although not all
2384  // of these steps are needed).
2385  if (!Introduced.empty() && !Deprecated.empty() &&
2386  !(Introduced <= Deprecated)) {
2387  S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2388  << 1 << PlatformName << Deprecated.getAsString()
2389  << 0 << Introduced.getAsString();
2390  return true;
2391  }
2392 
2393  if (!Introduced.empty() && !Obsoleted.empty() &&
2394  !(Introduced <= Obsoleted)) {
2395  S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2396  << 2 << PlatformName << Obsoleted.getAsString()
2397  << 0 << Introduced.getAsString();
2398  return true;
2399  }
2400 
2401  if (!Deprecated.empty() && !Obsoleted.empty() &&
2402  !(Deprecated <= Obsoleted)) {
2403  S.Diag(Range.getBegin(), diag::warn_availability_version_ordering)
2404  << 2 << PlatformName << Obsoleted.getAsString()
2405  << 1 << Deprecated.getAsString();
2406  return true;
2407  }
2408 
2409  return false;
2410 }
2411 
2412 /// Check whether the two versions match.
2413 ///
2414 /// If either version tuple is empty, then they are assumed to match. If
2415 /// \p BeforeIsOkay is true, then \p X can be less than or equal to \p Y.
2416 static bool versionsMatch(const VersionTuple &X, const VersionTuple &Y,
2417  bool BeforeIsOkay) {
2418  if (X.empty() || Y.empty())
2419  return true;
2420 
2421  if (X == Y)
2422  return true;
2423 
2424  if (BeforeIsOkay && X < Y)
2425  return true;
2426 
2427  return false;
2428 }
2429 
2431  NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform,
2432  bool Implicit, VersionTuple Introduced, VersionTuple Deprecated,
2433  VersionTuple Obsoleted, bool IsUnavailable, StringRef Message,
2434  bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK,
2435  int Priority) {
2436  VersionTuple MergedIntroduced = Introduced;
2437  VersionTuple MergedDeprecated = Deprecated;
2438  VersionTuple MergedObsoleted = Obsoleted;
2439  bool FoundAny = false;
2440  bool OverrideOrImpl = false;
2441  switch (AMK) {
2442  case AMK_None:
2443  case AMK_Redeclaration:
2444  OverrideOrImpl = false;
2445  break;
2446 
2447  case AMK_Override:
2448  case AMK_ProtocolImplementation:
2449  case AMK_OptionalProtocolImplementation:
2450  OverrideOrImpl = true;
2451  break;
2452  }
2453 
2454  if (D->hasAttrs()) {
2455  AttrVec &Attrs = D->getAttrs();
2456  for (unsigned i = 0, e = Attrs.size(); i != e;) {
2457  const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2458  if (!OldAA) {
2459  ++i;
2460  continue;
2461  }
2462 
2463  IdentifierInfo *OldPlatform = OldAA->getPlatform();
2464  if (OldPlatform != Platform) {
2465  ++i;
2466  continue;
2467  }
2468 
2469  // If there is an existing availability attribute for this platform that
2470  // has a lower priority use the existing one and discard the new
2471  // attribute.
2472  if (OldAA->getPriority() < Priority)
2473  return nullptr;
2474 
2475  // If there is an existing attribute for this platform that has a higher
2476  // priority than the new attribute then erase the old one and continue
2477  // processing the attributes.
2478  if (OldAA->getPriority() > Priority) {
2479  Attrs.erase(Attrs.begin() + i);
2480  --e;
2481  continue;
2482  }
2483 
2484  FoundAny = true;
2485  VersionTuple OldIntroduced = OldAA->getIntroduced();
2486  VersionTuple OldDeprecated = OldAA->getDeprecated();
2487  VersionTuple OldObsoleted = OldAA->getObsoleted();
2488  bool OldIsUnavailable = OldAA->getUnavailable();
2489 
2490  if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2491  !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2492  !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2493  !(OldIsUnavailable == IsUnavailable ||
2494  (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2495  if (OverrideOrImpl) {
2496  int Which = -1;
2497  VersionTuple FirstVersion;
2498  VersionTuple SecondVersion;
2499  if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2500  Which = 0;
2501  FirstVersion = OldIntroduced;
2502  SecondVersion = Introduced;
2503  } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2504  Which = 1;
2505  FirstVersion = Deprecated;
2506  SecondVersion = OldDeprecated;
2507  } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2508  Which = 2;
2509  FirstVersion = Obsoleted;
2510  SecondVersion = OldObsoleted;
2511  }
2512 
2513  if (Which == -1) {
2514  Diag(OldAA->getLocation(),
2515  diag::warn_mismatched_availability_override_unavail)
2516  << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2517  << (AMK == AMK_Override);
2518  } else if (Which != 1 && AMK == AMK_OptionalProtocolImplementation) {
2519  // Allow different 'introduced' / 'obsoleted' availability versions
2520  // on a method that implements an optional protocol requirement. It
2521  // makes less sense to allow this for 'deprecated' as the user can't
2522  // see if the method is 'deprecated' as 'respondsToSelector' will
2523  // still return true when the method is deprecated.
2524  ++i;
2525  continue;
2526  } else {
2527  Diag(OldAA->getLocation(),
2528  diag::warn_mismatched_availability_override)
2529  << Which
2530  << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2531  << FirstVersion.getAsString() << SecondVersion.getAsString()
2532  << (AMK == AMK_Override);
2533  }
2534  if (AMK == AMK_Override)
2535  Diag(CI.getLoc(), diag::note_overridden_method);
2536  else
2537  Diag(CI.getLoc(), diag::note_protocol_method);
2538  } else {
2539  Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2540  Diag(CI.getLoc(), diag::note_previous_attribute);
2541  }
2542 
2543  Attrs.erase(Attrs.begin() + i);
2544  --e;
2545  continue;
2546  }
2547 
2548  VersionTuple MergedIntroduced2 = MergedIntroduced;
2549  VersionTuple MergedDeprecated2 = MergedDeprecated;
2550  VersionTuple MergedObsoleted2 = MergedObsoleted;
2551 
2552  if (MergedIntroduced2.empty())
2553  MergedIntroduced2 = OldIntroduced;
2554  if (MergedDeprecated2.empty())
2555  MergedDeprecated2 = OldDeprecated;
2556  if (MergedObsoleted2.empty())
2557  MergedObsoleted2 = OldObsoleted;
2558 
2559  if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2560  MergedIntroduced2, MergedDeprecated2,
2561  MergedObsoleted2)) {
2562  Attrs.erase(Attrs.begin() + i);
2563  --e;
2564  continue;
2565  }
2566 
2567  MergedIntroduced = MergedIntroduced2;
2568  MergedDeprecated = MergedDeprecated2;
2569  MergedObsoleted = MergedObsoleted2;
2570  ++i;
2571  }
2572  }
2573 
2574  if (FoundAny &&
2575  MergedIntroduced == Introduced &&
2576  MergedDeprecated == Deprecated &&
2577  MergedObsoleted == Obsoleted)
2578  return nullptr;
2579 
2580  // Only create a new attribute if !OverrideOrImpl, but we want to do
2581  // the checking.
2582  if (!checkAvailabilityAttr(*this, CI.getRange(), Platform, MergedIntroduced,
2583  MergedDeprecated, MergedObsoleted) &&
2584  !OverrideOrImpl) {
2585  auto *Avail = ::new (Context) AvailabilityAttr(
2586  Context, CI, Platform, Introduced, Deprecated, Obsoleted, IsUnavailable,
2587  Message, IsStrict, Replacement, Priority);
2588  Avail->setImplicit(Implicit);
2589  return Avail;
2590  }
2591  return nullptr;
2592 }
2593 
2594 static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2595  if (isa<UsingDecl, UnresolvedUsingTypenameDecl, UnresolvedUsingValueDecl>(
2596  D)) {
2597  S.Diag(AL.getRange().getBegin(), diag::warn_deprecated_ignored_on_using)
2598  << AL;
2599  return;
2600  }
2601 
2602  if (!AL.checkExactlyNumArgs(S, 1))
2603  return;
2604  IdentifierLoc *Platform = AL.getArgAsIdent(0);
2605 
2606  IdentifierInfo *II = Platform->Ident;
2607  if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2608  S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2609  << Platform->Ident;
2610 
2611  auto *ND = dyn_cast<NamedDecl>(D);
2612  if (!ND) // We warned about this already, so just return.
2613  return;
2614 
2618  bool IsUnavailable = AL.getUnavailableLoc().isValid();
2619  bool IsStrict = AL.getStrictLoc().isValid();
2620  StringRef Str;
2621  if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getMessageExpr()))
2622  Str = SE->getString();
2623  StringRef Replacement;
2624  if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getReplacementExpr()))
2625  Replacement = SE->getString();
2626 
2627  if (II->isStr("swift")) {
2628  if (Introduced.isValid() || Obsoleted.isValid() ||
2629  (!IsUnavailable && !Deprecated.isValid())) {
2630  S.Diag(AL.getLoc(),
2631  diag::warn_availability_swift_unavailable_deprecated_only);
2632  return;
2633  }
2634  }
2635 
2636  if (II->isStr("fuchsia")) {
2637  Optional<unsigned> Min, Sub;
2638  if ((Min = Introduced.Version.getMinor()) ||
2639  (Sub = Introduced.Version.getSubminor())) {
2640  S.Diag(AL.getLoc(), diag::warn_availability_fuchsia_unavailable_minor);
2641  return;
2642  }
2643  }
2644 
2645  int PriorityModifier = AL.isPragmaClangAttribute()
2648  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2649  ND, AL, II, false /*Implicit*/, Introduced.Version, Deprecated.Version,
2650  Obsoleted.Version, IsUnavailable, Str, IsStrict, Replacement,
2651  Sema::AMK_None, PriorityModifier);
2652  if (NewAttr)
2653  D->addAttr(NewAttr);
2654 
2655  // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2656  // matches before the start of the watchOS platform.
2657  if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2658  IdentifierInfo *NewII = nullptr;
2659  if (II->getName() == "ios")
2660  NewII = &S.Context.Idents.get("watchos");
2661  else if (II->getName() == "ios_app_extension")
2662  NewII = &S.Context.Idents.get("watchos_app_extension");
2663 
2664  if (NewII) {
2665  const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking();
2666  const auto *IOSToWatchOSMapping =
2667  SDKInfo ? SDKInfo->getVersionMapping(
2669  : nullptr;
2670 
2671  auto adjustWatchOSVersion =
2672  [IOSToWatchOSMapping](VersionTuple Version) -> VersionTuple {
2673  if (Version.empty())
2674  return Version;
2675  auto MinimumWatchOSVersion = VersionTuple(2, 0);
2676 
2677  if (IOSToWatchOSMapping) {
2678  if (auto MappedVersion = IOSToWatchOSMapping->map(
2679  Version, MinimumWatchOSVersion, None)) {
2680  return MappedVersion.value();
2681  }
2682  }
2683 
2684  auto Major = Version.getMajor();
2685  auto NewMajor = Major >= 9 ? Major - 7 : 0;
2686  if (NewMajor >= 2) {
2687  if (Version.getMinor()) {
2688  if (Version.getSubminor())
2689  return VersionTuple(NewMajor, Version.getMinor().value(),
2690  Version.getSubminor().value());
2691  else
2692  return VersionTuple(NewMajor, Version.getMinor().value());
2693  }
2694  return VersionTuple(NewMajor);
2695  }
2696 
2697  return MinimumWatchOSVersion;
2698  };
2699 
2700  auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2701  auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2702  auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2703 
2704  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2705  ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2706  NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2708  PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2709  if (NewAttr)
2710  D->addAttr(NewAttr);
2711  }
2712  } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2713  // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2714  // matches before the start of the tvOS platform.
2715  IdentifierInfo *NewII = nullptr;
2716  if (II->getName() == "ios")
2717  NewII = &S.Context.Idents.get("tvos");
2718  else if (II->getName() == "ios_app_extension")
2719  NewII = &S.Context.Idents.get("tvos_app_extension");
2720 
2721  if (NewII) {
2722  const auto *SDKInfo = S.getDarwinSDKInfoForAvailabilityChecking();
2723  const auto *IOSToTvOSMapping =
2724  SDKInfo ? SDKInfo->getVersionMapping(
2726  : nullptr;
2727 
2728  auto AdjustTvOSVersion =
2729  [IOSToTvOSMapping](VersionTuple Version) -> VersionTuple {
2730  if (Version.empty())
2731  return Version;
2732 
2733  if (IOSToTvOSMapping) {
2734  if (auto MappedVersion =
2735  IOSToTvOSMapping->map(Version, VersionTuple(0, 0), None)) {
2736  return *MappedVersion;
2737  }
2738  }
2739  return Version;
2740  };
2741 
2742  auto NewIntroduced = AdjustTvOSVersion(Introduced.Version);
2743  auto NewDeprecated = AdjustTvOSVersion(Deprecated.Version);
2744  auto NewObsoleted = AdjustTvOSVersion(Obsoleted.Version);
2745 
2746  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2747  ND, AL, NewII, true /*Implicit*/, NewIntroduced, NewDeprecated,
2748  NewObsoleted, IsUnavailable, Str, IsStrict, Replacement,
2750  PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2751  if (NewAttr)
2752  D->addAttr(NewAttr);
2753  }
2754  } else if (S.Context.getTargetInfo().getTriple().getOS() ==
2755  llvm::Triple::IOS &&
2756  S.Context.getTargetInfo().getTriple().isMacCatalystEnvironment()) {
2757  auto GetSDKInfo = [&]() {
2759  "macOS");
2760  };
2761 
2762  // Transcribe "ios" to "maccatalyst" (and add a new attribute).
2763  IdentifierInfo *NewII = nullptr;
2764  if (II->getName() == "ios")
2765  NewII = &S.Context.Idents.get("maccatalyst");
2766  else if (II->getName() == "ios_app_extension")
2767  NewII = &S.Context.Idents.get("maccatalyst_app_extension");
2768  if (NewII) {
2769  auto MinMacCatalystVersion = [](const VersionTuple &V) {
2770  if (V.empty())
2771  return V;
2772  if (V.getMajor() < 13 ||
2773  (V.getMajor() == 13 && V.getMinor() && *V.getMinor() < 1))
2774  return VersionTuple(13, 1); // The min Mac Catalyst version is 13.1.
2775  return V;
2776  };
2777  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2778  ND, AL.getRange(), NewII, true /*Implicit*/,
2779  MinMacCatalystVersion(Introduced.Version),
2780  MinMacCatalystVersion(Deprecated.Version),
2781  MinMacCatalystVersion(Obsoleted.Version), IsUnavailable, Str,
2782  IsStrict, Replacement, Sema::AMK_None,
2783  PriorityModifier + Sema::AP_InferredFromOtherPlatform);
2784  if (NewAttr)
2785  D->addAttr(NewAttr);
2786  } else if (II->getName() == "macos" && GetSDKInfo() &&
2787  (!Introduced.Version.empty() || !Deprecated.Version.empty() ||
2788  !Obsoleted.Version.empty())) {
2789  if (const auto *MacOStoMacCatalystMapping =
2790  GetSDKInfo()->getVersionMapping(
2792  // Infer Mac Catalyst availability from the macOS availability attribute
2793  // if it has versioned availability. Don't infer 'unavailable'. This
2794  // inferred availability has lower priority than the other availability
2795  // attributes that are inferred from 'ios'.
2796  NewII = &S.Context.Idents.get("maccatalyst");
2797  auto RemapMacOSVersion =
2798  [&](const VersionTuple &V) -> Optional<VersionTuple> {
2799  if (V.empty())
2800  return None;
2801  // API_TO_BE_DEPRECATED is 100000.
2802  if (V.getMajor() == 100000)
2803  return VersionTuple(100000);
2804  // The minimum iosmac version is 13.1
2805  return MacOStoMacCatalystMapping->map(V, VersionTuple(13, 1), None);
2806  };
2807  Optional<VersionTuple> NewIntroduced =
2808  RemapMacOSVersion(Introduced.Version),
2809  NewDeprecated =
2810  RemapMacOSVersion(Deprecated.Version),
2811  NewObsoleted =
2812  RemapMacOSVersion(Obsoleted.Version);
2813  if (NewIntroduced || NewDeprecated || NewObsoleted) {
2814  auto VersionOrEmptyVersion =
2815  [](const Optional<VersionTuple> &V) -> VersionTuple {
2816  return V ? *V : VersionTuple();
2817  };
2818  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2819  ND, AL.getRange(), NewII, true /*Implicit*/,
2820  VersionOrEmptyVersion(NewIntroduced),
2821  VersionOrEmptyVersion(NewDeprecated),
2822  VersionOrEmptyVersion(NewObsoleted), /*IsUnavailable=*/false, Str,
2823  IsStrict, Replacement, Sema::AMK_None,
2824  PriorityModifier + Sema::AP_InferredFromOtherPlatform +
2826  if (NewAttr)
2827  D->addAttr(NewAttr);
2828  }
2829  }
2830  }
2831  }
2832 }
2833 
2835  const ParsedAttr &AL) {
2836  if (!AL.checkAtLeastNumArgs(S, 1) || !AL.checkAtMostNumArgs(S, 3))
2837  return;
2838 
2839  StringRef Language;
2840  if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0)))
2841  Language = SE->getString();
2842  StringRef DefinedIn;
2843  if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1)))
2844  DefinedIn = SE->getString();
2845  bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
2846 
2847  D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2848  S.Context, AL, Language, DefinedIn, IsGeneratedDeclaration));
2849 }
2850 
2851 template <class T>
2852 static T *mergeVisibilityAttr(Sema &S, Decl *D, const AttributeCommonInfo &CI,
2853  typename T::VisibilityType value) {
2854  T *existingAttr = D->getAttr<T>();
2855  if (existingAttr) {
2856  typename T::VisibilityType existingValue = existingAttr->getVisibility();
2857  if (existingValue == value)
2858  return nullptr;
2859  S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2860  S.Diag(CI.getLoc(), diag::note_previous_attribute);
2861  D->dropAttr<T>();
2862  }
2863  return ::new (S.Context) T(S.Context, CI, value);
2864 }
2865 
2866 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D,
2867  const AttributeCommonInfo &CI,
2868  VisibilityAttr::VisibilityType Vis) {
2869  return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, CI, Vis);
2870 }
2871 
2872 TypeVisibilityAttr *
2874  TypeVisibilityAttr::VisibilityType Vis) {
2875  return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, CI, Vis);
2876 }
2877 
2878 static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
2879  bool isTypeVisibility) {
2880  // Visibility attributes don't mean anything on a typedef.
2881  if (isa<TypedefNameDecl>(D)) {
2882  S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
2883  return;
2884  }
2885 
2886  // 'type_visibility' can only go on a type or namespace.
2887  if (isTypeVisibility &&
2888  !(isa<TagDecl>(D) ||
2889  isa<ObjCInterfaceDecl>(D) ||
2890  isa<NamespaceDecl>(D))) {
2891  S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2892  << AL << ExpectedTypeOrNamespace;
2893  return;
2894  }
2895 
2896  // Check that the argument is a string literal.
2897  StringRef TypeStr;
2898  SourceLocation LiteralLoc;
2899  if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
2900  return;
2901 
2902  VisibilityAttr::VisibilityType type;
2903  if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2904  S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
2905  << TypeStr;
2906  return;
2907  }
2908 
2909  // Complain about attempts to use protected visibility on targets
2910  // (like Darwin) that don't support it.
2911  if (type == VisibilityAttr::Protected &&
2913  S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
2914  type = VisibilityAttr::Default;
2915  }
2916 
2917  Attr *newAttr;
2918  if (isTypeVisibility) {
2919  newAttr = S.mergeTypeVisibilityAttr(
2920  D, AL, (TypeVisibilityAttr::VisibilityType)type);
2921  } else {
2922  newAttr = S.mergeVisibilityAttr(D, AL, type);
2923  }
2924  if (newAttr)
2925  D->addAttr(newAttr);
2926 }
2927 
2928 static void handleObjCDirectAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2929  // objc_direct cannot be set on methods declared in the context of a protocol
2930  if (isa<ObjCProtocolDecl>(D->getDeclContext())) {
2931  S.Diag(AL.getLoc(), diag::err_objc_direct_on_protocol) << false;
2932  return;
2933  }
2934 
2936  handleSimpleAttribute<ObjCDirectAttr>(S, D, AL);
2937  } else {
2938  S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
2939  }
2940 }
2941 
2943  const ParsedAttr &AL) {
2945  handleSimpleAttribute<ObjCDirectMembersAttr>(S, D, AL);
2946  } else {
2947  S.Diag(AL.getLoc(), diag::warn_objc_direct_ignored) << AL;
2948  }
2949 }
2950 
2951 static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2952  const auto *M = cast<ObjCMethodDecl>(D);
2953  if (!AL.isArgIdent(0)) {
2954  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2955  << AL << 1 << AANT_ArgumentIdentifier;
2956  return;
2957  }
2958 
2959  IdentifierLoc *IL = AL.getArgAsIdent(0);
2960  ObjCMethodFamilyAttr::FamilyKind F;
2961  if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2962  S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident;
2963  return;
2964  }
2965 
2966  if (F == ObjCMethodFamilyAttr::OMF_init &&
2967  !M->getReturnType()->isObjCObjectPointerType()) {
2968  S.Diag(M->getLocation(), diag::err_init_method_bad_return_type)
2969  << M->getReturnType();
2970  // Ignore the attribute.
2971  return;
2972  }
2973 
2974  D->addAttr(new (S.Context) ObjCMethodFamilyAttr(S.Context, AL, F));
2975 }
2976 
2977 static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) {
2978  if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2979  QualType T = TD->getUnderlyingType();
2980  if (!T->isCARCBridgableType()) {
2981  S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2982  return;
2983  }
2984  }
2985  else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2986  QualType T = PD->getType();
2987  if (!T->isCARCBridgableType()) {
2988  S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2989  return;
2990  }
2991  }
2992  else {
2993  // It is okay to include this attribute on properties, e.g.:
2994  //
2995  // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2996  //
2997  // In this case it follows tradition and suppresses an error in the above
2998  // case.
2999  S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
3000  }
3001  D->addAttr(::new (S.Context) ObjCNSObjectAttr(S.Context, AL));
3002 }
3003 
3004 static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) {
3005  if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
3006  QualType T = TD->getUnderlyingType();
3007  if (!T->isObjCObjectPointerType()) {
3008  S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
3009  return;
3010  }
3011  } else {
3012  S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
3013  return;
3014  }
3015  D->addAttr(::new (S.Context) ObjCIndependentClassAttr(S.Context, AL));
3016 }
3017 
3018 static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3019  if (!AL.isArgIdent(0)) {
3020  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3021  << AL << 1 << AANT_ArgumentIdentifier;
3022  return;
3023  }
3024 
3025  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3026  BlocksAttr::BlockType type;
3027  if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
3028  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3029  return;
3030  }
3031 
3032  D->addAttr(::new (S.Context) BlocksAttr(S.Context, AL, type));
3033 }
3034 
3035 static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3036  unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
3037  if (AL.getNumArgs() > 0) {
3038  Expr *E = AL.getArgAsExpr(0);
3040  if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) {
3041  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3042  << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
3043  return;
3044  }
3045 
3046  if (Idx->isSigned() && Idx->isNegative()) {
3047  S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
3048  << E->getSourceRange();
3049  return;
3050  }
3051 
3052  sentinel = Idx->getZExtValue();
3053  }
3054 
3055  unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
3056  if (AL.getNumArgs() > 1) {
3057  Expr *E = AL.getArgAsExpr(1);
3059  if (E->isTypeDependent() || !(Idx = E->getIntegerConstantExpr(S.Context))) {
3060  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3061  << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
3062  return;
3063  }
3064  nullPos = Idx->getZExtValue();
3065 
3066  if ((Idx->isSigned() && Idx->isNegative()) || nullPos > 1) {
3067  // FIXME: This error message could be improved, it would be nice
3068  // to say what the bounds actually are.
3069  S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
3070  << E->getSourceRange();
3071  return;
3072  }
3073  }
3074 
3075  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3076  const FunctionType *FT = FD->getType()->castAs<FunctionType>();
3077  if (isa<FunctionNoProtoType>(FT)) {
3078  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
3079  return;
3080  }
3081 
3082  if (!cast<FunctionProtoType>(FT)->isVariadic()) {
3083  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
3084  return;
3085  }
3086  } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
3087  if (!MD->isVariadic()) {
3088  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
3089  return;
3090  }
3091  } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
3092  if (!BD->isVariadic()) {
3093  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
3094  return;
3095  }
3096  } else if (const auto *V = dyn_cast<VarDecl>(D)) {
3097  QualType Ty = V->getType();
3098  if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
3099  const FunctionType *FT = Ty->isFunctionPointerType()
3100  ? D->getFunctionType()
3101  : Ty->castAs<BlockPointerType>()
3102  ->getPointeeType()
3103  ->castAs<FunctionType>();
3104  if (!cast<FunctionProtoType>(FT)->isVariadic()) {
3105  int m = Ty->isFunctionPointerType() ? 0 : 1;
3106  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
3107  return;
3108  }
3109  } else {
3110  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
3112  return;
3113  }
3114  } else {
3115  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
3117  return;
3118  }
3119  D->addAttr(::new (S.Context) SentinelAttr(S.Context, AL, sentinel, nullPos));
3120 }
3121 
3122 static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
3123  if (D->getFunctionType() &&
3125  !isa<CXXConstructorDecl>(D)) {
3126  S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
3127  return;
3128  }
3129  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
3130  if (MD->getReturnType()->isVoidType()) {
3131  S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
3132  return;
3133  }
3134 
3135  StringRef Str;
3136  if (AL.isStandardAttributeSyntax() && !AL.getScopeName()) {
3137  // The standard attribute cannot be applied to variable declarations such
3138  // as a function pointer.
3139  if (isa<VarDecl>(D))
3140  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type_str)
3141  << AL << "functions, classes, or enumerations";
3142 
3143  // If this is spelled as the standard C++17 attribute, but not in C++17,
3144  // warn about using it as an extension. If there are attribute arguments,
3145  // then claim it's a C++2a extension instead.
3146  // FIXME: If WG14 does not seem likely to adopt the same feature, add an
3147  // extension warning for C2x mode.
3148  const LangOptions &LO = S.getLangOpts();
3149  if (AL.getNumArgs() == 1) {
3150  if (LO.CPlusPlus && !LO.CPlusPlus20)
3151  S.Diag(AL.getLoc(), diag::ext_cxx20_attr) << AL;
3152 
3153  // Since this is spelled [[nodiscard]], get the optional string
3154  // literal. If in C++ mode, but not in C++2a mode, diagnose as an
3155  // extension.
3156  // FIXME: C2x should support this feature as well, even as an extension.
3157  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, nullptr))
3158  return;
3159  } else if (LO.CPlusPlus && !LO.CPlusPlus17)
3160  S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
3161  }
3162 
3163  if ((!AL.isGNUAttribute() &&
3164  !(AL.isStandardAttributeSyntax() && AL.isClangScope())) &&
3165  isa<TypedefNameDecl>(D)) {
3166  S.Diag(AL.getLoc(), diag::warn_unused_result_typedef_unsupported_spelling)
3167  << AL.isGNUScope();
3168  return;
3169  }
3170 
3171  D->addAttr(::new (S.Context) WarnUnusedResultAttr(S.Context, AL, Str));
3172 }
3173 
3174 static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3175  // weak_import only applies to variable & function declarations.
3176  bool isDef = false;
3177  if (!D->canBeWeakImported(isDef)) {
3178  if (isDef)
3179  S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
3180  << "weak_import";
3181  else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
3182  (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
3183  (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
3184  // Nothing to warn about here.
3185  } else
3186  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
3187  << AL << ExpectedVariableOrFunction;
3188 
3189  return;
3190  }
3191 
3192  D->addAttr(::new (S.Context) WeakImportAttr(S.Context, AL));
3193 }
3194 
3195 // Handles reqd_work_group_size and work_group_size_hint.
3196 template <typename WorkGroupAttr>
3197 static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
3198  uint32_t WGSize[3];
3199  for (unsigned i = 0; i < 3; ++i) {
3200  const Expr *E = AL.getArgAsExpr(i);
3201  if (!checkUInt32Argument(S, AL, E, WGSize[i], i,
3202  /*StrictlyUnsigned=*/true))
3203  return;
3204  if (WGSize[i] == 0) {
3205  S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
3206  << AL << E->getSourceRange();
3207  return;
3208  }
3209  }
3210 
3211  WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
3212  if (Existing && !(Existing->getXDim() == WGSize[0] &&
3213  Existing->getYDim() == WGSize[1] &&
3214  Existing->getZDim() == WGSize[2]))
3215  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3216 
3217  D->addAttr(::new (S.Context)
3218  WorkGroupAttr(S.Context, AL, WGSize[0], WGSize[1], WGSize[2]));
3219 }
3220 
3221 // Handles intel_reqd_sub_group_size.
3222 static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
3223  uint32_t SGSize;
3224  const Expr *E = AL.getArgAsExpr(0);
3225  if (!checkUInt32Argument(S, AL, E, SGSize))
3226  return;
3227  if (SGSize == 0) {
3228  S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
3229  << AL << E->getSourceRange();
3230  return;
3231  }
3232 
3233  OpenCLIntelReqdSubGroupSizeAttr *Existing =
3234  D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
3235  if (Existing && Existing->getSubGroupSize() != SGSize)
3236  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3237 
3238  D->addAttr(::new (S.Context)
3239  OpenCLIntelReqdSubGroupSizeAttr(S.Context, AL, SGSize));
3240 }
3241 
3242 static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
3243  if (!AL.hasParsedType()) {
3244  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3245  return;
3246  }
3247 
3248  TypeSourceInfo *ParmTSI = nullptr;
3249  QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
3250  assert(ParmTSI && "no type source info for attribute argument");
3251 
3252  if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
3253  (ParmType->isBooleanType() ||
3254  !ParmType->isIntegralType(S.getASTContext()))) {
3255  S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument) << 2 << AL;
3256  return;
3257  }
3258 
3259  if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
3260  if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
3261  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3262  return;
3263  }
3264  }
3265 
3266  D->addAttr(::new (S.Context) VecTypeHintAttr(S.Context, AL, ParmTSI));
3267 }
3268 
3270  StringRef Name) {
3271  // Explicit or partial specializations do not inherit
3272  // the section attribute from the primary template.
3273  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3274  if (CI.getAttributeSpellingListIndex() == SectionAttr::Declspec_allocate &&
3276  return nullptr;
3277  }
3278  if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
3279  if (ExistingAttr->getName() == Name)
3280  return nullptr;
3281  Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3282  << 1 /*section*/;
3283  Diag(CI.getLoc(), diag::note_previous_attribute);
3284  return nullptr;
3285  }
3286  return ::new (Context) SectionAttr(Context, CI, Name);
3287 }
3288 
3289 /// Used to implement to perform semantic checking on
3290 /// attribute((section("foo"))) specifiers.
3291 ///
3292 /// In this case, "foo" is passed in to be checked. If the section
3293 /// specifier is invalid, return an Error that indicates the problem.
3294 ///
3295 /// This is a simple quality of implementation feature to catch errors
3296 /// and give good diagnostics in cases when the assembler or code generator
3297 /// would otherwise reject the section specifier.
3298 llvm::Error Sema::isValidSectionSpecifier(StringRef SecName) {
3299  if (!Context.getTargetInfo().getTriple().isOSDarwin())
3300  return llvm::Error::success();
3301 
3302  // Let MCSectionMachO validate this.
3303  StringRef Segment, Section;
3304  unsigned TAA, StubSize;
3305  bool HasTAA;
3306  return llvm::MCSectionMachO::ParseSectionSpecifier(SecName, Segment, Section,
3307  TAA, HasTAA, StubSize);
3308 }
3309 
3310 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
3311  if (llvm::Error E = isValidSectionSpecifier(SecName)) {
3312  Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3313  << toString(std::move(E)) << 1 /*'section'*/;
3314  return false;
3315  }
3316  return true;
3317 }
3318 
3319 static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3320  // Make sure that there is a string literal as the sections's single
3321  // argument.
3322  StringRef Str;
3323  SourceLocation LiteralLoc;
3324  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3325  return;
3326 
3327  if (!S.checkSectionName(LiteralLoc, Str))
3328  return;
3329 
3330  SectionAttr *NewAttr = S.mergeSectionAttr(D, AL, Str);
3331  if (NewAttr) {
3332  D->addAttr(NewAttr);
3334  ObjCPropertyDecl>(D))
3335  S.UnifySection(NewAttr->getName(),
3337  cast<NamedDecl>(D));
3338  }
3339 }
3340 
3341 // This is used for `__declspec(code_seg("segname"))` on a decl.
3342 // `#pragma code_seg("segname")` uses checkSectionName() instead.
3343 static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc,
3344  StringRef CodeSegName) {
3345  if (llvm::Error E = S.isValidSectionSpecifier(CodeSegName)) {
3346  S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3347  << toString(std::move(E)) << 0 /*'code-seg'*/;
3348  return false;
3349  }
3350 
3351  return true;
3352 }
3353 
3355  StringRef Name) {
3356  // Explicit or partial specializations do not inherit
3357  // the code_seg attribute from the primary template.
3358  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3360  return nullptr;
3361  }
3362  if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3363  if (ExistingAttr->getName() == Name)
3364  return nullptr;
3365  Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3366  << 0 /*codeseg*/;
3367  Diag(CI.getLoc(), diag::note_previous_attribute);
3368  return nullptr;
3369  }
3370  return ::new (Context) CodeSegAttr(Context, CI, Name);
3371 }
3372 
3373 static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3374  StringRef Str;
3375  SourceLocation LiteralLoc;
3376  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3377  return;
3378  if (!checkCodeSegName(S, LiteralLoc, Str))
3379  return;
3380  if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3381  if (!ExistingAttr->isImplicit()) {
3382  S.Diag(AL.getLoc(),
3383  ExistingAttr->getName() == Str
3384  ? diag::warn_duplicate_codeseg_attribute
3385  : diag::err_conflicting_codeseg_attribute);
3386  return;
3387  }
3388  D->dropAttr<CodeSegAttr>();
3389  }
3390  if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL, Str))
3391  D->addAttr(CSA);
3392 }
3393 
3394 // Check for things we'd like to warn about. Multiversioning issues are
3395 // handled later in the process, once we know how many exist.
3396 bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3397  enum FirstParam { Unsupported, Duplicate, Unknown };
3398  enum SecondParam { None, CPU, Tune };
3399  enum ThirdParam { Target, TargetClones };
3400  if (AttrStr.contains("fpmath="))
3401  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3402  << Unsupported << None << "fpmath=" << Target;
3403 
3404  // Diagnose use of tune if target doesn't support it.
3405  if (!Context.getTargetInfo().supportsTargetAttributeTune() &&
3406  AttrStr.contains("tune="))
3407  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3408  << Unsupported << None << "tune=" << Target;
3409 
3410  ParsedTargetAttr ParsedAttrs =
3411  Context.getTargetInfo().parseTargetAttr(AttrStr);
3412 
3413  if (!ParsedAttrs.CPU.empty() &&
3414  !Context.getTargetInfo().isValidCPUName(ParsedAttrs.CPU))
3415  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3416  << Unknown << CPU << ParsedAttrs.CPU << Target;
3417 
3418  if (!ParsedAttrs.Tune.empty() &&
3419  !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Tune))
3420  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3421  << Unknown << Tune << ParsedAttrs.Tune << Target;
3422 
3423  if (ParsedAttrs.Duplicate != "")
3424  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3425  << Duplicate << None << ParsedAttrs.Duplicate << Target;
3426 
3427  for (const auto &Feature : ParsedAttrs.Features) {
3428  auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3429  if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3430  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3431  << Unsupported << None << CurFeature << Target;
3432  }
3433 
3435  StringRef DiagMsg;
3436  if (ParsedAttrs.BranchProtection.empty())
3437  return false;
3438  if (!Context.getTargetInfo().validateBranchProtection(
3439  ParsedAttrs.BranchProtection, ParsedAttrs.CPU, BPI, DiagMsg)) {
3440  if (DiagMsg.empty())
3441  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3442  << Unsupported << None << "branch-protection" << Target;
3443  return Diag(LiteralLoc, diag::err_invalid_branch_protection_spec)
3444  << DiagMsg;
3445  }
3446  if (!DiagMsg.empty())
3447  Diag(LiteralLoc, diag::warn_unsupported_branch_protection_spec) << DiagMsg;
3448 
3449  return false;
3450 }
3451 
3452 static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3453  StringRef Str;
3454  SourceLocation LiteralLoc;
3455  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3456  S.checkTargetAttr(LiteralLoc, Str))
3457  return;
3458 
3459  TargetAttr *NewAttr = ::new (S.Context) TargetAttr(S.Context, AL, Str);
3460  D->addAttr(NewAttr);
3461 }
3462 
3463 bool Sema::checkTargetClonesAttrString(SourceLocation LiteralLoc, StringRef Str,
3464  const StringLiteral *Literal,
3465  bool &HasDefault, bool &HasCommas,
3466  SmallVectorImpl<StringRef> &Strings) {
3467  enum FirstParam { Unsupported, Duplicate, Unknown };
3468  enum SecondParam { None, CPU, Tune };
3469  enum ThirdParam { Target, TargetClones };
3470  HasCommas = HasCommas || Str.contains(',');
3471  // Warn on empty at the beginning of a string.
3472  if (Str.size() == 0)
3473  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3474  << Unsupported << None << "" << TargetClones;
3475 
3476  std::pair<StringRef, StringRef> Parts = {{}, Str};
3477  while (!Parts.second.empty()) {
3478  Parts = Parts.second.split(',');
3479  StringRef Cur = Parts.first.trim();
3480  SourceLocation CurLoc = Literal->getLocationOfByte(
3481  Cur.data() - Literal->getString().data(), getSourceManager(),
3482  getLangOpts(), Context.getTargetInfo());
3483 
3484  bool DefaultIsDupe = false;
3485  if (Cur.empty())
3486  return Diag(CurLoc, diag::warn_unsupported_target_attribute)
3487  << Unsupported << None << "" << TargetClones;
3488 
3489  if (Cur.startswith("arch=")) {
3490  if (!Context.getTargetInfo().isValidCPUName(
3491  Cur.drop_front(sizeof("arch=") - 1)))
3492  return Diag(CurLoc, diag::warn_unsupported_target_attribute)
3493  << Unsupported << CPU << Cur.drop_front(sizeof("arch=") - 1)
3494  << TargetClones;
3495  } else if (Cur == "default") {
3496  DefaultIsDupe = HasDefault;
3497  HasDefault = true;
3498  } else if (!Context.getTargetInfo().isValidFeatureName(Cur))
3499  return Diag(CurLoc, diag::warn_unsupported_target_attribute)
3500  << Unsupported << None << Cur << TargetClones;
3501 
3502  if (llvm::is_contained(Strings, Cur) || DefaultIsDupe)
3503  Diag(CurLoc, diag::warn_target_clone_duplicate_options);
3504  // Note: Add even if there are duplicates, since it changes name mangling.
3505  Strings.push_back(Cur);
3506  }
3507 
3508  if (Str.rtrim().endswith(","))
3509  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3510  << Unsupported << None << "" << TargetClones;
3511  return false;
3512 }
3513 
3514 static void handleTargetClonesAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3515  // Ensure we don't combine these with themselves, since that causes some
3516  // confusing behavior.
3517  if (const auto *Other = D->getAttr<TargetClonesAttr>()) {
3518  S.Diag(AL.getLoc(), diag::err_disallowed_duplicate_attribute) << AL;
3519  S.Diag(Other->getLocation(), diag::note_conflicting_attribute);
3520  return;
3521  }
3522  if (checkAttrMutualExclusion<TargetClonesAttr>(S, D, AL))
3523  return;
3524 
3525  SmallVector<StringRef, 2> Strings;
3526  bool HasCommas = false, HasDefault = false;
3527 
3528  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
3529  StringRef CurStr;
3530  SourceLocation LiteralLoc;
3531  if (!S.checkStringLiteralArgumentAttr(AL, I, CurStr, &LiteralLoc) ||
3533  LiteralLoc, CurStr,
3534  cast<StringLiteral>(AL.getArgAsExpr(I)->IgnoreParenCasts()),
3535  HasDefault, HasCommas, Strings))
3536  return;
3537  }
3538 
3539  if (HasCommas && AL.getNumArgs() > 1)
3540  S.Diag(AL.getLoc(), diag::warn_target_clone_mixed_values);
3541 
3542  if (!HasDefault) {
3543  S.Diag(AL.getLoc(), diag::err_target_clone_must_have_default);
3544  return;
3545  }
3546 
3547  // FIXME: We could probably figure out how to get this to work for lambdas
3548  // someday.
3549  if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
3550  if (MD->getParent()->isLambda()) {
3551  S.Diag(D->getLocation(), diag::err_multiversion_doesnt_support)
3552  << static_cast<unsigned>(MultiVersionKind::TargetClones)
3553  << /*Lambda*/ 9;
3554  return;
3555  }
3556  }
3557 
3558  cast<FunctionDecl>(D)->setIsMultiVersion();
3559  TargetClonesAttr *NewAttr = ::new (S.Context)
3560  TargetClonesAttr(S.Context, AL, Strings.data(), Strings.size());
3561  D->addAttr(NewAttr);
3562 }
3563 
3564 static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3565  Expr *E = AL.getArgAsExpr(0);
3566  uint32_t VecWidth;
3567  if (!checkUInt32Argument(S, AL, E, VecWidth)) {
3568  AL.setInvalid();
3569  return;
3570  }
3571 
3572  MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
3573  if (Existing && Existing->getVectorWidth() != VecWidth) {
3574  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3575  return;
3576  }
3577 
3578  D->addAttr(::new (S.Context) MinVectorWidthAttr(S.Context, AL, VecWidth));
3579 }
3580 
3581 static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3582  Expr *E = AL.getArgAsExpr(0);
3583  SourceLocation Loc = E->getExprLoc();
3584  FunctionDecl *FD = nullptr;
3586 
3587  // gcc only allows for simple identifiers. Since we support more than gcc, we
3588  // will warn the user.
3589  if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3590  if (DRE->hasQualifier())
3591  S.Diag(Loc, diag::warn_cleanup_ext);
3592  FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3593  NI = DRE->getNameInfo();
3594  if (!FD) {
3595  S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3596  << NI.getName();
3597  return;
3598  }
3599  } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3600  if (ULE->hasExplicitTemplateArgs())
3601  S.Diag(Loc, diag::warn_cleanup_ext);
3603  NI = ULE->getNameInfo();
3604  if (!FD) {
3605  S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3606  << NI.getName();
3607  if (ULE->getType() == S.Context.OverloadTy)
3609  return;
3610  }
3611  } else {
3612  S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3613  return;
3614  }
3615 
3616  if (FD->getNumParams() != 1) {
3617  S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3618  << NI.getName();
3619  return;
3620  }
3621 
3622  // We're currently more strict than GCC about what function types we accept.
3623  // If this ever proves to be a problem it should be easy to fix.
3624  QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
3625  QualType ParamTy = FD->getParamDecl(0)->getType();
3627  ParamTy, Ty) != Sema::Compatible) {
3628  S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3629  << NI.getName() << ParamTy << Ty;
3630  return;
3631  }
3632 
3633  D->addAttr(::new (S.Context) CleanupAttr(S.Context, AL, FD));
3634 }
3635 
3637  const ParsedAttr &AL) {
3638  if (!AL.isArgIdent(0)) {
3639  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3640  << AL << 0 << AANT_ArgumentIdentifier;
3641  return;
3642  }
3643 
3644  EnumExtensibilityAttr::Kind ExtensibilityKind;
3645  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3646  if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3647  ExtensibilityKind)) {
3648  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3649  return;
3650  }
3651 
3652  D->addAttr(::new (S.Context)
3653  EnumExtensibilityAttr(S.Context, AL, ExtensibilityKind));
3654 }
3655 
3656 /// Handle __attribute__((format_arg((idx)))) attribute based on
3657 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3658 static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3659  Expr *IdxExpr = AL.getArgAsExpr(0);
3660  ParamIdx Idx;
3661  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
3662  return;
3663 
3664  // Make sure the format string is really a string.
3666 
3667  bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3668  if (NotNSStringTy &&
3669  !isCFStringType(Ty, S.Context) &&
3670  (!Ty->isPointerType() ||
3671  !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3672  S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3673  << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3674  return;
3675  }
3677  // replace instancetype with the class type
3678  auto Instancetype = S.Context.getObjCInstanceTypeDecl()->getTypeForDecl();
3679  if (Ty->getAs<TypedefType>() == Instancetype)
3680  if (auto *OMD = dyn_cast<ObjCMethodDecl>(D))
3681  if (auto *Interface = OMD->getClassInterface())
3683  QualType(Interface->getTypeForDecl(), 0));
3684  if (!isNSStringType(Ty, S.Context, /*AllowNSAttributedString=*/true) &&
3685  !isCFStringType(Ty, S.Context) &&
3686  (!Ty->isPointerType() ||
3687  !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3688  S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
3689  << (NotNSStringTy ? "string type" : "NSString")
3690  << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3691  return;
3692  }
3693 
3694  D->addAttr(::new (S.Context) FormatArgAttr(S.Context, AL, Idx));
3695 }
3696 
3704 };
3705 
3706 /// getFormatAttrKind - Map from format attribute names to supported format
3707 /// types.
3708 static FormatAttrKind getFormatAttrKind(StringRef Format) {
3709  return llvm::StringSwitch<FormatAttrKind>(Format)
3710  // Check for formats that get handled specially.
3711  .Case("NSString", NSStringFormat)
3712  .Case("CFString", CFStringFormat)
3713  .Case("strftime", StrftimeFormat)
3714 
3715  // Otherwise, check for supported formats.
3716  .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3717  .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3718  .Case("kprintf", SupportedFormat) // OpenBSD.
3719  .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3720  .Case("os_trace", SupportedFormat)
3721  .Case("os_log", SupportedFormat)
3722 
3723  .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3724  .Default(InvalidFormat);
3725 }
3726 
3727 /// Handle __attribute__((init_priority(priority))) attributes based on
3728 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3729 static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3730  if (!S.getLangOpts().CPlusPlus) {
3731  S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
3732  return;
3733  }
3734 
3735  if (S.getLangOpts().HLSL) {
3736  S.Diag(AL.getLoc(), diag::err_hlsl_init_priority_unsupported);
3737  return;
3738  }
3739 
3740  if (S.getCurFunctionOrMethodDecl()) {
3741  S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3742  AL.setInvalid();
3743  return;
3744  }
3745  QualType T = cast<VarDecl>(D)->getType();
3746  if (S.Context.getAsArrayType(T))
3747  T = S.Context.getBaseElementType(T);
3748  if (!T->getAs<RecordType>()) {
3749  S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3750  AL.setInvalid();
3751  return;
3752  }
3753 
3754  Expr *E = AL.getArgAsExpr(0);
3755  uint32_t prioritynum;
3756  if (!checkUInt32Argument(S, AL, E, prioritynum)) {
3757  AL.setInvalid();
3758  return;
3759  }
3760 
3761  // Only perform the priority check if the attribute is outside of a system
3762  // header. Values <= 100 are reserved for the implementation, and libc++
3763  // benefits from being able to specify values in that range.
3764  if ((prioritynum < 101 || prioritynum > 65535) &&
3766  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
3767  << E->getSourceRange() << AL << 101 << 65535;
3768  AL.setInvalid();
3769  return;
3770  }
3771  D->addAttr(::new (S.Context) InitPriorityAttr(S.Context, AL, prioritynum));
3772 }
3773 
3775  StringRef NewUserDiagnostic) {
3776  if (const auto *EA = D->getAttr<ErrorAttr>()) {
3777  std::string NewAttr = CI.getNormalizedFullName();
3778  assert((NewAttr == "error" || NewAttr == "warning") &&
3779  "unexpected normalized full name");
3780  bool Match = (EA->isError() && NewAttr == "error") ||
3781  (EA->isWarning() && NewAttr == "warning");
3782  if (!Match) {
3783  Diag(EA->getLocation(), diag::err_attributes_are_not_compatible)
3784  << CI << EA;
3785  Diag(CI.getLoc(), diag::note_conflicting_attribute);
3786  return nullptr;
3787  }
3788  if (EA->getUserDiagnostic() != NewUserDiagnostic) {
3789  Diag(CI.getLoc(), diag::warn_duplicate_attribute) << EA;
3790  Diag(EA->getLoc(), diag::note_previous_attribute);
3791  }
3792  D->dropAttr<ErrorAttr>();
3793  }
3794  return ::new (Context) ErrorAttr(Context, CI, NewUserDiagnostic);
3795 }
3796 
3798  IdentifierInfo *Format, int FormatIdx,
3799  int FirstArg) {
3800  // Check whether we already have an equivalent format attribute.
3801  for (auto *F : D->specific_attrs<FormatAttr>()) {
3802  if (F->getType() == Format &&
3803  F->getFormatIdx() == FormatIdx &&
3804  F->getFirstArg() == FirstArg) {
3805  // If we don't have a valid location for this attribute, adopt the
3806  // location.
3807  if (F->getLocation().isInvalid())
3808  F->setRange(CI.getRange());
3809  return nullptr;
3810  }
3811  }
3812 
3813  return ::new (Context) FormatAttr(Context, CI, Format, FormatIdx, FirstArg);
3814 }
3815 
3816 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3817 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3818 static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3819  if (!AL.isArgIdent(0)) {
3820  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3821  << AL << 1 << AANT_ArgumentIdentifier;
3822  return;
3823  }
3824 
3825  // In C++ the implicit 'this' function parameter also counts, and they are
3826  // counted from one.
3827  bool HasImplicitThisParam = isInstanceMethod(D);
3828  unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3829 
3830  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3831  StringRef Format = II->getName();
3832 
3833  if (normalizeName(Format)) {
3834  // If we've modified the string name, we need a new identifier for it.
3835  II = &S.Context.Idents.get(Format);
3836  }
3837 
3838  // Check for supported formats.
3840 
3841  if (Kind == IgnoredFormat)
3842  return;
3843 
3844  if (Kind == InvalidFormat) {
3845  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
3846  << AL << II->getName();
3847  return;
3848  }
3849 
3850  // checks for the 2nd argument
3851  Expr *IdxExpr = AL.getArgAsExpr(1);
3852  uint32_t Idx;
3853  if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2))
3854  return;
3855 
3856  if (Idx < 1 || Idx > NumArgs) {
3857  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3858  << AL << 2 << IdxExpr->getSourceRange();
3859  return;
3860  }
3861 
3862  // FIXME: Do we need to bounds check?
3863  unsigned ArgIdx = Idx - 1;
3864 
3865  if (HasImplicitThisParam) {
3866  if (ArgIdx == 0) {
3867  S.Diag(AL.getLoc(),
3868  diag::err_format_attribute_implicit_this_format_string)
3869  << IdxExpr->getSourceRange();
3870  return;
3871  }
3872  ArgIdx--;
3873  }
3874 
3875  // make sure the format string is really a string
3876  QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3877 
3878  if (!isNSStringType(Ty, S.Context, true) &&
3879  !isCFStringType(Ty, S.Context) &&
3880  (!Ty->isPointerType() ||
3881  !Ty->castAs<PointerType>()->getPointeeType()->isCharType())) {
3882  S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3883  << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, ArgIdx);
3884  return;
3885  }
3886 
3887  // check the 3rd argument
3888  Expr *FirstArgExpr = AL.getArgAsExpr(2);
3889  uint32_t FirstArg;
3890  if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
3891  return;
3892 
3893  // check if the function is variadic if the 3rd argument non-zero
3894  if (FirstArg != 0) {
3896  ++NumArgs; // +1 for ...
3897  else
3898  S.Diag(D->getLocation(), diag::warn_gcc_requires_variadic_function) << AL;
3899  }
3900 
3901  // strftime requires FirstArg to be 0 because it doesn't read from any
3902  // variable the input is just the current time + the format string.
3903  if (Kind == StrftimeFormat) {
3904  if (FirstArg != 0) {
3905  S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
3906  << FirstArgExpr->getSourceRange();
3907  return;
3908  }
3909  // if 0 it disables parameter checking (to use with e.g. va_list)
3910  } else if (FirstArg != 0 && FirstArg != NumArgs) {
3911  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3912  << AL << 3 << FirstArgExpr->getSourceRange();
3913  return;
3914  }
3915 
3916  FormatAttr *NewAttr = S.mergeFormatAttr(D, AL, II, Idx, FirstArg);
3917  if (NewAttr)
3918  D->addAttr(NewAttr);
3919 }
3920 
3921 /// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
3922 static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3923  // The index that identifies the callback callee is mandatory.
3924  if (AL.getNumArgs() == 0) {
3925  S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
3926  << AL.getRange();
3927  return;
3928  }
3929 
3930  bool HasImplicitThisParam = isInstanceMethod(D);
3931  int32_t NumArgs = getFunctionOrMethodNumParams(D);
3932 
3933  FunctionDecl *FD = D->getAsFunction();
3934  assert(FD && "Expected a function declaration!");
3935 
3936  llvm::StringMap<int> NameIdxMapping;
3937  NameIdxMapping["__"] = -1;
3938 
3939  NameIdxMapping["this"] = 0;
3940 
3941  int Idx = 1;
3942  for (const ParmVarDecl *PVD : FD->parameters())
3943  NameIdxMapping[PVD->getName()] = Idx++;
3944 
3945  auto UnknownName = NameIdxMapping.end();
3946 
3947  SmallVector<int, 8> EncodingIndices;
3948  for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
3949  SourceRange SR;
3950  int32_t ArgIdx;
3951 
3952  if (AL.isArgIdent(I)) {
3953  IdentifierLoc *IdLoc = AL.getArgAsIdent(I);
3954  auto It = NameIdxMapping.find(IdLoc->Ident->getName());
3955  if (It == UnknownName) {
3956  S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown)
3957  << IdLoc->Ident << IdLoc->Loc;
3958  return;
3959  }
3960 
3961  SR = SourceRange(IdLoc->Loc);
3962  ArgIdx = It->second;
3963  } else if (AL.isArgExpr(I)) {
3964  Expr *IdxExpr = AL.getArgAsExpr(I);
3965 
3966  // If the expression is not parseable as an int32_t we have a problem.
3967  if (!checkUInt32Argument(S, AL, IdxExpr, (uint32_t &)ArgIdx, I + 1,
3968  false)) {
3969  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3970  << AL << (I + 1) << IdxExpr->getSourceRange();
3971  return;
3972  }
3973 
3974  // Check oob, excluding the special values, 0 and -1.
3975  if (ArgIdx < -1 || ArgIdx > NumArgs) {
3976  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3977  << AL << (I + 1) << IdxExpr->getSourceRange();
3978  return;
3979  }
3980 
3981  SR = IdxExpr->getSourceRange();
3982  } else {
3983  llvm_unreachable("Unexpected ParsedAttr argument type!");
3984  }
3985 
3986  if (ArgIdx == 0 && !HasImplicitThisParam) {
3987  S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available)
3988  << (I + 1) << SR;
3989  return;
3990  }
3991 
3992  // Adjust for the case we do not have an implicit "this" parameter. In this
3993  // case we decrease all positive values by 1 to get LLVM argument indices.
3994  if (!HasImplicitThisParam && ArgIdx > 0)
3995  ArgIdx -= 1;
3996 
3997  EncodingIndices.push_back(ArgIdx);
3998  }
3999 
4000  int CalleeIdx = EncodingIndices.front();
4001  // Check if the callee index is proper, thus not "this" and not "unknown".
4002  // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
4003  // is false and positive if "HasImplicitThisParam" is true.
4004  if (CalleeIdx < (int)HasImplicitThisParam) {
4005  S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee)
4006  << AL.getRange();
4007  return;
4008  }
4009 
4010  // Get the callee type, note the index adjustment as the AST doesn't contain
4011  // the this type (which the callee cannot reference anyway!).
4012  const Type *CalleeType =
4013  getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam)
4014  .getTypePtr();
4015  if (!CalleeType || !CalleeType->isFunctionPointerType()) {
4016  S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
4017  << AL.getRange();
4018  return;
4019  }
4020 
4021  const Type *CalleeFnType =
4023 
4024  // TODO: Check the type of the callee arguments.
4025 
4026  const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType);
4027  if (!CalleeFnProtoType) {
4028  S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
4029  << AL.getRange();
4030  return;
4031  }
4032 
4033  if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) {
4034  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
4035  << AL << (unsigned)(EncodingIndices.size() - 1);
4036  return;
4037  }
4038 
4039  if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) {
4040  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
4041  << AL << (unsigned)(EncodingIndices.size() - 1);
4042  return;
4043  }
4044 
4045  if (CalleeFnProtoType->isVariadic()) {
4046  S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange();
4047  return;
4048  }
4049 
4050  // Do not allow multiple callback attributes.
4051  if (D->hasAttr<CallbackAttr>()) {
4052  S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange();
4053  return;
4054  }
4055 
4056  D->addAttr(::new (S.Context) CallbackAttr(
4057  S.Context, AL, EncodingIndices.data(), EncodingIndices.size()));
4058 }
4059 
4060 static bool isFunctionLike(const Type &T) {
4061  // Check for explicit function types.
4062  // 'called_once' is only supported in Objective-C and it has
4063  // function pointers and block pointers.
4064  return T.isFunctionPointerType() || T.isBlockPointerType();
4065 }
4066 
4067 /// Handle 'called_once' attribute.
4068 static void handleCalledOnceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4069  // 'called_once' only applies to parameters representing functions.
4070  QualType T = cast<ParmVarDecl>(D)->getType();
4071 
4072  if (!isFunctionLike(*T)) {
4073  S.Diag(AL.getLoc(), diag::err_called_once_attribute_wrong_type);
4074  return;
4075  }
4076 
4077  D->addAttr(::new (S.Context) CalledOnceAttr(S.Context, AL));
4078 }
4079 
4080 static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4081  // Try to find the underlying union declaration.
4082  RecordDecl *RD = nullptr;
4083  const auto *TD = dyn_cast<TypedefNameDecl>(D);
4084  if (TD && TD->getUnderlyingType()->isUnionType())
4085  RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
4086  else
4087  RD = dyn_cast<RecordDecl>(D);
4088 
4089  if (!RD || !RD->isUnion()) {
4090  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL
4091  << ExpectedUnion;
4092  return;
4093  }
4094 
4095  if (!RD->isCompleteDefinition()) {
4096  if (!RD->isBeingDefined())
4097  S.Diag(AL.getLoc(),
4098  diag::warn_transparent_union_attribute_not_definition);
4099  return;
4100  }
4101 
4103  FieldEnd = RD->field_end();
4104  if (Field == FieldEnd) {
4105  S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
4106  return;
4107  }
4108 
4109  FieldDecl *FirstField = *Field;
4110  QualType FirstType = FirstField->getType();
4111  if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
4112  S.Diag(FirstField->getLocation(),
4113  diag::warn_transparent_union_attribute_floating)
4114  << FirstType->isVectorType() << FirstType;
4115  return;
4116  }
4117 
4118  if (FirstType->isIncompleteType())
4119  return;
4120  uint64_t FirstSize = S.Context.getTypeSize(FirstType);
4121  uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
4122  for (; Field != FieldEnd; ++Field) {
4123  QualType FieldType = Field->getType();
4124  if (FieldType->isIncompleteType())
4125  return;
4126  // FIXME: this isn't fully correct; we also need to test whether the
4127  // members of the union would all have the same calling convention as the
4128  // first member of the union. Checking just the size and alignment isn't
4129  // sufficient (consider structs passed on the stack instead of in registers
4130  // as an example).
4131  if (S.Context.getTypeSize(FieldType) != FirstSize ||
4132  S.Context.getTypeAlign(FieldType) > FirstAlign) {
4133  // Warn if we drop the attribute.
4134  bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
4135  unsigned FieldBits = isSize ? S.Context.getTypeSize(FieldType)
4136  : S.Context.getTypeAlign(FieldType);
4137  S.Diag(Field->getLocation(),
4138  diag::warn_transparent_union_attribute_field_size_align)
4139  << isSize << *Field << FieldBits;
4140  unsigned FirstBits = isSize ? FirstSize : FirstAlign;
4141  S.Diag(FirstField->getLocation(),
4142  diag::note_transparent_union_first_field_size_align)
4143  << isSize << FirstBits;
4144  return;
4145  }
4146  }
4147 
4148  RD->addAttr(::new (S.Context) TransparentUnionAttr(S.Context, AL));
4149 }
4150 
4152  StringRef Str, MutableArrayRef<Expr *> Args) {
4153  auto *Attr = AnnotateAttr::Create(Context, Str, Args.data(), Args.size(), CI);
4154  if (ConstantFoldAttrArgs(
4155  CI, MutableArrayRef<Expr *>(Attr->args_begin(), Attr->args_end()))) {
4156  D->addAttr(Attr);
4157  }
4158 }
4159 
4160 static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4161  // Make sure that there is a string literal as the annotation's first
4162  // argument.
4163  StringRef Str;
4164  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
4165  return;
4166 
4168  Args.reserve(AL.getNumArgs() - 1);
4169  for (unsigned Idx = 1; Idx < AL.getNumArgs(); Idx++) {
4170  assert(!AL.isArgIdent(Idx));
4171  Args.push_back(AL.getArgAsExpr(Idx));
4172  }
4173 
4174  S.AddAnnotationAttr(D, AL, Str, Args);
4175 }
4176 
4177 static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4178  S.AddAlignValueAttr(D, AL, AL.getArgAsExpr(0));
4179 }
4180 
4182  AlignValueAttr TmpAttr(Context, CI, E);
4183  SourceLocation AttrLoc = CI.getLoc();
4184 
4185  QualType T;
4186  if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
4187  T = TD->getUnderlyingType();
4188  else if (const auto *VD = dyn_cast<ValueDecl>(D))
4189  T = VD->getType();
4190  else
4191  llvm_unreachable("Unknown decl type for align_value");
4192 
4193  if (!T->isDependentType() && !T->isAnyPointerType() &&
4194  !T->isReferenceType() && !T->isMemberPointerType()) {
4195  Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
4196  << &TmpAttr << T << D->getSourceRange();
4197  return;
4198  }
4199 
4200  if (!E->isValueDependent()) {
4201  llvm::APSInt Alignment;
4202  ExprResult ICE = VerifyIntegerConstantExpression(
4203  E, &Alignment, diag::err_align_value_attribute_argument_not_int);
4204  if (ICE.isInvalid())
4205  return;
4206 
4207  if (!Alignment.isPowerOf2()) {
4208  Diag(AttrLoc, diag::err_alignment_not_power_of_two)
4209  << E->getSourceRange();
4210  return;
4211  }
4212 
4213  D->addAttr(::new (Context) AlignValueAttr(Context, CI, ICE.get()));
4214  return;
4215  }
4216 
4217  // Save dependent expressions in the AST to be instantiated.
4218  D->addAttr(::new (Context) AlignValueAttr(Context, CI, E));
4219 }
4220 
4221 static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4222  // check the attribute arguments.
4223  if (AL.getNumArgs() > 1) {
4224  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
4225  return;
4226  }
4227 
4228  if (AL.getNumArgs() == 0) {
4229  D->addAttr(::new (S.Context) AlignedAttr(S.Context, AL, true, nullptr));
4230  return;
4231  }
4232 
4233  Expr *E = AL.getArgAsExpr(0);
4235  S.Diag(AL.getEllipsisLoc(),
4236  diag::err_pack_expansion_without_parameter_packs);
4237  return;
4238  }
4239 
4241  return;
4242 
4243  S.AddAlignedAttr(D, AL, E, AL.isPackExpansion());
4244 }
4245 
4247  bool IsPackExpansion) {
4248  AlignedAttr TmpAttr(Context, CI, true, E);
4249  SourceLocation AttrLoc = CI.getLoc();
4250 
4251  // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
4252  if (TmpAttr.isAlignas()) {
4253  // C++11 [dcl.align]p1:
4254  // An alignment-specifier may be applied to a variable or to a class
4255  // data member, but it shall not be applied to a bit-field, a function
4256  // parameter, the formal parameter of a catch clause, or a variable
4257  // declared with the register storage class specifier. An
4258  // alignment-specifier may also be applied to the declaration of a class
4259  // or enumeration type.
4260  // CWG 2354:
4261  // CWG agreed to remove permission for alignas to be applied to
4262  // enumerations.
4263  // C11 6.7.5/2:
4264  // An alignment attribute shall not be specified in a declaration of
4265  // a typedef, or a bit-field, or a function, or a parameter, or an
4266  // object declared with the register storage-class specifier.
4267  int DiagKind = -1;
4268  if (isa<ParmVarDecl>(D)) {
4269  DiagKind = 0;
4270  } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
4271  if (VD->getStorageClass() == SC_Register)
4272  DiagKind = 1;
4273  if (VD->isExceptionVariable())
4274  DiagKind = 2;
4275  } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
4276  if (FD->isBitField())
4277  DiagKind = 3;
4278  } else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
4279  if (ED->getLangOpts().CPlusPlus)
4280  DiagKind = 4;
4281  } else if (!isa<TagDecl>(D)) {
4282  Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
4283  << (TmpAttr.isC11() ? ExpectedVariableOrField
4285  return;
4286  }
4287  if (DiagKind != -1) {
4288  Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
4289  << &TmpAttr << DiagKind;
4290  return;
4291  }
4292  }
4293 
4294  if (E->isValueDependent()) {
4295  // We can't support a dependent alignment on a non-dependent type,
4296  // because we have no way to model that a type is "alignment-dependent"
4297  // but not dependent in any other way.
4298  if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
4299  if (!TND->getUnderlyingType()->isDependentType()) {
4300  Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
4301  << E->getSourceRange();
4302  return;
4303  }
4304  }
4305 
4306  // Save dependent expressions in the AST to be instantiated.
4307  AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, E);
4308  AA->setPackExpansion(IsPackExpansion);
4309  D->addAttr(AA);
4310  return;
4311  }
4312 
4313  // FIXME: Cache the number on the AL object?
4314  llvm::APSInt Alignment;
4315  ExprResult ICE = VerifyIntegerConstantExpression(
4316  E, &Alignment, diag::err_aligned_attribute_argument_not_int);
4317  if (ICE.isInvalid())
4318  return;
4319 
4320  uint64_t AlignVal = Alignment.getZExtValue();
4321  // C++11 [dcl.align]p2:
4322  // -- if the constant expression evaluates to zero, the alignment
4323  // specifier shall have no effect
4324  // C11 6.7.5p6:
4325  // An alignment specification of zero has no effect.
4326  if (!(TmpAttr.isAlignas() && !Alignment)) {
4327  if (!llvm::isPowerOf2_64(AlignVal)) {
4328  Diag(AttrLoc, diag::err_alignment_not_power_of_two)
4329  << E->getSourceRange();
4330  return;
4331  }
4332  }
4333 
4334  uint64_t MaximumAlignment = Sema::MaximumAlignment;
4335  if (Context.getTargetInfo().getTriple().isOSBinFormatCOFF())
4336  MaximumAlignment = std::min(MaximumAlignment, uint64_t(8192));
4337  if (AlignVal > MaximumAlignment) {
4338  Diag(AttrLoc, diag::err_attribute_aligned_too_great)
4339  << MaximumAlignment << E->getSourceRange();
4340  return;
4341  }
4342 
4343  const auto *VD = dyn_cast<VarDecl>(D);
4344  if (VD) {
4345  unsigned MaxTLSAlign =
4346  Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
4347  .getQuantity();
4348  if (MaxTLSAlign && AlignVal > MaxTLSAlign &&
4349  VD->getTLSKind() != VarDecl::TLS_None) {
4350  Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
4351  << (unsigned)AlignVal << VD << MaxTLSAlign;
4352  return;
4353  }
4354  }
4355 
4356  // On AIX, an aligned attribute can not decrease the alignment when applied
4357  // to a variable declaration with vector type.
4358  if (VD && Context.getTargetInfo().getTriple().isOSAIX()) {
4359  const Type *Ty = VD->getType().getTypePtr();
4360  if (Ty->isVectorType() && AlignVal < 16) {
4361  Diag(VD->getLocation(), diag::warn_aligned_attr_underaligned)
4362  << VD->getType() << 16;
4363  return;
4364  }
4365  }
4366 
4367  AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, true, ICE.get());
4368  AA->setPackExpansion(IsPackExpansion);
4369  D->addAttr(AA);
4370 }
4371 
4373  TypeSourceInfo *TS, bool IsPackExpansion) {
4374  // FIXME: Cache the number on the AL object if non-dependent?
4375  // FIXME: Perform checking of type validity
4376  AlignedAttr *AA = ::new (Context) AlignedAttr(Context, CI, false, TS);
4377  AA->setPackExpansion(IsPackExpansion);
4378  D->addAttr(AA);
4379 }
4380 
4382  assert(D->hasAttrs() && "no attributes on decl");
4383 
4384  QualType UnderlyingTy, DiagTy;
4385  if (const auto *VD = dyn_cast<ValueDecl>(D)) {
4386  UnderlyingTy = DiagTy = VD->getType();
4387  } else {
4388  UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
4389  if (const auto *ED = dyn_cast<EnumDecl>(D))
4390  UnderlyingTy = ED->getIntegerType();
4391  }
4392  if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
4393  return;
4394 
4395  // C++11 [dcl.align]p5, C11 6.7.5/4:
4396  // The combined effect of all alignment attributes in a declaration shall
4397  // not specify an alignment that is less strict than the alignment that
4398  // would otherwise be required for the entity being declared.
4399  AlignedAttr *AlignasAttr = nullptr;
4400  AlignedAttr *LastAlignedAttr = nullptr;
4401  unsigned Align = 0;
4402  for (auto *I : D->specific_attrs<AlignedAttr>()) {
4403  if (I->isAlignmentDependent())
4404  return;
4405  if (I->isAlignas())
4406  AlignasAttr = I;
4407  Align = std::max(Align, I->getAlignment(Context));
4408  LastAlignedAttr = I;
4409  }
4410 
4411  if (Align && DiagTy->isSizelessType()) {
4412  Diag(LastAlignedAttr->getLocation(), diag::err_attribute_sizeless_type)
4413  << LastAlignedAttr << DiagTy;
4414  } else if (AlignasAttr && Align) {
4415  CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
4416  CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
4417  if (NaturalAlign > RequestedAlign)
4418  Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
4419  << DiagTy << (unsigned)NaturalAlign.getQuantity();
4420  }
4421 }
4422 
4424  CXXRecordDecl *RD, SourceRange Range, bool BestCase,
4425  MSInheritanceModel ExplicitModel) {
4426  assert(RD->hasDefinition() && "RD has no definition!");
4427 
4428  // We may not have seen base specifiers or any virtual methods yet. We will
4429  // have to wait until the record is defined to catch any mismatches.
4430  if (!RD->getDefinition()->isCompleteDefinition())
4431  return false;
4432 
4433  // The unspecified model never matches what a definition could need.
4434  if (ExplicitModel == MSInheritanceModel::Unspecified)
4435  return false;
4436 
4437  if (BestCase) {
4438  if (RD->calculateInheritanceModel() == ExplicitModel)
4439  return false;
4440  } else {
4441  if (RD->calculateInheritanceModel() <= ExplicitModel)
4442  return false;
4443  }
4444 
4445  Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
4446  << 0 /*definition*/;
4447  Diag(RD->getDefinition()->getLocation(), diag::note_defined_here) << RD;
4448  return true;
4449 }
4450 
4451 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
4452 /// attribute.
4453 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
4454  bool &IntegerMode, bool &ComplexMode,
4455  FloatModeKind &ExplicitType) {
4456  IntegerMode = true;
4457  ComplexMode = false;
4458  ExplicitType = FloatModeKind::NoFloat;
4459  switch (Str.size()) {
4460  case 2:
4461  switch (Str[0]) {
4462  case 'Q':
4463  DestWidth = 8;
4464  break;
4465  case 'H':
4466  DestWidth = 16;
4467  break;
4468  case 'S':
4469  DestWidth = 32;
4470  break;
4471  case 'D':
4472  DestWidth = 64;
4473  break;
4474  case 'X':
4475  DestWidth = 96;
4476  break;
4477  case 'K': // KFmode - IEEE quad precision (__float128)
4478  ExplicitType = FloatModeKind::Float128;
4479  DestWidth = Str[1] == 'I' ? 0 : 128;
4480  break;
4481  case 'T':
4482  ExplicitType = FloatModeKind::LongDouble;
4483  DestWidth = 128;
4484  break;
4485  case 'I':
4486  ExplicitType = FloatModeKind::Ibm128;
4487  DestWidth = Str[1] == 'I' ? 0 : 128;
4488  break;
4489  }
4490  if (Str[1] == 'F') {
4491  IntegerMode = false;
4492  } else if (Str[1] == 'C') {
4493  IntegerMode = false;
4494  ComplexMode = true;
4495  } else if (Str[1] != 'I') {
4496  DestWidth = 0;
4497  }
4498  break;
4499  case 4:
4500  // FIXME: glibc uses 'word' to define register_t; this is narrower than a
4501  // pointer on PIC16 and other embedded platforms.
4502  if (Str == "word")
4503  DestWidth = S.Context.getTargetInfo().getRegisterWidth();
4504  else if (Str == "byte")
4505  DestWidth = S.Context.getTargetInfo().getCharWidth();
4506  break;
4507  case 7:
4508  if (Str == "pointer")
4509  DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
4510  break;
4511  case 11:
4512  if (Str == "unwind_word")
4513  DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
4514  break;
4515  }
4516 }
4517 
4518 /// handleModeAttr - This attribute modifies the width of a decl with primitive
4519 /// type.
4520 ///
4521 /// Despite what would be logical, the mode attribute is a decl attribute, not a
4522 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
4523 /// HImode, not an intermediate pointer.
4524 static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4525  // This attribute isn't documented, but glibc uses it. It changes
4526  // the width of an int or unsigned int to the specified size.
4527  if (!AL.isArgIdent(0)) {
4528  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
4529  << AL << AANT_ArgumentIdentifier;
4530  return;
4531  }
4532 
4533  IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
4534 
4535  S.AddModeAttr(D, AL, Name);
4536 }
4537 
4539  IdentifierInfo *Name, bool InInstantiation) {
4540  StringRef Str = Name->getName();
4541  normalizeName(Str);
4542  SourceLocation AttrLoc = CI.getLoc();
4543 
4544  unsigned DestWidth = 0;
4545  bool IntegerMode = true;
4546  bool ComplexMode = false;
4547  FloatModeKind ExplicitType = FloatModeKind::NoFloat;
4548  llvm::APInt VectorSize(64, 0);
4549  if (Str.size() >= 4 && Str[0] == 'V') {
4550  // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
4551  size_t StrSize = Str.size();
4552  size_t VectorStringLength = 0;
4553  while ((VectorStringLength + 1) < StrSize &&
4554  isdigit(Str[VectorStringLength + 1]))
4555  ++VectorStringLength;
4556  if (VectorStringLength &&
4557  !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
4558  VectorSize.isPowerOf2()) {
4559  parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
4560  IntegerMode, ComplexMode, ExplicitType);
4561  // Avoid duplicate warning from template instantiation.
4562  if (!InInstantiation)
4563  Diag(AttrLoc, diag::warn_vector_mode_deprecated);
4564  } else {
4565  VectorSize = 0;
4566  }
4567  }
4568 
4569  if (!VectorSize)
4570  parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode,
4571  ExplicitType);
4572 
4573  // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
4574  // and friends, at least with glibc.
4575  // FIXME: Make sure floating-point mappings are accurate
4576  // FIXME: Support XF and TF types
4577  if (!DestWidth) {
4578  Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
4579  return;
4580  }
4581 
4582  QualType OldTy;
4583  if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
4584  OldTy = TD->getUnderlyingType();
4585  else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
4586  // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
4587  // Try to get type from enum declaration, default to int.
4588  OldTy = ED->getIntegerType();
4589  if (OldTy.isNull())
4590  OldTy = Context.IntTy;
4591  } else
4592  OldTy = cast<ValueDecl>(D)->getType();
4593 
4594  if (OldTy->isDependentType()) {
4595  D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4596  return;
4597  }
4598 
4599  // Base type can also be a vector type (see PR17453).
4600  // Distinguish between base type and base element type.
4601  QualType OldElemTy = OldTy;
4602  if (const auto *VT = OldTy->getAs<VectorType>())
4603  OldElemTy = VT->getElementType();
4604 
4605  // GCC allows 'mode' attribute on enumeration types (even incomplete), except
4606  // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
4607  // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
4608  if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
4609  VectorSize.getBoolValue()) {
4610  Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << CI.getRange();
4611  return;
4612  }
4613  bool IntegralOrAnyEnumType = (OldElemTy->isIntegralOrEnumerationType() &&
4614  !OldElemTy->isBitIntType()) ||
4615  OldElemTy->getAs<EnumType>();
4616 
4617  if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
4618  !IntegralOrAnyEnumType)
4619  Diag(AttrLoc, diag::err_mode_not_primitive);
4620  else if (IntegerMode) {
4621  if (!IntegralOrAnyEnumType)
4622  Diag(AttrLoc, diag::err_mode_wrong_type);
4623  } else if (ComplexMode) {
4624  if (!OldElemTy->isComplexType())
4625  Diag(AttrLoc, diag::err_mode_wrong_type);
4626  } else {
4627  if (!OldElemTy->isFloatingType())
4628  Diag(AttrLoc, diag::err_mode_wrong_type);
4629  }
4630 
4631  QualType NewElemTy;
4632 
4633  if (IntegerMode)
4634  NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
4635  OldElemTy->isSignedIntegerType());
4636  else
4637  NewElemTy = Context.getRealTypeForBitwidth(DestWidth, ExplicitType);
4638 
4639  if (NewElemTy.isNull()) {
4640  Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
4641  return;
4642  }
4643 
4644  if (ComplexMode) {
4645  NewElemTy = Context.getComplexType(NewElemTy);
4646  }
4647 
4648  QualType NewTy = NewElemTy;
4649  if (VectorSize.getBoolValue()) {
4650  NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
4652  } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
4653  // Complex machine mode does not support base vector types.
4654  if (ComplexMode) {
4655  Diag(AttrLoc, diag::err_complex_mode_vector_type);
4656  return;
4657  }
4658  unsigned NumElements = Context.getTypeSize(OldElemTy) *
4659  OldVT->getNumElements() /
4660  Context.getTypeSize(NewElemTy);
4661  NewTy =
4662  Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
4663  }
4664 
4665  if (NewTy.isNull()) {
4666  Diag(AttrLoc, diag::err_mode_wrong_type);
4667  return;
4668  }
4669 
4670  // Install the new type.
4671  if (auto *TD = dyn_cast<TypedefNameDecl>(D))
4672  TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
4673  else if (auto *ED = dyn_cast<EnumDecl>(D))
4674  ED->setIntegerType(NewTy);
4675  else
4676  cast<ValueDecl>(D)->setType(NewTy);
4677 
4678  D->addAttr(::new (Context) ModeAttr(Context, CI, Name));
4679 }
4680 
4681 static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4682  D->addAttr(::new (S.Context) NoDebugAttr(S.Context, AL));
4683 }
4684 
4685 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D,
4686  const AttributeCommonInfo &CI,
4687  const IdentifierInfo *Ident) {
4688  if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4689  Diag(CI.getLoc(), diag::warn_attribute_ignored) << Ident;
4690  Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4691  return nullptr;
4692  }
4693 
4694  if (D->hasAttr<AlwaysInlineAttr>())
4695  return nullptr;
4696 
4697  return ::new (Context) AlwaysInlineAttr(Context, CI);
4698 }
4699 
4700 InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
4701  const ParsedAttr &AL) {
4702  if (const auto *VD = dyn_cast<VarDecl>(D)) {
4703  // Attribute applies to Var but not any subclass of it (like ParmVar,
4704  // ImplicitParm or VarTemplateSpecialization).
4705  if (VD->getKind() != Decl::Var) {
4706  Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4707  << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4709  return nullptr;
4710  }
4711  // Attribute does not apply to non-static local variables.
4712  if (VD->hasLocalStorage()) {
4713  Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4714  return nullptr;
4715  }
4716  }
4717 
4718  return ::new (Context) InternalLinkageAttr(Context, AL);
4719 }
4720 InternalLinkageAttr *
4721 Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
4722  if (const auto *VD = dyn_cast<VarDecl>(D)) {
4723  // Attribute applies to Var but not any subclass of it (like ParmVar,
4724  // ImplicitParm or VarTemplateSpecialization).
4725  if (VD->getKind() != Decl::Var) {
4726  Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
4727  << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4729  return nullptr;
4730  }
4731  // Attribute does not apply to non-static local variables.
4732  if (VD->hasLocalStorage()) {
4733  Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4734  return nullptr;
4735  }
4736  }
4737 
4738  return ::new (Context) InternalLinkageAttr(Context, AL);
4739 }
4740 
4741 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI) {
4742  if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4743  Diag(CI.getLoc(), diag::warn_attribute_ignored) << "'minsize'";
4744  Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4745  return nullptr;
4746  }
4747 
4748  if (D->hasAttr<MinSizeAttr>())
4749  return nullptr;
4750 
4751  return ::new (Context) MinSizeAttr(Context, CI);
4752 }
4753 
4754 SwiftNameAttr *Sema::mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA,
4755  StringRef Name) {
4756  if (const auto *PrevSNA = D->getAttr<SwiftNameAttr>()) {
4757  if (PrevSNA->getName() != Name && !PrevSNA->isImplicit()) {
4758  Diag(PrevSNA->getLocation(), diag::err_attributes_are_not_compatible)
4759  << PrevSNA << &SNA;
4760  Diag(SNA.getLoc(), diag::note_conflicting_attribute);
4761  }
4762 
4763  D->dropAttr<SwiftNameAttr>();
4764  }
4765  return ::new (Context) SwiftNameAttr(Context, SNA, Name);
4766 }
4767 
4768 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D,
4769  const AttributeCommonInfo &CI) {
4770  if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4771  Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4772  Diag(CI.getLoc(), diag::note_conflicting_attribute);
4773  D->dropAttr<AlwaysInlineAttr>();
4774  }
4775  if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4776  Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4777  Diag(CI.getLoc(), diag::note_conflicting_attribute);
4778  D->dropAttr<MinSizeAttr>();
4779  }
4780 
4781  if (D->hasAttr<OptimizeNoneAttr>())
4782  return nullptr;
4783 
4784  return ::new (Context) OptimizeNoneAttr(Context, CI);
4785 }
4786 
4787 static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4788  if (AlwaysInlineAttr *Inline =
4789  S.mergeAlwaysInlineAttr(D, AL, AL.getAttrName()))
4790  D->addAttr(Inline);
4791 }
4792 
4793 static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4794  if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(D, AL))
4795  D->addAttr(MinSize);
4796 }
4797 
4798 static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4799  if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(D, AL))
4800  D->addAttr(Optnone);
4801 }
4802 
4803 static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4804  const auto *VD = cast<VarDecl>(D);
4805  if (VD->hasLocalStorage()) {
4806  S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4807  return;
4808  }
4809  // constexpr variable may already get an implicit constant attr, which should
4810  // be replaced by the explicit constant attr.
4811  if (auto *A = D->getAttr<CUDAConstantAttr>()) {
4812  if (!A->isImplicit())
4813  return;
4814  D->dropAttr<CUDAConstantAttr>();
4815  }
4816  D->addAttr(::new (S.Context) CUDAConstantAttr(S.Context, AL));
4817 }
4818 
4819 static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4820  const auto *VD = cast<VarDecl>(D);
4821  // extern __shared__ is only allowed on arrays with no length (e.g.
4822  // "int x[]").
4823  if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
4824  !isa<IncompleteArrayType>(VD->getType())) {
4825  S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
4826  return;
4827  }
4828  if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4829  S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
4830  << S.CurrentCUDATarget())
4831  return;
4832  D->addAttr(::new (S.Context) CUDASharedAttr(S.Context, AL));
4833 }
4834 
4835 static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4836  const auto *FD = cast<FunctionDecl>(D);
4837  if (!FD->getReturnType()->isVoidType() &&
4838  !FD->getReturnType()->getAs<AutoType>() &&
4840  SourceRange RTRange = FD->getReturnTypeSourceRange();
4841  S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4842  << FD->getType()
4843  << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4844  : FixItHint());
4845  return;
4846  }
4847  if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4848  if (Method->isInstance()) {
4849  S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
4850  << Method;
4851  return;
4852  }
4853  S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
4854  }
4855  // Only warn for "inline" when compiling for host, to cut down on noise.
4856  if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4857  S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
4858 
4859  D->addAttr(::new (S.Context) CUDAGlobalAttr(S.Context, AL));
4860  // In host compilation the kernel is emitted as a stub function, which is
4861  // a helper function for launching the kernel. The instructions in the helper
4862  // function has nothing to do with the source code of the kernel. Do not emit
4863  // debug info for the stub function to avoid confusing the debugger.
4864  if (S.LangOpts.HIP && !S.LangOpts.CUDAIsDevice)
4865  D->addAttr(NoDebugAttr::CreateImplicit(S.Context));
4866 }
4867 
4868 static void handleDeviceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4869  if (const auto *VD = dyn_cast<VarDecl>(D)) {
4870  if (VD->hasLocalStorage()) {
4871  S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4872  return;
4873  }
4874  }
4875 
4876  if (auto *A = D->getAttr<CUDADeviceAttr>()) {
4877  if (!A->isImplicit())
4878  return;
4879  D->dropAttr<CUDADeviceAttr>();
4880  }
4881  D->addAttr(::new (S.Context) CUDADeviceAttr(S.Context, AL));
4882 }
4883 
4884 static void handleManagedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4885  if (const auto *VD = dyn_cast<VarDecl>(D)) {
4886  if (VD->hasLocalStorage()) {
4887  S.Diag(AL.getLoc(), diag::err_cuda_nonstatic_constdev);
4888  return;
4889  }
4890  }
4891  if (!D->hasAttr<HIPManagedAttr>())
4892  D->addAttr(::new (S.Context) HIPManagedAttr(S.Context, AL));
4893  if (!D->hasAttr<CUDADeviceAttr>())
4894  D->addAttr(CUDADeviceAttr::CreateImplicit(S.Context));
4895 }
4896 
4897 static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4898  const auto *Fn = cast<FunctionDecl>(D);
4899  if (!Fn->isInlineSpecified()) {
4900  S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4901  return;
4902  }
4903 
4904  if (S.LangOpts.CPlusPlus && Fn->getStorageClass() != SC_Extern)
4905  S.Diag(AL.getLoc(), diag::warn_gnu_inline_cplusplus_without_extern);
4906 
4907  D->addAttr(::new (S.Context) GNUInlineAttr(S.Context, AL));
4908 }
4909 
4910 static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4911  if (hasDeclarator(D)) return;
4912 
4913  // Diagnostic is emitted elsewhere: here we store the (valid) AL
4914  // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4915  CallingConv CC;
4916  if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr))
4917  return;
4918 
4919  if (!isa<ObjCMethodDecl>(D)) {
4920  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4921  << AL << ExpectedFunctionOrMethod;
4922  return;
4923  }
4924 
4925  switch (AL.getKind()) {
4926  case ParsedAttr::AT_FastCall:
4927  D->addAttr(::new (S.Context) FastCallAttr(S.Context, AL));
4928  return;
4929  case ParsedAttr::AT_StdCall:
4930  D->addAttr(::new (S.Context) StdCallAttr(S.Context, AL));
4931  return;
4932  case ParsedAttr::AT_ThisCall:
4933  D->addAttr(::new (S.Context) ThisCallAttr(S.Context, AL));
4934  return;
4935  case ParsedAttr::AT_CDecl:
4936  D->addAttr(::new (S.Context) CDeclAttr(S.Context, AL));
4937  return;
4938  case ParsedAttr::AT_Pascal:
4939  D->addAttr(::new (S.Context) PascalAttr(S.Context, AL));
4940  return;
4941  case ParsedAttr::AT_SwiftCall:
4942  D->addAttr(::new (S.Context) SwiftCallAttr(S.Context, AL));
4943  return;
4944  case ParsedAttr::AT_SwiftAsyncCall:
4945  D->addAttr(::new (S.Context) SwiftAsyncCallAttr(S.Context, AL));
4946  return;
4947  case ParsedAttr::AT_VectorCall:
4948  D->addAttr(::new (S.Context) VectorCallAttr(S.Context, AL));
4949  return;
4950  case ParsedAttr::AT_MSABI:
4951  D->addAttr(::new (S.Context) MSABIAttr(S.Context, AL));
4952  return;
4953  case ParsedAttr::AT_SysVABI:
4954  D->addAttr(::new (S.Context) SysVABIAttr(S.Context, AL));
4955  return;
4956  case ParsedAttr::AT_RegCall:
4957  D->addAttr(::new (S.Context) RegCallAttr(S.Context, AL));
4958  return;
4959  case ParsedAttr::AT_Pcs: {
4960  PcsAttr::PCSType PCS;
4961  switch (CC) {
4962  case CC_AAPCS:
4963  PCS = PcsAttr::AAPCS;
4964  break;
4965  case CC_AAPCS_VFP:
4966  PCS = PcsAttr::AAPCS_VFP;
4967  break;
4968  default:
4969  llvm_unreachable("unexpected calling convention in pcs attribute");
4970  }
4971 
4972  D->addAttr(::new (S.Context) PcsAttr(S.Context, AL, PCS));
4973  return;
4974  }
4975  case ParsedAttr::AT_AArch64VectorPcs:
4976  D->addAttr(::new (S.Context) AArch64VectorPcsAttr(S.Context, AL));
4977  return;
4978  case ParsedAttr::AT_AArch64SVEPcs:
4979  D->addAttr(::new (S.Context) AArch64SVEPcsAttr(S.Context, AL));
4980  return;
4981  case ParsedAttr::AT_AMDGPUKernelCall:
4982  D->addAttr(::new (S.Context) AMDGPUKernelCallAttr(S.Context, AL));
4983  return;
4984  case ParsedAttr::AT_IntelOclBicc:
4985  D->addAttr(::new (S.Context) IntelOclBiccAttr(S.Context, AL));
4986  return;
4987  case ParsedAttr::AT_PreserveMost:
4988  D->addAttr(::new (S.Context) PreserveMostAttr(S.Context, AL));
4989  return;
4990  case ParsedAttr::AT_PreserveAll:
4991  D->addAttr(::new (S.Context) PreserveAllAttr(S.Context, AL));
4992  return;
4993  default:
4994  llvm_unreachable("unexpected attribute kind");
4995  }
4996 }
4997 
4998 static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4999  if (!AL.checkAtLeastNumArgs(S, 1))
5000  return;
5001 
5002  std::vector<StringRef> DiagnosticIdentifiers;
5003  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
5004  StringRef RuleName;
5005 
5006  if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr))
5007  return;
5008 
5009  // FIXME: Warn if the rule name is unknown. This is tricky because only
5010  // clang-tidy knows about available rules.
5011  DiagnosticIdentifiers.push_back(RuleName);
5012  }
5013  D->addAttr(::new (S.Context)
5014  SuppressAttr(S.Context, AL, DiagnosticIdentifiers.data(),
5015  DiagnosticIdentifiers.size()));
5016 }
5017 
5018 static void handleLifetimeCategoryAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5019  TypeSourceInfo *DerefTypeLoc = nullptr;
5020  QualType ParmType;
5021  if (AL.hasParsedType()) {
5022  ParmType = S.GetTypeFromParser(AL.getTypeArg(), &DerefTypeLoc);
5023 
5024  unsigned SelectIdx = ~0U;
5025  if (ParmType->isReferenceType())
5026  SelectIdx = 0;
5027  else if (ParmType->isArrayType())
5028  SelectIdx = 1;
5029 
5030  if (SelectIdx != ~0U) {
5031  S.Diag(AL.getLoc(), diag::err_attribute_invalid_argument)
5032  << SelectIdx << AL;
5033  return;
5034  }
5035  }
5036 
5037  // To check if earlier decl attributes do not conflict the newly parsed ones
5038  // we always add (and check) the attribute to the canonical decl. We need
5039  // to repeat the check for attribute mutual exclusion because we're attaching
5040  // all of the attributes to the canonical declaration rather than the current
5041  // declaration.
5042  D = D->getCanonicalDecl();
5043  if (AL.getKind() == ParsedAttr::AT_Owner) {
5044  if (checkAttrMutualExclusion<PointerAttr>(S, D, AL))
5045  return;
5046  if (const auto *OAttr = D->getAttr<OwnerAttr>()) {
5047  const Type *ExistingDerefType = OAttr->getDerefTypeLoc()
5048  ? OAttr->getDerefType().getTypePtr()
5049  : nullptr;
5050  if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
5051  S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
5052  << AL << OAttr;
5053  S.Diag(OAttr->getLocation(), diag::note_conflicting_attribute);
5054  }
5055  return;
5056  }
5057  for (Decl *Redecl : D->redecls()) {
5058  Redecl->addAttr(::new (S.Context) OwnerAttr(S.Context, AL, DerefTypeLoc));
5059  }
5060  } else {
5061  if (checkAttrMutualExclusion<OwnerAttr>(S, D, AL))
5062  return;
5063  if (const auto *PAttr = D->getAttr<PointerAttr>()) {
5064  const Type *ExistingDerefType = PAttr->getDerefTypeLoc()
5065  ? PAttr->getDerefType().getTypePtr()
5066  : nullptr;
5067  if (ExistingDerefType != ParmType.getTypePtrOrNull()) {
5068  S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)
5069  << AL << PAttr;
5070  S.Diag(PAttr->getLocation(), diag::note_conflicting_attribute);
5071  }
5072  return;
5073  }
5074  for (Decl *Redecl : D->redecls()) {
5075  Redecl->addAttr(::new (S.Context)
5076  PointerAttr(S.Context, AL, DerefTypeLoc));
5077  }
5078  }
5079 }
5080 
5081 static void handleRandomizeLayoutAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5082  if (checkAttrMutualExclusion<NoRandomizeLayoutAttr>(S, D, AL))
5083  return;
5084  if (!D->hasAttr<RandomizeLayoutAttr>())
5085  D->addAttr(::new (S.Context) RandomizeLayoutAttr(S.Context, AL));
5086 }
5087 
5089  const ParsedAttr &AL) {
5090  if (checkAttrMutualExclusion<RandomizeLayoutAttr>(S, D, AL))
5091  return;
5092  if (!D->hasAttr<NoRandomizeLayoutAttr>())
5093  D->addAttr(::new (S.Context) NoRandomizeLayoutAttr(S.Context, AL));
5094 }
5095 
5097  const FunctionDecl *FD) {
5098  if (Attrs.isInvalid())
5099  return true;
5100 
5101  if (Attrs.hasProcessingCache()) {
5102  CC = (CallingConv) Attrs.getProcessingCache();
5103  return false;
5104  }
5105 
5106  unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
5107  if (!Attrs.checkExactlyNumArgs(*this, ReqArgs)) {
5108  Attrs.setInvalid();
5109  return true;
5110  }
5111 
5112  // TODO: diagnose uses of these conventions on the wrong target.
5113  switch (Attrs.getKind()) {
5114  case ParsedAttr::AT_CDecl:
5115  CC = CC_C;
5116  break;
5117  case ParsedAttr::AT_FastCall:
5118  CC = CC_X86FastCall;
5119  break;
5120  case ParsedAttr::AT_StdCall:
5121  CC = CC_X86StdCall;
5122  break;
5123  case ParsedAttr::AT_ThisCall:
5124  CC = CC_X86ThisCall;
5125  break;
5126  case ParsedAttr::AT_Pascal:
5127  CC = CC_X86Pascal;
5128  break;
5129  case ParsedAttr::AT_SwiftCall:
5130  CC = CC_Swift;
5131  break;
5132  case ParsedAttr::AT_SwiftAsyncCall:
5133  CC = CC_SwiftAsync;
5134  break;
5135  case ParsedAttr::AT_VectorCall:
5136  CC = CC_X86VectorCall;
5137  break;
5138  case ParsedAttr::AT_AArch64VectorPcs:
5139  CC = CC_AArch64VectorCall;
5140  break;
5141  case ParsedAttr::AT_AArch64SVEPcs:
5142  CC = CC_AArch64SVEPCS;
5143  break;
5144  case ParsedAttr::AT_AMDGPUKernelCall:
5145  CC = CC_AMDGPUKernelCall;
5146  break;
5147  case ParsedAttr::AT_RegCall:
5148  CC = CC_X86RegCall;
5149  break;
5150  case ParsedAttr::AT_MSABI:
5151  CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
5152  CC_Win64;
5153  break;
5154  case ParsedAttr::AT_SysVABI:
5155  CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
5156  CC_C;
5157  break;
5158  case ParsedAttr::AT_Pcs: {
5159  StringRef StrRef;
5160  if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
5161  Attrs.setInvalid();
5162  return true;
5163  }
5164  if (StrRef == "aapcs") {
5165  CC = CC_AAPCS;
5166  break;
5167  } else if (StrRef == "aapcs-vfp") {
5168  CC = CC_AAPCS_VFP;
5169  break;
5170  }
5171 
5172  Attrs.setInvalid();
5173  Diag(Attrs.getLoc(), diag::err_invalid_pcs);
5174  return true;
5175  }
5176  case ParsedAttr::AT_IntelOclBicc:
5177  CC = CC_IntelOclBicc;
5178  break;
5179  case ParsedAttr::AT_PreserveMost:
5180  CC = CC_PreserveMost;
5181  break;
5182  case ParsedAttr::AT_PreserveAll:
5183  CC = CC_PreserveAll;
5184  break;
5185  default: llvm_unreachable("unexpected attribute kind");
5186  }
5187 
5189  const TargetInfo &TI = Context.getTargetInfo();
5190  // CUDA functions may have host and/or device attributes which indicate
5191  // their targeted execution environment, therefore the calling convention
5192  // of functions in CUDA should be checked against the target deduced based
5193  // on their host/device attributes.
5194  if (LangOpts.CUDA) {
5195  auto *Aux = Context.getAuxTargetInfo();
5196  auto CudaTarget = IdentifyCUDATarget(FD);
5197  bool CheckHost = false, CheckDevice = false;
5198  switch (CudaTarget) {
5199  case CFT_HostDevice:
5200  CheckHost = true;
5201  CheckDevice = true;
5202  break;
5203  case CFT_Host:
5204  CheckHost = true;
5205  break;
5206  case CFT_Device:
5207  case CFT_Global:
5208  CheckDevice = true;
5209  break;
5210  case CFT_InvalidTarget:
5211  llvm_unreachable("unexpected cuda target");
5212  }
5213  auto *HostTI = LangOpts.CUDAIsDevice ? Aux : &TI;
5214  auto *DeviceTI = LangOpts.CUDAIsDevice ? &TI : Aux;
5215  if (CheckHost && HostTI)
5216  A = HostTI->checkCallingConvention(CC);
5217  if (A == TargetInfo::CCCR_OK && CheckDevice && DeviceTI)
5218  A = DeviceTI->checkCallingConvention(CC);
5219  } else {
5220  A = TI.checkCallingConvention(CC);
5221  }
5222 
5223  switch (A) {
5224  case TargetInfo::CCCR_OK:
5225  break;
5226 
5228  // Treat an ignored convention as if it was an explicit C calling convention
5229  // attribute. For example, __stdcall on Win x64 functions as __cdecl, so
5230  // that command line flags that change the default convention to
5231  // __vectorcall don't affect declarations marked __stdcall.
5232  CC = CC_C;
5233  break;
5234 
5236  Diag(Attrs.getLoc(), diag::error_cconv_unsupported)
5237  << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
5238  break;
5239 
5240  case TargetInfo::CCCR_Warning: {
5241  Diag(Attrs.getLoc(), diag::warn_cconv_unsupported)
5242  << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
5243 
5244  // This convention is not valid for the target. Use the default function or
5245  // method calling convention.
5246  bool IsCXXMethod = false, IsVariadic = false;
5247  if (FD) {
5248  IsCXXMethod = FD->isCXXInstanceMember();
5249  IsVariadic = FD->isVariadic();
5250  }
5251  CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
5252  break;
5253  }
5254  }
5255 
5256  Attrs.setProcessingCache((unsigned) CC);
5257  return false;
5258 }
5259 
5260 /// Pointer-like types in the default address space.
5262  if (!Ty->hasPointerRepresentation())
5263  return Ty->isDependentType();
5265 }
5266 
5267 /// Pointers and references in the default address space.
5269  if (const auto *PtrType = Ty->getAs<PointerType>()) {
5270  Ty = PtrType->getPointeeType();
5271  } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
5272  Ty = RefType->getPointeeType();
5273  } else {
5274  return Ty->isDependentType();
5275  }
5276  return Ty.getAddressSpace() == LangAS::Default;
5277 }
5278 
5279 /// Pointers and references to pointers in the default address space.
5281  if (const auto *PtrType = Ty->getAs<PointerType>()) {
5282  Ty = PtrType->getPointeeType();
5283  } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
5284  Ty = RefType->getPointeeType();
5285  } else {
5286  return Ty->isDependentType();
5287  }
5288  if (!Ty.getQualifiers().empty())
5289  return false;
5290  return isValidSwiftContextType(Ty);
5291 }
5292 
5294  ParameterABI abi) {
5295 
5296  QualType type = cast<ParmVarDecl>(D)->getType();
5297 
5298  if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
5299  if (existingAttr->getABI() != abi) {
5300  Diag(CI.getLoc(), diag::err_attributes_are_not_compatible)
5301  << getParameterABISpelling(abi) << existingAttr;
5302  Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
5303  return;
5304  }
5305  }
5306 
5307  switch (abi) {
5309  llvm_unreachable("explicit attribute for ordinary parameter ABI?");
5310 
5312  if (!isValidSwiftContextType(type)) {
5313  Diag(CI.getLoc(), diag::err_swift_abi_parameter_wrong_type)
5314  << getParameterABISpelling(abi) << /*pointer to pointer */ 0 << type;
5315  }