clang  10.0.0svn
SemaDeclAttr.cpp
Go to the documentation of this file.
1 //===--- SemaDeclAttr.cpp - Declaration Attribute Handling ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements decl-related attribute processing.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/AST/Mangle.h"
24 #include "clang/Basic/CharInfo.h"
26 #include "clang/Basic/TargetInfo.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Sema/DeclSpec.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/Scope.h"
33 #include "clang/Sema/ScopeInfo.h"
35 #include "llvm/ADT/STLExtras.h"
36 #include "llvm/ADT/StringExtras.h"
37 #include "llvm/Support/MathExtras.h"
38 
39 using namespace clang;
40 using namespace sema;
41 
43  enum LANG {
44  C,
45  Cpp,
47  };
48 } // end namespace AttributeLangSupport
49 
50 //===----------------------------------------------------------------------===//
51 // Helper functions
52 //===----------------------------------------------------------------------===//
53 
54 /// isFunctionOrMethod - Return true if the given decl has function
55 /// type (function or function-typed variable) or an Objective-C
56 /// method.
57 static bool isFunctionOrMethod(const Decl *D) {
58  return (D->getFunctionType() != nullptr) || isa<ObjCMethodDecl>(D);
59 }
60 
61 /// Return true if the given decl has function type (function or
62 /// function-typed variable) or an Objective-C method or a block.
63 static bool isFunctionOrMethodOrBlock(const Decl *D) {
64  return isFunctionOrMethod(D) || isa<BlockDecl>(D);
65 }
66 
67 /// Return true if the given decl has a declarator that should have
68 /// been processed by Sema::GetTypeForDeclarator.
69 static bool hasDeclarator(const Decl *D) {
70  // In some sense, TypedefDecl really *ought* to be a DeclaratorDecl.
71  return isa<DeclaratorDecl>(D) || isa<BlockDecl>(D) || isa<TypedefNameDecl>(D) ||
72  isa<ObjCPropertyDecl>(D);
73 }
74 
75 /// hasFunctionProto - Return true if the given decl has a argument
76 /// information. This decl should have already passed
77 /// isFunctionOrMethod or isFunctionOrMethodOrBlock.
78 static bool hasFunctionProto(const Decl *D) {
79  if (const FunctionType *FnTy = D->getFunctionType())
80  return isa<FunctionProtoType>(FnTy);
81  return isa<ObjCMethodDecl>(D) || isa<BlockDecl>(D);
82 }
83 
84 /// getFunctionOrMethodNumParams - Return number of function or method
85 /// parameters. It is an error to call this on a K&R function (use
86 /// hasFunctionProto first).
87 static unsigned getFunctionOrMethodNumParams(const Decl *D) {
88  if (const FunctionType *FnTy = D->getFunctionType())
89  return cast<FunctionProtoType>(FnTy)->getNumParams();
90  if (const auto *BD = dyn_cast<BlockDecl>(D))
91  return BD->getNumParams();
92  return cast<ObjCMethodDecl>(D)->param_size();
93 }
94 
95 static const ParmVarDecl *getFunctionOrMethodParam(const Decl *D,
96  unsigned Idx) {
97  if (const auto *FD = dyn_cast<FunctionDecl>(D))
98  return FD->getParamDecl(Idx);
99  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
100  return MD->getParamDecl(Idx);
101  if (const auto *BD = dyn_cast<BlockDecl>(D))
102  return BD->getParamDecl(Idx);
103  return nullptr;
104 }
105 
106 static QualType getFunctionOrMethodParamType(const Decl *D, unsigned Idx) {
107  if (const FunctionType *FnTy = D->getFunctionType())
108  return cast<FunctionProtoType>(FnTy)->getParamType(Idx);
109  if (const auto *BD = dyn_cast<BlockDecl>(D))
110  return BD->getParamDecl(Idx)->getType();
111 
112  return cast<ObjCMethodDecl>(D)->parameters()[Idx]->getType();
113 }
114 
115 static SourceRange getFunctionOrMethodParamRange(const Decl *D, unsigned Idx) {
116  if (auto *PVD = getFunctionOrMethodParam(D, Idx))
117  return PVD->getSourceRange();
118  return SourceRange();
119 }
120 
122  if (const FunctionType *FnTy = D->getFunctionType())
123  return FnTy->getReturnType();
124  return cast<ObjCMethodDecl>(D)->getReturnType();
125 }
126 
128  if (const auto *FD = dyn_cast<FunctionDecl>(D))
129  return FD->getReturnTypeSourceRange();
130  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
131  return MD->getReturnTypeSourceRange();
132  return SourceRange();
133 }
134 
135 static bool isFunctionOrMethodVariadic(const Decl *D) {
136  if (const FunctionType *FnTy = D->getFunctionType())
137  return cast<FunctionProtoType>(FnTy)->isVariadic();
138  if (const auto *BD = dyn_cast<BlockDecl>(D))
139  return BD->isVariadic();
140  return cast<ObjCMethodDecl>(D)->isVariadic();
141 }
142 
143 static bool isInstanceMethod(const Decl *D) {
144  if (const auto *MethodDecl = dyn_cast<CXXMethodDecl>(D))
145  return MethodDecl->isInstance();
146  return false;
147 }
148 
149 static inline bool isNSStringType(QualType T, ASTContext &Ctx) {
150  const auto *PT = T->getAs<ObjCObjectPointerType>();
151  if (!PT)
152  return false;
153 
154  ObjCInterfaceDecl *Cls = PT->getObjectType()->getInterface();
155  if (!Cls)
156  return false;
157 
158  IdentifierInfo* ClsName = Cls->getIdentifier();
159 
160  // FIXME: Should we walk the chain of classes?
161  return ClsName == &Ctx.Idents.get("NSString") ||
162  ClsName == &Ctx.Idents.get("NSMutableString");
163 }
164 
165 static inline bool isCFStringType(QualType T, ASTContext &Ctx) {
166  const auto *PT = T->getAs<PointerType>();
167  if (!PT)
168  return false;
169 
170  const auto *RT = PT->getPointeeType()->getAs<RecordType>();
171  if (!RT)
172  return false;
173 
174  const RecordDecl *RD = RT->getDecl();
175  if (RD->getTagKind() != TTK_Struct)
176  return false;
177 
178  return RD->getIdentifier() == &Ctx.Idents.get("__CFString");
179 }
180 
181 static unsigned getNumAttributeArgs(const ParsedAttr &AL) {
182  // FIXME: Include the type in the argument list.
183  return AL.getNumArgs() + AL.hasParsedType();
184 }
185 
186 template <typename Compare>
187 static bool checkAttributeNumArgsImpl(Sema &S, const ParsedAttr &AL,
188  unsigned Num, unsigned Diag,
189  Compare Comp) {
190  if (Comp(getNumAttributeArgs(AL), Num)) {
191  S.Diag(AL.getLoc(), Diag) << AL << Num;
192  return false;
193  }
194 
195  return true;
196 }
197 
198 /// Check if the attribute has exactly as many args as Num. May
199 /// output an error.
200 static bool checkAttributeNumArgs(Sema &S, const ParsedAttr &AL, unsigned Num) {
201  return checkAttributeNumArgsImpl(S, AL, Num,
202  diag::err_attribute_wrong_number_arguments,
203  std::not_equal_to<unsigned>());
204 }
205 
206 /// Check if the attribute has at least as many args as Num. May
207 /// output an error.
208 static bool checkAttributeAtLeastNumArgs(Sema &S, const ParsedAttr &AL,
209  unsigned Num) {
210  return checkAttributeNumArgsImpl(S, AL, Num,
211  diag::err_attribute_too_few_arguments,
212  std::less<unsigned>());
213 }
214 
215 /// Check if the attribute has at most as many args as Num. May
216 /// output an error.
217 static bool checkAttributeAtMostNumArgs(Sema &S, const ParsedAttr &AL,
218  unsigned Num) {
219  return checkAttributeNumArgsImpl(S, AL, Num,
220  diag::err_attribute_too_many_arguments,
221  std::greater<unsigned>());
222 }
223 
224 /// A helper function to provide Attribute Location for the Attr types
225 /// AND the ParsedAttr.
226 template <typename AttrInfo>
227 static typename std::enable_if<std::is_base_of<Attr, AttrInfo>::value,
229 getAttrLoc(const AttrInfo &AL) {
230  return AL.getLocation();
231 }
232 static SourceLocation getAttrLoc(const ParsedAttr &AL) { return AL.getLoc(); }
233 
234 /// If Expr is a valid integer constant, get the value of the integer
235 /// expression and return success or failure. May output an error.
236 ///
237 /// Negative argument is implicitly converted to unsigned, unless
238 /// \p StrictlyUnsigned is true.
239 template <typename AttrInfo>
240 static bool checkUInt32Argument(Sema &S, const AttrInfo &AI, const Expr *Expr,
241  uint32_t &Val, unsigned Idx = UINT_MAX,
242  bool StrictlyUnsigned = false) {
243  llvm::APSInt I(32);
244  if (Expr->isTypeDependent() || Expr->isValueDependent() ||
245  !Expr->isIntegerConstantExpr(I, S.Context)) {
246  if (Idx != UINT_MAX)
247  S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
248  << &AI << Idx << AANT_ArgumentIntegerConstant
249  << Expr->getSourceRange();
250  else
251  S.Diag(getAttrLoc(AI), diag::err_attribute_argument_type)
252  << &AI << AANT_ArgumentIntegerConstant << Expr->getSourceRange();
253  return false;
254  }
255 
256  if (!I.isIntN(32)) {
257  S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
258  << I.toString(10, false) << 32 << /* Unsigned */ 1;
259  return false;
260  }
261 
262  if (StrictlyUnsigned && I.isSigned() && I.isNegative()) {
263  S.Diag(getAttrLoc(AI), diag::err_attribute_requires_positive_integer)
264  << &AI << /*non-negative*/ 1;
265  return false;
266  }
267 
268  Val = (uint32_t)I.getZExtValue();
269  return true;
270 }
271 
272 /// Wrapper around checkUInt32Argument, with an extra check to be sure
273 /// that the result will fit into a regular (signed) int. All args have the same
274 /// purpose as they do in checkUInt32Argument.
275 template <typename AttrInfo>
276 static bool checkPositiveIntArgument(Sema &S, const AttrInfo &AI, const Expr *Expr,
277  int &Val, unsigned Idx = UINT_MAX) {
278  uint32_t UVal;
279  if (!checkUInt32Argument(S, AI, Expr, UVal, Idx))
280  return false;
281 
282  if (UVal > (uint32_t)std::numeric_limits<int>::max()) {
283  llvm::APSInt I(32); // for toString
284  I = UVal;
285  S.Diag(Expr->getExprLoc(), diag::err_ice_too_large)
286  << I.toString(10, false) << 32 << /* Unsigned */ 0;
287  return false;
288  }
289 
290  Val = UVal;
291  return true;
292 }
293 
294 /// Diagnose mutually exclusive attributes when present on a given
295 /// declaration. Returns true if diagnosed.
296 template <typename AttrTy>
297 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const ParsedAttr &AL) {
298  if (const auto *A = D->getAttr<AttrTy>()) {
299  S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible) << AL << A;
300  S.Diag(A->getLocation(), diag::note_conflicting_attribute);
301  return true;
302  }
303  return false;
304 }
305 
306 template <typename AttrTy>
307 static bool checkAttrMutualExclusion(Sema &S, Decl *D, const Attr &AL) {
308  if (const auto *A = D->getAttr<AttrTy>()) {
309  S.Diag(AL.getLocation(), diag::err_attributes_are_not_compatible) << &AL
310  << A;
311  S.Diag(A->getLocation(), diag::note_conflicting_attribute);
312  return true;
313  }
314  return false;
315 }
316 
317 /// Check if IdxExpr is a valid parameter index for a function or
318 /// instance method D. May output an error.
319 ///
320 /// \returns true if IdxExpr is a valid index.
321 template <typename AttrInfo>
323  Sema &S, const Decl *D, const AttrInfo &AI, unsigned AttrArgNum,
324  const Expr *IdxExpr, ParamIdx &Idx, bool CanIndexImplicitThis = false) {
325  assert(isFunctionOrMethodOrBlock(D));
326 
327  // In C++ the implicit 'this' function parameter also counts.
328  // Parameters are counted from one.
329  bool HP = hasFunctionProto(D);
330  bool HasImplicitThisParam = isInstanceMethod(D);
331  bool IV = HP && isFunctionOrMethodVariadic(D);
332  unsigned NumParams =
333  (HP ? getFunctionOrMethodNumParams(D) : 0) + HasImplicitThisParam;
334 
335  llvm::APSInt IdxInt;
336  if (IdxExpr->isTypeDependent() || IdxExpr->isValueDependent() ||
337  !IdxExpr->isIntegerConstantExpr(IdxInt, S.Context)) {
338  S.Diag(getAttrLoc(AI), diag::err_attribute_argument_n_type)
339  << &AI << AttrArgNum << AANT_ArgumentIntegerConstant
340  << IdxExpr->getSourceRange();
341  return false;
342  }
343 
344  unsigned IdxSource = IdxInt.getLimitedValue(UINT_MAX);
345  if (IdxSource < 1 || (!IV && IdxSource > NumParams)) {
346  S.Diag(getAttrLoc(AI), diag::err_attribute_argument_out_of_bounds)
347  << &AI << AttrArgNum << IdxExpr->getSourceRange();
348  return false;
349  }
350  if (HasImplicitThisParam && !CanIndexImplicitThis) {
351  if (IdxSource == 1) {
352  S.Diag(getAttrLoc(AI), diag::err_attribute_invalid_implicit_this_argument)
353  << &AI << IdxExpr->getSourceRange();
354  return false;
355  }
356  }
357 
358  Idx = ParamIdx(IdxSource, D);
359  return true;
360 }
361 
362 /// Check if the argument \p ArgNum of \p Attr is a ASCII string literal.
363 /// If not emit an error and return false. If the argument is an identifier it
364 /// will emit an error with a fixit hint and treat it as if it was a string
365 /// literal.
366 bool Sema::checkStringLiteralArgumentAttr(const ParsedAttr &AL, unsigned ArgNum,
367  StringRef &Str,
368  SourceLocation *ArgLocation) {
369  // Look for identifiers. If we have one emit a hint to fix it to a literal.
370  if (AL.isArgIdent(ArgNum)) {
371  IdentifierLoc *Loc = AL.getArgAsIdent(ArgNum);
372  Diag(Loc->Loc, diag::err_attribute_argument_type)
373  << AL << AANT_ArgumentString
374  << FixItHint::CreateInsertion(Loc->Loc, "\"")
375  << FixItHint::CreateInsertion(getLocForEndOfToken(Loc->Loc), "\"");
376  Str = Loc->Ident->getName();
377  if (ArgLocation)
378  *ArgLocation = Loc->Loc;
379  return true;
380  }
381 
382  // Now check for an actual string literal.
383  Expr *ArgExpr = AL.getArgAsExpr(ArgNum);
384  const auto *Literal = dyn_cast<StringLiteral>(ArgExpr->IgnoreParenCasts());
385  if (ArgLocation)
386  *ArgLocation = ArgExpr->getBeginLoc();
387 
388  if (!Literal || !Literal->isAscii()) {
389  Diag(ArgExpr->getBeginLoc(), diag::err_attribute_argument_type)
390  << AL << AANT_ArgumentString;
391  return false;
392  }
393 
394  Str = Literal->getString();
395  return true;
396 }
397 
398 /// Applies the given attribute to the Decl without performing any
399 /// additional semantic checking.
400 template <typename AttrType>
402  unsigned SpellingIndex) {
403  D->addAttr(::new (S.Context) AttrType(SR, S.Context, SpellingIndex));
404 }
405 
406 template <typename AttrType>
407 static void handleSimpleAttribute(Sema &S, Decl *D, const ParsedAttr &AL) {
408  handleSimpleAttribute<AttrType>(S, D, AL.getRange(),
410 }
411 
412 
413 template <typename... DiagnosticArgs>
414 static const Sema::SemaDiagnosticBuilder&
416  return Bldr;
417 }
418 
419 template <typename T, typename... DiagnosticArgs>
420 static const Sema::SemaDiagnosticBuilder&
422  DiagnosticArgs &&... ExtraArgs) {
423  return appendDiagnostics(Bldr << std::forward<T>(ExtraArg),
424  std::forward<DiagnosticArgs>(ExtraArgs)...);
425 }
426 
427 /// Add an attribute {@code AttrType} to declaration {@code D}, provided that
428 /// {@code PassesCheck} is true.
429 /// Otherwise, emit diagnostic {@code DiagID}, passing in all parameters
430 /// specified in {@code ExtraArgs}.
431 template <typename AttrType, typename... DiagnosticArgs>
432 static void
433 handleSimpleAttributeOrDiagnose(Sema &S, Decl *D, SourceRange SR,
434  unsigned SpellingIndex,
435  bool PassesCheck,
436  unsigned DiagID, DiagnosticArgs&&... ExtraArgs) {
437  if (!PassesCheck) {
438  Sema::SemaDiagnosticBuilder DB = S.Diag(D->getBeginLoc(), DiagID);
439  appendDiagnostics(DB, std::forward<DiagnosticArgs>(ExtraArgs)...);
440  return;
441  }
442  handleSimpleAttribute<AttrType>(S, D, SR, SpellingIndex);
443 }
444 
445 template <typename AttrType, typename... DiagnosticArgs>
446 static void
447 handleSimpleAttributeOrDiagnose(Sema &S, Decl *D, const ParsedAttr &AL,
448  bool PassesCheck,
449  unsigned DiagID,
450  DiagnosticArgs&&... ExtraArgs) {
451  return handleSimpleAttributeOrDiagnose<AttrType>(
452  S, D, AL.getRange(), AL.getAttributeSpellingListIndex(), PassesCheck,
453  DiagID, std::forward<DiagnosticArgs>(ExtraArgs)...);
454 }
455 
456 template <typename AttrType>
457 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
458  const ParsedAttr &AL) {
459  handleSimpleAttribute<AttrType>(S, D, AL);
460 }
461 
462 /// Applies the given attribute to the Decl so long as the Decl doesn't
463 /// already have one of the given incompatible attributes.
464 template <typename AttrType, typename IncompatibleAttrType,
465  typename... IncompatibleAttrTypes>
466 static void handleSimpleAttributeWithExclusions(Sema &S, Decl *D,
467  const ParsedAttr &AL) {
468  if (checkAttrMutualExclusion<IncompatibleAttrType>(S, D, AL))
469  return;
470  handleSimpleAttributeWithExclusions<AttrType, IncompatibleAttrTypes...>(S, D,
471  AL);
472 }
473 
474 /// Check if the passed-in expression is of type int or bool.
475 static bool isIntOrBool(Expr *Exp) {
476  QualType QT = Exp->getType();
477  return QT->isBooleanType() || QT->isIntegerType();
478 }
479 
480 
481 // Check to see if the type is a smart pointer of some kind. We assume
482 // it's a smart pointer if it defines both operator-> and operator*.
483 static bool threadSafetyCheckIsSmartPointer(Sema &S, const RecordType* RT) {
484  auto IsOverloadedOperatorPresent = [&S](const RecordDecl *Record,
486  DeclContextLookupResult Result =
488  return !Result.empty();
489  };
490 
491  const RecordDecl *Record = RT->getDecl();
492  bool foundStarOperator = IsOverloadedOperatorPresent(Record, OO_Star);
493  bool foundArrowOperator = IsOverloadedOperatorPresent(Record, OO_Arrow);
494  if (foundStarOperator && foundArrowOperator)
495  return true;
496 
497  const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record);
498  if (!CXXRecord)
499  return false;
500 
501  for (auto BaseSpecifier : CXXRecord->bases()) {
502  if (!foundStarOperator)
503  foundStarOperator = IsOverloadedOperatorPresent(
504  BaseSpecifier.getType()->getAsRecordDecl(), OO_Star);
505  if (!foundArrowOperator)
506  foundArrowOperator = IsOverloadedOperatorPresent(
507  BaseSpecifier.getType()->getAsRecordDecl(), OO_Arrow);
508  }
509 
510  if (foundStarOperator && foundArrowOperator)
511  return true;
512 
513  return false;
514 }
515 
516 /// Check if passed in Decl is a pointer type.
517 /// Note that this function may produce an error message.
518 /// \return true if the Decl is a pointer type; false otherwise
519 static bool threadSafetyCheckIsPointer(Sema &S, const Decl *D,
520  const ParsedAttr &AL) {
521  const auto *VD = cast<ValueDecl>(D);
522  QualType QT = VD->getType();
523  if (QT->isAnyPointerType())
524  return true;
525 
526  if (const auto *RT = QT->getAs<RecordType>()) {
527  // If it's an incomplete type, it could be a smart pointer; skip it.
528  // (We don't want to force template instantiation if we can avoid it,
529  // since that would alter the order in which templates are instantiated.)
530  if (RT->isIncompleteType())
531  return true;
532 
533  if (threadSafetyCheckIsSmartPointer(S, RT))
534  return true;
535  }
536 
537  S.Diag(AL.getLoc(), diag::warn_thread_attribute_decl_not_pointer) << AL << QT;
538  return false;
539 }
540 
541 /// Checks that the passed in QualType either is of RecordType or points
542 /// to RecordType. Returns the relevant RecordType, null if it does not exit.
543 static const RecordType *getRecordType(QualType QT) {
544  if (const auto *RT = QT->getAs<RecordType>())
545  return RT;
546 
547  // Now check if we point to record type.
548  if (const auto *PT = QT->getAs<PointerType>())
549  return PT->getPointeeType()->getAs<RecordType>();
550 
551  return nullptr;
552 }
553 
554 template <typename AttrType>
555 static bool checkRecordDeclForAttr(const RecordDecl *RD) {
556  // Check if the record itself has the attribute.
557  if (RD->hasAttr<AttrType>())
558  return true;
559 
560  // Else check if any base classes have the attribute.
561  if (const auto *CRD = dyn_cast<CXXRecordDecl>(RD)) {
562  CXXBasePaths BPaths(false, false);
563  if (CRD->lookupInBases(
564  [](const CXXBaseSpecifier *BS, CXXBasePath &) {
565  const auto &Ty = *BS->getType();
566  // If it's type-dependent, we assume it could have the attribute.
567  if (Ty.isDependentType())
568  return true;
569  return Ty.getAs<RecordType>()->getDecl()->hasAttr<AttrType>();
570  },
571  BPaths, true))
572  return true;
573  }
574  return false;
575 }
576 
577 static bool checkRecordTypeForCapability(Sema &S, QualType Ty) {
578  const RecordType *RT = getRecordType(Ty);
579 
580  if (!RT)
581  return false;
582 
583  // Don't check for the capability if the class hasn't been defined yet.
584  if (RT->isIncompleteType())
585  return true;
586 
587  // Allow smart pointers to be used as capability objects.
588  // FIXME -- Check the type that the smart pointer points to.
589  if (threadSafetyCheckIsSmartPointer(S, RT))
590  return true;
591 
592  return checkRecordDeclForAttr<CapabilityAttr>(RT->getDecl());
593 }
594 
595 static bool checkTypedefTypeForCapability(QualType Ty) {
596  const auto *TD = Ty->getAs<TypedefType>();
597  if (!TD)
598  return false;
599 
600  TypedefNameDecl *TN = TD->getDecl();
601  if (!TN)
602  return false;
603 
604  return TN->hasAttr<CapabilityAttr>();
605 }
606 
607 static bool typeHasCapability(Sema &S, QualType Ty) {
608  if (checkTypedefTypeForCapability(Ty))
609  return true;
610 
611  if (checkRecordTypeForCapability(S, Ty))
612  return true;
613 
614  return false;
615 }
616 
617 static bool isCapabilityExpr(Sema &S, const Expr *Ex) {
618  // Capability expressions are simple expressions involving the boolean logic
619  // operators &&, || or !, a simple DeclRefExpr, CastExpr or a ParenExpr. Once
620  // a DeclRefExpr is found, its type should be checked to determine whether it
621  // is a capability or not.
622 
623  if (const auto *E = dyn_cast<CastExpr>(Ex))
624  return isCapabilityExpr(S, E->getSubExpr());
625  else if (const auto *E = dyn_cast<ParenExpr>(Ex))
626  return isCapabilityExpr(S, E->getSubExpr());
627  else if (const auto *E = dyn_cast<UnaryOperator>(Ex)) {
628  if (E->getOpcode() == UO_LNot || E->getOpcode() == UO_AddrOf ||
629  E->getOpcode() == UO_Deref)
630  return isCapabilityExpr(S, E->getSubExpr());
631  return false;
632  } else if (const auto *E = dyn_cast<BinaryOperator>(Ex)) {
633  if (E->getOpcode() == BO_LAnd || E->getOpcode() == BO_LOr)
634  return isCapabilityExpr(S, E->getLHS()) &&
635  isCapabilityExpr(S, E->getRHS());
636  return false;
637  }
638 
639  return typeHasCapability(S, Ex->getType());
640 }
641 
642 /// Checks that all attribute arguments, starting from Sidx, resolve to
643 /// a capability object.
644 /// \param Sidx The attribute argument index to start checking with.
645 /// \param ParamIdxOk Whether an argument can be indexing into a function
646 /// parameter list.
647 static void checkAttrArgsAreCapabilityObjs(Sema &S, Decl *D,
648  const ParsedAttr &AL,
650  unsigned Sidx = 0,
651  bool ParamIdxOk = false) {
652  if (Sidx == AL.getNumArgs()) {
653  // If we don't have any capability arguments, the attribute implicitly
654  // refers to 'this'. So we need to make sure that 'this' exists, i.e. we're
655  // a non-static method, and that the class is a (scoped) capability.
656  const auto *MD = dyn_cast<const CXXMethodDecl>(D);
657  if (MD && !MD->isStatic()) {
658  const CXXRecordDecl *RD = MD->getParent();
659  // FIXME -- need to check this again on template instantiation
660  if (!checkRecordDeclForAttr<CapabilityAttr>(RD) &&
661  !checkRecordDeclForAttr<ScopedLockableAttr>(RD))
662  S.Diag(AL.getLoc(),
663  diag::warn_thread_attribute_not_on_capability_member)
664  << AL << MD->getParent();
665  } else {
666  S.Diag(AL.getLoc(), diag::warn_thread_attribute_not_on_non_static_member)
667  << AL;
668  }
669  }
670 
671  for (unsigned Idx = Sidx; Idx < AL.getNumArgs(); ++Idx) {
672  Expr *ArgExp = AL.getArgAsExpr(Idx);
673 
674  if (ArgExp->isTypeDependent()) {
675  // FIXME -- need to check this again on template instantiation
676  Args.push_back(ArgExp);
677  continue;
678  }
679 
680  if (const auto *StrLit = dyn_cast<StringLiteral>(ArgExp)) {
681  if (StrLit->getLength() == 0 ||
682  (StrLit->isAscii() && StrLit->getString() == StringRef("*"))) {
683  // Pass empty strings to the analyzer without warnings.
684  // Treat "*" as the universal lock.
685  Args.push_back(ArgExp);
686  continue;
687  }
688 
689  // We allow constant strings to be used as a placeholder for expressions
690  // that are not valid C++ syntax, but warn that they are ignored.
691  S.Diag(AL.getLoc(), diag::warn_thread_attribute_ignored) << AL;
692  Args.push_back(ArgExp);
693  continue;
694  }
695 
696  QualType ArgTy = ArgExp->getType();
697 
698  // A pointer to member expression of the form &MyClass::mu is treated
699  // specially -- we need to look at the type of the member.
700  if (const auto *UOp = dyn_cast<UnaryOperator>(ArgExp))
701  if (UOp->getOpcode() == UO_AddrOf)
702  if (const auto *DRE = dyn_cast<DeclRefExpr>(UOp->getSubExpr()))
703  if (DRE->getDecl()->isCXXInstanceMember())
704  ArgTy = DRE->getDecl()->getType();
705 
706  // First see if we can just cast to record type, or pointer to record type.
707  const RecordType *RT = getRecordType(ArgTy);
708 
709  // Now check if we index into a record type function param.
710  if(!RT && ParamIdxOk) {
711  const auto *FD = dyn_cast<FunctionDecl>(D);
712  const auto *IL = dyn_cast<IntegerLiteral>(ArgExp);
713  if(FD && IL) {
714  unsigned int NumParams = FD->getNumParams();
715  llvm::APInt ArgValue = IL->getValue();
716  uint64_t ParamIdxFromOne = ArgValue.getZExtValue();
717  uint64_t ParamIdxFromZero = ParamIdxFromOne - 1;
718  if (!ArgValue.isStrictlyPositive() || ParamIdxFromOne > NumParams) {
719  S.Diag(AL.getLoc(),
720  diag::err_attribute_argument_out_of_bounds_extra_info)
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, /*Idx=*/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, /*Idx=*/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_out_of_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  /*AttrArgNum=*/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(
2288  NamedDecl *D, SourceRange Range, IdentifierInfo *Platform, bool Implicit,
2289  VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted,
2290  bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement,
2291  AvailabilityMergeKind AMK, int Priority, unsigned AttrSpellingListIndex) {
2292  VersionTuple MergedIntroduced = Introduced;
2293  VersionTuple MergedDeprecated = Deprecated;
2294  VersionTuple MergedObsoleted = Obsoleted;
2295  bool FoundAny = false;
2296  bool OverrideOrImpl = false;
2297  switch (AMK) {
2298  case AMK_None:
2299  case AMK_Redeclaration:
2300  OverrideOrImpl = false;
2301  break;
2302 
2303  case AMK_Override:
2304  case AMK_ProtocolImplementation:
2305  OverrideOrImpl = true;
2306  break;
2307  }
2308 
2309  if (D->hasAttrs()) {
2310  AttrVec &Attrs = D->getAttrs();
2311  for (unsigned i = 0, e = Attrs.size(); i != e;) {
2312  const auto *OldAA = dyn_cast<AvailabilityAttr>(Attrs[i]);
2313  if (!OldAA) {
2314  ++i;
2315  continue;
2316  }
2317 
2318  IdentifierInfo *OldPlatform = OldAA->getPlatform();
2319  if (OldPlatform != Platform) {
2320  ++i;
2321  continue;
2322  }
2323 
2324  // If there is an existing availability attribute for this platform that
2325  // has a lower priority use the existing one and discard the new
2326  // attribute.
2327  if (OldAA->getPriority() < Priority)
2328  return nullptr;
2329 
2330  // If there is an existing attribute for this platform that has a higher
2331  // priority than the new attribute then erase the old one and continue
2332  // processing the attributes.
2333  if (OldAA->getPriority() > Priority) {
2334  Attrs.erase(Attrs.begin() + i);
2335  --e;
2336  continue;
2337  }
2338 
2339  FoundAny = true;
2340  VersionTuple OldIntroduced = OldAA->getIntroduced();
2341  VersionTuple OldDeprecated = OldAA->getDeprecated();
2342  VersionTuple OldObsoleted = OldAA->getObsoleted();
2343  bool OldIsUnavailable = OldAA->getUnavailable();
2344 
2345  if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl) ||
2346  !versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl) ||
2347  !versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl) ||
2348  !(OldIsUnavailable == IsUnavailable ||
2349  (OverrideOrImpl && !OldIsUnavailable && IsUnavailable))) {
2350  if (OverrideOrImpl) {
2351  int Which = -1;
2352  VersionTuple FirstVersion;
2353  VersionTuple SecondVersion;
2354  if (!versionsMatch(OldIntroduced, Introduced, OverrideOrImpl)) {
2355  Which = 0;
2356  FirstVersion = OldIntroduced;
2357  SecondVersion = Introduced;
2358  } else if (!versionsMatch(Deprecated, OldDeprecated, OverrideOrImpl)) {
2359  Which = 1;
2360  FirstVersion = Deprecated;
2361  SecondVersion = OldDeprecated;
2362  } else if (!versionsMatch(Obsoleted, OldObsoleted, OverrideOrImpl)) {
2363  Which = 2;
2364  FirstVersion = Obsoleted;
2365  SecondVersion = OldObsoleted;
2366  }
2367 
2368  if (Which == -1) {
2369  Diag(OldAA->getLocation(),
2370  diag::warn_mismatched_availability_override_unavail)
2371  << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2372  << (AMK == AMK_Override);
2373  } else {
2374  Diag(OldAA->getLocation(),
2375  diag::warn_mismatched_availability_override)
2376  << Which
2377  << AvailabilityAttr::getPrettyPlatformName(Platform->getName())
2378  << FirstVersion.getAsString() << SecondVersion.getAsString()
2379  << (AMK == AMK_Override);
2380  }
2381  if (AMK == AMK_Override)
2382  Diag(Range.getBegin(), diag::note_overridden_method);
2383  else
2384  Diag(Range.getBegin(), diag::note_protocol_method);
2385  } else {
2386  Diag(OldAA->getLocation(), diag::warn_mismatched_availability);
2387  Diag(Range.getBegin(), diag::note_previous_attribute);
2388  }
2389 
2390  Attrs.erase(Attrs.begin() + i);
2391  --e;
2392  continue;
2393  }
2394 
2395  VersionTuple MergedIntroduced2 = MergedIntroduced;
2396  VersionTuple MergedDeprecated2 = MergedDeprecated;
2397  VersionTuple MergedObsoleted2 = MergedObsoleted;
2398 
2399  if (MergedIntroduced2.empty())
2400  MergedIntroduced2 = OldIntroduced;
2401  if (MergedDeprecated2.empty())
2402  MergedDeprecated2 = OldDeprecated;
2403  if (MergedObsoleted2.empty())
2404  MergedObsoleted2 = OldObsoleted;
2405 
2406  if (checkAvailabilityAttr(*this, OldAA->getRange(), Platform,
2407  MergedIntroduced2, MergedDeprecated2,
2408  MergedObsoleted2)) {
2409  Attrs.erase(Attrs.begin() + i);
2410  --e;
2411  continue;
2412  }
2413 
2414  MergedIntroduced = MergedIntroduced2;
2415  MergedDeprecated = MergedDeprecated2;
2416  MergedObsoleted = MergedObsoleted2;
2417  ++i;
2418  }
2419  }
2420 
2421  if (FoundAny &&
2422  MergedIntroduced == Introduced &&
2423  MergedDeprecated == Deprecated &&
2424  MergedObsoleted == Obsoleted)
2425  return nullptr;
2426 
2427  // Only create a new attribute if !OverrideOrImpl, but we want to do
2428  // the checking.
2429  if (!checkAvailabilityAttr(*this, Range, Platform, MergedIntroduced,
2430  MergedDeprecated, MergedObsoleted) &&
2431  !OverrideOrImpl) {
2432  auto *Avail = ::new (Context)
2433  AvailabilityAttr(Range, Context, Platform, Introduced, Deprecated,
2434  Obsoleted, IsUnavailable, Message, IsStrict,
2435  Replacement, Priority, AttrSpellingListIndex);
2436  Avail->setImplicit(Implicit);
2437  return Avail;
2438  }
2439  return nullptr;
2440 }
2441 
2442 static void handleAvailabilityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2443  if (!checkAttributeNumArgs(S, AL, 1))
2444  return;
2445  IdentifierLoc *Platform = AL.getArgAsIdent(0);
2446  unsigned Index = AL.getAttributeSpellingListIndex();
2447 
2448  IdentifierInfo *II = Platform->Ident;
2449  if (AvailabilityAttr::getPrettyPlatformName(II->getName()).empty())
2450  S.Diag(Platform->Loc, diag::warn_availability_unknown_platform)
2451  << Platform->Ident;
2452 
2453  auto *ND = dyn_cast<NamedDecl>(D);
2454  if (!ND) // We warned about this already, so just return.
2455  return;
2456 
2460  bool IsUnavailable = AL.getUnavailableLoc().isValid();
2461  bool IsStrict = AL.getStrictLoc().isValid();
2462  StringRef Str;
2463  if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getMessageExpr()))
2464  Str = SE->getString();
2465  StringRef Replacement;
2466  if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getReplacementExpr()))
2467  Replacement = SE->getString();
2468 
2469  if (II->isStr("swift")) {
2470  if (Introduced.isValid() || Obsoleted.isValid() ||
2471  (!IsUnavailable && !Deprecated.isValid())) {
2472  S.Diag(AL.getLoc(),
2473  diag::warn_availability_swift_unavailable_deprecated_only);
2474  return;
2475  }
2476  }
2477 
2478  int PriorityModifier = AL.isPragmaClangAttribute()
2481  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2482  ND, AL.getRange(), II, false /*Implicit*/, Introduced.Version,
2483  Deprecated.Version, Obsoleted.Version, IsUnavailable, Str, IsStrict,
2484  Replacement, Sema::AMK_None, PriorityModifier, Index);
2485  if (NewAttr)
2486  D->addAttr(NewAttr);
2487 
2488  // Transcribe "ios" to "watchos" (and add a new attribute) if the versioning
2489  // matches before the start of the watchOS platform.
2490  if (S.Context.getTargetInfo().getTriple().isWatchOS()) {
2491  IdentifierInfo *NewII = nullptr;
2492  if (II->getName() == "ios")
2493  NewII = &S.Context.Idents.get("watchos");
2494  else if (II->getName() == "ios_app_extension")
2495  NewII = &S.Context.Idents.get("watchos_app_extension");
2496 
2497  if (NewII) {
2498  auto adjustWatchOSVersion = [](VersionTuple Version) -> VersionTuple {
2499  if (Version.empty())
2500  return Version;
2501  auto Major = Version.getMajor();
2502  auto NewMajor = Major >= 9 ? Major - 7 : 0;
2503  if (NewMajor >= 2) {
2504  if (Version.getMinor().hasValue()) {
2505  if (Version.getSubminor().hasValue())
2506  return VersionTuple(NewMajor, Version.getMinor().getValue(),
2507  Version.getSubminor().getValue());
2508  else
2509  return VersionTuple(NewMajor, Version.getMinor().getValue());
2510  }
2511  return VersionTuple(NewMajor);
2512  }
2513 
2514  return VersionTuple(2, 0);
2515  };
2516 
2517  auto NewIntroduced = adjustWatchOSVersion(Introduced.Version);
2518  auto NewDeprecated = adjustWatchOSVersion(Deprecated.Version);
2519  auto NewObsoleted = adjustWatchOSVersion(Obsoleted.Version);
2520 
2521  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2522  ND, AL.getRange(), NewII, true /*Implicit*/, NewIntroduced,
2523  NewDeprecated, NewObsoleted, IsUnavailable, Str, IsStrict,
2524  Replacement, Sema::AMK_None,
2525  PriorityModifier + Sema::AP_InferredFromOtherPlatform, Index);
2526  if (NewAttr)
2527  D->addAttr(NewAttr);
2528  }
2529  } else if (S.Context.getTargetInfo().getTriple().isTvOS()) {
2530  // Transcribe "ios" to "tvos" (and add a new attribute) if the versioning
2531  // matches before the start of the tvOS platform.
2532  IdentifierInfo *NewII = nullptr;
2533  if (II->getName() == "ios")
2534  NewII = &S.Context.Idents.get("tvos");
2535  else if (II->getName() == "ios_app_extension")
2536  NewII = &S.Context.Idents.get("tvos_app_extension");
2537 
2538  if (NewII) {
2539  AvailabilityAttr *NewAttr = S.mergeAvailabilityAttr(
2540  ND, AL.getRange(), NewII, true /*Implicit*/, Introduced.Version,
2541  Deprecated.Version, Obsoleted.Version, IsUnavailable, Str, IsStrict,
2542  Replacement, Sema::AMK_None,
2543  PriorityModifier + Sema::AP_InferredFromOtherPlatform, Index);
2544  if (NewAttr)
2545  D->addAttr(NewAttr);
2546  }
2547  }
2548 }
2549 
2550 static void handleExternalSourceSymbolAttr(Sema &S, Decl *D,
2551  const ParsedAttr &AL) {
2552  if (!checkAttributeAtLeastNumArgs(S, AL, 1))
2553  return;
2554  assert(checkAttributeAtMostNumArgs(S, AL, 3) &&
2555  "Invalid number of arguments in an external_source_symbol attribute");
2556 
2557  StringRef Language;
2558  if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(0)))
2559  Language = SE->getString();
2560  StringRef DefinedIn;
2561  if (const auto *SE = dyn_cast_or_null<StringLiteral>(AL.getArgAsExpr(1)))
2562  DefinedIn = SE->getString();
2563  bool IsGeneratedDeclaration = AL.getArgAsIdent(2) != nullptr;
2564 
2565  D->addAttr(::new (S.Context) ExternalSourceSymbolAttr(
2566  AL.getRange(), S.Context, Language, DefinedIn, IsGeneratedDeclaration,
2568 }
2569 
2570 template <class T>
2571 static T *mergeVisibilityAttr(Sema &S, Decl *D, SourceRange range,
2572  typename T::VisibilityType value,
2573  unsigned attrSpellingListIndex) {
2574  T *existingAttr = D->getAttr<T>();
2575  if (existingAttr) {
2576  typename T::VisibilityType existingValue = existingAttr->getVisibility();
2577  if (existingValue == value)
2578  return nullptr;
2579  S.Diag(existingAttr->getLocation(), diag::err_mismatched_visibility);
2580  S.Diag(range.getBegin(), diag::note_previous_attribute);
2581  D->dropAttr<T>();
2582  }
2583  return ::new (S.Context) T(range, S.Context, value, attrSpellingListIndex);
2584 }
2585 
2586 VisibilityAttr *Sema::mergeVisibilityAttr(Decl *D, SourceRange Range,
2587  VisibilityAttr::VisibilityType Vis,
2588  unsigned AttrSpellingListIndex) {
2589  return ::mergeVisibilityAttr<VisibilityAttr>(*this, D, Range, Vis,
2590  AttrSpellingListIndex);
2591 }
2592 
2593 TypeVisibilityAttr *Sema::mergeTypeVisibilityAttr(Decl *D, SourceRange Range,
2594  TypeVisibilityAttr::VisibilityType Vis,
2595  unsigned AttrSpellingListIndex) {
2596  return ::mergeVisibilityAttr<TypeVisibilityAttr>(*this, D, Range, Vis,
2597  AttrSpellingListIndex);
2598 }
2599 
2600 static void handleVisibilityAttr(Sema &S, Decl *D, const ParsedAttr &AL,
2601  bool isTypeVisibility) {
2602  // Visibility attributes don't mean anything on a typedef.
2603  if (isa<TypedefNameDecl>(D)) {
2604  S.Diag(AL.getRange().getBegin(), diag::warn_attribute_ignored) << AL;
2605  return;
2606  }
2607 
2608  // 'type_visibility' can only go on a type or namespace.
2609  if (isTypeVisibility &&
2610  !(isa<TagDecl>(D) ||
2611  isa<ObjCInterfaceDecl>(D) ||
2612  isa<NamespaceDecl>(D))) {
2613  S.Diag(AL.getRange().getBegin(), diag::err_attribute_wrong_decl_type)
2614  << AL << ExpectedTypeOrNamespace;
2615  return;
2616  }
2617 
2618  // Check that the argument is a string literal.
2619  StringRef TypeStr;
2620  SourceLocation LiteralLoc;
2621  if (!S.checkStringLiteralArgumentAttr(AL, 0, TypeStr, &LiteralLoc))
2622  return;
2623 
2624  VisibilityAttr::VisibilityType type;
2625  if (!VisibilityAttr::ConvertStrToVisibilityType(TypeStr, type)) {
2626  S.Diag(LiteralLoc, diag::warn_attribute_type_not_supported) << AL
2627  << TypeStr;
2628  return;
2629  }
2630 
2631  // Complain about attempts to use protected visibility on targets
2632  // (like Darwin) that don't support it.
2633  if (type == VisibilityAttr::Protected &&
2635  S.Diag(AL.getLoc(), diag::warn_attribute_protected_visibility);
2636  type = VisibilityAttr::Default;
2637  }
2638 
2639  unsigned Index = AL.getAttributeSpellingListIndex();
2640  Attr *newAttr;
2641  if (isTypeVisibility) {
2642  newAttr = S.mergeTypeVisibilityAttr(D, AL.getRange(),
2643  (TypeVisibilityAttr::VisibilityType) type,
2644  Index);
2645  } else {
2646  newAttr = S.mergeVisibilityAttr(D, AL.getRange(), type, Index);
2647  }
2648  if (newAttr)
2649  D->addAttr(newAttr);
2650 }
2651 
2652 static void handleObjCMethodFamilyAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2653  const auto *M = cast<ObjCMethodDecl>(D);
2654  if (!AL.isArgIdent(0)) {
2655  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2656  << AL << 1 << AANT_ArgumentIdentifier;
2657  return;
2658  }
2659 
2660  IdentifierLoc *IL = AL.getArgAsIdent(0);
2661  ObjCMethodFamilyAttr::FamilyKind F;
2662  if (!ObjCMethodFamilyAttr::ConvertStrToFamilyKind(IL->Ident->getName(), F)) {
2663  S.Diag(IL->Loc, diag::warn_attribute_type_not_supported) << AL << IL->Ident;
2664  return;
2665  }
2666 
2667  if (F == ObjCMethodFamilyAttr::OMF_init &&
2668  !M->getReturnType()->isObjCObjectPointerType()) {
2669  S.Diag(M->getLocation(), diag::err_init_method_bad_return_type)
2670  << M->getReturnType();
2671  // Ignore the attribute.
2672  return;
2673  }
2674 
2675  D->addAttr(new (S.Context) ObjCMethodFamilyAttr(
2676  AL.getRange(), S.Context, F, AL.getAttributeSpellingListIndex()));
2677 }
2678 
2679 static void handleObjCNSObject(Sema &S, Decl *D, const ParsedAttr &AL) {
2680  if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2681  QualType T = TD->getUnderlyingType();
2682  if (!T->isCARCBridgableType()) {
2683  S.Diag(TD->getLocation(), diag::err_nsobject_attribute);
2684  return;
2685  }
2686  }
2687  else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
2688  QualType T = PD->getType();
2689  if (!T->isCARCBridgableType()) {
2690  S.Diag(PD->getLocation(), diag::err_nsobject_attribute);
2691  return;
2692  }
2693  }
2694  else {
2695  // It is okay to include this attribute on properties, e.g.:
2696  //
2697  // @property (retain, nonatomic) struct Bork *Q __attribute__((NSObject));
2698  //
2699  // In this case it follows tradition and suppresses an error in the above
2700  // case.
2701  S.Diag(D->getLocation(), diag::warn_nsobject_attribute);
2702  }
2703  D->addAttr(::new (S.Context)
2704  ObjCNSObjectAttr(AL.getRange(), S.Context,
2706 }
2707 
2708 static void handleObjCIndependentClass(Sema &S, Decl *D, const ParsedAttr &AL) {
2709  if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
2710  QualType T = TD->getUnderlyingType();
2711  if (!T->isObjCObjectPointerType()) {
2712  S.Diag(TD->getLocation(), diag::warn_ptr_independentclass_attribute);
2713  return;
2714  }
2715  } else {
2716  S.Diag(D->getLocation(), diag::warn_independentclass_attribute);
2717  return;
2718  }
2719  D->addAttr(::new (S.Context)
2720  ObjCIndependentClassAttr(AL.getRange(), S.Context,
2722 }
2723 
2724 static void handleBlocksAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2725  if (!AL.isArgIdent(0)) {
2726  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2727  << AL << 1 << AANT_ArgumentIdentifier;
2728  return;
2729  }
2730 
2731  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
2732  BlocksAttr::BlockType type;
2733  if (!BlocksAttr::ConvertStrToBlockType(II->getName(), type)) {
2734  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
2735  return;
2736  }
2737 
2738  D->addAttr(::new (S.Context)
2739  BlocksAttr(AL.getRange(), S.Context, type,
2741 }
2742 
2743 static void handleSentinelAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2744  unsigned sentinel = (unsigned)SentinelAttr::DefaultSentinel;
2745  if (AL.getNumArgs() > 0) {
2746  Expr *E = AL.getArgAsExpr(0);
2747  llvm::APSInt Idx(32);
2748  if (E->isTypeDependent() || E->isValueDependent() ||
2749  !E->isIntegerConstantExpr(Idx, S.Context)) {
2750  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2751  << AL << 1 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2752  return;
2753  }
2754 
2755  if (Idx.isSigned() && Idx.isNegative()) {
2756  S.Diag(AL.getLoc(), diag::err_attribute_sentinel_less_than_zero)
2757  << E->getSourceRange();
2758  return;
2759  }
2760 
2761  sentinel = Idx.getZExtValue();
2762  }
2763 
2764  unsigned nullPos = (unsigned)SentinelAttr::DefaultNullPos;
2765  if (AL.getNumArgs() > 1) {
2766  Expr *E = AL.getArgAsExpr(1);
2767  llvm::APSInt Idx(32);
2768  if (E->isTypeDependent() || E->isValueDependent() ||
2769  !E->isIntegerConstantExpr(Idx, S.Context)) {
2770  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
2771  << AL << 2 << AANT_ArgumentIntegerConstant << E->getSourceRange();
2772  return;
2773  }
2774  nullPos = Idx.getZExtValue();
2775 
2776  if ((Idx.isSigned() && Idx.isNegative()) || nullPos > 1) {
2777  // FIXME: This error message could be improved, it would be nice
2778  // to say what the bounds actually are.
2779  S.Diag(AL.getLoc(), diag::err_attribute_sentinel_not_zero_or_one)
2780  << E->getSourceRange();
2781  return;
2782  }
2783  }
2784 
2785  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2786  const FunctionType *FT = FD->getType()->castAs<FunctionType>();
2787  if (isa<FunctionNoProtoType>(FT)) {
2788  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_named_arguments);
2789  return;
2790  }
2791 
2792  if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2793  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2794  return;
2795  }
2796  } else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
2797  if (!MD->isVariadic()) {
2798  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 0;
2799  return;
2800  }
2801  } else if (const auto *BD = dyn_cast<BlockDecl>(D)) {
2802  if (!BD->isVariadic()) {
2803  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << 1;
2804  return;
2805  }
2806  } else if (const auto *V = dyn_cast<VarDecl>(D)) {
2807  QualType Ty = V->getType();
2808  if (Ty->isBlockPointerType() || Ty->isFunctionPointerType()) {
2809  const FunctionType *FT = Ty->isFunctionPointerType()
2810  ? D->getFunctionType()
2811  : Ty->getAs<BlockPointerType>()->getPointeeType()->getAs<FunctionType>();
2812  if (!cast<FunctionProtoType>(FT)->isVariadic()) {
2813  int m = Ty->isFunctionPointerType() ? 0 : 1;
2814  S.Diag(AL.getLoc(), diag::warn_attribute_sentinel_not_variadic) << m;
2815  return;
2816  }
2817  } else {
2818  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2820  return;
2821  }
2822  } else {
2823  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2825  return;
2826  }
2827  D->addAttr(::new (S.Context)
2828  SentinelAttr(AL.getRange(), S.Context, sentinel, nullPos,
2830 }
2831 
2832 static void handleWarnUnusedResult(Sema &S, Decl *D, const ParsedAttr &AL) {
2833  if (D->getFunctionType() &&
2835  S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 0;
2836  return;
2837  }
2838  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D))
2839  if (MD->getReturnType()->isVoidType()) {
2840  S.Diag(AL.getLoc(), diag::warn_attribute_void_function_method) << AL << 1;
2841  return;
2842  }
2843 
2844  StringRef Str;
2845  if ((AL.isCXX11Attribute() || AL.isC2xAttribute()) && !AL.getScopeName()) {
2846  // If this is spelled as the standard C++17 attribute, but not in C++17,
2847  // warn about using it as an extension. If there are attribute arguments,
2848  // then claim it's a C++2a extension instead.
2849  // FIXME: If WG14 does not seem likely to adopt the same feature, add an
2850  // extension warning for C2x mode.
2851  const LangOptions &LO = S.getLangOpts();
2852  if (AL.getNumArgs() == 1) {
2853  if (LO.CPlusPlus && !LO.CPlusPlus2a)
2854  S.Diag(AL.getLoc(), diag::ext_cxx2a_attr) << AL;
2855 
2856  // Since this this is spelled [[nodiscard]], get the optional string
2857  // literal. If in C++ mode, but not in C++2a mode, diagnose as an
2858  // extension.
2859  // FIXME: C2x should support this feature as well, even as an extension.
2860  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, nullptr))
2861  return;
2862  } else if (LO.CPlusPlus && !LO.CPlusPlus17)
2863  S.Diag(AL.getLoc(), diag::ext_cxx17_attr) << AL;
2864  }
2865 
2866  D->addAttr(::new (S.Context)
2867  WarnUnusedResultAttr(AL.getRange(), S.Context, Str,
2869 }
2870 
2871 static void handleWeakImportAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
2872  // weak_import only applies to variable & function declarations.
2873  bool isDef = false;
2874  if (!D->canBeWeakImported(isDef)) {
2875  if (isDef)
2876  S.Diag(AL.getLoc(), diag::warn_attribute_invalid_on_definition)
2877  << "weak_import";
2878  else if (isa<ObjCPropertyDecl>(D) || isa<ObjCMethodDecl>(D) ||
2879  (S.Context.getTargetInfo().getTriple().isOSDarwin() &&
2880  (isa<ObjCInterfaceDecl>(D) || isa<EnumDecl>(D)))) {
2881  // Nothing to warn about here.
2882  } else
2883  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
2884  << AL << ExpectedVariableOrFunction;
2885 
2886  return;
2887  }
2888 
2889  D->addAttr(::new (S.Context)
2890  WeakImportAttr(AL.getRange(), S.Context,
2892 }
2893 
2894 // Handles reqd_work_group_size and work_group_size_hint.
2895 template <typename WorkGroupAttr>
2896 static void handleWorkGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2897  uint32_t WGSize[3];
2898  for (unsigned i = 0; i < 3; ++i) {
2899  const Expr *E = AL.getArgAsExpr(i);
2900  if (!checkUInt32Argument(S, AL, E, WGSize[i], i,
2901  /*StrictlyUnsigned=*/true))
2902  return;
2903  if (WGSize[i] == 0) {
2904  S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2905  << AL << E->getSourceRange();
2906  return;
2907  }
2908  }
2909 
2910  WorkGroupAttr *Existing = D->getAttr<WorkGroupAttr>();
2911  if (Existing && !(Existing->getXDim() == WGSize[0] &&
2912  Existing->getYDim() == WGSize[1] &&
2913  Existing->getZDim() == WGSize[2]))
2914  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2915 
2916  D->addAttr(::new (S.Context) WorkGroupAttr(AL.getRange(), S.Context,
2917  WGSize[0], WGSize[1], WGSize[2],
2919 }
2920 
2921 // Handles intel_reqd_sub_group_size.
2922 static void handleSubGroupSize(Sema &S, Decl *D, const ParsedAttr &AL) {
2923  uint32_t SGSize;
2924  const Expr *E = AL.getArgAsExpr(0);
2925  if (!checkUInt32Argument(S, AL, E, SGSize))
2926  return;
2927  if (SGSize == 0) {
2928  S.Diag(AL.getLoc(), diag::err_attribute_argument_is_zero)
2929  << AL << E->getSourceRange();
2930  return;
2931  }
2932 
2933  OpenCLIntelReqdSubGroupSizeAttr *Existing =
2934  D->getAttr<OpenCLIntelReqdSubGroupSizeAttr>();
2935  if (Existing && Existing->getSubGroupSize() != SGSize)
2936  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2937 
2938  D->addAttr(::new (S.Context) OpenCLIntelReqdSubGroupSizeAttr(
2939  AL.getRange(), S.Context, SGSize,
2941 }
2942 
2943 static void handleVecTypeHint(Sema &S, Decl *D, const ParsedAttr &AL) {
2944  if (!AL.hasParsedType()) {
2945  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
2946  return;
2947  }
2948 
2949  TypeSourceInfo *ParmTSI = nullptr;
2950  QualType ParmType = S.GetTypeFromParser(AL.getTypeArg(), &ParmTSI);
2951  assert(ParmTSI && "no type source info for attribute argument");
2952 
2953  if (!ParmType->isExtVectorType() && !ParmType->isFloatingType() &&
2954  (ParmType->isBooleanType() ||
2955  !ParmType->isIntegralType(S.getASTContext()))) {
2956  S.Diag(AL.getLoc(), diag::err_attribute_argument_vec_type_hint)
2957  << ParmType;
2958  return;
2959  }
2960 
2961  if (VecTypeHintAttr *A = D->getAttr<VecTypeHintAttr>()) {
2962  if (!S.Context.hasSameType(A->getTypeHint(), ParmType)) {
2963  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
2964  return;
2965  }
2966  }
2967 
2968  D->addAttr(::new (S.Context) VecTypeHintAttr(AL.getLoc(), S.Context,
2969  ParmTSI,
2971 }
2972 
2973 SectionAttr *Sema::mergeSectionAttr(Decl *D, SourceRange Range,
2974  StringRef Name,
2975  unsigned AttrSpellingListIndex) {
2976  // Explicit or partial specializations do not inherit
2977  // the section attribute from the primary template.
2978  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2979  if (AttrSpellingListIndex == SectionAttr::Declspec_allocate &&
2981  return nullptr;
2982  }
2983  if (SectionAttr *ExistingAttr = D->getAttr<SectionAttr>()) {
2984  if (ExistingAttr->getName() == Name)
2985  return nullptr;
2986  Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
2987  << 1 /*section*/;
2988  Diag(Range.getBegin(), diag::note_previous_attribute);
2989  return nullptr;
2990  }
2991  return ::new (Context) SectionAttr(Range, Context, Name,
2992  AttrSpellingListIndex);
2993 }
2994 
2995 bool Sema::checkSectionName(SourceLocation LiteralLoc, StringRef SecName) {
2996  std::string Error = Context.getTargetInfo().isValidSectionSpecifier(SecName);
2997  if (!Error.empty()) {
2998  Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target) << Error
2999  << 1 /*'section'*/;
3000  return false;
3001  }
3002  return true;
3003 }
3004 
3005 static void handleSectionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3006  // Make sure that there is a string literal as the sections's single
3007  // argument.
3008  StringRef Str;
3009  SourceLocation LiteralLoc;
3010  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3011  return;
3012 
3013  if (!S.checkSectionName(LiteralLoc, Str))
3014  return;
3015 
3016  // If the target wants to validate the section specifier, make it happen.
3017  std::string Error = S.Context.getTargetInfo().isValidSectionSpecifier(Str);
3018  if (!Error.empty()) {
3019  S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3020  << Error;
3021  return;
3022  }
3023 
3024  unsigned Index = AL.getAttributeSpellingListIndex();
3025  SectionAttr *NewAttr = S.mergeSectionAttr(D, AL.getRange(), Str, Index);
3026  if (NewAttr)
3027  D->addAttr(NewAttr);
3028 }
3029 
3030 // This is used for `__declspec(code_seg("segname"))` on a decl.
3031 // `#pragma code_seg("segname")` uses checkSectionName() instead.
3032 static bool checkCodeSegName(Sema &S, SourceLocation LiteralLoc,
3033  StringRef CodeSegName) {
3034  std::string Error =
3036  if (!Error.empty()) {
3037  S.Diag(LiteralLoc, diag::err_attribute_section_invalid_for_target)
3038  << Error << 0 /*'code-seg'*/;
3039  return false;
3040  }
3041 
3042  return true;
3043 }
3044 
3045 CodeSegAttr *Sema::mergeCodeSegAttr(Decl *D, SourceRange Range,
3046  StringRef Name,
3047  unsigned AttrSpellingListIndex) {
3048  // Explicit or partial specializations do not inherit
3049  // the code_seg attribute from the primary template.
3050  if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
3052  return nullptr;
3053  }
3054  if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3055  if (ExistingAttr->getName() == Name)
3056  return nullptr;
3057  Diag(ExistingAttr->getLocation(), diag::warn_mismatched_section)
3058  << 0 /*codeseg*/;
3059  Diag(Range.getBegin(), diag::note_previous_attribute);
3060  return nullptr;
3061  }
3062  return ::new (Context) CodeSegAttr(Range, Context, Name,
3063  AttrSpellingListIndex);
3064 }
3065 
3066 static void handleCodeSegAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3067  StringRef Str;
3068  SourceLocation LiteralLoc;
3069  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc))
3070  return;
3071  if (!checkCodeSegName(S, LiteralLoc, Str))
3072  return;
3073  if (const auto *ExistingAttr = D->getAttr<CodeSegAttr>()) {
3074  if (!ExistingAttr->isImplicit()) {
3075  S.Diag(AL.getLoc(),
3076  ExistingAttr->getName() == Str
3077  ? diag::warn_duplicate_codeseg_attribute
3078  : diag::err_conflicting_codeseg_attribute);
3079  return;
3080  }
3081  D->dropAttr<CodeSegAttr>();
3082  }
3083  if (CodeSegAttr *CSA = S.mergeCodeSegAttr(D, AL.getRange(), Str,
3085  D->addAttr(CSA);
3086 }
3087 
3088 // Check for things we'd like to warn about. Multiversioning issues are
3089 // handled later in the process, once we know how many exist.
3090 bool Sema::checkTargetAttr(SourceLocation LiteralLoc, StringRef AttrStr) {
3091  enum FirstParam { Unsupported, Duplicate };
3092  enum SecondParam { None, Architecture };
3093  for (auto Str : {"tune=", "fpmath="})
3094  if (AttrStr.find(Str) != StringRef::npos)
3095  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3096  << Unsupported << None << Str;
3097 
3098  TargetAttr::ParsedTargetAttr ParsedAttrs = TargetAttr::parse(AttrStr);
3099 
3100  if (!ParsedAttrs.Architecture.empty() &&
3101  !Context.getTargetInfo().isValidCPUName(ParsedAttrs.Architecture))
3102  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3103  << Unsupported << Architecture << ParsedAttrs.Architecture;
3104 
3105  if (ParsedAttrs.DuplicateArchitecture)
3106  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3107  << Duplicate << None << "arch=";
3108 
3109  for (const auto &Feature : ParsedAttrs.Features) {
3110  auto CurFeature = StringRef(Feature).drop_front(); // remove + or -.
3111  if (!Context.getTargetInfo().isValidFeatureName(CurFeature))
3112  return Diag(LiteralLoc, diag::warn_unsupported_target_attribute)
3113  << Unsupported << None << CurFeature;
3114  }
3115 
3116  return false;
3117 }
3118 
3119 static void handleTargetAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3120  StringRef Str;
3121  SourceLocation LiteralLoc;
3122  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str, &LiteralLoc) ||
3123  S.checkTargetAttr(LiteralLoc, Str))
3124  return;
3125 
3126  unsigned Index = AL.getAttributeSpellingListIndex();
3127  TargetAttr *NewAttr =
3128  ::new (S.Context) TargetAttr(AL.getRange(), S.Context, Str, Index);
3129  D->addAttr(NewAttr);
3130 }
3131 
3132 static void handleMinVectorWidthAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3133  Expr *E = AL.getArgAsExpr(0);
3134  uint32_t VecWidth;
3135  if (!checkUInt32Argument(S, AL, E, VecWidth)) {
3136  AL.setInvalid();
3137  return;
3138  }
3139 
3140  MinVectorWidthAttr *Existing = D->getAttr<MinVectorWidthAttr>();
3141  if (Existing && Existing->getVectorWidth() != VecWidth) {
3142  S.Diag(AL.getLoc(), diag::warn_duplicate_attribute) << AL;
3143  return;
3144  }
3145 
3146  D->addAttr(::new (S.Context)
3147  MinVectorWidthAttr(AL.getRange(), S.Context, VecWidth,
3149 }
3150 
3151 static void handleCleanupAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3152  Expr *E = AL.getArgAsExpr(0);
3153  SourceLocation Loc = E->getExprLoc();
3154  FunctionDecl *FD = nullptr;
3156 
3157  // gcc only allows for simple identifiers. Since we support more than gcc, we
3158  // will warn the user.
3159  if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
3160  if (DRE->hasQualifier())
3161  S.Diag(Loc, diag::warn_cleanup_ext);
3162  FD = dyn_cast<FunctionDecl>(DRE->getDecl());
3163  NI = DRE->getNameInfo();
3164  if (!FD) {
3165  S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 1
3166  << NI.getName();
3167  return;
3168  }
3169  } else if (auto *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
3170  if (ULE->hasExplicitTemplateArgs())
3171  S.Diag(Loc, diag::warn_cleanup_ext);
3173  NI = ULE->getNameInfo();
3174  if (!FD) {
3175  S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 2
3176  << NI.getName();
3177  if (ULE->getType() == S.Context.OverloadTy)
3179  return;
3180  }
3181  } else {
3182  S.Diag(Loc, diag::err_attribute_cleanup_arg_not_function) << 0;
3183  return;
3184  }
3185 
3186  if (FD->getNumParams() != 1) {
3187  S.Diag(Loc, diag::err_attribute_cleanup_func_must_take_one_arg)
3188  << NI.getName();
3189  return;
3190  }
3191 
3192  // We're currently more strict than GCC about what function types we accept.
3193  // If this ever proves to be a problem it should be easy to fix.
3194  QualType Ty = S.Context.getPointerType(cast<VarDecl>(D)->getType());
3195  QualType ParamTy = FD->getParamDecl(0)->getType();
3197  ParamTy, Ty) != Sema::Compatible) {
3198  S.Diag(Loc, diag::err_attribute_cleanup_func_arg_incompatible_type)
3199  << NI.getName() << ParamTy << Ty;
3200  return;
3201  }
3202 
3203  D->addAttr(::new (S.Context)
3204  CleanupAttr(AL.getRange(), S.Context, FD,
3206 }
3207 
3208 static void handleEnumExtensibilityAttr(Sema &S, Decl *D,
3209  const ParsedAttr &AL) {
3210  if (!AL.isArgIdent(0)) {
3211  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3212  << AL << 0 << AANT_ArgumentIdentifier;
3213  return;
3214  }
3215 
3216  EnumExtensibilityAttr::Kind ExtensibilityKind;
3217  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3218  if (!EnumExtensibilityAttr::ConvertStrToKind(II->getName(),
3219  ExtensibilityKind)) {
3220  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported) << AL << II;
3221  return;
3222  }
3223 
3224  D->addAttr(::new (S.Context) EnumExtensibilityAttr(
3225  AL.getRange(), S.Context, ExtensibilityKind,
3227 }
3228 
3229 /// Handle __attribute__((format_arg((idx)))) attribute based on
3230 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3231 static void handleFormatArgAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3232  Expr *IdxExpr = AL.getArgAsExpr(0);
3233  ParamIdx Idx;
3234  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, IdxExpr, Idx))
3235  return;
3236 
3237  // Make sure the format string is really a string.
3239 
3240  bool NotNSStringTy = !isNSStringType(Ty, S.Context);
3241  if (NotNSStringTy &&
3242  !isCFStringType(Ty, S.Context) &&
3243  (!Ty->isPointerType() ||
3244  !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3245  S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3246  << "a string type" << IdxExpr->getSourceRange()
3248  return;
3249  }
3251  if (!isNSStringType(Ty, S.Context) &&
3252  !isCFStringType(Ty, S.Context) &&
3253  (!Ty->isPointerType() ||
3254  !Ty->getAs<PointerType>()->getPointeeType()->isCharType())) {
3255  S.Diag(AL.getLoc(), diag::err_format_attribute_result_not)
3256  << (NotNSStringTy ? "string type" : "NSString")
3257  << IdxExpr->getSourceRange() << getFunctionOrMethodParamRange(D, 0);
3258  return;
3259  }
3260 
3261  D->addAttr(::new (S.Context) FormatArgAttr(
3262  AL.getRange(), S.Context, Idx, AL.getAttributeSpellingListIndex()));
3263 }
3264 
3265 enum FormatAttrKind {
3266  CFStringFormat,
3267  NSStringFormat,
3268  StrftimeFormat,
3269  SupportedFormat,
3270  IgnoredFormat,
3271  InvalidFormat
3272 };
3273 
3274 /// getFormatAttrKind - Map from format attribute names to supported format
3275 /// types.
3276 static FormatAttrKind getFormatAttrKind(StringRef Format) {
3277  return llvm::StringSwitch<FormatAttrKind>(Format)
3278  // Check for formats that get handled specially.
3279  .Case("NSString", NSStringFormat)
3280  .Case("CFString", CFStringFormat)
3281  .Case("strftime", StrftimeFormat)
3282 
3283  // Otherwise, check for supported formats.
3284  .Cases("scanf", "printf", "printf0", "strfmon", SupportedFormat)
3285  .Cases("cmn_err", "vcmn_err", "zcmn_err", SupportedFormat)
3286  .Case("kprintf", SupportedFormat) // OpenBSD.
3287  .Case("freebsd_kprintf", SupportedFormat) // FreeBSD.
3288  .Case("os_trace", SupportedFormat)
3289  .Case("os_log", SupportedFormat)
3290 
3291  .Cases("gcc_diag", "gcc_cdiag", "gcc_cxxdiag", "gcc_tdiag", IgnoredFormat)
3292  .Default(InvalidFormat);
3293 }
3294 
3295 /// Handle __attribute__((init_priority(priority))) attributes based on
3296 /// http://gcc.gnu.org/onlinedocs/gcc/C_002b_002b-Attributes.html
3297 static void handleInitPriorityAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3298  if (!S.getLangOpts().CPlusPlus) {
3299  S.Diag(AL.getLoc(), diag::warn_attribute_ignored) << AL;
3300  return;
3301  }
3302 
3303  if (S.getCurFunctionOrMethodDecl()) {
3304  S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3305  AL.setInvalid();
3306  return;
3307  }
3308  QualType T = cast<VarDecl>(D)->getType();
3309  if (S.Context.getAsArrayType(T))
3310  T = S.Context.getBaseElementType(T);
3311  if (!T->getAs<RecordType>()) {
3312  S.Diag(AL.getLoc(), diag::err_init_priority_object_attr);
3313  AL.setInvalid();
3314  return;
3315  }
3316 
3317  Expr *E = AL.getArgAsExpr(0);
3318  uint32_t prioritynum;
3319  if (!checkUInt32Argument(S, AL, E, prioritynum)) {
3320  AL.setInvalid();
3321  return;
3322  }
3323 
3324  if (prioritynum < 101 || prioritynum > 65535) {
3325  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_range)
3326  << E->getSourceRange() << AL << 101 << 65535;
3327  AL.setInvalid();
3328  return;
3329  }
3330  D->addAttr(::new (S.Context)
3331  InitPriorityAttr(AL.getRange(), S.Context, prioritynum,
3333 }
3334 
3335 FormatAttr *Sema::mergeFormatAttr(Decl *D, SourceRange Range,
3336  IdentifierInfo *Format, int FormatIdx,
3337  int FirstArg,
3338  unsigned AttrSpellingListIndex) {
3339  // Check whether we already have an equivalent format attribute.
3340  for (auto *F : D->specific_attrs<FormatAttr>()) {
3341  if (F->getType() == Format &&
3342  F->getFormatIdx() == FormatIdx &&
3343  F->getFirstArg() == FirstArg) {
3344  // If we don't have a valid location for this attribute, adopt the
3345  // location.
3346  if (F->getLocation().isInvalid())
3347  F->setRange(Range);
3348  return nullptr;
3349  }
3350  }
3351 
3352  return ::new (Context) FormatAttr(Range, Context, Format, FormatIdx,
3353  FirstArg, AttrSpellingListIndex);
3354 }
3355 
3356 /// Handle __attribute__((format(type,idx,firstarg))) attributes based on
3357 /// http://gcc.gnu.org/onlinedocs/gcc/Function-Attributes.html
3358 static void handleFormatAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3359  if (!AL.isArgIdent(0)) {
3360  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
3361  << AL << 1 << AANT_ArgumentIdentifier;
3362  return;
3363  }
3364 
3365  // In C++ the implicit 'this' function parameter also counts, and they are
3366  // counted from one.
3367  bool HasImplicitThisParam = isInstanceMethod(D);
3368  unsigned NumArgs = getFunctionOrMethodNumParams(D) + HasImplicitThisParam;
3369 
3370  IdentifierInfo *II = AL.getArgAsIdent(0)->Ident;
3371  StringRef Format = II->getName();
3372 
3373  if (normalizeName(Format)) {
3374  // If we've modified the string name, we need a new identifier for it.
3375  II = &S.Context.Idents.get(Format);
3376  }
3377 
3378  // Check for supported formats.
3379  FormatAttrKind Kind = getFormatAttrKind(Format);
3380 
3381  if (Kind == IgnoredFormat)
3382  return;
3383 
3384  if (Kind == InvalidFormat) {
3385  S.Diag(AL.getLoc(), diag::warn_attribute_type_not_supported)
3386  << AL << II->getName();
3387  return;
3388  }
3389 
3390  // checks for the 2nd argument
3391  Expr *IdxExpr = AL.getArgAsExpr(1);
3392  uint32_t Idx;
3393  if (!checkUInt32Argument(S, AL, IdxExpr, Idx, 2))
3394  return;
3395 
3396  if (Idx < 1 || Idx > NumArgs) {
3397  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3398  << AL << 2 << IdxExpr->getSourceRange();
3399  return;
3400  }
3401 
3402  // FIXME: Do we need to bounds check?
3403  unsigned ArgIdx = Idx - 1;
3404 
3405  if (HasImplicitThisParam) {
3406  if (ArgIdx == 0) {
3407  S.Diag(AL.getLoc(),
3408  diag::err_format_attribute_implicit_this_format_string)
3409  << IdxExpr->getSourceRange();
3410  return;
3411  }
3412  ArgIdx--;
3413  }
3414 
3415  // make sure the format string is really a string
3416  QualType Ty = getFunctionOrMethodParamType(D, ArgIdx);
3417 
3418  if (Kind == CFStringFormat) {
3419  if (!isCFStringType(Ty, S.Context)) {
3420  S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3421  << "a CFString" << IdxExpr->getSourceRange()
3422  << getFunctionOrMethodParamRange(D, ArgIdx);
3423  return;
3424  }
3425  } else if (Kind == NSStringFormat) {
3426  // FIXME: do we need to check if the type is NSString*? What are the
3427  // semantics?
3428  if (!isNSStringType(Ty, S.Context)) {
3429  S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3430  << "an NSString" << IdxExpr->getSourceRange()
3431  << getFunctionOrMethodParamRange(D, ArgIdx);
3432  return;
3433  }
3434  } else if (!Ty->isPointerType() ||
3435  !Ty->getAs<PointerType>()->getPointeeType()->isCharType()) {
3436  S.Diag(AL.getLoc(), diag::err_format_attribute_not)
3437  << "a string type" << IdxExpr->getSourceRange()
3438  << getFunctionOrMethodParamRange(D, ArgIdx);
3439  return;
3440  }
3441 
3442  // check the 3rd argument
3443  Expr *FirstArgExpr = AL.getArgAsExpr(2);
3444  uint32_t FirstArg;
3445  if (!checkUInt32Argument(S, AL, FirstArgExpr, FirstArg, 3))
3446  return;
3447 
3448  // check if the function is variadic if the 3rd argument non-zero
3449  if (FirstArg != 0) {
3450  if (isFunctionOrMethodVariadic(D)) {
3451  ++NumArgs; // +1 for ...
3452  } else {
3453  S.Diag(D->getLocation(), diag::err_format_attribute_requires_variadic);
3454  return;
3455  }
3456  }
3457 
3458  // strftime requires FirstArg to be 0 because it doesn't read from any
3459  // variable the input is just the current time + the format string.
3460  if (Kind == StrftimeFormat) {
3461  if (FirstArg != 0) {
3462  S.Diag(AL.getLoc(), diag::err_format_strftime_third_parameter)
3463  << FirstArgExpr->getSourceRange();
3464  return;
3465  }
3466  // if 0 it disables parameter checking (to use with e.g. va_list)
3467  } else if (FirstArg != 0 && FirstArg != NumArgs) {
3468  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3469  << AL << 3 << FirstArgExpr->getSourceRange();
3470  return;
3471  }
3472 
3473  FormatAttr *NewAttr = S.mergeFormatAttr(D, AL.getRange(), II,
3474  Idx, FirstArg,
3476  if (NewAttr)
3477  D->addAttr(NewAttr);
3478 }
3479 
3480 /// Handle __attribute__((callback(CalleeIdx, PayloadIdx0, ...))) attributes.
3481 static void handleCallbackAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3482  // The index that identifies the callback callee is mandatory.
3483  if (AL.getNumArgs() == 0) {
3484  S.Diag(AL.getLoc(), diag::err_callback_attribute_no_callee)
3485  << AL.getRange();
3486  return;
3487  }
3488 
3489  bool HasImplicitThisParam = isInstanceMethod(D);
3490  int32_t NumArgs = getFunctionOrMethodNumParams(D);
3491 
3492  FunctionDecl *FD = D->getAsFunction();
3493  assert(FD && "Expected a function declaration!");
3494 
3495  llvm::StringMap<int> NameIdxMapping;
3496  NameIdxMapping["__"] = -1;
3497 
3498  NameIdxMapping["this"] = 0;
3499 
3500  int Idx = 1;
3501  for (const ParmVarDecl *PVD : FD->parameters())
3502  NameIdxMapping[PVD->getName()] = Idx++;
3503 
3504  auto UnknownName = NameIdxMapping.end();
3505 
3506  SmallVector<int, 8> EncodingIndices;
3507  for (unsigned I = 0, E = AL.getNumArgs(); I < E; ++I) {
3508  SourceRange SR;
3509  int32_t ArgIdx;
3510 
3511  if (AL.isArgIdent(I)) {
3512  IdentifierLoc *IdLoc = AL.getArgAsIdent(I);
3513  auto It = NameIdxMapping.find(IdLoc->Ident->getName());
3514  if (It == UnknownName) {
3515  S.Diag(AL.getLoc(), diag::err_callback_attribute_argument_unknown)
3516  << IdLoc->Ident << IdLoc->Loc;
3517  return;
3518  }
3519 
3520  SR = SourceRange(IdLoc->Loc);
3521  ArgIdx = It->second;
3522  } else if (AL.isArgExpr(I)) {
3523  Expr *IdxExpr = AL.getArgAsExpr(I);
3524 
3525  // If the expression is not parseable as an int32_t we have a problem.
3526  if (!checkUInt32Argument(S, AL, IdxExpr, (uint32_t &)ArgIdx, I + 1,
3527  false)) {
3528  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3529  << AL << (I + 1) << IdxExpr->getSourceRange();
3530  return;
3531  }
3532 
3533  // Check oob, excluding the special values, 0 and -1.
3534  if (ArgIdx < -1 || ArgIdx > NumArgs) {
3535  S.Diag(AL.getLoc(), diag::err_attribute_argument_out_of_bounds)
3536  << AL << (I + 1) << IdxExpr->getSourceRange();
3537  return;
3538  }
3539 
3540  SR = IdxExpr->getSourceRange();
3541  } else {
3542  llvm_unreachable("Unexpected ParsedAttr argument type!");
3543  }
3544 
3545  if (ArgIdx == 0 && !HasImplicitThisParam) {
3546  S.Diag(AL.getLoc(), diag::err_callback_implicit_this_not_available)
3547  << (I + 1) << SR;
3548  return;
3549  }
3550 
3551  // Adjust for the case we do not have an implicit "this" parameter. In this
3552  // case we decrease all positive values by 1 to get LLVM argument indices.
3553  if (!HasImplicitThisParam && ArgIdx > 0)
3554  ArgIdx -= 1;
3555 
3556  EncodingIndices.push_back(ArgIdx);
3557  }
3558 
3559  int CalleeIdx = EncodingIndices.front();
3560  // Check if the callee index is proper, thus not "this" and not "unknown".
3561  // This means the "CalleeIdx" has to be non-negative if "HasImplicitThisParam"
3562  // is false and positive if "HasImplicitThisParam" is true.
3563  if (CalleeIdx < (int)HasImplicitThisParam) {
3564  S.Diag(AL.getLoc(), diag::err_callback_attribute_invalid_callee)
3565  << AL.getRange();
3566  return;
3567  }
3568 
3569  // Get the callee type, note the index adjustment as the AST doesn't contain
3570  // the this type (which the callee cannot reference anyway!).
3571  const Type *CalleeType =
3572  getFunctionOrMethodParamType(D, CalleeIdx - HasImplicitThisParam)
3573  .getTypePtr();
3574  if (!CalleeType || !CalleeType->isFunctionPointerType()) {
3575  S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3576  << AL.getRange();
3577  return;
3578  }
3579 
3580  const Type *CalleeFnType =
3582 
3583  // TODO: Check the type of the callee arguments.
3584 
3585  const auto *CalleeFnProtoType = dyn_cast<FunctionProtoType>(CalleeFnType);
3586  if (!CalleeFnProtoType) {
3587  S.Diag(AL.getLoc(), diag::err_callback_callee_no_function_type)
3588  << AL.getRange();
3589  return;
3590  }
3591 
3592  if (CalleeFnProtoType->getNumParams() > EncodingIndices.size() - 1) {
3593  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3594  << AL << (unsigned)(EncodingIndices.size() - 1);
3595  return;
3596  }
3597 
3598  if (CalleeFnProtoType->getNumParams() < EncodingIndices.size() - 1) {
3599  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments)
3600  << AL << (unsigned)(EncodingIndices.size() - 1);
3601  return;
3602  }
3603 
3604  if (CalleeFnProtoType->isVariadic()) {
3605  S.Diag(AL.getLoc(), diag::err_callback_callee_is_variadic) << AL.getRange();
3606  return;
3607  }
3608 
3609  // Do not allow multiple callback attributes.
3610  if (D->hasAttr<CallbackAttr>()) {
3611  S.Diag(AL.getLoc(), diag::err_callback_attribute_multiple) << AL.getRange();
3612  return;
3613  }
3614 
3615  D->addAttr(::new (S.Context) CallbackAttr(
3616  AL.getRange(), S.Context, EncodingIndices.data(), EncodingIndices.size(),
3618 }
3619 
3620 static void handleTransparentUnionAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3621  // Try to find the underlying union declaration.
3622  RecordDecl *RD = nullptr;
3623  const auto *TD = dyn_cast<TypedefNameDecl>(D);
3624  if (TD && TD->getUnderlyingType()->isUnionType())
3625  RD = TD->getUnderlyingType()->getAsUnionType()->getDecl();
3626  else
3627  RD = dyn_cast<RecordDecl>(D);
3628 
3629  if (!RD || !RD->isUnion()) {
3630  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type) << AL
3631  << ExpectedUnion;
3632  return;
3633  }
3634 
3635  if (!RD->isCompleteDefinition()) {
3636  if (!RD->isBeingDefined())
3637  S.Diag(AL.getLoc(),
3638  diag::warn_transparent_union_attribute_not_definition);
3639  return;
3640  }
3641 
3643  FieldEnd = RD->field_end();
3644  if (Field == FieldEnd) {
3645  S.Diag(AL.getLoc(), diag::warn_transparent_union_attribute_zero_fields);
3646  return;
3647  }
3648 
3649  FieldDecl *FirstField = *Field;
3650  QualType FirstType = FirstField->getType();
3651  if (FirstType->hasFloatingRepresentation() || FirstType->isVectorType()) {
3652  S.Diag(FirstField->getLocation(),
3653  diag::warn_transparent_union_attribute_floating)
3654  << FirstType->isVectorType() << FirstType;
3655  return;
3656  }
3657 
3658  if (FirstType->isIncompleteType())
3659  return;
3660  uint64_t FirstSize = S.Context.getTypeSize(FirstType);
3661  uint64_t FirstAlign = S.Context.getTypeAlign(FirstType);
3662  for (; Field != FieldEnd; ++Field) {
3663  QualType FieldType = Field->getType();
3664  if (FieldType->isIncompleteType())
3665  return;
3666  // FIXME: this isn't fully correct; we also need to test whether the
3667  // members of the union would all have the same calling convention as the
3668  // first member of the union. Checking just the size and alignment isn't
3669  // sufficient (consider structs passed on the stack instead of in registers
3670  // as an example).
3671  if (S.Context.getTypeSize(FieldType) != FirstSize ||
3672  S.Context.getTypeAlign(FieldType) > FirstAlign) {
3673  // Warn if we drop the attribute.
3674  bool isSize = S.Context.getTypeSize(FieldType) != FirstSize;
3675  unsigned FieldBits = isSize? S.Context.getTypeSize(FieldType)
3676  : S.Context.getTypeAlign(FieldType);
3677  S.Diag(Field->getLocation(),
3678  diag::warn_transparent_union_attribute_field_size_align)
3679  << isSize << Field->getDeclName() << FieldBits;
3680  unsigned FirstBits = isSize? FirstSize : FirstAlign;
3681  S.Diag(FirstField->getLocation(),
3682  diag::note_transparent_union_first_field_size_align)
3683  << isSize << FirstBits;
3684  return;
3685  }
3686  }
3687 
3688  RD->addAttr(::new (S.Context)
3689  TransparentUnionAttr(AL.getRange(), S.Context,
3691 }
3692 
3693 static void handleAnnotateAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3694  // Make sure that there is a string literal as the annotation's single
3695  // argument.
3696  StringRef Str;
3697  if (!S.checkStringLiteralArgumentAttr(AL, 0, Str))
3698  return;
3699 
3700  // Don't duplicate annotations that are already set.
3701  for (const auto *I : D->specific_attrs<AnnotateAttr>()) {
3702  if (I->getAnnotation() == Str)
3703  return;
3704  }
3705 
3706  D->addAttr(::new (S.Context)
3707  AnnotateAttr(AL.getRange(), S.Context, Str,
3709 }
3710 
3711 static void handleAlignValueAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3712  S.AddAlignValueAttr(AL.getRange(), D, AL.getArgAsExpr(0),
3714 }
3715 
3716 void Sema::AddAlignValueAttr(SourceRange AttrRange, Decl *D, Expr *E,
3717  unsigned SpellingListIndex) {
3718  AlignValueAttr TmpAttr(AttrRange, Context, E, SpellingListIndex);
3719  SourceLocation AttrLoc = AttrRange.getBegin();
3720 
3721  QualType T;
3722  if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
3723  T = TD->getUnderlyingType();
3724  else if (const auto *VD = dyn_cast<ValueDecl>(D))
3725  T = VD->getType();
3726  else
3727  llvm_unreachable("Unknown decl type for align_value");
3728 
3729  if (!T->isDependentType() && !T->isAnyPointerType() &&
3730  !T->isReferenceType() && !T->isMemberPointerType()) {
3731  Diag(AttrLoc, diag::warn_attribute_pointer_or_reference_only)
3732  << &TmpAttr /*TmpAttr.getName()*/ << T << D->getSourceRange();
3733  return;
3734  }
3735 
3736  if (!E->isValueDependent()) {
3737  llvm::APSInt Alignment;
3738  ExprResult ICE
3739  = VerifyIntegerConstantExpression(E, &Alignment,
3740  diag::err_align_value_attribute_argument_not_int,
3741  /*AllowFold*/ false);
3742  if (ICE.isInvalid())
3743  return;
3744 
3745  if (!Alignment.isPowerOf2()) {
3746  Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3747  << E->getSourceRange();
3748  return;
3749  }
3750 
3751  D->addAttr(::new (Context)
3752  AlignValueAttr(AttrRange, Context, ICE.get(),
3753  SpellingListIndex));
3754  return;
3755  }
3756 
3757  // Save dependent expressions in the AST to be instantiated.
3758  D->addAttr(::new (Context) AlignValueAttr(TmpAttr));
3759 }
3760 
3761 static void handleAlignedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
3762  // check the attribute arguments.
3763  if (AL.getNumArgs() > 1) {
3764  S.Diag(AL.getLoc(), diag::err_attribute_wrong_number_arguments) << AL << 1;
3765  return;
3766  }
3767 
3768  if (AL.getNumArgs() == 0) {
3769  D->addAttr(::new (S.Context) AlignedAttr(AL.getRange(), S.Context,
3770  true, nullptr, AL.getAttributeSpellingListIndex()));
3771  return;
3772  }
3773 
3774  Expr *E = AL.getArgAsExpr(0);
3776  S.Diag(AL.getEllipsisLoc(),
3777  diag::err_pack_expansion_without_parameter_packs);
3778  return;
3779  }
3780 
3782  return;
3783 
3785  AL.isPackExpansion());
3786 }
3787 
3788 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, Expr *E,
3789  unsigned SpellingListIndex, bool IsPackExpansion) {
3790  AlignedAttr TmpAttr(AttrRange, Context, true, E, SpellingListIndex);
3791  SourceLocation AttrLoc = AttrRange.getBegin();
3792 
3793  // C++11 alignas(...) and C11 _Alignas(...) have additional requirements.
3794  if (TmpAttr.isAlignas()) {
3795  // C++11 [dcl.align]p1:
3796  // An alignment-specifier may be applied to a variable or to a class
3797  // data member, but it shall not be applied to a bit-field, a function
3798  // parameter, the formal parameter of a catch clause, or a variable
3799  // declared with the register storage class specifier. An
3800  // alignment-specifier may also be applied to the declaration of a class
3801  // or enumeration type.
3802  // C11 6.7.5/2:
3803  // An alignment attribute shall not be specified in a declaration of
3804  // a typedef, or a bit-field, or a function, or a parameter, or an
3805  // object declared with the register storage-class specifier.
3806  int DiagKind = -1;
3807  if (isa<ParmVarDecl>(D)) {
3808  DiagKind = 0;
3809  } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
3810  if (VD->getStorageClass() == SC_Register)
3811  DiagKind = 1;
3812  if (VD->isExceptionVariable())
3813  DiagKind = 2;
3814  } else if (const auto *FD = dyn_cast<FieldDecl>(D)) {
3815  if (FD->isBitField())
3816  DiagKind = 3;
3817  } else if (!isa<TagDecl>(D)) {
3818  Diag(AttrLoc, diag::err_attribute_wrong_decl_type) << &TmpAttr
3819  << (TmpAttr.isC11() ? ExpectedVariableOrField
3821  return;
3822  }
3823  if (DiagKind != -1) {
3824  Diag(AttrLoc, diag::err_alignas_attribute_wrong_decl_type)
3825  << &TmpAttr << DiagKind;
3826  return;
3827  }
3828  }
3829 
3830  if (E->isValueDependent()) {
3831  // We can't support a dependent alignment on a non-dependent type,
3832  // because we have no way to model that a type is "alignment-dependent"
3833  // but not dependent in any other way.
3834  if (const auto *TND = dyn_cast<TypedefNameDecl>(D)) {
3835  if (!TND->getUnderlyingType()->isDependentType()) {
3836  Diag(AttrLoc, diag::err_alignment_dependent_typedef_name)
3837  << E->getSourceRange();
3838  return;
3839  }
3840  }
3841 
3842  // Save dependent expressions in the AST to be instantiated.
3843  AlignedAttr *AA = ::new (Context) AlignedAttr(TmpAttr);
3844  AA->setPackExpansion(IsPackExpansion);
3845  D->addAttr(AA);
3846  return;
3847  }
3848 
3849  // FIXME: Cache the number on the AL object?
3850  llvm::APSInt Alignment;
3851  ExprResult ICE
3852  = VerifyIntegerConstantExpression(E, &Alignment,
3853  diag::err_aligned_attribute_argument_not_int,
3854  /*AllowFold*/ false);
3855  if (ICE.isInvalid())
3856  return;
3857 
3858  uint64_t AlignVal = Alignment.getZExtValue();
3859 
3860  // C++11 [dcl.align]p2:
3861  // -- if the constant expression evaluates to zero, the alignment
3862  // specifier shall have no effect
3863  // C11 6.7.5p6:
3864  // An alignment specification of zero has no effect.
3865  if (!(TmpAttr.isAlignas() && !Alignment)) {
3866  if (!llvm::isPowerOf2_64(AlignVal)) {
3867  Diag(AttrLoc, diag::err_alignment_not_power_of_two)
3868  << E->getSourceRange();
3869  return;
3870  }
3871  }
3872 
3873  // Alignment calculations can wrap around if it's greater than 2**28.
3874  unsigned MaxValidAlignment =
3875  Context.getTargetInfo().getTriple().isOSBinFormatCOFF() ? 8192
3876  : 268435456;
3877  if (AlignVal > MaxValidAlignment) {
3878  Diag(AttrLoc, diag::err_attribute_aligned_too_great) << MaxValidAlignment
3879  << E->getSourceRange();
3880  return;
3881  }
3882 
3883  if (Context.getTargetInfo().isTLSSupported()) {
3884  unsigned MaxTLSAlign =
3885  Context.toCharUnitsFromBits(Context.getTargetInfo().getMaxTLSAlign())
3886  .getQuantity();
3887  const auto *VD = dyn_cast<VarDecl>(D);
3888  if (MaxTLSAlign && AlignVal > MaxTLSAlign && VD &&
3889  VD->getTLSKind() != VarDecl::TLS_None) {
3890  Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
3891  << (unsigned)AlignVal << VD << MaxTLSAlign;
3892  return;
3893  }
3894  }
3895 
3896  AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, true,
3897  ICE.get(), SpellingListIndex);
3898  AA->setPackExpansion(IsPackExpansion);
3899  D->addAttr(AA);
3900 }
3901 
3902 void Sema::AddAlignedAttr(SourceRange AttrRange, Decl *D, TypeSourceInfo *TS,
3903  unsigned SpellingListIndex, bool IsPackExpansion) {
3904  // FIXME: Cache the number on the AL object if non-dependent?
3905  // FIXME: Perform checking of type validity
3906  AlignedAttr *AA = ::new (Context) AlignedAttr(AttrRange, Context, false, TS,
3907  SpellingListIndex);
3908  AA->setPackExpansion(IsPackExpansion);
3909  D->addAttr(AA);
3910 }
3911 
3913  assert(D->hasAttrs() && "no attributes on decl");
3914 
3915  QualType UnderlyingTy, DiagTy;
3916  if (const auto *VD = dyn_cast<ValueDecl>(D)) {
3917  UnderlyingTy = DiagTy = VD->getType();
3918  } else {
3919  UnderlyingTy = DiagTy = Context.getTagDeclType(cast<TagDecl>(D));
3920  if (const auto *ED = dyn_cast<EnumDecl>(D))
3921  UnderlyingTy = ED->getIntegerType();
3922  }
3923  if (DiagTy->isDependentType() || DiagTy->isIncompleteType())
3924  return;
3925 
3926  // C++11 [dcl.align]p5, C11 6.7.5/4:
3927  // The combined effect of all alignment attributes in a declaration shall
3928  // not specify an alignment that is less strict than the alignment that
3929  // would otherwise be required for the entity being declared.
3930  AlignedAttr *AlignasAttr = nullptr;
3931  unsigned Align = 0;
3932  for (auto *I : D->specific_attrs<AlignedAttr>()) {
3933  if (I->isAlignmentDependent())
3934  return;
3935  if (I->isAlignas())
3936  AlignasAttr = I;
3937  Align = std::max(Align, I->getAlignment(Context));
3938  }
3939 
3940  if (AlignasAttr && Align) {
3941  CharUnits RequestedAlign = Context.toCharUnitsFromBits(Align);
3942  CharUnits NaturalAlign = Context.getTypeAlignInChars(UnderlyingTy);
3943  if (NaturalAlign > RequestedAlign)
3944  Diag(AlignasAttr->getLocation(), diag::err_alignas_underaligned)
3945  << DiagTy << (unsigned)NaturalAlign.getQuantity();
3946  }
3947 }
3948 
3950  CXXRecordDecl *RD, SourceRange Range, bool BestCase,
3951  MSInheritanceAttr::Spelling SemanticSpelling) {
3952  assert(RD->hasDefinition() && "RD has no definition!");
3953 
3954  // We may not have seen base specifiers or any virtual methods yet. We will
3955  // have to wait until the record is defined to catch any mismatches.
3956  if (!RD->getDefinition()->isCompleteDefinition())
3957  return false;
3958 
3959  // The unspecified model never matches what a definition could need.
3960  if (SemanticSpelling == MSInheritanceAttr::Keyword_unspecified_inheritance)
3961  return false;
3962 
3963  if (BestCase) {
3964  if (RD->calculateInheritanceModel() == SemanticSpelling)
3965  return false;
3966  } else {
3967  if (RD->calculateInheritanceModel() <= SemanticSpelling)
3968  return false;
3969  }
3970 
3971  Diag(Range.getBegin(), diag::err_mismatched_ms_inheritance)
3972  << 0 /*definition*/;
3973  Diag(RD->getDefinition()->getLocation(), diag::note_defined_here)
3974  << RD->getNameAsString();
3975  return true;
3976 }
3977 
3978 /// parseModeAttrArg - Parses attribute mode string and returns parsed type
3979 /// attribute.
3980 static void parseModeAttrArg(Sema &S, StringRef Str, unsigned &DestWidth,
3981  bool &IntegerMode, bool &ComplexMode) {
3982  IntegerMode = true;
3983  ComplexMode = false;
3984  switch (Str.size()) {
3985  case 2:
3986  switch (Str[0]) {
3987  case 'Q':
3988  DestWidth = 8;
3989  break;
3990  case 'H':
3991  DestWidth = 16;
3992  break;
3993  case 'S':
3994  DestWidth = 32;
3995  break;
3996  case 'D':
3997  DestWidth = 64;
3998  break;
3999  case 'X':
4000  DestWidth = 96;
4001  break;
4002  case 'T':
4003  DestWidth = 128;
4004  break;
4005  }
4006  if (Str[1] == 'F') {
4007  IntegerMode = false;
4008  } else if (Str[1] == 'C') {
4009  IntegerMode = false;
4010  ComplexMode = true;
4011  } else if (Str[1] != 'I') {
4012  DestWidth = 0;
4013  }
4014  break;
4015  case 4:
4016  // FIXME: glibc uses 'word' to define register_t; this is narrower than a
4017  // pointer on PIC16 and other embedded platforms.
4018  if (Str == "word")
4019  DestWidth = S.Context.getTargetInfo().getRegisterWidth();
4020  else if (Str == "byte")
4021  DestWidth = S.Context.getTargetInfo().getCharWidth();
4022  break;
4023  case 7:
4024  if (Str == "pointer")
4025  DestWidth = S.Context.getTargetInfo().getPointerWidth(0);
4026  break;
4027  case 11:
4028  if (Str == "unwind_word")
4029  DestWidth = S.Context.getTargetInfo().getUnwindWordWidth();
4030  break;
4031  }
4032 }
4033 
4034 /// handleModeAttr - This attribute modifies the width of a decl with primitive
4035 /// type.
4036 ///
4037 /// Despite what would be logical, the mode attribute is a decl attribute, not a
4038 /// type attribute: 'int ** __attribute((mode(HI))) *G;' tries to make 'G' be
4039 /// HImode, not an intermediate pointer.
4040 static void handleModeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4041  // This attribute isn't documented, but glibc uses it. It changes
4042  // the width of an int or unsigned int to the specified size.
4043  if (!AL.isArgIdent(0)) {
4044  S.Diag(AL.getLoc(), diag::err_attribute_argument_type)
4045  << AL << AANT_ArgumentIdentifier;
4046  return;
4047  }
4048 
4049  IdentifierInfo *Name = AL.getArgAsIdent(0)->Ident;
4050 
4051  S.AddModeAttr(AL.getRange(), D, Name, AL.getAttributeSpellingListIndex());
4052 }
4053 
4054 void Sema::AddModeAttr(SourceRange AttrRange, Decl *D, IdentifierInfo *Name,
4055  unsigned SpellingListIndex, bool InInstantiation) {
4056  StringRef Str = Name->getName();
4057  normalizeName(Str);
4058  SourceLocation AttrLoc = AttrRange.getBegin();
4059 
4060  unsigned DestWidth = 0;
4061  bool IntegerMode = true;
4062  bool ComplexMode = false;
4063  llvm::APInt VectorSize(64, 0);
4064  if (Str.size() >= 4 && Str[0] == 'V') {
4065  // Minimal length of vector mode is 4: 'V' + NUMBER(>=1) + TYPE(>=2).
4066  size_t StrSize = Str.size();
4067  size_t VectorStringLength = 0;
4068  while ((VectorStringLength + 1) < StrSize &&
4069  isdigit(Str[VectorStringLength + 1]))
4070  ++VectorStringLength;
4071  if (VectorStringLength &&
4072  !Str.substr(1, VectorStringLength).getAsInteger(10, VectorSize) &&
4073  VectorSize.isPowerOf2()) {
4074  parseModeAttrArg(*this, Str.substr(VectorStringLength + 1), DestWidth,
4075  IntegerMode, ComplexMode);
4076  // Avoid duplicate warning from template instantiation.
4077  if (!InInstantiation)
4078  Diag(AttrLoc, diag::warn_vector_mode_deprecated);
4079  } else {
4080  VectorSize = 0;
4081  }
4082  }
4083 
4084  if (!VectorSize)
4085  parseModeAttrArg(*this, Str, DestWidth, IntegerMode, ComplexMode);
4086 
4087  // FIXME: Sync this with InitializePredefinedMacros; we need to match int8_t
4088  // and friends, at least with glibc.
4089  // FIXME: Make sure floating-point mappings are accurate
4090  // FIXME: Support XF and TF types
4091  if (!DestWidth) {
4092  Diag(AttrLoc, diag::err_machine_mode) << 0 /*Unknown*/ << Name;
4093  return;
4094  }
4095 
4096  QualType OldTy;
4097  if (const auto *TD = dyn_cast<TypedefNameDecl>(D))
4098  OldTy = TD->getUnderlyingType();
4099  else if (const auto *ED = dyn_cast<EnumDecl>(D)) {
4100  // Something like 'typedef enum { X } __attribute__((mode(XX))) T;'.
4101  // Try to get type from enum declaration, default to int.
4102  OldTy = ED->getIntegerType();
4103  if (OldTy.isNull())
4104  OldTy = Context.IntTy;
4105  } else
4106  OldTy = cast<ValueDecl>(D)->getType();
4107 
4108  if (OldTy->isDependentType()) {
4109  D->addAttr(::new (Context)
4110  ModeAttr(AttrRange, Context, Name, SpellingListIndex));
4111  return;
4112  }
4113 
4114  // Base type can also be a vector type (see PR17453).
4115  // Distinguish between base type and base element type.
4116  QualType OldElemTy = OldTy;
4117  if (const auto *VT = OldTy->getAs<VectorType>())
4118  OldElemTy = VT->getElementType();
4119 
4120  // GCC allows 'mode' attribute on enumeration types (even incomplete), except
4121  // for vector modes. So, 'enum X __attribute__((mode(QI)));' forms a complete
4122  // type, 'enum { A } __attribute__((mode(V4SI)))' is rejected.
4123  if ((isa<EnumDecl>(D) || OldElemTy->getAs<EnumType>()) &&
4124  VectorSize.getBoolValue()) {
4125  Diag(AttrLoc, diag::err_enum_mode_vector_type) << Name << AttrRange;
4126  return;
4127  }
4128  bool IntegralOrAnyEnumType =
4129  OldElemTy->isIntegralOrEnumerationType() || OldElemTy->getAs<EnumType>();
4130 
4131  if (!OldElemTy->getAs<BuiltinType>() && !OldElemTy->isComplexType() &&
4132  !IntegralOrAnyEnumType)
4133  Diag(AttrLoc, diag::err_mode_not_primitive);
4134  else if (IntegerMode) {
4135  if (!IntegralOrAnyEnumType)
4136  Diag(AttrLoc, diag::err_mode_wrong_type);
4137  } else if (ComplexMode) {
4138  if (!OldElemTy->isComplexType())
4139  Diag(AttrLoc, diag::err_mode_wrong_type);
4140  } else {
4141  if (!OldElemTy->isFloatingType())
4142  Diag(AttrLoc, diag::err_mode_wrong_type);
4143  }
4144 
4145  QualType NewElemTy;
4146 
4147  if (IntegerMode)
4148  NewElemTy = Context.getIntTypeForBitwidth(DestWidth,
4149  OldElemTy->isSignedIntegerType());
4150  else
4151  NewElemTy = Context.getRealTypeForBitwidth(DestWidth);
4152 
4153  if (NewElemTy.isNull()) {
4154  Diag(AttrLoc, diag::err_machine_mode) << 1 /*Unsupported*/ << Name;
4155  return;
4156  }
4157 
4158  if (ComplexMode) {
4159  NewElemTy = Context.getComplexType(NewElemTy);
4160  }
4161 
4162  QualType NewTy = NewElemTy;
4163  if (VectorSize.getBoolValue()) {
4164  NewTy = Context.getVectorType(NewTy, VectorSize.getZExtValue(),
4166  } else if (const auto *OldVT = OldTy->getAs<VectorType>()) {
4167  // Complex machine mode does not support base vector types.
4168  if (ComplexMode) {
4169  Diag(AttrLoc, diag::err_complex_mode_vector_type);
4170  return;
4171  }
4172  unsigned NumElements = Context.getTypeSize(OldElemTy) *
4173  OldVT->getNumElements() /
4174  Context.getTypeSize(NewElemTy);
4175  NewTy =
4176  Context.getVectorType(NewElemTy, NumElements, OldVT->getVectorKind());
4177  }
4178 
4179  if (NewTy.isNull()) {
4180  Diag(AttrLoc, diag::err_mode_wrong_type);
4181  return;
4182  }
4183 
4184  // Install the new type.
4185  if (auto *TD = dyn_cast<TypedefNameDecl>(D))
4186  TD->setModedTypeSourceInfo(TD->getTypeSourceInfo(), NewTy);
4187  else if (auto *ED = dyn_cast<EnumDecl>(D))
4188  ED->setIntegerType(NewTy);
4189  else
4190  cast<ValueDecl>(D)->setType(NewTy);
4191 
4192  D->addAttr(::new (Context)
4193  ModeAttr(AttrRange, Context, Name, SpellingListIndex));
4194 }
4195 
4196 static void handleNoDebugAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4197  D->addAttr(::new (S.Context)
4198  NoDebugAttr(AL.getRange(), S.Context,
4200 }
4201 
4202 AlwaysInlineAttr *Sema::mergeAlwaysInlineAttr(Decl *D, SourceRange Range,
4203  IdentifierInfo *Ident,
4204  unsigned AttrSpellingListIndex) {
4205  if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4206  Diag(Range.getBegin(), diag::warn_attribute_ignored) << Ident;
4207  Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4208  return nullptr;
4209  }
4210 
4211  if (D->hasAttr<AlwaysInlineAttr>())
4212  return nullptr;
4213 
4214  return ::new (Context) AlwaysInlineAttr(Range, Context,
4215  AttrSpellingListIndex);
4216 }
4217 
4218 CommonAttr *Sema::mergeCommonAttr(Decl *D, const ParsedAttr &AL) {
4219  if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, AL))
4220  return nullptr;
4221 
4222  return ::new (Context)
4223  CommonAttr(AL.getRange(), Context, AL.getAttributeSpellingListIndex());
4224 }
4225 
4226 CommonAttr *Sema::mergeCommonAttr(Decl *D, const CommonAttr &AL) {
4227  if (checkAttrMutualExclusion<InternalLinkageAttr>(*this, D, AL))
4228  return nullptr;
4229 
4230  return ::new (Context)
4231  CommonAttr(AL.getRange(), Context, AL.getSpellingListIndex());
4232 }
4233 
4234 InternalLinkageAttr *Sema::mergeInternalLinkageAttr(Decl *D,
4235  const ParsedAttr &AL) {
4236  if (const auto *VD = dyn_cast<VarDecl>(D)) {
4237  // Attribute applies to Var but not any subclass of it (like ParmVar,
4238  // ImplicitParm or VarTemplateSpecialization).
4239  if (VD->getKind() != Decl::Var) {
4240  Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4241  << AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4243  return nullptr;
4244  }
4245  // Attribute does not apply to non-static local variables.
4246  if (VD->hasLocalStorage()) {
4247  Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4248  return nullptr;
4249  }
4250  }
4251 
4252  if (checkAttrMutualExclusion<CommonAttr>(*this, D, AL))
4253  return nullptr;
4254 
4255  return ::new (Context) InternalLinkageAttr(
4256  AL.getRange(), Context, AL.getAttributeSpellingListIndex());
4257 }
4258 InternalLinkageAttr *
4259 Sema::mergeInternalLinkageAttr(Decl *D, const InternalLinkageAttr &AL) {
4260  if (const auto *VD = dyn_cast<VarDecl>(D)) {
4261  // Attribute applies to Var but not any subclass of it (like ParmVar,
4262  // ImplicitParm or VarTemplateSpecialization).
4263  if (VD->getKind() != Decl::Var) {
4264  Diag(AL.getLocation(), diag::warn_attribute_wrong_decl_type)
4265  << &AL << (getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass
4267  return nullptr;
4268  }
4269  // Attribute does not apply to non-static local variables.
4270  if (VD->hasLocalStorage()) {
4271  Diag(VD->getLocation(), diag::warn_internal_linkage_local_storage);
4272  return nullptr;
4273  }
4274  }
4275 
4276  if (checkAttrMutualExclusion<CommonAttr>(*this, D, AL))
4277  return nullptr;
4278 
4279  return ::new (Context)
4280  InternalLinkageAttr(AL.getRange(), Context, AL.getSpellingListIndex());
4281 }
4282 
4283 MinSizeAttr *Sema::mergeMinSizeAttr(Decl *D, SourceRange Range,
4284  unsigned AttrSpellingListIndex) {
4285  if (OptimizeNoneAttr *Optnone = D->getAttr<OptimizeNoneAttr>()) {
4286  Diag(Range.getBegin(), diag::warn_attribute_ignored) << "'minsize'";
4287  Diag(Optnone->getLocation(), diag::note_conflicting_attribute);
4288  return nullptr;
4289  }
4290 
4291  if (D->hasAttr<MinSizeAttr>())
4292  return nullptr;
4293 
4294  return ::new (Context) MinSizeAttr(Range, Context, AttrSpellingListIndex);
4295 }
4296 
4297 NoSpeculativeLoadHardeningAttr *Sema::mergeNoSpeculativeLoadHardeningAttr(
4298  Decl *D, const NoSpeculativeLoadHardeningAttr &AL) {
4299  if (checkAttrMutualExclusion<SpeculativeLoadHardeningAttr>(*this, D, AL))
4300  return nullptr;
4301 
4302  return ::new (Context) NoSpeculativeLoadHardeningAttr(
4303  AL.getRange(), Context, AL.getSpellingListIndex());
4304 }
4305 
4306 OptimizeNoneAttr *Sema::mergeOptimizeNoneAttr(Decl *D, SourceRange Range,
4307  unsigned AttrSpellingListIndex) {
4308  if (AlwaysInlineAttr *Inline = D->getAttr<AlwaysInlineAttr>()) {
4309  Diag(Inline->getLocation(), diag::warn_attribute_ignored) << Inline;
4310  Diag(Range.getBegin(), diag::note_conflicting_attribute);
4311  D->dropAttr<AlwaysInlineAttr>();
4312  }
4313  if (MinSizeAttr *MinSize = D->getAttr<MinSizeAttr>()) {
4314  Diag(MinSize->getLocation(), diag::warn_attribute_ignored) << MinSize;
4315  Diag(Range.getBegin(), diag::note_conflicting_attribute);
4316  D->dropAttr<MinSizeAttr>();
4317  }
4318 
4319  if (D->hasAttr<OptimizeNoneAttr>())
4320  return nullptr;
4321 
4322  return ::new (Context) OptimizeNoneAttr(Range, Context,
4323  AttrSpellingListIndex);
4324 }
4325 
4326 SpeculativeLoadHardeningAttr *Sema::mergeSpeculativeLoadHardeningAttr(
4327  Decl *D, const SpeculativeLoadHardeningAttr &AL) {
4328  if (checkAttrMutualExclusion<NoSpeculativeLoadHardeningAttr>(*this, D, AL))
4329  return nullptr;
4330 
4331  return ::new (Context) SpeculativeLoadHardeningAttr(
4332  AL.getRange(), Context, AL.getSpellingListIndex());
4333 }
4334 
4335 static void handleAlwaysInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4336  if (checkAttrMutualExclusion<NotTailCalledAttr>(S, D, AL))
4337  return;
4338 
4339  if (AlwaysInlineAttr *Inline = S.mergeAlwaysInlineAttr(
4340  D, AL.getRange(), AL.getName(),
4342  D->addAttr(Inline);
4343 }
4344 
4345 static void handleMinSizeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4346  if (MinSizeAttr *MinSize = S.mergeMinSizeAttr(
4347  D, AL.getRange(), AL.getAttributeSpellingListIndex()))
4348  D->addAttr(MinSize);
4349 }
4350 
4351 static void handleOptimizeNoneAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4352  if (OptimizeNoneAttr *Optnone = S.mergeOptimizeNoneAttr(
4353  D, AL.getRange(), AL.getAttributeSpellingListIndex()))
4354  D->addAttr(Optnone);
4355 }
4356 
4357 static void handleConstantAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4358  if (checkAttrMutualExclusion<CUDASharedAttr>(S, D, AL))
4359  return;
4360  const auto *VD = cast<VarDecl>(D);
4361  if (!VD->hasGlobalStorage()) {
4362  S.Diag(AL.getLoc(), diag::err_cuda_nonglobal_constant);
4363  return;
4364  }
4365  D->addAttr(::new (S.Context) CUDAConstantAttr(
4367 }
4368 
4369 static void handleSharedAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4370  if (checkAttrMutualExclusion<CUDAConstantAttr>(S, D, AL))
4371  return;
4372  const auto *VD = cast<VarDecl>(D);
4373  // extern __shared__ is only allowed on arrays with no length (e.g.
4374  // "int x[]").
4375  if (!S.getLangOpts().GPURelocatableDeviceCode && VD->hasExternalStorage() &&
4376  !isa<IncompleteArrayType>(VD->getType())) {
4377  S.Diag(AL.getLoc(), diag::err_cuda_extern_shared) << VD;
4378  return;
4379  }
4380  if (S.getLangOpts().CUDA && VD->hasLocalStorage() &&
4381  S.CUDADiagIfHostCode(AL.getLoc(), diag::err_cuda_host_shared)
4382  << S.CurrentCUDATarget())
4383  return;
4384  D->addAttr(::new (S.Context) CUDASharedAttr(
4386 }
4387 
4388 static void handleGlobalAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4389  if (checkAttrMutualExclusion<CUDADeviceAttr>(S, D, AL) ||
4390  checkAttrMutualExclusion<CUDAHostAttr>(S, D, AL)) {
4391  return;
4392  }
4393  const auto *FD = cast<FunctionDecl>(D);
4394  if (!FD->getReturnType()->isVoidType()) {
4395  SourceRange RTRange = FD->getReturnTypeSourceRange();
4396  S.Diag(FD->getTypeSpecStartLoc(), diag::err_kern_type_not_void_return)
4397  << FD->getType()
4398  << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
4399  : FixItHint());
4400  return;
4401  }
4402  if (const auto *Method = dyn_cast<CXXMethodDecl>(FD)) {
4403  if (Method->isInstance()) {
4404  S.Diag(Method->getBeginLoc(), diag::err_kern_is_nonstatic_method)
4405  << Method;
4406  return;
4407  }
4408  S.Diag(Method->getBeginLoc(), diag::warn_kern_is_method) << Method;
4409  }
4410  // Only warn for "inline" when compiling for host, to cut down on noise.
4411  if (FD->isInlineSpecified() && !S.getLangOpts().CUDAIsDevice)
4412  S.Diag(FD->getBeginLoc(), diag::warn_kern_is_inline) << FD;
4413 
4414  D->addAttr(::new (S.Context)
4415  CUDAGlobalAttr(AL.getRange(), S.Context,
4417 }
4418 
4419 static void handleGNUInlineAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4420  const auto *Fn = cast<FunctionDecl>(D);
4421  if (!Fn->isInlineSpecified()) {
4422  S.Diag(AL.getLoc(), diag::warn_gnu_inline_attribute_requires_inline);
4423  return;
4424  }
4425 
4426  D->addAttr(::new (S.Context)
4427  GNUInlineAttr(AL.getRange(), S.Context,
4429 }
4430 
4431 static void handleCallConvAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4432  if (hasDeclarator(D)) return;
4433 
4434  // Diagnostic is emitted elsewhere: here we store the (valid) AL
4435  // in the Decl node for syntactic reasoning, e.g., pretty-printing.
4436  CallingConv CC;
4437  if (S.CheckCallingConvAttr(AL, CC, /*FD*/nullptr))
4438  return;
4439 
4440  if (!isa<ObjCMethodDecl>(D)) {
4441  S.Diag(AL.getLoc(), diag::warn_attribute_wrong_decl_type)
4442  << AL << ExpectedFunctionOrMethod;
4443  return;
4444  }
4445 
4446  switch (AL.getKind()) {
4447  case ParsedAttr::AT_FastCall:
4448  D->addAttr(::new (S.Context)
4449  FastCallAttr(AL.getRange(), S.Context,
4451  return;
4452  case ParsedAttr::AT_StdCall:
4453  D->addAttr(::new (S.Context)
4454  StdCallAttr(AL.getRange(), S.Context,
4456  return;
4457  case ParsedAttr::AT_ThisCall:
4458  D->addAttr(::new (S.Context)
4459  ThisCallAttr(AL.getRange(), S.Context,
4461  return;
4462  case ParsedAttr::AT_CDecl:
4463  D->addAttr(::new (S.Context)
4464  CDeclAttr(AL.getRange(), S.Context,
4466  return;
4467  case ParsedAttr::AT_Pascal:
4468  D->addAttr(::new (S.Context)
4469  PascalAttr(AL.getRange(), S.Context,
4471  return;
4472  case ParsedAttr::AT_SwiftCall:
4473  D->addAttr(::new (S.Context)
4474  SwiftCallAttr(AL.getRange(), S.Context,
4476  return;
4477  case ParsedAttr::AT_VectorCall:
4478  D->addAttr(::new (S.Context)
4479  VectorCallAttr(AL.getRange(), S.Context,
4481  return;
4482  case ParsedAttr::AT_MSABI:
4483  D->addAttr(::new (S.Context)
4484  MSABIAttr(AL.getRange(), S.Context,
4486  return;
4487  case ParsedAttr::AT_SysVABI:
4488  D->addAttr(::new (S.Context)
4489  SysVABIAttr(AL.getRange(), S.Context,
4491  return;
4492  case ParsedAttr::AT_RegCall:
4493  D->addAttr(::new (S.Context) RegCallAttr(
4495  return;
4496  case ParsedAttr::AT_Pcs: {
4497  PcsAttr::PCSType PCS;
4498  switch (CC) {
4499  case CC_AAPCS:
4500  PCS = PcsAttr::AAPCS;
4501  break;
4502  case CC_AAPCS_VFP:
4503  PCS = PcsAttr::AAPCS_VFP;
4504  break;
4505  default:
4506  llvm_unreachable("unexpected calling convention in pcs attribute");
4507  }
4508 
4509  D->addAttr(::new (S.Context)
4510  PcsAttr(AL.getRange(), S.Context, PCS,
4512  return;
4513  }
4514  case ParsedAttr::AT_AArch64VectorPcs:
4515  D->addAttr(::new(S.Context)
4516  AArch64VectorPcsAttr(AL.getRange(), S.Context,
4518  return;
4519  case ParsedAttr::AT_IntelOclBicc:
4520  D->addAttr(::new (S.Context)
4521  IntelOclBiccAttr(AL.getRange(), S.Context,
4523  return;
4524  case ParsedAttr::AT_PreserveMost:
4525  D->addAttr(::new (S.Context) PreserveMostAttr(
4527  return;
4528  case ParsedAttr::AT_PreserveAll:
4529  D->addAttr(::new (S.Context) PreserveAllAttr(
4531  return;
4532  default:
4533  llvm_unreachable("unexpected attribute kind");
4534  }
4535 }
4536 
4537 static void handleSuppressAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4538  if (!checkAttributeAtLeastNumArgs(S, AL, 1))
4539  return;
4540 
4541  std::vector<StringRef> DiagnosticIdentifiers;
4542  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
4543  StringRef RuleName;
4544 
4545  if (!S.checkStringLiteralArgumentAttr(AL, I, RuleName, nullptr))
4546  return;
4547 
4548  // FIXME: Warn if the rule name is unknown. This is tricky because only
4549  // clang-tidy knows about available rules.
4550  DiagnosticIdentifiers.push_back(RuleName);
4551  }
4552  D->addAttr(::new (S.Context) SuppressAttr(
4553  AL.getRange(), S.Context, DiagnosticIdentifiers.data(),
4554  DiagnosticIdentifiers.size(), AL.getAttributeSpellingListIndex()));
4555 }
4556 
4557 bool Sema::CheckCallingConvAttr(const ParsedAttr &Attrs, CallingConv &CC,
4558  const FunctionDecl *FD) {
4559  if (Attrs.isInvalid())
4560  return true;
4561 
4562  if (Attrs.hasProcessingCache()) {
4563  CC = (CallingConv) Attrs.getProcessingCache();
4564  return false;
4565  }
4566 
4567  unsigned ReqArgs = Attrs.getKind() == ParsedAttr::AT_Pcs ? 1 : 0;
4568  if (!checkAttributeNumArgs(*this, Attrs, ReqArgs)) {
4569  Attrs.setInvalid();
4570  return true;
4571  }
4572 
4573  // TODO: diagnose uses of these conventions on the wrong target.
4574  switch (Attrs.getKind()) {
4575  case ParsedAttr::AT_CDecl:
4576  CC = CC_C;
4577  break;
4578  case ParsedAttr::AT_FastCall:
4579  CC = CC_X86FastCall;
4580  break;
4581  case ParsedAttr::AT_StdCall:
4582  CC = CC_X86StdCall;
4583  break;
4584  case ParsedAttr::AT_ThisCall:
4585  CC = CC_X86ThisCall;
4586  break;
4587  case ParsedAttr::AT_Pascal:
4588  CC = CC_X86Pascal;
4589  break;
4590  case ParsedAttr::AT_SwiftCall:
4591  CC = CC_Swift;
4592  break;
4593  case ParsedAttr::AT_VectorCall:
4594  CC = CC_X86VectorCall;
4595  break;
4596  case ParsedAttr::AT_AArch64VectorPcs:
4597  CC = CC_AArch64VectorCall;
4598  break;
4599  case ParsedAttr::AT_RegCall:
4600  CC = CC_X86RegCall;
4601  break;
4602  case ParsedAttr::AT_MSABI:
4603  CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_C :
4604  CC_Win64;
4605  break;
4606  case ParsedAttr::AT_SysVABI:
4607  CC = Context.getTargetInfo().getTriple().isOSWindows() ? CC_X86_64SysV :
4608  CC_C;
4609  break;
4610  case ParsedAttr::AT_Pcs: {
4611  StringRef StrRef;
4612  if (!checkStringLiteralArgumentAttr(Attrs, 0, StrRef)) {
4613  Attrs.setInvalid();
4614  return true;
4615  }
4616  if (StrRef == "aapcs") {
4617  CC = CC_AAPCS;
4618  break;
4619  } else if (StrRef == "aapcs-vfp") {
4620  CC = CC_AAPCS_VFP;
4621  break;
4622  }
4623 
4624  Attrs.setInvalid();
4625  Diag(Attrs.getLoc(), diag::err_invalid_pcs);
4626  return true;
4627  }
4628  case ParsedAttr::AT_IntelOclBicc:
4629  CC = CC_IntelOclBicc;
4630  break;
4631  case ParsedAttr::AT_PreserveMost:
4632  CC = CC_PreserveMost;
4633  break;
4634  case ParsedAttr::AT_PreserveAll:
4635  CC = CC_PreserveAll;
4636  break;
4637  default: llvm_unreachable("unexpected attribute kind");
4638  }
4639 
4641  const TargetInfo &TI = Context.getTargetInfo();
4642  // CUDA functions may have host and/or device attributes which indicate
4643  // their targeted execution environment, therefore the calling convention
4644  // of functions in CUDA should be checked against the target deduced based
4645  // on their host/device attributes.
4646  if (LangOpts.CUDA) {
4647  auto *Aux = Context.getAuxTargetInfo();
4648  auto CudaTarget = IdentifyCUDATarget(FD);
4649  bool CheckHost = false, CheckDevice = false;
4650  switch (CudaTarget) {
4651  case CFT_HostDevice:
4652  CheckHost = true;
4653  CheckDevice = true;
4654  break;
4655  case CFT_Host:
4656  CheckHost = true;
4657  break;
4658  case CFT_Device:
4659  case CFT_Global:
4660  CheckDevice = true;
4661  break;
4662  case CFT_InvalidTarget:
4663  llvm_unreachable("unexpected cuda target");
4664  }
4665  auto *HostTI = LangOpts.CUDAIsDevice ? Aux : &TI;
4666  auto *DeviceTI = LangOpts.CUDAIsDevice ? &TI : Aux;
4667  if (CheckHost && HostTI)
4668  A = HostTI->checkCallingConvention(CC);
4669  if (A == TargetInfo::CCCR_OK && CheckDevice && DeviceTI)
4670  A = DeviceTI->checkCallingConvention(CC);
4671  } else {
4672  A = TI.checkCallingConvention(CC);
4673  }
4674 
4675  switch (A) {
4676  case TargetInfo::CCCR_OK:
4677  break;
4678 
4680  // Treat an ignored convention as if it was an explicit C calling convention
4681  // attribute. For example, __stdcall on Win x64 functions as __cdecl, so
4682  // that command line flags that change the default convention to
4683  // __vectorcall don't affect declarations marked __stdcall.
4684  CC = CC_C;
4685  break;
4686 
4688  Diag(Attrs.getLoc(), diag::error_cconv_unsupported)
4689  << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
4690  break;
4691 
4692  case TargetInfo::CCCR_Warning: {
4693  Diag(Attrs.getLoc(), diag::warn_cconv_unsupported)
4694  << Attrs << (int)CallingConventionIgnoredReason::ForThisTarget;
4695 
4696  // This convention is not valid for the target. Use the default function or
4697  // method calling convention.
4698  bool IsCXXMethod = false, IsVariadic = false;
4699  if (FD) {
4700  IsCXXMethod = FD->isCXXInstanceMember();
4701  IsVariadic = FD->isVariadic();
4702  }
4703  CC = Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod);
4704  break;
4705  }
4706  }
4707 
4708  Attrs.setProcessingCache((unsigned) CC);
4709  return false;
4710 }
4711 
4712 /// Pointer-like types in the default address space.
4713 static bool isValidSwiftContextType(QualType Ty) {
4714  if (!Ty->hasPointerRepresentation())
4715  return Ty->isDependentType();
4717 }
4718 
4719 /// Pointers and references in the default address space.
4720 static bool isValidSwiftIndirectResultType(QualType Ty) {
4721  if (const auto *PtrType = Ty->getAs<PointerType>()) {
4722  Ty = PtrType->getPointeeType();
4723  } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4724  Ty = RefType->getPointeeType();
4725  } else {
4726  return Ty->isDependentType();
4727  }
4728  return Ty.getAddressSpace() == LangAS::Default;
4729 }
4730 
4731 /// Pointers and references to pointers in the default address space.
4732 static bool isValidSwiftErrorResultType(QualType Ty) {
4733  if (const auto *PtrType = Ty->getAs<PointerType>()) {
4734  Ty = PtrType->getPointeeType();
4735  } else if (const auto *RefType = Ty->getAs<ReferenceType>()) {
4736  Ty = RefType->getPointeeType();
4737  } else {
4738  return Ty->isDependentType();
4739  }
4740  if (!Ty.getQualifiers().empty())
4741  return false;
4742  return isValidSwiftContextType(Ty);
4743 }
4744 
4745 static void handleParameterABIAttr(Sema &S, Decl *D, const ParsedAttr &Attrs,
4746  ParameterABI Abi) {
4747  S.AddParameterABIAttr(Attrs.getRange(), D, Abi,
4749 }
4750 
4752  unsigned spellingIndex) {
4753 
4754  QualType type = cast<ParmVarDecl>(D)->getType();
4755 
4756  if (auto existingAttr = D->getAttr<ParameterABIAttr>()) {
4757  if (existingAttr->getABI() != abi) {
4758  Diag(range.getBegin(), diag::err_attributes_are_not_compatible)
4759  << getParameterABISpelling(abi) << existingAttr;
4760  Diag(existingAttr->getLocation(), diag::note_conflicting_attribute);
4761  return;
4762  }
4763  }
4764 
4765  switch (abi) {
4767  llvm_unreachable("explicit attribute for ordinary parameter ABI?");
4768 
4770  if (!isValidSwiftContextType(type)) {
4771  Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4772  << getParameterABISpelling(abi)
4773  << /*pointer to pointer */ 0 << type;
4774  }
4775  D->addAttr(::new (Context)
4776  SwiftContextAttr(range, Context, spellingIndex));
4777  return;
4778 
4780  if (!isValidSwiftErrorResultType(type)) {
4781  Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4782  << getParameterABISpelling(abi)
4783  << /*pointer to pointer */ 1 << type;
4784  }
4785  D->addAttr(::new (Context)
4786  SwiftErrorResultAttr(range, Context, spellingIndex));
4787  return;
4788 
4790  if (!isValidSwiftIndirectResultType(type)) {
4791  Diag(range.getBegin(), diag::err_swift_abi_parameter_wrong_type)
4792  << getParameterABISpelling(abi)
4793  << /*pointer*/ 0 << type;
4794  }
4795  D->addAttr(::new (Context)
4796  SwiftIndirectResultAttr(range, Context, spellingIndex));
4797  return;
4798  }
4799  llvm_unreachable("bad parameter ABI attribute");
4800 }
4801 
4802 /// Checks a regparm attribute, returning true if it is ill-formed and
4803 /// otherwise setting numParams to the appropriate value.
4804 bool Sema::CheckRegparmAttr(const ParsedAttr &AL, unsigned &numParams) {
4805  if (AL.isInvalid())
4806  return true;
4807 
4808  if (!checkAttributeNumArgs(*this, AL, 1)) {
4809  AL.setInvalid();
4810  return true;
4811  }
4812 
4813  uint32_t NP;
4814  Expr *NumParamsExpr = AL.getArgAsExpr(0);
4815  if (!checkUInt32Argument(*this, AL, NumParamsExpr, NP)) {
4816  AL.setInvalid();
4817  return true;
4818  }
4819 
4820  if (Context.getTargetInfo().getRegParmMax() == 0) {
4821  Diag(AL.getLoc(), diag::err_attribute_regparm_wrong_platform)
4822  << NumParamsExpr->getSourceRange();
4823  AL.setInvalid();
4824  return true;
4825  }
4826 
4827  numParams = NP;
4828  if (numParams > Context.getTargetInfo().getRegParmMax()) {
4829  Diag(AL.getLoc(), diag::err_attribute_regparm_invalid_number)
4830  << Context.getTargetInfo().getRegParmMax() << NumParamsExpr->getSourceRange();
4831  AL.setInvalid();
4832  return true;
4833  }
4834 
4835  return false;
4836 }
4837 
4838 // Checks whether an argument of launch_bounds attribute is
4839 // acceptable, performs implicit conversion to Rvalue, and returns
4840 // non-nullptr Expr result on success. Otherwise, it returns nullptr
4841 // and may output an error.
4842 static Expr *makeLaunchBoundsArgExpr(Sema &S, Expr *E,
4843  const CUDALaunchBoundsAttr &AL,
4844  const unsigned Idx) {
4846  return nullptr;
4847 
4848  // Accept template arguments for now as they depend on something else.
4849  // We'll get to check them when they eventually get instantiated.
4850  if (E->isValueDependent())
4851  return E;
4852 
4853  llvm::APSInt I(64);
4854  if (!E->isIntegerConstantExpr(I, S.Context)) {
4855  S.Diag(E->getExprLoc(), diag::err_attribute_argument_n_type)
4856  << &AL << Idx << AANT_ArgumentIntegerConstant << E->getSourceRange();
4857  return nullptr;
4858  }
4859  // Make sure we can fit it in 32 bits.
4860  if (!I.isIntN(32)) {
4861  S.Diag(E->getExprLoc(), diag::err_ice_too_large) << I.toString(10, false)
4862  << 32 << /* Unsigned */ 1;
4863  return nullptr;
4864  }
4865  if (I < 0)
4866  S.Diag(E->getExprLoc(), diag::warn_attribute_argument_n_negative)
4867  << &AL << Idx << E->getSourceRange();
4868 
4869  // We may need to perform implicit conversion of the argument.
4871  S.Context, S.Context.getConstType(S.Context.IntTy), /*consume*/ false);
4872  ExprResult ValArg = S.PerformCopyInitialization(Entity, SourceLocation(), E);
4873  assert(!ValArg.isInvalid() &&
4874  "Unexpected PerformCopyInitialization() failure.");
4875 
4876  return ValArg.getAs<Expr>();
4877 }
4878 
4879 void Sema::AddLaunchBoundsAttr(SourceRange AttrRange, Decl *D, Expr *MaxThreads,
4880  Expr *MinBlocks, unsigned SpellingListIndex) {
4881  CUDALaunchBoundsAttr TmpAttr(AttrRange, Context, MaxThreads, MinBlocks,
4882  SpellingListIndex);
4883  MaxThreads = makeLaunchBoundsArgExpr(*this, MaxThreads, TmpAttr, 0);
4884  if (MaxThreads == nullptr)
4885  return;
4886 
4887  if (MinBlocks) {
4888  MinBlocks = makeLaunchBoundsArgExpr(*this, MinBlocks, TmpAttr, 1);
4889  if (MinBlocks == nullptr)
4890  return;
4891  }
4892 
4893  D->addAttr(::new (Context) CUDALaunchBoundsAttr(
4894  AttrRange, Context, MaxThreads, MinBlocks, SpellingListIndex));
4895 }
4896 
4897 static void handleLaunchBoundsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4898  if (!checkAttributeAtLeastNumArgs(S, AL, 1) ||
4899  !checkAttributeAtMostNumArgs(S, AL, 2))
4900  return;
4901 
4902  S.AddLaunchBoundsAttr(AL.getRange(), D, AL.getArgAsExpr(0),
4903  AL.getNumArgs() > 1 ? AL.getArgAsExpr(1) : nullptr,
4905 }
4906 
4907 static void handleArgumentWithTypeTagAttr(Sema &S, Decl *D,
4908  const ParsedAttr &AL) {
4909  if (!AL.isArgIdent(0)) {
4910  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
4911  << AL << /* arg num = */ 1 << AANT_ArgumentIdentifier;
4912  return;
4913  }
4914 
4915  ParamIdx ArgumentIdx;
4916  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 2, AL.getArgAsExpr(1),
4917  ArgumentIdx))
4918  return;
4919 
4920  ParamIdx TypeTagIdx;
4921  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 3, AL.getArgAsExpr(2),
4922  TypeTagIdx))
4923  return;
4924 
4925  bool IsPointer = AL.getName()->getName() == "pointer_with_type_tag";
4926  if (IsPointer) {
4927  // Ensure that buffer has a pointer type.
4928  unsigned ArgumentIdxAST = ArgumentIdx.getASTIndex();
4929  if (ArgumentIdxAST >= getFunctionOrMethodNumParams(D) ||
4930  !getFunctionOrMethodParamType(D, ArgumentIdxAST)->isPointerType())
4931  S.Diag(AL.getLoc(), diag::err_attribute_pointers_only) << AL << 0;
4932  }
4933 
4934  D->addAttr(::new (S.Context) ArgumentWithTypeTagAttr(
4935  AL.getRange(), S.Context, AL.getArgAsIdent(0)->Ident, ArgumentIdx,
4936  TypeTagIdx, IsPointer, AL.getAttributeSpellingListIndex()));
4937 }
4938 
4939 static void handleTypeTagForDatatypeAttr(Sema &S, Decl *D,
4940  const ParsedAttr &AL) {
4941  if (!AL.isArgIdent(0)) {
4942  S.Diag(AL.getLoc(), diag::err_attribute_argument_n_type)
4943  << AL << 1 << AANT_ArgumentIdentifier;
4944  return;
4945  }
4946 
4947  if (!checkAttributeNumArgs(S, AL, 1))
4948  return;
4949 
4950  if (!isa<VarDecl>(D)) {
4951  S.Diag(AL.getLoc(), diag::err_attribute_wrong_decl_type)
4952  << AL << ExpectedVariable;
4953  return;
4954  }
4955 
4956  IdentifierInfo *PointerKind = AL.getArgAsIdent(0)->Ident;
4957  TypeSourceInfo *MatchingCTypeLoc = nullptr;
4958  S.GetTypeFromParser(AL.getMatchingCType(), &MatchingCTypeLoc);
4959  assert(MatchingCTypeLoc && "no type source info for attribute argument");
4960 
4961  D->addAttr(::new (S.Context)
4962  TypeTagForDatatypeAttr(AL.getRange(), S.Context, PointerKind,
4963  MatchingCTypeLoc,
4964  AL.getLayoutCompatible(),
4965  AL.getMustBeNull(),
4967 }
4968 
4969 static void handleXRayLogArgsAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
4970  ParamIdx ArgCount;
4971 
4972  if (!checkFunctionOrMethodParameterIndex(S, D, AL, 1, AL.getArgAsExpr(0),
4973  ArgCount,
4974  true /* CanIndexImplicitThis */))
4975  return;
4976 
4977  // ArgCount isn't a parameter index [0;n), it's a count [1;n]
4978  D->addAttr(::new (S.Context) XRayLogArgsAttr(
4979  AL.getRange(), S.Context, ArgCount.getSourceIndex(),
4981 }
4982 
4983 //===----------------------------------------------------------------------===//
4984 // Checker-specific attribute handlers.
4985 //===----------------------------------------------------------------------===//
4986 static bool isValidSubjectOfNSReturnsRetainedAttribute(QualType QT) {
4987  return QT->isDependentType() || QT->isObjCRetainableType();
4988 }
4989 
4990 static bool isValidSubjectOfNSAttribute(QualType QT) {
4991  return QT->isDependentType() || QT->isObjCObjectPointerType() ||
4992  QT->isObjCNSObjectType();
4993 }
4994 
4995 static bool isValidSubjectOfCFAttribute(QualType QT) {
4996  return QT->isDependentType() || QT->isPointerType() ||
4997  isValidSubjectOfNSAttribute(QT);
4998 }
4999 
5000 static bool isValidSubjectOfOSAttribute(QualType QT) {
5001  if (QT->isDependentType())
5002  return true;
5003  QualType PT = QT->getPointeeType();
5004  return !PT.isNull() && PT->getAsCXXRecordDecl() != nullptr;
5005 }
5006 
5007 void Sema::AddXConsumedAttr(Decl *D, SourceRange SR, unsigned SpellingIndex,
5008  RetainOwnershipKind K,
5009  bool IsTemplateInstantiation) {
5010  ValueDecl *VD = cast<ValueDecl>(D);
5011  switch (K) {
5012  case RetainOwnershipKind::OS:
5013  handleSimpleAttributeOrDiagnose<OSConsumedAttr>(
5014  *this, VD, SR, SpellingIndex, isValidSubjectOfOSAttribute(VD->getType()),
5015  diag::warn_ns_attribute_wrong_parameter_type,
5016  /*ExtraArgs=*/SR, "os_consumed", /*pointers*/ 1);
5017  return;
5018  case RetainOwnershipKind::NS:
5019  handleSimpleAttributeOrDiagnose<NSConsumedAttr>(
5020  *this, VD, SR, SpellingIndex, isValidSubjectOfNSAttribute(VD->getType()),
5021 
5022  // These attributes are normally just advisory, but in ARC, ns_consumed
5023  // is significant. Allow non-dependent code to contain inappropriate
5024  // attributes even in ARC, but require template instantiations to be
5025  // set up correctly.
5026  ((IsTemplateInstantiation && getLangOpts().ObjCAutoRefCount)
5027  ? diag::err_ns_attribute_wrong_parameter_type
5028  : diag::warn_ns_attribute_wrong_parameter_type),
5029  /*ExtraArgs=*/SR, "ns_consumed", /*objc pointers*/ 0);
5030  return;
5031  case RetainOwnershipKind::CF:
5032  handleSimpleAttributeOrDiagnose<CFConsumedAttr>(
5033  *this, VD, SR, SpellingIndex,
5034  isValidSubjectOfCFAttribute(VD->getType()),
5035  diag::warn_ns_attribute_wrong_parameter_type,
5036  /*ExtraArgs=*/SR, "cf_consumed", /*pointers*/1);
5037  return;
5038  }
5039 }
5040 
5042 parsedAttrToRetainOwnershipKind(const ParsedAttr &AL) {
5043  switch (AL.getKind()) {
5044  case ParsedAttr::AT_CFConsumed:
5045  case ParsedAttr::AT_CFReturnsRetained:
5046  case ParsedAttr::AT_CFReturnsNotRetained:
5048  case ParsedAttr::AT_OSConsumesThis:
5049  case ParsedAttr::AT_OSConsumed:
5050  case ParsedAttr::AT_OSReturnsRetained:
5051  case ParsedAttr::AT_OSReturnsNotRetained:
5052  case ParsedAttr::AT_OSReturnsRetainedOnZero:
5053  case ParsedAttr::AT_OSReturnsRetainedOnNonZero:
5055  case ParsedAttr::AT_NSConsumesSelf:
5056  case ParsedAttr::AT_NSConsumed:
5057  case ParsedAttr::AT_NSReturnsRetained:
5058  case ParsedAttr::AT_NSReturnsNotRetained:
5059  case ParsedAttr::AT_NSReturnsAutoreleased:
5061  default:
5062  llvm_unreachable("Wrong argument supplied");
5063  }
5064 }
5065 
5067  if (isValidSubjectOfNSReturnsRetainedAttribute(QT))
5068  return false;
5069 
5070  Diag(Loc, diag::warn_ns_attribute_wrong_return_type)
5071  << "'ns_returns_retained'" << 0 << 0;
5072  return true;
5073 }
5074 
5075 /// \return whether the parameter is a pointer to OSObject pointer.
5076 static bool isValidOSObjectOutParameter(const Decl *D) {
5077  const auto *PVD = dyn_cast<ParmVarDecl>(D);
5078  if (!PVD)
5079  return false;
5080  QualType QT = PVD->getType();
5081  QualType PT = QT->getPointeeType();
5082  return !PT.isNull() && isValidSubjectOfOSAttribute(PT);
5083 }
5084 
5085 static void handleXReturnsXRetainedAttr(Sema &S, Decl *D,
5086  const ParsedAttr &AL) {
5087  QualType ReturnType;
5088  Sema::RetainOwnershipKind K = parsedAttrToRetainOwnershipKind(AL);
5089 
5090  if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
5091  ReturnType = MD->getReturnType();
5092  } else if (S.getLangOpts().ObjCAutoRefCount && hasDeclarator(D) &&
5093  (AL.getKind() == ParsedAttr::AT_NSReturnsRetained)) {
5094  return; // ignore: was handled as a type attribute
5095  } else if (const auto *PD = dyn_cast<ObjCPropertyDecl>(D)) {
5096  ReturnType = PD->getType();
5097  } else if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
5098  ReturnType = FD->getReturnType();
5099  } else if (const auto *Param = dyn_cast<ParmVarDecl>(D)) {
5100  // Attributes on parameters are used for out-parameters,
5101  // passed as pointers-to-pointers.
5102  unsigned DiagID = K == Sema::RetainOwnershipKind::CF
5103  ? /*pointer-to-CF-pointer*/2
5104  : /*pointer-to-OSObject-pointer*/3;
5105  ReturnType = Param->getType()->getPointeeType();
5106  if (ReturnType.isNull()) {
5107  S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
5108  << AL << DiagID << AL.getRange();
5109  return;
5110  }
5111  } else if (AL.isUsedAsTypeAttr()) {
5112  return;
5113  } else {
5114  AttributeDeclKind ExpectedDeclKind;
5115  switch (AL.getKind()) {
5116  default: llvm_unreachable("invalid ownership attribute");
5117  case ParsedAttr::AT_NSReturnsRetained:
5118  case ParsedAttr::AT_NSReturnsAutoreleased:
5119  case ParsedAttr::AT_NSReturnsNotRetained:
5120  ExpectedDeclKind = ExpectedFunctionOrMethod;
5121  break;
5122 
5123  case ParsedAttr::AT_OSReturnsRetained:
5124  case ParsedAttr::AT_OSReturnsNotRetained:
5125  case ParsedAttr::AT_CFReturnsRetained:
5126  case ParsedAttr::AT_CFReturnsNotRetained:
5127  ExpectedDeclKind = ExpectedFunctionMethodOrParameter;
5128  break;
5129  }
5130  S.Diag(D->getBeginLoc(), diag::warn_attribute_wrong_decl_type)
5131  << AL.getRange() << AL << ExpectedDeclKind;
5132  return;
5133  }
5134 
5135  bool TypeOK;
5136  bool Cf;
5137  unsigned ParmDiagID = 2; // Pointer-to-CF-pointer
5138  switch (AL.getKind()) {
5139  default: llvm_unreachable("invalid ownership attribute");
5140  case ParsedAttr::AT_NSReturnsRetained:
5141  TypeOK = isValidSubjectOfNSReturnsRetainedAttribute(ReturnType);
5142  Cf = false;
5143  break;
5144 
5145  case ParsedAttr::AT_NSReturnsAutoreleased:
5146  case ParsedAttr::AT_NSReturnsNotRetained:
5147  TypeOK = isValidSubjectOfNSAttribute(ReturnType);
5148  Cf = false;
5149  break;
5150 
5151  case ParsedAttr::AT_CFReturnsRetained:
5152  case ParsedAttr::AT_CFReturnsNotRetained:
5153  TypeOK = isValidSubjectOfCFAttribute(ReturnType);
5154  Cf = true;
5155  break;
5156 
5157  case ParsedAttr::AT_OSReturnsRetained:
5158  case ParsedAttr::AT_OSReturnsNotRetained:
5159  TypeOK = isValidSubjectOfOSAttribute(ReturnType);
5160  Cf = true;
5161  ParmDiagID = 3; // Pointer-to-OSObject-pointer
5162  break;
5163  }
5164 
5165  if (!TypeOK) {
5166  if (AL.isUsedAsTypeAttr())
5167  return;
5168 
5169  if (isa<ParmVarDecl>(D)) {
5170  S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_parameter_type)
5171  << AL << ParmDiagID << AL.getRange();
5172  } else {
5173  // Needs to be kept in sync with warn_ns_attribute_wrong_return_type.
5174  enum : unsigned {
5175  Function,
5176  Method,
5177  Property
5178  } SubjectKind = Function;
5179  if (isa<ObjCMethodDecl>(D))
5180  SubjectKind = Method;
5181  else if (isa<ObjCPropertyDecl>(D))
5182  SubjectKind = Property;
5183  S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
5184  << AL << SubjectKind << Cf << AL.getRange();
5185  }
5186  return;
5187  }
5188 
5189  switch (AL.getKind()) {
5190  default:
5191  llvm_unreachable("invalid ownership attribute");
5192  case ParsedAttr::AT_NSReturnsAutoreleased:
5193  handleSimpleAttribute<NSReturnsAutoreleasedAttr>(S, D, AL);
5194  return;
5195  case ParsedAttr::AT_CFReturnsNotRetained:
5196  handleSimpleAttribute<CFReturnsNotRetainedAttr>(S, D, AL);
5197  return;
5198  case ParsedAttr::AT_NSReturnsNotRetained:
5199  handleSimpleAttribute<NSReturnsNotRetainedAttr>(S, D, AL);
5200  return;
5201  case ParsedAttr::AT_CFReturnsRetained:
5202  handleSimpleAttribute<CFReturnsRetainedAttr>(S, D, AL);
5203  return;
5204  case ParsedAttr::AT_NSReturnsRetained:
5205  handleSimpleAttribute<NSReturnsRetainedAttr>(S, D, AL);
5206  return;
5207  case ParsedAttr::AT_OSReturnsRetained:
5208  handleSimpleAttribute<OSReturnsRetainedAttr>(S, D, AL);
5209  return;
5210  case ParsedAttr::AT_OSReturnsNotRetained:
5211  handleSimpleAttribute<OSReturnsNotRetainedAttr>(S, D, AL);
5212  return;
5213  };
5214 }
5215 
5216 static void handleObjCReturnsInnerPointerAttr(Sema &S, Decl *D,
5217  const ParsedAttr &Attrs) {
5218  const int EP_ObjCMethod = 1;
5219  const int EP_ObjCProperty = 2;
5220 
5221  SourceLocation loc = Attrs.getLoc();
5222  QualType resultType;
5223  if (isa<ObjCMethodDecl>(D))
5224  resultType = cast<ObjCMethodDecl>(D)->getReturnType();
5225  else
5226  resultType = cast<ObjCPropertyDecl>(D)->getType();
5227 
5228  if (!resultType->isReferenceType() &&
5229  (!resultType->isPointerType() || resultType->isObjCRetainableType())) {
5230  S.Diag(D->getBeginLoc(), diag::warn_ns_attribute_wrong_return_type)
5231  << SourceRange(loc) << Attrs
5232  << (isa<ObjCMethodDecl>(D) ? EP_ObjCMethod : EP_ObjCProperty)
5233  << /*non-retainable pointer*/ 2;
5234 
5235  // Drop the attribute.
5236  return;
5237  }
5238 
5239  D->addAttr(::new (S.Context) ObjCReturnsInnerPointerAttr(
5240  Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
5241 }
5242 
5243 static void handleObjCRequiresSuperAttr(Sema &S, Decl *D,
5244  const ParsedAttr &Attrs) {
5245  const auto *Method = cast<ObjCMethodDecl>(D);
5246 
5247  const DeclContext *DC = Method->getDeclContext();
5248  if (const auto *PDecl = dyn_cast_or_null<ObjCProtocolDecl>(DC)) {
5249  S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5250  << 0;
5251  S.Diag(PDecl->getLocation(), diag::note_protocol_decl);
5252  return;
5253  }
5254  if (Method->getMethodFamily() == OMF_dealloc) {
5255  S.Diag(D->getBeginLoc(), diag::warn_objc_requires_super_protocol) << Attrs
5256  << 1;
5257  return;
5258  }
5259 
5260  D->addAttr(::new (S.Context) ObjCRequiresSuperAttr(
5261  Attrs.getRange(), S.Context, Attrs.getAttributeSpellingListIndex()));
5262 }
5263 
5264 static void handleObjCBridgeAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5265  IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5266 
5267  if (!Parm) {
5268  S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5269  return;
5270  }
5271 
5272  // Typedefs only allow objc_bridge(id) and have some additional checking.
5273  if (const auto *TD = dyn_cast<TypedefNameDecl>(D)) {
5274  if (!Parm->Ident->isStr("id")) {
5275  S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_id) << AL;
5276  return;
5277  }
5278 
5279  // Only allow 'cv void *'.
5280  QualType T = TD->getUnderlyingType();
5281  if (!T->isVoidPointerType()) {
5282  S.Diag(AL.getLoc(), diag::err_objc_attr_typedef_not_void_pointer);
5283  return;
5284  }
5285  }
5286 
5287  D->addAttr(::new (S.Context)
5288  ObjCBridgeAttr(AL.getRange(), S.Context, Parm->Ident,
5290 }
5291 
5292 static void handleObjCBridgeMutableAttr(Sema &S, Decl *D,
5293  const ParsedAttr &AL) {
5294  IdentifierLoc *Parm = AL.isArgIdent(0) ? AL.getArgAsIdent(0) : nullptr;
5295 
5296  if (!Parm) {
5297  S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5298  return;
5299  }
5300 
5301  D->addAttr(::new (S.Context)
5302  ObjCBridgeMutableAttr(AL.getRange(), S.Context, Parm->Ident,
5304 }
5305 
5306 static void handleObjCBridgeRelatedAttr(Sema &S, Decl *D,
5307  const ParsedAttr &AL) {
5308  IdentifierInfo *RelatedClass =
5309  AL.isArgIdent(0) ? AL.getArgAsIdent(0)->Ident : nullptr;
5310  if (!RelatedClass) {
5311  S.Diag(D->getBeginLoc(), diag::err_objc_attr_not_id) << AL << 0;
5312  return;
5313  }
5314  IdentifierInfo *ClassMethod =
5315  AL.getArgAsIdent(1) ? AL.getArgAsIdent(1)->Ident : nullptr;
5316  IdentifierInfo *InstanceMethod =
5317  AL.getArgAsIdent(2) ? AL.getArgAsIdent(2)->Ident : nullptr;
5318  D->addAttr(::new (S.Context)
5319  ObjCBridgeRelatedAttr(AL.getRange(), S.Context, RelatedClass,
5320  ClassMethod, InstanceMethod,
5322 }
5323 
5324 static void handleObjCDesignatedInitializer(Sema &S, Decl *D,
5325  const ParsedAttr &AL) {
5326  DeclContext *Ctx = D->getDeclContext();
5327 
5328  // This attribute can only be applied to methods in interfaces or class
5329  // extensions.
5330  if (!isa<ObjCInterfaceDecl>(Ctx) &&
5331  !(isa<ObjCCategoryDecl>(Ctx) &&
5332  cast<ObjCCategoryDecl>(Ctx)->IsClassExtension())) {
5333  S.Diag(D->getLocation(), diag::err_designated_init_attr_non_init);
5334  return;
5335  }
5336 
5337  ObjCInterfaceDecl *IFace;
5338  if (auto *CatDecl = dyn_cast<ObjCCategoryDecl>(Ctx))
5339  IFace = CatDecl->getClassInterface();
5340  else
5341  IFace = cast<ObjCInterfaceDecl>(Ctx);
5342 
5343  if (!IFace)
5344  return;
5345 
5347  D->addAttr(::new (S.Context)
5348  ObjCDesignatedInitializerAttr(AL.getRange(), S.Context,
5350 }
5351 
5352 static void handleObjCRuntimeName(Sema &S, Decl *D, const ParsedAttr &AL) {
5353  StringRef MetaDataName;
5354  if (!S.checkStringLiteralArgumentAttr(AL, 0, MetaDataName))
5355  return;
5356  D->addAttr(::new (S.Context)
5357  ObjCRuntimeNameAttr(AL.getRange(), S.Context,
5358  MetaDataName,
5360 }
5361 
5362 // When a user wants to use objc_boxable with a union or struct
5363 // but they don't have access to the declaration (legacy/third-party code)
5364 // then they can 'enable' this feature with a typedef:
5365 // typedef struct __attribute((objc_boxable)) legacy_struct legacy_struct;
5366 static void handleObjCBoxable(Sema &S, Decl *D, const ParsedAttr &AL) {
5367  bool notify = false;
5368 
5369  auto *RD = dyn_cast<RecordDecl>(D);
5370  if (RD && RD->getDefinition()) {
5371  RD = RD->getDefinition();
5372  notify = true;
5373  }
5374 
5375  if (RD) {
5376  ObjCBoxableAttr *BoxableAttr = ::new (S.Context)
5377  ObjCBoxableAttr(AL.getRange(), S.Context,
5379  RD->addAttr(BoxableAttr);
5380  if (notify) {
5381  // we need to notify ASTReader/ASTWriter about
5382  // modification of existing declaration
5384  L->AddedAttributeToRecord(BoxableAttr, RD);
5385  }
5386  }
5387 }
5388 
5389 static void handleObjCOwnershipAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5390  if (hasDeclarator(D)) return;
5391 
5392  S.Diag(D->getBeginLoc(), diag::err_attribute_wrong_decl_type)
5393  << AL.getRange() << AL << ExpectedVariable;
5394 }
5395 
5396 static void handleObjCPreciseLifetimeAttr(Sema &S, Decl *D,
5397  const ParsedAttr &AL) {
5398  const auto *VD = cast<ValueDecl>(D);
5399  QualType QT = VD->getType();
5400 
5401  if (!QT->isDependentType() &&
5402  !QT->isObjCLifetimeType()) {
5403  S.Diag(AL.getLoc(), diag::err_objc_precise_lifetime_bad_type)
5404  << QT;
5405  return;
5406  }
5407 
5408  Qualifiers::ObjCLifetime Lifetime = QT.getObjCLifetime();
5409 
5410  // If we have no lifetime yet, check the lifetime we're presumably
5411  // going to infer.
5412  if (Lifetime == Qualifiers::OCL_None && !QT->isDependentType())
5413  Lifetime = QT->getObjCARCImplicitLifetime();
5414 
5415  switch (Lifetime) {
5416  case Qualifiers::OCL_None:
5417  assert(QT->isDependentType() &&
5418  "didn't infer lifetime for non-dependent type?");
5419  break;
5420 
5421  case Qualifiers::OCL_Weak: // meaningful
5422  case Qualifiers::OCL_Strong: // meaningful
5423  break;
5424 
5427  S.Diag(AL.getLoc(), diag::warn_objc_precise_lifetime_meaningless)
5428  << (Lifetime == Qualifiers::OCL_Autoreleasing);
5429  break;
5430  }
5431 
5432  D->addAttr(::new (S.Context)
5433  ObjCPreciseLifetimeAttr(AL.getRange(), S.Context,
5435 }
5436 
5437 //===----------------------------------------------------------------------===//
5438 // Microsoft specific attribute handlers.
5439 //===----------------------------------------------------------------------===//
5440 
5441 UuidAttr *Sema::mergeUuidAttr(Decl *D, SourceRange Range,
5442  unsigned AttrSpellingListIndex, StringRef Uuid) {
5443  if (const auto *UA = D->getAttr<UuidAttr>()) {
5444  if (UA->getGuid().equals_lower(Uuid))
5445  return nullptr;
5446  Diag(UA->getLocation(), diag::err_mismatched_uuid);
5447  Diag(Range.getBegin(), diag::note_previous_uuid);
5448  D->dropAttr<UuidAttr>();
5449  }
5450 
5451  return ::new (Context) UuidAttr(Range, Context, Uuid, AttrSpellingListIndex);
5452 }
5453 
5454 static void handleUuidAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5455  if (!S.LangOpts.CPlusPlus) {
5456  S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
5457  << AL << AttributeLangSupport::C;
5458  return;
5459  }
5460 
5461  StringRef StrRef;
5462  SourceLocation LiteralLoc;
5463  if (!S.checkStringLiteralArgumentAttr(AL, 0, StrRef, &LiteralLoc))
5464  return;
5465 
5466  // GUID format is "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX" or
5467  // "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}", normalize to the former.
5468  if (StrRef.size() == 38 && StrRef.front() == '{' && StrRef.back() == '}')
5469  StrRef = StrRef.drop_front().drop_back();
5470 
5471  // Validate GUID length.
5472  if (StrRef.size() != 36) {
5473  S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5474  return;
5475  }
5476 
5477  for (unsigned i = 0; i < 36; ++i) {
5478  if (i == 8 || i == 13 || i == 18 || i == 23) {
5479  if (StrRef[i] != '-') {
5480  S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5481  return;
5482  }
5483  } else if (!isHexDigit(StrRef[i])) {
5484  S.Diag(LiteralLoc, diag::err_attribute_uuid_malformed_guid);
5485  return;
5486  }
5487  }
5488 
5489  // FIXME: It'd be nice to also emit a fixit removing uuid(...) (and, if it's
5490  // the only thing in the [] list, the [] too), and add an insertion of
5491  // __declspec(uuid(...)). But sadly, neither the SourceLocs of the commas
5492  // separating attributes nor of the [ and the ] are in the AST.
5493  // Cf "SourceLocations of attribute list delimiters - [[ ... , ... ]] etc"
5494  // on cfe-dev.
5495  if (AL.isMicrosoftAttribute()) // Check for [uuid(...)] spelling.
5496  S.Diag(AL.getLoc(), diag::warn_atl_uuid_deprecated);
5497 
5498  UuidAttr *UA = S.mergeUuidAttr(D, AL.getRange(),
5499  AL.getAttributeSpellingListIndex(), StrRef);
5500  if (UA)
5501  D->addAttr(UA);
5502 }
5503 
5504 static void handleMSInheritanceAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5505  if (!S.LangOpts.CPlusPlus) {
5506  S.Diag(AL.getLoc(), diag::err_attribute_not_supported_in_lang)
5507  << AL << AttributeLangSupport::C;
5508  return;
5509  }
5510  MSInheritanceAttr *IA = S.mergeMSInheritanceAttr(
5511  D, AL.getRange(), /*BestCase=*/true,
5513  (MSInheritanceAttr::Spelling)AL.getSemanticSpelling());
5514  if (IA) {
5515  D->addAttr(IA);
5516  S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
5517  }
5518 }
5519 
5520 static void handleDeclspecThreadAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5521  const auto *VD = cast<VarDecl>(D);
5522  if (!S.Context.getTargetInfo().isTLSSupported()) {
5523  S.Diag(AL.getLoc(), diag::err_thread_unsupported);
5524  return;
5525  }
5526  if (VD->getTSCSpec() != TSCS_unspecified) {
5527  S.Diag(AL.getLoc(), diag::err_declspec_thread_on_thread_variable);
5528  return;
5529  }
5530  if (VD->hasLocalStorage()) {
5531  S.Diag(AL.getLoc(), diag::err_thread_non_global) << "__declspec(thread)";
5532  return;
5533  }
5534  D->addAttr(::new (S.Context) ThreadAttr(AL.getRange(), S.Context,
5536 }
5537 
5538 static void handleAbiTagAttr(Sema &S, Decl *D, const ParsedAttr &AL) {
5540  for (unsigned I = 0, E = AL.getNumArgs(); I != E; ++I) {
5541  StringRef Tag;
5542  if (!S.checkStringLiteralArgumentAttr(AL, I, Tag))
5543  return;
5544  Tags.push_back(Tag);