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