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