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