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